npm package: @harbyx/aasp-sdk
Description: Harbyx AASP SDK for Node.js - AI Agent Security Protocol
Author: Harbyx
Latest version: 0.1.0

# @harbyx/aasp-sdk

Official Node.js SDK for **Harbyx AASP** (AI Agent Security Protocol) - a security control plane for AI agents.

## Installation

```bash
npm install @harbyx/aasp-sdk
# or
pnpm add @harbyx/aasp-sdk
# or
yarn add @harbyx/aasp-sdk
```

## Quick Start

```typescript
import { AASPClient } from '@harbyx/aasp-sdk'

const client = new AASPClient({
  apiKey: process.env.HARBYX_API_KEY!,
})

// Evaluate an action before execution
const result = await client.evaluate({
  agentId: 'my-chatbot',
  actionType: 'tool_call',
  target: 'send_email',
  params: { to: 'user@example.com', subject: 'Hello' },
})

if (result.decision === 'allow') {
  // Safe to execute the action
} else if (result.decision === 'block') {
  // Action was blocked by policy
  console.log('Blocked:', result.reason)
} else if (result.decision === 'require_approval') {
  // Wait for human approval
  await client.waitForApproval(result.approvalId!)
}
```

## Features

- **Core Client**: Evaluate actions, check approval status, wait for approvals
- **Express Middleware**: Secure Express.js routes with AASP policies
- **Fastify Plugin**: Secure Fastify routes with AASP policies
- **LangChain.js Integration**: Automatic tool call interception
- **Decorators/HOFs**: Wrap functions with security checks
- **CLI Tool**: Policy as Code with `harbyx` commands

## Usage

### Basic Client

```typescript
import { AASPClient, ErrorMode } from '@harbyx/aasp-sdk'

const client = new AASPClient({
  apiKey: 'aasp_live_xxx',
  baseUrl: 'https://app.harbyx.com/api/v1', // optional
  timeout: 30000, // optional, in ms
  errorMode: ErrorMode.FAIL_CLOSED, // or OBSERVABILITY_ONLY
})

// Evaluate and throw on block
try {
  await client.evaluateOrThrow({
    agentId: 'my-agent',
    actionType: 'api_call',
    target: 'stripe:refund',
    params: { amount: 15000 },
  })
  // Action allowed, proceed
} catch (error) {
  if (error instanceof ToolBlockedError) {
    console.log('Blocked by policy:', error.reason)
  }
}
```

### Express Middleware

```typescript
import express from 'express'
import { aaspMiddleware } from '@harbyx/aasp-sdk/express'

const app = express()

// Protect all routes
app.use(aaspMiddleware({
  client: { apiKey: process.env.HARBYX_API_KEY },
  agentId: 'my-api',
  skip: ['/health', '/metrics'],
}))

// Or protect specific routes
app.post('/api/payments',
  aaspMiddleware({
    client: { apiKey: process.env.HARBYX_API_KEY },
    agentId: 'payment-api',
    actionType: 'api_call',
    getTarget: (req) => `payment:${req.body?.type || 'unknown'}`,
  }),
  paymentHandler
)
```

### LangChain.js Integration

```typescript
import { ChatOpenAI } from '@langchain/openai'
import { AASPCallbackHandler } from '@harbyx/aasp-sdk/langchain'

const aaspHandler = new AASPCallbackHandler({
  apiKey: process.env.HARBYX_API_KEY,
  agentId: 'my-langchain-agent',
  waitForApproval: true,
})

const model = new ChatOpenAI({
  callbacks: [aaspHandler],
})

// Tools are now automatically secured by AASP policies
```

### Decorators / Higher-Order Functions

```typescript
import { secureToolCall, secureApiCall } from '@harbyx/aasp-sdk'

// Wrap a function with AASP security
const secureSendEmail = secureToolCall({
  target: 'email:send',
  agentId: 'email-agent',
})(async (to: string, subject: string, body: string) => {
  return await emailService.send(to, subject, body)
})

// Now calling secureSendEmail will check AASP first
await secureSendEmail('user@example.com', 'Hello', 'World')
```

## CLI (Policy as Code)

```bash
# Initialize a config file
npx harbyx init

# Validate local policies
npx harbyx validate

# Compare local vs remote
npx harbyx diff

# Deploy policies to server
npx harbyx deploy
```

### Config File (harbyx.config.js)

```javascript
module.exports = {
  policies: [
    {
      name: 'Payment Controls',
      priority: 100,
      rules: [
        {
          actionType: 'api_call',
          targetPattern: 'stripe:refund.*',
          conditions: [
            { field: 'amount', operator: 'gt', value: 50000 }
          ],
          effect: 'block',
          reason: 'Refunds over $500 are blocked',
        },
      ],
    },
  ],
}
```

## Error Handling

```typescript
import {
  AASPError,
  ToolBlockedError,
  ApprovalTimeoutError,
  ApprovalRejectedError,
  AuthenticationError,
  NetworkError,
} from '@harbyx/aasp-sdk'

try {
  await client.evaluateAndWait(params)
} catch (error) {
  if (error instanceof ToolBlockedError) {
    console.log('Blocked:', error.reason, 'Policy:', error.policyId)
  } else if (error instanceof ApprovalTimeoutError) {
    console.log('Approval timed out after', error.waitedMs, 'ms')
  } else if (error instanceof ApprovalRejectedError) {
    console.log('Rejected by', error.rejectedBy, ':', error.reason)
  } else if (error instanceof AuthenticationError) {
    console.log('Invalid API key')
  } else if (error instanceof NetworkError) {
    console.log('Network error:', error.message)
  }
}
```

## API Reference

### AASPClient

| Method | Description |
|--------|-------------|
| `evaluate(params)` | Evaluate an action against policies |
| `evaluateOrThrow(params)` | Evaluate and throw if blocked |
| `evaluateAndWait(params, options?)` | Evaluate and wait for approval if needed |
| `checkApprovalStatus(approvalId)` | Check approval status |
| `waitForApproval(approvalId, options?)` | Wait for approval decision |
| `logActionResult(actionId, output)` | Log action result for audit |

### Action Types

- `tool_call` - AI agent tool invocations
- `api_call` - External API calls
- `db_query` - Database operations
- `file_access` - File system operations

### Decisions

- `allow` - Action is permitted
- `block` - Action is blocked by policy
- `require_approval` - Action needs human approval

## Environment Variables

| Variable | Description |
|----------|-------------|
| `HARBYX_API_KEY` | Your API key (alternative to config) |
| `HARBYX_BASE_URL` | Custom API base URL |

## License

MIT

## Links

- [Documentation](https://app.harbyx.com/docs)
- [Dashboard](https://app.harbyx.com)
- [GitHub Issues](https://github.com/harbyx/aasp-sdk/issues)