{"_id":"@agentlattice/sdk","_rev":"3-ebbb6ed20c277e0fc59d0c12caa1c1ed","name":"@agentlattice/sdk","dist-tags":{"latest":"0.2.0"},"versions":{"0.1.0":{"name":"@agentlattice/sdk","version":"0.1.0","keywords":["agentlattice","ai-governance","audit","compliance"],"license":"MIT","_id":"@agentlattice/sdk@0.1.0","maintainers":[{"name":"indernpm","email":"inder.sabharwal@gmail.com"}],"homepage":"https://github.com/inder/agentlattice#readme","bugs":{"url":"https://github.com/inder/agentlattice/issues"},"dist":{"shasum":"370729c887a6cacc2ce6e5d1e95361b375e440a2","tarball":"https://registry.npmjs.org/@agentlattice/sdk/-/sdk-0.1.0.tgz","fileCount":7,"integrity":"sha512-6aET8ckrk4Xt2Isq0niY39rwwosAbp0lnu+WFAbAdYN9PS0NFGG54I0Y7dyFY5rCVK56upS1nB581tCTF+hiFQ==","signatures":[{"sig":"MEUCICW8rjFWmM+HyHzpKKNmuvrOmDb2IDlyS+IBfrUVqesqAiEA6Vx952046Pqu+wMp85jGtt/lljadygBRSkDcNrqaJE0=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":55422},"main":"./dist/index.js","types":"./dist/index.d.ts","module":"./dist/index.mjs","engines":{"node":">=14.17.0"},"exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.mjs","default":"./dist/index.js","require":"./dist/index.js"}},"scripts":{"dev":"tsup src/index.ts --format cjs,esm --dts --watch","test":"vitest run","build":"tsup src/index.ts --format cjs,esm --dts"},"_npmUser":{"name":"indernpm","email":"inder.sabharwal@gmail.com"},"repository":{"url":"git+https://github.com/inder/agentlattice.git","type":"git","directory":"packages/sdk-ts"},"_npmVersion":"11.9.0","description":"AgentLattice SDK — governance-aware AI agent actions","directories":{},"_nodeVersion":"25.6.1","dependencies":{},"_hasShrinkwrap":false,"devDependencies":{"tsup":"^8.0.0","vitest":"^1.0.0","typescript":"^5.0.0"},"_npmOperationalInternal":{"tmp":"tmp/sdk_0.1.0_1774650202587_0.43495410569306303","host":"s3://npm-registry-packages-npm-production"}},"0.1.1":{"name":"@agentlattice/sdk","version":"0.1.1","keywords":["agentlattice","ai-governance","audit","compliance"],"license":"MIT","_id":"@agentlattice/sdk@0.1.1","maintainers":[{"name":"indernpm","email":"inder.sabharwal@gmail.com"}],"homepage":"https://github.com/inder/agentlattice#readme","bugs":{"url":"https://github.com/inder/agentlattice/issues"},"dist":{"shasum":"b49487ae6e6de4a91ab8f750f02f443610a9b918","tarball":"https://registry.npmjs.org/@agentlattice/sdk/-/sdk-0.1.1.tgz","fileCount":8,"integrity":"sha512-4mxb4QhxGah2C77DukdAh7/kuovpOpB7SzzhTRs8oKn2H2FYAta+gLfl4pRRNDy7AjAWxSs2svZDDkrNReUkCA==","signatures":[{"sig":"MEQCIE3zhaHzUeFaou3uYPiPXOtIRXjwMzlqwdMZU+lbPGTQAiAFjaWg9p5Q1Mfno+pITEPTs8OuvlNy+Pq/uy1z+ZOJug==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":1220996},"main":"./dist/index.js","types":"./dist/index.d.ts","module":"./dist/index.mjs","engines":{"node":">=14.17.0"},"exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.mjs","default":"./dist/index.js","require":"./dist/index.js"}},"gitHead":"1f91f553fb76ba2266b99336fb4a38ead918072b","scripts":{"dev":"tsup src/index.ts --format cjs,esm --dts --watch","test":"vitest run","build":"tsup src/index.ts --format cjs,esm --dts","prepublishOnly":"npm run build"},"_npmUser":{"name":"indernpm","email":"inder.sabharwal@gmail.com"},"repository":{"url":"git+https://github.com/inder/agentlattice.git","type":"git","directory":"packages/sdk-ts"},"_npmVersion":"10.8.2","description":"AgentLattice SDK — governance-aware AI agent actions","directories":{},"_nodeVersion":"20.20.1","dependencies":{},"_hasShrinkwrap":false,"devDependencies":{"tsup":"^8.0.0","vitest":"^1.0.0","typescript":"^5.0.0"},"_npmOperationalInternal":{"tmp":"tmp/sdk_0.1.1_1774831550824_0.08290422611801107","host":"s3://npm-registry-packages-npm-production"}},"0.2.0":{"name":"@agentlattice/sdk","version":"0.2.0","description":"AgentLattice SDK — governance-aware AI agent actions","main":"./dist/index.js","module":"./dist/index.mjs","types":"./dist/index.d.ts","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.mjs","require":"./dist/index.js","default":"./dist/index.js"}},"repository":{"type":"git","url":"git+https://github.com/inder/agentlattice.git","directory":"packages/sdk-ts"},"scripts":{"prepublishOnly":"npm run build","build":"tsup src/index.ts --format cjs,esm --dts","dev":"tsup src/index.ts --format cjs,esm --dts --watch","test":"vitest run"},"engines":{"node":">=14.17.0"},"keywords":["agentlattice","ai-governance","audit","compliance"],"license":"MIT","devDependencies":{"@anthropic-ai/sdk":"^0.90.0","tsup":"^8.0.0","typescript":"^5.0.0","vitest":"^1.0.0"},"gitHead":"d62127779827a58dcc9af20b0e36504ba1f06609","_id":"@agentlattice/sdk@0.2.0","bugs":{"url":"https://github.com/inder/agentlattice/issues"},"homepage":"https://github.com/inder/agentlattice#readme","_nodeVersion":"24.14.1","_npmVersion":"11.11.0","dist":{"integrity":"sha512-H+GWuVpUSX/WDkB+8dJJrWxWG55IGG+1FD2tFYBJEoG8pMFxeSYKVwe2c/sXofTtG5YT6m8ZPEhVzCo1rz+2pA==","shasum":"8c9ac84038ff56b7d44ca8b95fa89cc3efdf0273","tarball":"https://registry.npmjs.org/@agentlattice/sdk/-/sdk-0.2.0.tgz","fileCount":8,"unpackedSize":1249419,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIQCAq89QdznTBv1fMO2sonBh/0wqqU2ufTPhAwf10RAyRQIgU0i5r0jktPmkYgDDLp1ja5rMQJbaU3DwNYz48xaKOy4="}]},"_npmUser":{"name":"indernpm","email":"inder.sabharwal@gmail.com"},"directories":{},"maintainers":[{"name":"indernpm","email":"inder.sabharwal@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/sdk_0.2.0_1776618190800_0.5001187337067474"},"_hasShrinkwrap":false}},"time":{"created":"2026-03-27T22:23:22.517Z","modified":"2026-04-19T17:03:11.171Z","0.1.0":"2026-03-27T22:23:22.801Z","0.1.1":"2026-03-30T00:45:51.081Z","0.2.0":"2026-04-19T17:03:11.018Z"},"bugs":{"url":"https://github.com/inder/agentlattice/issues"},"license":"MIT","homepage":"https://github.com/inder/agentlattice#readme","keywords":["agentlattice","ai-governance","audit","compliance"],"repository":{"type":"git","url":"git+https://github.com/inder/agentlattice.git","directory":"packages/sdk-ts"},"description":"AgentLattice SDK — governance-aware AI agent actions","maintainers":[{"name":"indernpm","email":"inder.sabharwal@gmail.com"}],"readme":"# @agentlattice/sdk\n\nGovernance SDK for AI agents. Every action your agent takes goes through AgentLattice's audit trail, policy engine, and approval gates.\n\n## Install\n\n```bash\nnpm install @agentlattice/sdk\n```\n\nRequires Node.js >=14.17.0.\n\n## Method Inventory\n\n### Core\n\n| Capability | Method | Usage | Details |\n|-----------|--------|-------|---------|\n| Execute action | `al.execute(actionType, opts?)` | `await al.execute(\"pr.open\")` | [Reference](#alexecuteactiontype-options) |\n| Gate (block until approved) | `al.gate(actionType, opts?)` | `await al.gate(\"pr.merge\")` | [Reference](#algateactiontype-options) |\n\n### Managed Agents\n\n| Capability | Method | Usage | Details |\n|-----------|--------|-------|---------|\n| Govern a managed agent | `al.govern(agentId, message, opts?)` | `await al.govern(\"agent_011Ca...\", \"Analyze this report\")` | [Reference](#algovernagentid-message-options) |\n\n### Delegation\n\n| Capability | Method | Usage | Details |\n|-----------|--------|-------|---------|\n| Delegate sub-agent | `al.delegate(name, opts, cb)` | `await al.delegate(\"reader\", { capabilities: [...], ttl: 300 }, async (sub) => { ... })` | [Reference](#aldelegatename-options-callback) |\n| Parallel fan-out | `AgentLattice.parallel([...])` | `await AgentLattice.parallel([al.delegate(...), al.delegate(...)])` | [Reference](#agentlatticeparalleldelegates) |\n| Execute as child | `sub.execute(actionType, opts?)` | `await sub.execute(\"read_data\")` | [Reference](#delegatedagent) |\n| Gate as child | `sub.gate(actionType, opts?)` | `await sub.gate(\"read_data\")` | [Reference](#delegatedagent) |\n| Chain delegation | `sub.delegate(name, opts, cb)` | `await sub.delegate(\"sub-reader\", { capabilities: [...], ttl: 60 }, async (s) => { ... })` | [Reference](#delegatedagent) |\n\n### Types & Errors\n\n| Export | Description | Details |\n|--------|-------------|---------|\n| `ActionResult` | Return type of `execute()` — status, audit ID, conditions | [Reference](#alexecuteactiontype-options) |\n| `ActionOptions` | Options for `execute()` and `gate()` — data_accessed, metadata, event_id | [Reference](#options) |\n| `AgentLatticeError` | Base error — code, message, details | [Reference](#error-classes) |\n| `AgentLatticeDeniedError` | Policy denial or reviewer rejection — reason, policy, conditions | [Reference](#error-classes) |\n| `AgentLatticeTimeoutError` | Approval window expired — approvalId | [Reference](#error-classes) |\n\n---\n\n## Quickstart\n\n```typescript\nimport { AgentLattice } from \"@agentlattice/sdk\";\n\nconst al = new AgentLattice({ apiKey: process.env.AL_API_KEY! });\n\n// gate() blocks until a human approves (or throws if denied/timed out)\nawait al.gate(\"pr.merge\");\n\n// Your agent code only runs if the action was approved\nawait mergePR(42);\n```\n\nWith richer context for risk scoring:\n\n```typescript\nawait al.gate(\"pr.merge\", {\n  data_accessed: [\n    { type: \"source_code\", count: 142, sensitivity: \"medium\" },\n  ],\n  metadata: { pr_number: 42, repo: \"acme/backend\" },\n});\n```\n\n---\n\n## API Reference\n\n### `new AgentLattice(config)`\n\n| Field | Required | Default | Description |\n|-------|----------|---------|-------------|\n| `apiKey` | Yes | — | Bearer token from your operator config |\n| `baseUrl` | No | `https://www.agentlattice.io` | Override for self-hosted or staging |\n| `gatePollTimeoutMs` | No | `8 * 60 * 60 * 1000` (8 hours) | How long `gate()` polls for approval |\n| `gatePollIntervalMs` | No | `5000` (5 seconds) | How often to check approval status |\n\n---\n\n### `al.govern(agentId, message, options?)`\n\nRun a governed Anthropic Managed Agent session. Requires `@anthropic-ai/sdk` as a peer dependency.\n\n```typescript\nconst al = new AgentLattice({\n  apiKey: process.env.AL_API_KEY,\n  anthropicApiKey: process.env.ANTHROPIC_API_KEY,\n});\n\nconst result = await al.govern(\"agent_011Ca...\", \"Analyze this earnings report\", {\n  onToolCall: (tool) => console.log(`Tool: ${tool.name}`),\n  onDecision: (d) => console.log(`${d.allowed ? \"Allowed\" : \"Denied\"}: ${d.actionType}`),\n  onMessage: (text) => console.log(`Agent: ${text}`),\n  failOpen: false, // default: deny if AL unreachable\n});\n\nconsole.log(result.output);     // Agent's text response\nconsole.log(result.decisions);  // Per-tool governance decisions\nconsole.log(result.sessionId);  // Anthropic session ID\n```\n\nReturns `GovernResult` with `output`, `decisions` (array of `GovernDecision`), `sessionId`, `environmentId`, and `completed`.\n\nPass `sessionId` and `environmentId` in options to reuse an existing Anthropic session instead of creating one.\n\nSee [Managed Agents guide](/docs/guide/managed-agents) for full setup instructions.\n\n---\n\n### `al.gate(actionType, options?)`\n\nBlocks until the action is approved. Returns `void` on approval.\n\nThrows on denial or timeout — use a try/catch to handle gracefully:\n\n```typescript\ntry {\n  await al.gate(\"pr.merge\", { metadata: { pr_number: 42 } });\n  await mergePR(42);\n} catch (e) {\n  if (e instanceof AgentLatticeDeniedError) {\n    // Denied — could be a policy rule or a human reviewer\n    console.log(`Denied: ${e.reason}`);             // \"CONDITIONS_DENIED\" or \"DENIED_BY_REVIEWER\"\n    console.log(`Policy: ${e.policy}`);              // \"PR merge policy\"\n    console.log(`Failed rules:`, e.conditions);      // [{field:\"pr_size\", operator:\"lt\", expected:100, result:false}]\n  } else if (e instanceof AgentLatticeTimeoutError) {\n    // Approval window expired — log and abort\n    console.log(`Approval timed out (id: ${e.approvalId})`);\n  }\n}\n```\n\n---\n\n### `al.execute(actionType, options?)`\n\nSubmit an action and return immediately without waiting for approval. Use this for logging or when you don't need to block.\n\nReturns `ActionResult`:\n\n```typescript\ntype ActionResult = {\n  status: \"executed\" | \"requested\" | \"denied\" | \"timed_out\" | \"policy_not_found\";\n  audit_event_id: string;\n  approval_id?: string;      // set when status is \"requested\" — poll this to check resolution\n  denial_reason?: string;    // set when status is \"denied\" — e.g. \"CONDITIONS_DENIED\"\n  policy_name?: string;      // the policy that governs this action type\n  conditions_evaluated?: Array<{\n    field: string;\n    operator: string;\n    expected: unknown;\n    result: boolean;         // false = this rule failed\n  }>;\n};\n```\n\n---\n\n### Options\n\n```typescript\ninterface ActionOptions {\n  resource?: string;  // target of the action: URL, table name, file path, API endpoint.\n                      // used for resource-scoped policies (e.g., allow web.query only for linkedin.com)\n  data_accessed?: Array<{\n    type: string;    // what kind of resource: \"source_code\" | \"database\" | \"external_api\" |\n                     //   \"user_data\" | \"credentials\" | \"filesystem\" | \"network_request\"\n    count: number;   // how many records/files/rows accessed\n    sensitivity: \"low\" | \"medium\" | \"high\" | \"critical\";\n  }>;\n  metadata?: Record<string, unknown>;  // arbitrary context (pr_number, repo, filename...)\n  event_id?: string;  // idempotency key — duplicate submissions with the same key return\n                      // the existing audit record without creating a new one. Pass a\n                      // stable ID (e.g. task ID) when your agent might retry.\n}\n```\n\n---\n\n### Error classes\n\n```typescript\n// Thrown by gate() when a policy rule fires or a reviewer declines\nclass AgentLatticeDeniedError extends AgentLatticeError {\n  approvalId?: string;   // present for reviewer-denied actions, absent for policy denials\n  reason?: string;       // \"CONDITIONS_DENIED\" | \"POLICY_TAMPERED\" | \"DENIED_BY_REVIEWER\"\n  policy?: string;       // policy name that governed this action\n  conditions?: Array<{ field: string; operator: string; expected: unknown; result: boolean }>;\n}\n\n// Thrown by gate() when the approval window expires before a decision\nclass AgentLatticeTimeoutError extends AgentLatticeError {\n  approvalId: string;\n}\n\n// Base class — check error.code for programmatic handling\nclass AgentLatticeError extends Error {\n  code: string;    // \"MISSING_API_KEY\" | \"POLICY_NOT_FOUND\" | \"API_ERROR\" | ...\n  details?: unknown;\n}\n```\n\n---\n\n## Delegation — Scoped Sub-Agents\n\nCreate short-lived child agents with narrowed capabilities. Cleanup is automatic.\n\n```typescript\nconst result = await al.delegate(\"data-processor\", {\n  capabilities: [\"read_data\", \"write_results\"],\n  ttl: 300,  // seconds\n}, async (sub) => {\n  await sub.execute(\"read_data\", { metadata: { rows: 100 } });\n  return sub.execute(\"write_results\");\n});\n```\n\n### `al.delegate(name, options, callback)`\n\n| Field | Required | Description |\n|-------|----------|-------------|\n| `name` | Yes | Display name for the ephemeral child agent |\n| `options.capabilities` | Yes | Array of action types the child can perform (must be subset of parent's) |\n| `options.ttl` | Yes | Time-to-live in seconds (max 86400 = 24 hours) |\n| `callback` | Yes | Async function receiving a `DelegatedAgent` |\n\nThe callback runs inside a `try/finally` — cleanup always happens, even on error.\nThe child agent's scope is enforced server-side: any `sub.execute()` call outside\nthe granted capabilities returns a 403.\n\n### DelegatedAgent\n\n| Method | Description |\n|--------|-------------|\n| `sub.execute(actionType, options?)` | Execute an action as the child (includes `X-AL-Delegation-ID` header) |\n| `sub.gate(actionType, options?)` | Execute + block until approved |\n| `sub.delegate(name, options, callback)` | Chain further — create a sub-sub-agent with narrower scope |\n\n### `AgentLattice.parallel(delegates)`\n\nRuns N delegation callbacks concurrently via `Promise.all`. Each delegation\nmanages its own cleanup independently.\n\n```typescript\nconst results = await AgentLattice.parallel([\n  al.delegate(\"reader-1\", { capabilities: [\"read_data\"], ttl: 60 }, async (sub) => {\n    return sub.execute(\"read_data\", { metadata: { shard: 1 } });\n  }),\n  al.delegate(\"reader-2\", { capabilities: [\"read_data\"], ttl: 60 }, async (sub) => {\n    return sub.execute(\"read_data\", { metadata: { shard: 2 } });\n  }),\n]);\n```\n\nSee [docs/ephemeral-agents.md](../../docs/ephemeral-agents.md) for architecture details,\nsecurity model, and cleanup guarantees.\n\n---\n\n## Action Types\n\nAction types are free-form strings matched against your configured policies. Use dot-notation namespaces:\n\n| Action | Example |\n|--------|---------|\n| `code.commit` | Agent commits code changes |\n| `pr.open` | Agent opens a pull request |\n| `pr.merge` | Agent merges a pull request |\n| `file.write` | Agent writes to a file |\n| `file.delete` | Agent deletes a file |\n| `db.migrate` | Agent runs a database migration |\n| `secret.read` | Agent reads a secret or credential |\n| `deploy.trigger` | Agent triggers a deployment |\n\nDefine policies for each action type in your AgentLattice dashboard.\n\n---\n\n## Patterns\n\n### Self-correcting agent\n\n`conditions_evaluated` closes the feedback loop — agents can read which specific\nrule fired and adapt, not just fail.\n\n```typescript\nconst al = new AgentLattice({ apiKey: process.env.AL_API_KEY! });\n\nasync function openPRWithGovernance(files: string[]): Promise<void> {\n  try {\n    await al.gate(\"pr.open\", {\n      metadata: { pr_size: files.length, repo: \"acme/backend\" },\n    });\n    await openPR(files);\n\n  } catch (e) {\n    if (e instanceof AgentLatticeDeniedError && e.reason === \"CONDITIONS_DENIED\") {\n      const failed = e.conditions?.filter(c => !c.result) ?? [];\n      // e.g. [{field:\"pr_size\", operator:\"lt\", expected:50, result:false}]\n\n      const prSizeRule = failed.find(c => c.field === \"pr_size\");\n      if (prSizeRule) {\n        // Policy says PRs must be < 50 files — split and retry\n        const mid = Math.floor(files.length / 2);\n        await openPRWithGovernance(files.slice(0, mid));\n        await openPRWithGovernance(files.slice(mid));\n        return;\n      }\n    }\n    throw e; // reviewer denial or policy tamper — no retry\n  }\n}\n```\n\n### LangGraph integration\n\n```typescript\nimport { tool } from \"@langchain/core/tools\";\nimport { AgentLattice } from \"@agentlattice/sdk\";\n\nconst al = new AgentLattice({ apiKey: process.env.AL_API_KEY! });\n\nconst mergeCodeTool = tool(async ({ pr_number, repo }) => {\n  await al.gate(\"pr.merge\", {\n    metadata: { pr_number, repo },\n  });\n  return await mergePR(pr_number); // only reached if approved\n}, {\n  name: \"merge_pr\",\n  description: \"Merge a pull request (requires human approval)\",\n  schema: z.object({ pr_number: z.number(), repo: z.string() }),\n});\n```\n\n### Fire-and-forget logging\n\n```typescript\n// Doesn't block — submits the audit event and continues\nconst { audit_event_id } = await al.execute(\"file.read\", {\n  data_accessed: [{ type: \"filesystem\", count: 1, sensitivity: \"low\" }],\n  metadata: { path: \"/etc/config.yaml\" },\n  event_id: `task-${taskId}-read`,  // stable ID for idempotency\n});\n```\n\n---\n\n## Reliability\n\n`execute()` and `gate()` retry automatically on 5xx and network errors — up to 3 attempts with 1s/2s/4s exponential backoff. Each request has a 30-second timeout. Pass `event_id` to make retries idempotent — the server deduplicates by that key and returns the existing audit record instead of creating a duplicate.\n","readmeFilename":"README.md"}