npm package: @rayenbenabdallah/agentos-sdk
Description: TypeScript SDK for AgentOS — client, runtime, signing, and adapters
Latest version: 1.0.2

# @rayenbenabdallah/agentos-sdk

TypeScript SDK for [AgentOS](https://github.com/rayenbenabdallah/agentos) — client, runtime, signing, and adapters.

[![npm version](https://img.shields.io/npm/v/@rayenbenabdallah/agentos-sdk)](https://www.npmjs.com/package/@rayenbenabdallah/agentos-sdk)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](./LICENSE)

---

## What is this?

`@rayenbenabdallah/agentos-sdk` is the official TypeScript SDK for interacting with an AgentOS server. It handles:

- **Cryptographic request signing** — Ed25519 signatures over canonical payload hashes, clock-skew, and nonce management.
- **Agent runtime** — A high-level `AgentRuntime` that orchestrates the full governed execution loop (memory → policy → decision → action).
- **Human-in-the-loop approvals** — Automatic pause/resume when actions exceed risk thresholds.
- **Framework adapters** — Ready-made integrations for OpenAI function calling and LangChain.

---

## Installation

```bash
npm install @rayenbenabdallah/agentos-sdk
# or
pnpm add @rayenbenabdallah/agentos-sdk
```

**Requirements:** Node.js ≥ 18

---

## Quick Start

### 1. Create a client

```typescript
import { AgentOSClient } from '@rayenbenabdallah/agentos-sdk';

const client = new AgentOSClient({
  baseUrl: 'http://localhost:3000',
  agentId: process.env.AGENTOS_AGENT_ID!,
  versionId: process.env.AGENTOS_VERSION_ID!,
  keyId: process.env.AGENTOS_KEY_ID!,
  privateKey: process.env.AGENTOS_PRIVATE_KEY!, // base64 Ed25519 private key
});
```

All requests are automatically signed with the agent's Ed25519 key. You never need to manage signatures manually.

### 2. Use the runtime

```typescript
import { AgentRuntime, ApprovalRequiredError } from '@rayenbenabdallah/agentos-sdk';

const runtime = new AgentRuntime(client);

try {
  const result = await runtime.runTask({
    tenantId: 'acme',
    policyId: 'policy-1',
    task: 'Resolve support ticket #1234',
    intent: {
      tool: 'zendesk',
      action: 'update_ticket',
      environment: 'prod',
      dataSensitivity: 'low',
    },
    planner: async (task, memories) => {
      // Build a plan using retrieved memories
      return { task, steps: ['lookup', 'reply'], memoryCount: memories.length };
    },
    executor: async (plan) => {
      // Execute the plan
      return { ticketId: '1234', status: 'resolved' };
    },
  });

  console.log('Done:', result);
} catch (error) {
  if (error instanceof ApprovalRequiredError) {
    console.log('Waiting for approval:', error.approval.approvalId);
    // Resume after external approval
    await runtime.resumeWithApproval(error.approval.approvalId);
  }
}
```

The runtime handles the full governed loop automatically:

1. **Memory query** — Retrieves relevant context via semantic search.
2. **Policy evaluation** — Checks intent against published policies and risk scoring.
3. **Decision record** — Creates a signed decision snapshot with retrieved memory IDs.
4. **Action log** — Appends the executed action to the tamper-evident hash chain.

---

## API Reference

### `AgentOSClient`

The low-level client. Use this when you need fine-grained control.

```typescript
// Memory
await client.memoryWrite({
  tenantId: 'acme',
  namespaceId: 'ns-1',
  type: 'episodic',
  content: 'Customer reported login loop after password reset',
  timestamp: new Date().toISOString(),
});

const results = await client.memoryQuery({
  tenantId: 'acme',
  taskType: 'support_triage',
  query: 'login loop',
  topK: 5,
});

// Policy evaluation
const evaluation = await client.policyEvaluate({
  tenantId: 'acme',
  policyId: 'policy-1',
  intent: { tool: 'zendesk', action: 'update_ticket', environment: 'prod' },
});

// Decisions
const decision = await client.decisions.create({
  tenantId: 'acme',
  timestamp: new Date().toISOString(),
  goal: 'Resolve ticket #1234',
  intentHash: '...',
  policyEvalId: evaluation.policyEvalId,
  planSummary: 'Look up context, then reply to customer',
});

// Actions
const action = await client.actions.log({
  tenantId: 'acme',
  actionType: 'tool_call',
  tool: 'zendesk',
  policyEvalId: evaluation.policyEvalId,
  decisionId: decision.decisionId,
  paramsHash: '...',
  resultHash: '...',
  timestamp: new Date().toISOString(),
});
```

### `AgentRuntime`

High-level orchestrator that handles the full governed execution loop. Manages memory retrieval, policy checks, decision recording, action logging, and approval flows automatically.

| Method | Description |
|--------|-------------|
| `runTask(input)` | Execute a governed task end-to-end |
| `resumeWithApproval(approvalId)` | Resume a paused task after human approval |

### `PayloadSigner`

Low-level signing utility. Typically not used directly — `AgentOSClient` handles signing internally.

```typescript
import { PayloadSigner } from '@rayenbenabdallah/agentos-sdk';

const signer = new PayloadSigner(base64PrivateKey);
const bodyHash = signer.hashCanonicalPayload(payload);
const signature = signer.sign(requestEnvelope);
```

---

## Framework Adapters

### OpenAI Function Calling

```typescript
import { makeAgentOSTools } from '@rayenbenabdallah/agentos-sdk/adapters/openai_tools';

const tools = makeAgentOSTools(client);
// Returns tool descriptors for:
//   agentos_memory_query    — Semantic memory search
//   agentos_memory_write    — Write memory items
//   agentos_policy_evaluate — Evaluate intent against policies
//   agentos_actions_log     — Log signed actions
//   agentos_decisions_create — Create decision records
```

Pass `tools` directly to the OpenAI `chat.completions.create` call with `tool_choice: 'auto'`.

### LangChain

```typescript
import { makeLangChainAdapter } from '@rayenbenabdallah/agentos-sdk/adapters/langchain';

const adapter = makeLangChainAdapter(client);

// Use in your LangChain pipeline
await adapter.memoryQuery('login issue', 'support_triage', 'acme');
await adapter.memoryWrite({ tenantId: 'acme', namespaceId: 'ns-1', type: 'episodic', content: '...', timestamp: new Date().toISOString() });
await adapter.onDecision({ /* decision payload */ });
await adapter.onAction({ /* action payload */ });
```

---

## Utilities

```typescript
import { canonicalJsonStringify, normalizePrivateKey } from '@rayenbenabdallah/agentos-sdk';

// Deterministic JSON serialization (sorted keys, no undefined)
const canonical = canonicalJsonStringify({ b: 2, a: 1 }); // '{"a":1,"b":2}'

// Normalize a base64 Ed25519 private key to PEM format
const pem = normalizePrivateKey(base64Key);
```

---

## Exports

| Export | Description |
|--------|-------------|
| `AgentOSClient` | Low-level API client with automatic request signing |
| `AgentRuntime` | High-level governed execution orchestrator |
| `PayloadSigner` | Ed25519 payload signing utility |
| `makeAgentOSTools` | OpenAI function-calling tool descriptors |
| `makeLangChainAdapter` | LangChain integration adapter |
| `ApprovalRequiredError` | Error thrown when human approval is needed |
| `AgentOSClientError` | Error for failed API requests |
| `canonicalJsonStringify` | Deterministic JSON serialization |
| `normalizePrivateKey` | Base64-to-PEM key normalization |

---

## Types

All request/response types are fully exported:

- `ClientConfig`
- `MemoryWriteRequest` / `MemoryWriteResponse`
- `MemoryQueryRequest` / `MemoryQueryResponse` / `MemoryQueryItem`
- `PolicyEvaluateRequest` / `PolicyEvaluateResponse`
- `DecisionCreateRequest` / `DecisionCreateResponse`
- `ActionLogRequest` / `ActionLogResponse`
- `RunTaskInput`

---

## Environment Variables

| Variable | Description |
|----------|-------------|
| `AGENTOS_AGENT_ID` | Agent UUID |
| `AGENTOS_VERSION_ID` | Agent version UUID |
| `AGENTOS_KEY_ID` | Agent key UUID |
| `AGENTOS_PRIVATE_KEY` | Ed25519 private key (base64) |

---

## Part of AgentOS

This SDK is part of the [AgentOS](https://github.com/rayenbenabdallah/agentos) platform — an operating layer for autonomous AI agents providing cryptographic identity, governed policy evaluation, tamper-evident audit trails, namespaced semantic memory, and cross-tenant knowledge federation.

## License

[MIT](./LICENSE)