{"_id":"@agentbudget/agentbudget","_rev":"2-5cabf30fe11e58d6ff857c78722b01e7","name":"@agentbudget/agentbudget","dist-tags":{"latest":"0.3.1"},"versions":{"0.3.0":{"name":"@agentbudget/agentbudget","version":"0.3.0","keywords":["ai","agents","budget","cost","openai","anthropic","llm","cost-tracking"],"author":{"name":"AgentBudget"},"license":"Apache-2.0","_id":"@agentbudget/agentbudget@0.3.0","maintainers":[{"name":"sahiljagtap","email":"sahil.jagtap45@gmail.com"}],"homepage":"https://agentbudget.dev","bugs":{"url":"https://github.com/AgentBudget/agentbudget/issues"},"dist":{"shasum":"54ff9ec3d37088380c9d4a76e3017028c6e3b1ce","tarball":"https://registry.npmjs.org/@agentbudget/agentbudget/-/agentbudget-0.3.0.tgz","fileCount":6,"integrity":"sha512-ovzMhdOhbWbqkbNWyA3IaWfaBzjJInp5MqmddoA7uHhZDr2XT+rMv1dDPzO4Lp+QBDmBj7vkp/YDs+eHJ/XHuQ==","signatures":[{"sig":"MEUCIQDm427e3WTEU4ow2J/blgHMneOU4WPkh8wjTYOCgdWhWAIgYAQHN3gs/l9ppdQNcQUsHkxjkBKNiXU93pqUfDa4z0g=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":57126},"main":"./dist/index.js","types":"./dist/index.d.ts","module":"./dist/index.mjs","engines":{"node":">=18.0.0"},"exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.mjs","require":"./dist/index.js"}},"gitHead":"71af95cfb07e48e8283da23ef4eb812e0643095c","scripts":{"dev":"tsup src/index.ts --format cjs,esm --dts --watch","test":"node --experimental-vm-modules node_modules/.bin/jest","build":"tsup src/index.ts --format cjs,esm --dts --clean","typecheck":"tsc --noEmit"},"_npmUser":{"name":"sahiljagtap","email":"sahil.jagtap45@gmail.com"},"repository":{"url":"git+https://github.com/AgentBudget/agentbudget.git","type":"git","directory":"sdks/typescript"},"_npmVersion":"11.5.1","description":"Real-time cost enforcement for AI agent sessions — works with OpenAI and Anthropic","directories":{},"_nodeVersion":"24.7.0","_hasShrinkwrap":false,"devDependencies":{"tsup":"^8.5.1","typescript":"^5.9.3","@types/node":"^20.19.37"},"peerDependencies":{"openai":">=4.0.0","@anthropic-ai/sdk":">=0.20.0"},"peerDependenciesMeta":{"openai":{"optional":true},"@anthropic-ai/sdk":{"optional":true}},"_npmOperationalInternal":{"tmp":"tmp/agentbudget_0.3.0_1775085755171_0.9395082844064708","host":"s3://npm-registry-packages-npm-production"}},"0.3.1":{"name":"@agentbudget/agentbudget","version":"0.3.1","description":"Real-time cost enforcement for AI agent sessions — works with OpenAI and Anthropic","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"}},"scripts":{"build":"tsup src/index.ts --format cjs,esm --dts --clean","dev":"tsup src/index.ts --format cjs,esm --dts --watch","typecheck":"tsc --noEmit","test":"node --experimental-vm-modules node_modules/.bin/jest"},"keywords":["ai","agents","budget","cost","openai","anthropic","llm","cost-tracking"],"author":{"name":"AgentBudget"},"license":"Apache-2.0","homepage":"https://agentbudget.dev","repository":{"type":"git","url":"git+https://github.com/AgentBudget/agentbudget.git","directory":"sdks/typescript"},"devDependencies":{"@types/node":"^20.19.37","tsup":"^8.5.1","typescript":"^5.9.3"},"peerDependencies":{"@anthropic-ai/sdk":">=0.20.0","openai":">=4.0.0"},"peerDependenciesMeta":{"openai":{"optional":true},"@anthropic-ai/sdk":{"optional":true}},"engines":{"node":">=18.0.0"},"_id":"@agentbudget/agentbudget@0.3.1","gitHead":"8f27dfe28c77767a9b9dcc64ae58130256c0bdf2","bugs":{"url":"https://github.com/AgentBudget/agentbudget/issues"},"_nodeVersion":"24.7.0","_npmVersion":"11.5.1","dist":{"integrity":"sha512-rOaeH827fnoCLw1e7pcRG/94ov63S509zSR2LnMmbbUday1ngAsmYmWN1Hf5PeWPcSv3ByjHn8Sx1udc9ol0BQ==","shasum":"27130e27477311bf38fb05ad5d92c12e3110e8cf","tarball":"https://registry.npmjs.org/@agentbudget/agentbudget/-/agentbudget-0.3.1.tgz","fileCount":6,"unpackedSize":57165,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEQCIFXEGvfhe1bXNeQhBUScprq7DxOuqO6yMuUJHlWSGET8AiBGy/w5eZAgyobhs9cLd3vsn247QBoB+EOBmXbfHZdovQ=="}]},"_npmUser":{"name":"sahiljagtap","email":"sahil.jagtap45@gmail.com"},"directories":{},"maintainers":[{"name":"sahiljagtap","email":"sahil.jagtap45@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/agentbudget_0.3.1_1775086179381_0.7672583794859997"},"_hasShrinkwrap":false}},"time":{"created":"2026-04-01T23:22:35.070Z","modified":"2026-04-01T23:29:39.639Z","0.3.0":"2026-04-01T23:22:35.323Z","0.3.1":"2026-04-01T23:29:39.527Z"},"bugs":{"url":"https://github.com/AgentBudget/agentbudget/issues"},"author":{"name":"AgentBudget"},"license":"Apache-2.0","homepage":"https://agentbudget.dev","keywords":["ai","agents","budget","cost","openai","anthropic","llm","cost-tracking"],"repository":{"type":"git","url":"git+https://github.com/AgentBudget/agentbudget.git","directory":"sdks/typescript"},"description":"Real-time cost enforcement for AI agent sessions — works with OpenAI and Anthropic","maintainers":[{"name":"sahiljagtap","email":"sahil.jagtap45@gmail.com"}],"readme":"# AgentBudget TypeScript SDK\n\nReal-time cost enforcement for AI agent sessions — TypeScript/JavaScript edition.\n\n[![npm](https://img.shields.io/npm/v/@agentbudget/agentbudget)](https://www.npmjs.com/package/@agentbudget/agentbudget)\n[![License](https://img.shields.io/github/license/AgentBudget/agentbudget)](https://github.com/AgentBudget/agentbudget/blob/main/LICENSE)\n\n---\n\n## Install\n\n```bash\nnpm install @agentbudget/agentbudget\n```\n\nWorks with `openai` ≥ 4.0 and `@anthropic-ai/sdk` ≥ 0.20 (both optional peer dependencies).\nNode.js 18+. Zero runtime dependencies.\n\n---\n\n## Quickstart\n\n```ts\nimport { AgentBudget } from \"agentbudget\";\nimport OpenAI from \"openai\";\n\nconst budget = new AgentBudget(\"$5.00\");\nconst session = budget.newSession();\n\nconst openai = new OpenAI();\nconst resp = await openai.chat.completions.create({\n  model: \"gpt-4o\",\n  messages: [{ role: \"user\", content: \"Summarize this market report...\" }],\n});\n\n// Wrap the response — extracts model + tokens and records cost\nsession.wrapOpenAI(resp);\n\nconsole.log(`spent: $${session.spent.toFixed(4)}  remaining: $${session.remaining.toFixed(4)}`);\nconsole.log(session.report());\n\nsession.close();\n```\n\n---\n\n## OpenAI Example\n\n```ts\nimport { AgentBudget, BudgetExhausted, LoopDetected } from \"agentbudget\";\nimport OpenAI from \"openai\";\n\nconst budget = new AgentBudget(\"$5.00\", {\n  onSoftLimit: (r) => console.warn(`⚠️ 90% budget used — $${r.total_spent.toFixed(4)}`),\n  onHardLimit: (r) => console.error(`🛑 hard limit hit: $${r.total_spent.toFixed(4)}`),\n});\n\nconst openai = new OpenAI();\nconst session = budget.newSession();\n\ntry {\n  const resp = await openai.chat.completions.create({\n    model: \"gpt-4o\",\n    messages: [{ role: \"user\", content: \"Research CRM competitors\" }],\n  });\n\n  session.wrapOpenAI(resp);\n  console.log(resp.choices[0]?.message.content);\n} catch (err) {\n  if (err instanceof BudgetExhausted) {\n    console.error(`Hard limit: $${err.spent.toFixed(4)} spent of $${err.budget.toFixed(2)}`);\n  } else if (err instanceof LoopDetected) {\n    console.error(`Loop detected on: ${err.key}`);\n  }\n} finally {\n  session.close();\n}\n```\n\n---\n\n## Anthropic Example\n\n```ts\nimport Anthropic from \"@anthropic-ai/sdk\";\nimport { AgentBudget } from \"agentbudget\";\n\nconst budget = new AgentBudget(\"$5.00\");\nconst session = budget.newSession();\n\nconst anthropic = new Anthropic();\nconst resp = await anthropic.messages.create({\n  model: \"claude-opus-4-6-20250514\",\n  max_tokens: 1024,\n  messages: [{ role: \"user\", content: \"Analyze this dataset\" }],\n});\n\nsession.wrapAnthropic(resp);\nconsole.log(`spent: $${session.spent.toFixed(4)}`);\nsession.close();\n```\n\n---\n\n## Auto-patching a Client with `wrapClient`\n\nAttach a session to a specific client instance — every call on that instance is tracked automatically:\n\n```ts\nimport { AgentBudget, wrapClient } from \"agentbudget\";\nimport OpenAI from \"openai\";\n\nconst budget = new AgentBudget(\"$5.00\");\nconst session = budget.newSession();\n\n// Only this client instance is tracked\nconst client = wrapClient(new OpenAI(), session);\nawait client.chat.completions.create({ ... }); // tracked\n\nconst other = new OpenAI();\nawait other.chat.completions.create({ ... }); // NOT tracked\n```\n\nWorks with OpenAI and Anthropic client instances.\n\n---\n\n## Tracking Tool Costs\n\n```ts\nconst searchResult = await callSerpAPI(query);\n// Record a fixed cost for the tool call\nsession.track(searchResult, 0.01, \"serp_api\");\n// track() returns the result unchanged, so you can inline it:\nconst data = session.track(await fetchData(url), 0.05, \"fetch\");\n```\n\n---\n\n## Circuit Breaker\n\n```ts\nconst budget = new AgentBudget(\"$5.00\", {\n  softLimit: 0.8,             // warn at 80% (default 0.9)\n  loopMaxCalls: 10,           // trips after 10 repeated calls\n  loopWindowSeconds: 60,      // within a 60-second window\n  onSoftLimit: (r) => alertOps(r),\n  onHardLimit: (r) => logBudgetEvent(r),\n  onLoopDetected: (r) => killAgent(r),\n});\n```\n\n- **Soft limit** — fires callback once, agent can wrap up gracefully\n- **Hard limit** — throws `BudgetExhausted`, no further spend allowed\n- **Loop detection** — same model/tool called N times in window throws `LoopDetected`\n\n---\n\n## Finalization Reserve\n\n```ts\nconst budget = new AgentBudget(\"$1.00\", {\n  finalizationReserve: 0.05, // hard limit fires at $0.95\n});\n\nconst session = budget.newSession();\n\nif (session.wouldExceed(estimatedFinalCost)) {\n  return \"Here's what I completed so far...\";\n}\n// Safe to proceed\nsession.wrapOpenAI(await openai.chat.completions.create({ ... }));\n```\n\n---\n\n## Child Sessions\n\n```ts\nconst parent = budget.newSession();\n\nconst child = parent.childSession(2.0); // sub-budget: $2 or parent's remaining\nchild.wrapOpenAI(resp);\nchild.close();\n\n// Roll up child spend to parent\nparent.track(null, child.spent, \"subtask\");\n```\n\n---\n\n## Custom Model Pricing\n\n```ts\nimport { registerModel } from \"agentbudget\";\n\nregisterModel(\"my-model-v1\", 5.00, 20.00); // per million tokens\n```\n\n---\n\n## Cost Report\n\n```ts\nconst report = session.report();\n// {\n//   session_id:       \"sess_...\",\n//   budget:           5.0,\n//   total_spent:      3.421,\n//   remaining:        1.579,\n//   breakdown:        { llm: { total, calls, by_model }, tools: { ... } },\n//   duration_seconds: 34.2,\n//   terminated_by:    null,  // null | \"budget_exhausted\" | \"loop_detected\"\n//   event_count:      12,\n// }\n```\n\n---\n\n## Error Handling\n\n```ts\nimport { BudgetExhausted, LoopDetected } from \"agentbudget\";\n\ntry {\n  session.wrapOpenAI(resp);\n} catch (err) {\n  if (err instanceof BudgetExhausted) {\n    // err.budget, err.spent\n  } else if (err instanceof LoopDetected) {\n    // err.key\n  }\n}\n```\n\n---\n\n## API Reference\n\n### `new AgentBudget(maxSpend, opts?)`\n\n| Option | Default | Description |\n|---|---|---|\n| `softLimit` | `0.9` | Fraction of budget at which soft-limit callback fires |\n| `loopMaxCalls` | `10` | Repeated calls per window before LoopDetected |\n| `loopWindowSeconds` | `60` | Loop detection window |\n| `finalizationReserve` | `0` | Fraction held back from hard limit |\n| `onSoftLimit` | — | Called once when soft limit triggers |\n| `onHardLimit` | — | Called when BudgetExhausted is thrown |\n| `onLoopDetected` | — | Called when LoopDetected is thrown |\n\n### `budget.newSession(opts?): BudgetSession`\n\n| Option | Description |\n|---|---|\n| `id` | Custom session ID |\n\n### `BudgetSession` methods\n\n| Method | Description |\n|---|---|\n| `wrapOpenAI(response)` | Record cost from OpenAI response |\n| `wrapAnthropic(response)` | Record cost from Anthropic response |\n| `wrapUsage(model, inputTokens, outputTokens)` | Record cost from raw token counts |\n| `track(result, cost, toolName?, metadata?)` | Record fixed-cost action, returns result |\n| `wouldExceed(cost): boolean` | Pre-flight check without recording |\n| `spent: number` | Total dollars spent |\n| `remaining: number` | Dollars remaining |\n| `childSession(maxSpend, opts?): BudgetSession` | Create a sub-budget session |\n| `report(): Report` | Structured cost summary |\n| `close()` | Mark session ended |\n\n### `wrapClient(client, session): client`\n\nAttach a session to an OpenAI or Anthropic client instance for automatic tracking.\n\n---\n\n## Publishing to npm\n\n```bash\ncd sdks/typescript\nnpm run build\nnpm publish\n```\n\n---\n\n## License\n\nApache 2.0 — see [LICENSE](../../LICENSE)\n","readmeFilename":"README.md"}