{"_id":"@agent-ledger/sdk-ts","_rev":"5-8e782fb9ad0bb66bd52a2552f43dc0b7","name":"@agent-ledger/sdk-ts","dist-tags":{"latest":"0.0.5"},"versions":{"0.0.1":{"name":"@agent-ledger/sdk-ts","version":"0.0.1","_id":"@agent-ledger/sdk-ts@0.0.1","maintainers":[{"name":"furahadamien","email":"furahadamien30@gmail.com"}],"dist":{"shasum":"2e29047673e86775bc8852a4e2ed2dc4de902be1","tarball":"https://registry.npmjs.org/@agent-ledger/sdk-ts/-/sdk-ts-0.0.1.tgz","fileCount":6,"integrity":"sha512-7akzOhKiE7B+D6yOOMSNdOZ0ArBqe8kS85Q1VPY7w5Hn5kBjyz10wENvIMgXKceg3Twyp3uR4KjRdoo6WpMEvQ==","signatures":[{"sig":"MEYCIQDSQkfmt3St1Rdlo63/NbMtP7lm18fCN9FHOsbcf9/oQwIhANrX5ciIaisxepL/yixEXsnY9DJpUbjYbtgjbt2nav+z","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":13946},"main":"dist/index.js","type":"module","_from":"file:agent-ledger-sdk-ts-0.0.1.tgz","types":"dist/index.d.ts","module":"dist/index.js","private":false,"scripts":{"dev":"tsc -w -p tsconfig.build.json","build":"tsc -p tsconfig.build.json"},"_npmUser":{"name":"furahadamien","email":"furahadamien30@gmail.com"},"_resolved":"/private/var/folders/_z/d8529mp910vfyljhjwghh54w0000gn/T/a189d0bb6fa58419561e305edc9f5e55/agent-ledger-sdk-ts-0.0.1.tgz","_integrity":"sha512-7akzOhKiE7B+D6yOOMSNdOZ0ArBqe8kS85Q1VPY7w5Hn5kBjyz10wENvIMgXKceg3Twyp3uR4KjRdoo6WpMEvQ==","_npmVersion":"10.9.2","directories":{},"_nodeVersion":"22.13.0","dependencies":{},"_hasShrinkwrap":false,"devDependencies":{"typescript":"^5.6.0"},"_npmOperationalInternal":{"tmp":"tmp/sdk-ts_0.0.1_1764813670297_0.6846383710985062","host":"s3://npm-registry-packages-npm-production"}},"0.0.2":{"name":"@agent-ledger/sdk-ts","version":"0.0.2","_id":"@agent-ledger/sdk-ts@0.0.2","maintainers":[{"name":"furahadamien","email":"furahadamien30@gmail.com"}],"dist":{"shasum":"b375a7f803b6e803947ebabe576881d0fa391d9d","tarball":"https://registry.npmjs.org/@agent-ledger/sdk-ts/-/sdk-ts-0.0.2.tgz","fileCount":7,"integrity":"sha512-IBjGSu49IeRdhlPGWKSMfe1+1fCezNG5sCSNfB5/bpERSU7Fm3vmSYP0FVsdrxMidPw+JprIcND2RwZOTgkmFQ==","signatures":[{"sig":"MEUCIQDlNpWni4O7G/UTH3EHjntz189W+s/1IxMdl5GKrUhQtAIgRMVEEShRmz02WSLWzD6zi99UB3WZytacZbgN5mvDPV0=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":16318},"main":"dist/index.js","type":"module","_from":"file:agent-ledger-sdk-ts-0.0.2.tgz","types":"dist/index.d.ts","module":"dist/index.js","private":false,"scripts":{"dev":"tsc -w -p tsconfig.build.json","build":"tsc -p tsconfig.build.json"},"_npmUser":{"name":"furahadamien","email":"furahadamien30@gmail.com"},"_resolved":"/private/var/folders/_z/d8529mp910vfyljhjwghh54w0000gn/T/a55206f7ea219082b030d0ff0aa00e34/agent-ledger-sdk-ts-0.0.2.tgz","_integrity":"sha512-IBjGSu49IeRdhlPGWKSMfe1+1fCezNG5sCSNfB5/bpERSU7Fm3vmSYP0FVsdrxMidPw+JprIcND2RwZOTgkmFQ==","_npmVersion":"10.9.2","description":"Official TypeScript client for Agent Ledger. The SDK instruments your agents so you can stream sessions, log LLM/tool activity, and enforce budget guardrails against the Agent Ledger API.","directories":{},"_nodeVersion":"22.13.0","dependencies":{},"_hasShrinkwrap":false,"devDependencies":{"typescript":"^5.6.0"},"_npmOperationalInternal":{"tmp":"tmp/sdk-ts_0.0.2_1764813916788_0.5977013969358085","host":"s3://npm-registry-packages-npm-production"}},"0.0.3":{"name":"@agent-ledger/sdk-ts","version":"0.0.3","_id":"@agent-ledger/sdk-ts@0.0.3","maintainers":[{"name":"furahadamien","email":"furahadamien30@gmail.com"}],"dist":{"shasum":"b51118419c98bc21445767b2b76cadfdc849ffbe","tarball":"https://registry.npmjs.org/@agent-ledger/sdk-ts/-/sdk-ts-0.0.3.tgz","fileCount":7,"integrity":"sha512-SAyfqXrTKAj7BD2S77vEBiu5YRG1dLZ09DMwR3huGieja7oyp0787I9l1Lx+2E6nzHpaUM9wHeMyW6bbWP2b9Q==","signatures":[{"sig":"MEQCIAFXbAtAEMNWTstAuOF7ZsWJ4pHXLwVIwpuQo6hvzop+AiBs4Eh8i2w84titW/cXZh75UVDvIYQ8oiBd9yDIfM9qQA==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":15826},"main":"dist/index.js","type":"module","_from":"file:agent-ledger-sdk-ts-0.0.3.tgz","types":"dist/index.d.ts","module":"dist/index.js","private":false,"scripts":{"dev":"tsc -w -p tsconfig.build.json","build":"tsc -p tsconfig.build.json"},"_npmUser":{"name":"furahadamien","email":"furahadamien30@gmail.com"},"_resolved":"/private/var/folders/_z/d8529mp910vfyljhjwghh54w0000gn/T/562e2498caddb7bc81370f5f00fcd2b5/agent-ledger-sdk-ts-0.0.3.tgz","_integrity":"sha512-SAyfqXrTKAj7BD2S77vEBiu5YRG1dLZ09DMwR3huGieja7oyp0787I9l1Lx+2E6nzHpaUM9wHeMyW6bbWP2b9Q==","_npmVersion":"10.9.2","description":"Official TypeScript client for Agent Ledger. The SDK instruments your agents so you can stream sessions, log LLM/tool activity, and enforce budget guardrails against the Agent Ledger API.","directories":{},"_nodeVersion":"22.13.0","dependencies":{},"_hasShrinkwrap":false,"devDependencies":{"typescript":"^5.6.0"},"_npmOperationalInternal":{"tmp":"tmp/sdk-ts_0.0.3_1764816379521_0.35160305164870387","host":"s3://npm-registry-packages-npm-production"}},"0.0.4":{"name":"@agent-ledger/sdk-ts","version":"0.0.4","_id":"@agent-ledger/sdk-ts@0.0.4","maintainers":[{"name":"furahadamien","email":"furahadamien30@gmail.com"}],"dist":{"shasum":"8a8847202729ea236df08bf1d5e3503956c795dd","tarball":"https://registry.npmjs.org/@agent-ledger/sdk-ts/-/sdk-ts-0.0.4.tgz","fileCount":7,"integrity":"sha512-bxlNlh5waxcV9T4xcH3HpYmVV+TlslBQBzQHg6spar5oUicN75RsDAabw488YdaYweMp7/pU9Jy9vVz/YDgSkw==","signatures":[{"sig":"MEYCIQCqvHDoYA63nJmZCciQiCzYR10T83i71sxoBjJm5DDCTgIhAKnajtCxPDNMP4fgvoJCU/l3g25ljJup1tWuGcj5Dwy6","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":21804},"main":"dist/index.js","type":"module","_from":"file:agent-ledger-sdk-ts-0.0.4.tgz","types":"dist/index.d.ts","module":"dist/index.js","private":false,"scripts":{"dev":"tsc -w -p tsconfig.build.json","build":"tsc -p tsconfig.build.json"},"_npmUser":{"name":"furahadamien","email":"furahadamien30@gmail.com"},"_resolved":"/private/var/folders/_z/d8529mp910vfyljhjwghh54w0000gn/T/fa8808e1cf13865719920bd4e9d41bc2/agent-ledger-sdk-ts-0.0.4.tgz","_integrity":"sha512-bxlNlh5waxcV9T4xcH3HpYmVV+TlslBQBzQHg6spar5oUicN75RsDAabw488YdaYweMp7/pU9Jy9vVz/YDgSkw==","_npmVersion":"10.9.2","description":"Official TypeScript client for Agent Ledger. Use it to instrument any Node.js/Edge agent with structured telemetry, stream session events, and receive immediate feedback when budget guardrails block spending.","directories":{},"_nodeVersion":"22.13.0","dependencies":{},"_hasShrinkwrap":false,"devDependencies":{"typescript":"^5.6.0"},"_npmOperationalInternal":{"tmp":"tmp/sdk-ts_0.0.4_1765051194121_0.4729239075027394","host":"s3://npm-registry-packages-npm-production"}},"0.0.5":{"name":"@agent-ledger/sdk-ts","version":"0.0.5","private":false,"type":"module","main":"dist/index.js","module":"dist/index.js","types":"dist/index.d.ts","dependencies":{},"devDependencies":{"typescript":"^5.6.0"},"scripts":{"build":"tsc -p tsconfig.build.json","dev":"tsc -w -p tsconfig.build.json"},"_id":"@agent-ledger/sdk-ts@0.0.5","description":"Official TypeScript client for Agent Ledger. Use it to instrument any Node.js/Edge agent with structured telemetry, stream session events, and receive immediate feedback when budget guardrails block spending.","_integrity":"sha512-3Z0bLsqf+/AbpZw6oFFt65sHMRzA2hTbKdsrVMH0fbn6+8Ap61dozDy8ra6LD8TZ/r8xPhLJFp7WKXjQc43TsA==","_resolved":"/private/var/folders/_z/d8529mp910vfyljhjwghh54w0000gn/T/bfac40e4e27706a63df66360d24a0a8d/agent-ledger-sdk-ts-0.0.5.tgz","_from":"file:agent-ledger-sdk-ts-0.0.5.tgz","_nodeVersion":"22.13.0","_npmVersion":"10.9.2","dist":{"integrity":"sha512-3Z0bLsqf+/AbpZw6oFFt65sHMRzA2hTbKdsrVMH0fbn6+8Ap61dozDy8ra6LD8TZ/r8xPhLJFp7WKXjQc43TsA==","shasum":"ce8f3731def964a0fb5f7d68b3e3b293e1063f67","tarball":"https://registry.npmjs.org/@agent-ledger/sdk-ts/-/sdk-ts-0.0.5.tgz","fileCount":7,"unpackedSize":31669,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEQCIA2NEoRnWRw5ddNiSrBvwh+VUSbYqaSyrmLns/9cKBonAiAibqHk/KQhIljN60Cg3+sotbFo+3OzasuOIgE2S1cM3w=="}]},"_npmUser":{"name":"furahadamien","email":"furahadamien30@gmail.com"},"directories":{},"maintainers":[{"name":"furahadamien","email":"furahadamien30@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/sdk-ts_0.0.5_1767298184089_0.11237779658610769"},"_hasShrinkwrap":false}},"time":{"created":"2025-12-04T02:01:10.131Z","modified":"2026-01-01T20:09:44.481Z","0.0.1":"2025-12-04T02:01:10.523Z","0.0.2":"2025-12-04T02:05:16.948Z","0.0.3":"2025-12-04T02:46:19.656Z","0.0.4":"2025-12-06T19:59:54.270Z","0.0.5":"2026-01-01T20:09:44.253Z"},"description":"Official TypeScript client for Agent Ledger. Use it to instrument any Node.js/Edge agent with structured telemetry, stream session events, and receive immediate feedback when budget guardrails block spending.","maintainers":[{"name":"furahadamien","email":"furahadamien30@gmail.com"}],"readme":"# @agent-ledger/sdk-ts\n\nOfficial TypeScript client for Agent Ledger. Use it to instrument any Node.js/Edge agent with structured telemetry, stream session events, and receive immediate feedback when budget guardrails block spending.\n\nPortal: https://agent-ledger.thabo.xyz/\n\n## Table of contents\n\n1. [Features](#features)\n2. [Installation](#installation)\n3. [Runtime requirements](#runtime-requirements)\n4. [Getting started](#getting-started)\n5. [Session lifecycle](#session-lifecycle)\n6. [Event reference](#event-reference)\n7. [API reference](#api-reference)\n8. [Error handling](#error-handling)\n9. [Configuration & environments](#configuration--environments)\n10. [Recipes](#recipes)\n11. [Testing & local dev](#testing--local-dev)\n12. [License](#license)\n\n## Features\n\n- Minimal, dependency-free client that speaks directly to the Agent Ledger REST API (`/v1/sessions` and `/v1/events`).\n- First-class TypeScript typings for every event structure (`LlmCallEvent`, `ToolCallEvent`, `ToolResultEvent`).\n- Built-in budget guardrail awareness through `BudgetGuardrailError` so you can halt expensive runs immediately.\n- Works anywhere `fetch` is available (Node.js 18+, Bun, Deno, Edge runtimes, or browsers talking to your own proxy).\n- Simple abstractions so you can reuse the same instrumentation across CLI scripts, background workers, or serverless functions.\n\n## Installation\n\n```bash\npnpm add @agent-ledger/sdk-ts\n# or\nnpm install @agent-ledger/sdk-ts\n# or\nyarn add @agent-ledger/sdk-ts\n```\n\n## Runtime requirements\n\n- Node.js 18 or newer (for the built-in `fetch` implementation). If you run older Node versions, polyfill `fetch` before importing the SDK.\n- An Agent Ledger API key generated from the dashboard (Settings → API Keys).\n- Outbound HTTPS access to `https://agent-ledger-api.azurewebsites.net` (or your self-hosted instance).\n\n## Getting started\n\n```ts\nimport {\n  AgentLedgerClient,\n  BudgetGuardrailError,\n  withSession,\n  instrumentTool,\n} from \"@agent-ledger/sdk-ts\";\n\nconst ledger = new AgentLedgerClient({\n  apiKey: process.env.AGENT_LEDGER_API_KEY!,\n});\n\nexport async function runSupportAgent(prompt: string) {\n  return withSession(ledger, \"support-bot\", async ({ sessionId, steps }) => {\n    try {\n      // 1. Run your own LLM logic\n      const response = await callModel(prompt);\n\n      // 2. Log the LLM call (Agent Ledger auto-computes spend from provider/model/tokens)\n      await ledger.logLLMCall(sessionId, {\n        stepIndex: steps.next(),\n        provider: \"openai\",\n        model: \"gpt-4o-mini\",\n        prompt,\n        response: response.text,\n        tokensIn: response.usage.inputTokens,\n        tokensOut: response.usage.outputTokens,\n        latencyMs: response.latencyMs,\n      });\n\n      // 3. Example tool wrapper (automatically logs tool_call + tool_result)\n      await instrumentTool({\n        ledger,\n        sessionId,\n        stepIndex: steps.next(),\n        toolName: \"weather\",\n        toolInput: { city: \"Boston\" },\n        run: async () => fetchWeather(\"Boston\"),\n      });\n\n      return response.text;\n    } catch (err) {\n      if (err instanceof BudgetGuardrailError) {\n        console.warn(\"Budget exceeded\", err.details);\n      }\n      throw err;\n    }\n  });\n}\n```\n\n## Session lifecycle\n\n1. **Start sessions** early with `startSession(agentName)` to capture every downstream event.\n2. **Log events** whenever you call an LLM or tool:\n   - `logLLMCall` for prompts/responses.\n   - `logToolCall` for tool invocations (store the inputs).\n   - `logToolResult` for tool responses (store outputs/latency).\n   - `logEvents` if you need to batch arbitrary event objects.\n3. **End sessions** with `endSession(sessionId, \"success\" | \"error\", { errorMessage? })` so the dashboard knows whether the run finished cleanly.\n\nTip: keep a simple helper that wraps this flow so every agent in your repo emits consistent telemetry.\n\n## Event reference\n\n| Event | Required fields | Optional fields | Notes |\n| --- | --- | --- | --- |\n| `LlmCallEvent` | `stepIndex`, `model`, `provider`, `prompt`, `response`, `tokensIn`, `tokensOut`, `latencyMs` | — | `logLLMCall` automatically sets `type` to `llm_call` and lets the backend price the call based on provider/model. |\n| `ToolCallEvent` | `stepIndex`, `toolName`, `toolInput` | — | Capture the structured input you sent to an internal or external tool. |\n| `ToolResultEvent` | `stepIndex`, `toolName`, `toolOutput`, `latencyMs` | — | Use together with `ToolCallEvent` to understand tool latency and result size. |\n| Custom | Whatever your workflow needs plus `type` | — | Supply via `logEvents` if you want to store derived signals (examples: `session_start`, `session_end`, `guardrail_trigger`). |\n\nConventions:\n\n- `stepIndex` is a zero-based counter that makes it easy to diff runs. Increment it in the order events happen, even if multiple tools share the same LLM output.\n- Keep prompts/responses under 64 KB per event so they render nicely in the dashboard diff view.\n- All numeric values are stored as numbers (no strings) so the API can aggregate cost statistics.\n\n## API reference\n\n### `new AgentLedgerClient(options)`\n\n| Option | Type | Description |\n| --- | --- | --- |\n| `apiKey` | `string` (required) | Workspace API key from the dashboard. |\n\n### `startSession(agentName: string): Promise<string>`\n\nCreates a session row and returns its UUID. `agentName` should match how you identify the workflow in the dashboard (e.g., `support-bot`, `retrieval-worker`).\n\n### `endSession(sessionId, status, opts?)`\n\nMarks the session closed. Pass `{ errorMessage }` for failures so the UI shows context next to the run.\n\n### `logEvents(sessionId, events)`\n\nLowest-level ingestion helper. Accepts an array of plain objects, so you can batch multiple events into a single network call. Events must include a `type` string (e.g., `llm_call`).\n\n### `logLLMCall(sessionId, event)` / `logToolCall` / `logToolResult`\n\nTyped helpers that:\n\n- Fill the `type` automatically.\n- Validate required fields at compile time.\n- Call `logEvents` under the hood.\n\n### Types exported\n\n`AgentLedgerClient`, `AgentLedgerClientOptions`, `BudgetGuardrailError`, `BudgetGuardrailDetails`, `LlmCallEvent`, `ToolCallEvent`, `ToolResultEvent`, `AnyEvent`, `EventType`.\n\n## Error handling\n\n- **`BudgetGuardrailError`** (HTTP 429): thrown when the backend refuses the event because the agent exceeded its daily limit. Inspect `error.details`:\n\n  ```ts\n  {\n    agentName: string;\n    dailyLimitUsd: number;\n    spentTodayUsd: number;\n    attemptedCostUsd: number;\n    projectedCostUsd: number;\n    remainingBudgetUsd: number;\n  }\n  ```\n\n- **Generic `Error`**: wraps any other non-2xx response (`startSession`, `endSession`, `logEvents`). The `.message` contains the server-provided text when available.\n\nRecommended practice: catch errors where you call `logEvents` so your business logic can continue (or at least emit a structured failure) even when the telemetry call is rejected.\n\n## Configuration & environments\n\n- Provide `AGENT_LEDGER_API_KEY` (or load it from your preferred secrets manager) and the SDK connects to the hosted API automatically.\n- Default endpoint → `https://agent-ledger-api.azurewebsites.net`.\n- For local API experiments, keep the SDK untouched and proxy traffic through your own tooling (MSW, mock servers, etc.).\n\nBecause the client is stateless, you can instantiate one per agent type or share a singleton across the entire app.\n\n## Recipes\n\n### Streaming agents / multi-step workflows\n\nReuse a monotonically increasing `stepIndex` while you stream partial responses. You can emit interim tool calls before the final LLM response lands to visualize branching logic.\n\n### Custom tool instrumentation\n\n```ts\nasync function callWeather(sessionId: string, city: string, stepIndex: number) {\n  await ledger.logToolCall(sessionId, {\n    stepIndex,\n    toolName: \"weather\",\n    toolInput: { city },\n  });\n\n  const result = await fetchWeather(city);\n\n  await ledger.logToolResult(sessionId, {\n    stepIndex,\n    toolName: \"weather\",\n    toolOutput: result,\n    latencyMs: result.latencyMs,\n  });\n}\n```\n\n### Handling guardrail blocks\n\n```ts\ntry {\n  await ledger.logLLMCall(sessionId, event);\n} catch (err) {\n  if (err instanceof BudgetGuardrailError) {\n    await ledger.endSession(sessionId, \"error\", {\n      errorMessage: `Budget exceeded: remaining ${err.details.remainingBudgetUsd}`,\n    });\n    return;\n  }\n  throw err;\n}\n```\n\n## Testing & local dev\n\n- The SDK performs real HTTP requests. For unit tests, stub `global.fetch` or intercept calls with tools like [MSW](https://mswjs.io/).\n- When running the Agent Ledger API locally, ensure your test key exists in the development database and export it via `AGENT_LEDGER_API_KEY`.\n\n## License\n\nMIT\n","readmeFilename":"README.md"}