{"_id":"@claudebuddy/claudebuddy-agent-sdk","_rev":"5-bbf8e1bb7fda4151acc1f95ed1ed1978","name":"@claudebuddy/claudebuddy-agent-sdk","dist-tags":{"latest":"0.7.1"},"versions":{"0.4.0":{"name":"@claudebuddy/claudebuddy-agent-sdk","version":"0.4.0","keywords":["open-agent-sdk","agent","sdk","ai","llm","tools","agentic","coding-agent","mcp"],"author":{"url":"https://github.com/LuckyGJX","name":"LuckyGJX"},"license":"MIT","_id":"@claudebuddy/claudebuddy-agent-sdk@0.4.0","maintainers":[{"name":"claudebuddy","email":"lovexzdxxz@gmail.com"}],"homepage":"https://github.com/claudebuddy/claudebuddy-agent-sdk","bugs":{"url":"https://github.com/claudebuddy/claudebuddy-agent-sdk/issues"},"dist":{"shasum":"672f665a1402754cfffbfd7e168d8ae01fd4d6a7","tarball":"https://registry.npmjs.org/@claudebuddy/claudebuddy-agent-sdk/-/claudebuddy-agent-sdk-0.4.0.tgz","fileCount":223,"integrity":"sha512-V/aIruv/QHwPnX5D9/uJaxhotOREi7/HO84VogU3e1V/6MJ+uNOjOfZkUzGxnL7TLaSU7P+SA7DMlGKckS1b5w==","signatures":[{"sig":"MEUCIGwwY95ncq/AxdmjZImpc8m4F/2Ca847mjj2JIEvs1D8AiEA7Qg9q4Nw+DOkpXeDKy6m5824sz7wF33Tx6v+SJIbdm8=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":551661},"main":"./dist/index.js","type":"module","types":"./dist/index.d.ts","engines":{"node":">=18.0.0"},"exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js"}},"gitHead":"c1f3217787370d3610b1c0be4b9b4df7a346b97d","scripts":{"dev":"tsc --watch","web":"npx tsx examples/web/server.ts","test":"npx tsx examples/01-simple-query.ts","build":"tsc","test:all":"for f in examples/*.ts; do echo \"--- Running $f ---\"; npx tsx $f; echo; done","publish:npm":"npm publish --registry=https://registry.npmjs.org/","prepublishOnly":"npm run build","publish:github":"npm publish --registry=https://npm.pkg.github.com/"},"_npmUser":{"name":"claudebuddy","email":"lovexzdxxz@gmail.com"},"repository":{"url":"git+https://github.com/claudebuddy/claudebuddy-agent-sdk.git","type":"git"},"_npmVersion":"10.9.8","description":"Open-source Agent SDK. Runs the full agent loop in-process — no local CLI required. Deploy anywhere: cloud, serverless, Docker, CI/CD.","directories":{},"_nodeVersion":"22.23.2","dependencies":{"zod":"^3.23.0","@anthropic-ai/sdk":"^0.52.0","zod-to-json-schema":"^3.24.0","@modelcontextprotocol/sdk":"^1.12.1"},"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"_hasShrinkwrap":false,"devDependencies":{"tsx":"^4.19.0","typescript":"^5.7.0","@types/node":"^22.0.0"},"_npmOperationalInternal":{"tmp":"tmp/claudebuddy-agent-sdk_0.4.0_1788854845101_0.149212106310735","host":"s3://npm-registry-packages-npm-production"}},"0.5.0":{"name":"@claudebuddy/claudebuddy-agent-sdk","version":"0.5.0","keywords":["open-agent-sdk","agent","sdk","ai","llm","tools","agentic","coding-agent","mcp"],"author":{"url":"https://github.com/LuckyGJX","name":"LuckyGJX"},"license":"MIT","_id":"@claudebuddy/claudebuddy-agent-sdk@0.5.0","maintainers":[{"name":"claudebuddy","email":"lovexzdxxz@gmail.com"}],"homepage":"https://github.com/claudebuddy/claudebuddy-agent-sdk","bugs":{"url":"https://github.com/claudebuddy/claudebuddy-agent-sdk/issues"},"dist":{"shasum":"20e2621f7371d5926d9a75d12b7503b812571cbb","tarball":"https://registry.npmjs.org/@claudebuddy/claudebuddy-agent-sdk/-/claudebuddy-agent-sdk-0.5.0.tgz","fileCount":238,"integrity":"sha512-s/K+j9zQZUgM8opNUWceR02CKD6O383XhlFLChcdmF06UtI0yjqwKswGZVuuXOCCu+3wlupsPS2Elqcj6sM8jA==","signatures":[{"sig":"MEYCIQDg5qBdxmt3ICiJ+67oLAEMDL4rnWOHjoV/0b6QTtj/dAIhAI7zm7LCJVE+/pT3XVo1fIbwGvGIbt2lV5LX0g8ElqEt","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":645839},"main":"./dist/index.js","type":"module","_from":"file:/tmp/claudebuddy-sdk-release-0.5.0/claudebuddy-claudebuddy-agent-sdk-0.5.0.tgz","types":"./dist/index.d.ts","engines":{"node":">=18.0.0"},"exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js"}},"scripts":{"dev":"tsc --watch","web":"npx tsx examples/web/server.ts","test":"tsx --test tests/*.test.ts","build":"tsc","test:all":"npm test && npm run build","publish:npm":"npm publish --registry=https://registry.npmjs.org/","test:examples":"for f in examples/*.ts; do npx tsx \"$f\" || exit $?; done","prepublishOnly":"npm run build","publish:github":"npm publish --registry=https://npm.pkg.github.com/"},"_npmUser":{"name":"claudebuddy","email":"lovexzdxxz@gmail.com"},"_resolved":"/tmp/claudebuddy-sdk-release-0.5.0/claudebuddy-claudebuddy-agent-sdk-0.5.0.tgz","_integrity":"sha512-s/K+j9zQZUgM8opNUWceR02CKD6O383XhlFLChcdmF06UtI0yjqwKswGZVuuXOCCu+3wlupsPS2Elqcj6sM8jA==","repository":{"url":"git+https://github.com/claudebuddy/claudebuddy-agent-sdk.git","type":"git"},"_npmVersion":"10.9.8","description":"Open-source Agent SDK. Runs the full agent loop in-process — no local CLI required. Deploy anywhere: cloud, serverless, Docker, CI/CD.","directories":{},"_nodeVersion":"22.23.2","dependencies":{"zod":"^3.23.0","@anthropic-ai/sdk":"^0.52.0","zod-to-json-schema":"^3.24.0","@modelcontextprotocol/sdk":"^1.12.1"},"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"_hasShrinkwrap":false,"devDependencies":{"tsx":"^4.19.0","typescript":"^5.7.0","@types/node":"^22.0.0"},"_npmOperationalInternal":{"tmp":"tmp/claudebuddy-agent-sdk_0.5.0_1789030033467_0.0614035306292664","host":"s3://npm-registry-packages-npm-production"}},"0.6.0":{"name":"@claudebuddy/claudebuddy-agent-sdk","version":"0.6.0","keywords":["open-agent-sdk","agent","sdk","ai","llm","tools","agentic","coding-agent","mcp"],"author":{"url":"https://github.com/LuckyGJX","name":"LuckyGJX"},"license":"MIT","_id":"@claudebuddy/claudebuddy-agent-sdk@0.6.0","maintainers":[{"name":"claudebuddy","email":"lovexzdxxz@gmail.com"}],"homepage":"https://github.com/claudebuddy/claudebuddy-agent-sdk","bugs":{"url":"https://github.com/claudebuddy/claudebuddy-agent-sdk/issues"},"dist":{"shasum":"6ee19661aa1147d03fd79e4fee5bee11de7697e4","tarball":"https://registry.npmjs.org/@claudebuddy/claudebuddy-agent-sdk/-/claudebuddy-agent-sdk-0.6.0.tgz","fileCount":243,"integrity":"sha512-SoC/GjQG7NTNlnSB/OVWqJvWqQZavXSo5eFubANYRvpQu/OJcBqTg8CcQhwVEdZcxk7T56OpQW3k9/tuG8Q3dw==","signatures":[{"sig":"MEUCIQDYQqMI22XiSfU6cnX5j1PiNWXV/CuXDyQSKRICC9EdnAIgbjzX3YkLP8VwBI4/0mXrAK9F5NTw42EpZ6/6lChw3U0=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":683304},"main":"./dist/index.js","type":"module","_from":"file:/tmp/claudebuddy-sdk-release-0.6.0/claudebuddy-claudebuddy-agent-sdk-0.6.0.tgz","types":"./dist/index.d.ts","engines":{"node":">=18.0.0"},"exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js"}},"scripts":{"dev":"tsc --watch","web":"npx tsx examples/web/server.ts","test":"tsx --test tests/*.test.ts","build":"tsc","test:all":"npm test && npm run build","publish:npm":"npm publish --registry=https://registry.npmjs.org/","test:examples":"for f in examples/*.ts; do npx tsx \"$f\" || exit $?; done","prepublishOnly":"npm run build","publish:github":"npm publish --registry=https://npm.pkg.github.com/"},"_npmUser":{"name":"claudebuddy","email":"lovexzdxxz@gmail.com"},"_resolved":"/tmp/claudebuddy-sdk-release-0.6.0/claudebuddy-claudebuddy-agent-sdk-0.6.0.tgz","_integrity":"sha512-SoC/GjQG7NTNlnSB/OVWqJvWqQZavXSo5eFubANYRvpQu/OJcBqTg8CcQhwVEdZcxk7T56OpQW3k9/tuG8Q3dw==","repository":{"url":"git+https://github.com/claudebuddy/claudebuddy-agent-sdk.git","type":"git"},"_npmVersion":"10.9.8","description":"Open-source Agent SDK. Runs the full agent loop in-process — no local CLI required. Deploy anywhere: cloud, serverless, Docker, CI/CD.","directories":{},"_nodeVersion":"22.23.2","dependencies":{"zod":"^3.23.0","@anthropic-ai/sdk":"^0.52.0","zod-to-json-schema":"^3.24.0","@modelcontextprotocol/sdk":"^1.12.1"},"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"_hasShrinkwrap":false,"devDependencies":{"tsx":"^4.19.0","typescript":"^5.7.0","@types/node":"^22.0.0"},"_npmOperationalInternal":{"tmp":"tmp/claudebuddy-agent-sdk_0.6.0_1789108012778_0.42456942794963415","host":"s3://npm-registry-packages-npm-production"}},"0.7.0":{"name":"@claudebuddy/claudebuddy-agent-sdk","version":"0.7.0","keywords":["open-agent-sdk","agent","sdk","ai","llm","tools","agentic","coding-agent","mcp"],"author":{"url":"https://github.com/LuckyGJX","name":"LuckyGJX"},"license":"MIT","_id":"@claudebuddy/claudebuddy-agent-sdk@0.7.0","maintainers":[{"name":"claudebuddy","email":"lovexzdxxz@gmail.com"}],"homepage":"https://github.com/claudebuddy/claudebuddy-agent-sdk","bugs":{"url":"https://github.com/claudebuddy/claudebuddy-agent-sdk/issues"},"dist":{"shasum":"f6495dce25e556101ca1678a69a6dfb5dce8465a","tarball":"https://registry.npmjs.org/@claudebuddy/claudebuddy-agent-sdk/-/claudebuddy-agent-sdk-0.7.0.tgz","fileCount":264,"integrity":"sha512-eTlYaEgP30qpR95jYN0LjO2ky0ChRJ13mRD0hVABhGkafXenHnFdo396KGbPjnbQS0q7OSSL5ukMyXFFMK0wBQ==","signatures":[{"sig":"MEYCIQD4vWZpHLXNqQTsnXGiXRybe+YdJnPyjr3bmgoE1gKRGwIhAL+btZDJQovfEbkxw1TvVLiiejqjP8f4xLG5Fxbn1qts","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":752248},"main":"./dist/index.js","type":"module","types":"./dist/index.d.ts","engines":{"node":">=18.0.0"},"exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js"}},"gitHead":"92d4140820379011743e9333c681fe4d9b1e509b","scripts":{"dev":"tsc --watch","web":"npx tsx examples/web/server.ts","test":"tsx --test tests/*.test.ts","build":"tsc","test:all":"npm test && npm run build","publish:npm":"npm publish --registry=https://registry.npmjs.org/","test:examples":"for f in examples/*.ts; do npx tsx \"$f\" || exit $?; done","prepublishOnly":"npm run build","publish:github":"npm publish --registry=https://npm.pkg.github.com/"},"_npmUser":{"name":"claudebuddy","email":"lovexzdxxz@gmail.com"},"repository":{"url":"git+https://github.com/claudebuddy/claudebuddy-agent-sdk.git","type":"git"},"_npmVersion":"10.9.8","description":"Open-source Agent SDK. Runs the full agent loop in-process — no local CLI required. Deploy anywhere: cloud, serverless, Docker, CI/CD.","directories":{},"_nodeVersion":"22.23.2","dependencies":{"zod":"^3.23.0","cron-parser":"^5.10.0","@anthropic-ai/sdk":"^0.52.0","zod-to-json-schema":"^3.24.0","@modelcontextprotocol/sdk":"^1.12.1"},"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"_hasShrinkwrap":false,"devDependencies":{"tsx":"^4.19.0","typescript":"^5.7.0","@types/node":"^22.0.0"},"_npmOperationalInternal":{"tmp":"tmp/claudebuddy-agent-sdk_0.7.0_1789132393835_0.15999407210692862","host":"s3://npm-registry-packages-npm-production"}},"0.7.1":{"_id":"@claudebuddy/claudebuddy-agent-sdk@0.7.1","bugs":{"url":"https://github.com/claudebuddy/claudebuddy-agent-sdk/issues"},"dist":{"shasum":"ccd1fe9b90e6dcd3e9d453485ee87ad8800652d1","tarball":"https://registry.npmjs.org/@claudebuddy/claudebuddy-agent-sdk/-/claudebuddy-agent-sdk-0.7.1.tgz","fileCount":264,"integrity":"sha512-bM0KDascLZ0/zrNWYxELNqWojci+rCLRSTyQdLu4IcC3cwzjq+Ms1P+jiyDvuWEiuYGqQeS0xYR5eVa62CPP0w==","signatures":[{"sig":"MEUCIADbZFb1aBdw97o4q28F/s5jHf9y1skiKVu10puafVjYAiEA3uQAScewFS6bfHMCR+UdiBZfOqgkb99Er7iu0EyzOY0=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"},{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEQCIHlfcc/UfAk/jl7o4IPTO39DlXIgUwlEIbdhqqqJTQoWAiA4ME94S9z8/D+fX3pWfoyhquhweoDbBkDTY5SZveSIPQ=="}],"unpackedSize":752362},"main":"./dist/index.js","name":"@claudebuddy/claudebuddy-agent-sdk","type":"module","types":"./dist/index.d.ts","author":{"url":"https://github.com/LuckyGJX","name":"LuckyGJX"},"engines":{"node":">=18.0.0"},"exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js"}},"gitHead":"836e78ae8115109d0abca55be38f5320bc4f6322","license":"MIT","scripts":{"dev":"tsc --watch","web":"npx tsx examples/web/server.ts","test":"tsx --test tests/*.test.ts","build":"tsc","test:all":"npm test && npm run build","publish:npm":"npm publish --registry=https://registry.npmjs.org/","test:examples":"for f in examples/*.ts; do npx tsx \"$f\" || exit $?; done","prepublishOnly":"npm run build","publish:github":"npm publish --registry=https://npm.pkg.github.com/"},"version":"0.7.1","_npmUser":{"name":"claudebuddy","email":"lovexzdxxz@gmail.com"},"homepage":"https://github.com/claudebuddy/claudebuddy-agent-sdk","keywords":["open-agent-sdk","agent","sdk","ai","llm","tools","agentic","coding-agent","mcp"],"repository":{"url":"git+https://github.com/claudebuddy/claudebuddy-agent-sdk.git","type":"git"},"_npmVersion":"10.9.8","description":"Open-source Agent SDK. Runs the full agent loop in-process — no local CLI required. Deploy anywhere: cloud, serverless, Docker, CI/CD.","directories":{},"maintainers":[{"name":"claudebuddy","email":"lovexzdxxz@gmail.com"}],"_nodeVersion":"22.23.2","dependencies":{"zod":"^4.6.5","cron-parser":"^5.10.0","@anthropic-ai/sdk":"^0.52.0","@modelcontextprotocol/sdk":"^1.12.1"},"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"_hasShrinkwrap":false,"devDependencies":{"tsx":"^4.19.0","typescript":"^5.7.0","@types/node":"^22.0.0"},"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/claudebuddy-agent-sdk_0.7.1_1790147691958_0.23557073526428485"}}},"time":{"created":"2026-09-08T08:07:24.882Z","modified":"2026-09-23T07:14:52.278Z","0.4.0":"2026-09-08T08:07:25.247Z","0.5.0":"2026-09-10T08:47:13.628Z","0.6.0":"2026-09-11T06:26:52.909Z","0.7.0":"2026-09-11T13:13:13.987Z","0.7.1":"2026-09-23T07:14:52.044Z"},"bugs":{"url":"https://github.com/claudebuddy/claudebuddy-agent-sdk/issues"},"author":{"url":"https://github.com/LuckyGJX","name":"LuckyGJX"},"license":"MIT","homepage":"https://github.com/claudebuddy/claudebuddy-agent-sdk","keywords":["open-agent-sdk","agent","sdk","ai","llm","tools","agentic","coding-agent","mcp"],"repository":{"url":"git+https://github.com/claudebuddy/claudebuddy-agent-sdk.git","type":"git"},"description":"Open-source Agent SDK. Runs the full agent loop in-process — no local CLI required. Deploy anywhere: cloud, serverless, Docker, CI/CD.","maintainers":[{"name":"claudebuddy","email":"lovexzdxxz@gmail.com"}],"readme":"# ClaudeBuddy Agent SDK (TypeScript)\n\n[![npm version](https://img.shields.io/npm/v/@claudebuddy/claudebuddy-agent-sdk)](https://www.npmjs.com/package/@claudebuddy/claudebuddy-agent-sdk)\n[![Node.js](https://img.shields.io/badge/node-%3E%3D18-brightgreen)](https://nodejs.org)\n[![License: MIT](https://img.shields.io/badge/license-MIT-blue)](./LICENSE)\n\nclaudebuddy Agent SDK that runs the full agent loop **in-process** — no subprocess or CLI required. Supports both **Anthropic** and **OpenAI-compatible** APIs. Deploy anywhere: cloud, serverless, Docker, CI/CD.\n\n\n## Get started\n\n```bash\nnpm install @claudebuddy/claudebuddy-agent-sdk\n```\n\nSet your API key:\n\n```bash\nexport CLAUDEBUDDY_API_KEY=your-api-key\n```\n\n### OpenAI-compatible models\n\nWorks with OpenAI, DeepSeek, Qwen, Mistral, or any OpenAI-compatible endpoint:\n\n```bash\nexport CLAUDEBUDDY_API_TYPE=openai-completions\nexport CLAUDEBUDDY_API_KEY=sk-...\nexport CLAUDEBUDDY_BASE_URL=https://api.openai.com/v1\nexport CLAUDEBUDDY_MODEL=gpt-4o\n```\n\n### Third-party Anthropic-compatible providers\n\n```bash\nexport CLAUDEBUDDY_BASE_URL=https://openrouter.ai/api\nexport CLAUDEBUDDY_API_KEY=sk-or-...\nexport CLAUDEBUDDY_MODEL=anthropic/claude-sonnet-4\n```\n\n## Quick start\n\n### One-shot query (streaming)\n\n```typescript\nimport { query } from \"@claudebuddy/claudebuddy-agent-sdk\";\n\nfor await (const message of query({\n  prompt: \"Read package.json and tell me the project name.\",\n  options: {\n    allowedTools: [\"Read\", \"Glob\"],\n    permissionMode: \"bypassPermissions\",\n  },\n})) {\n  if (message.type === \"assistant\") {\n    for (const block of message.message.content) {\n      if (\"text\" in block) console.log(block.text);\n    }\n  }\n}\n```\n\n### Simple blocking prompt\n\n```typescript\nimport { createAgent } from \"@claudebuddy/claudebuddy-agent-sdk\";\n\nconst agent = createAgent({ model: \"claude-sonnet-4-6\" });\nconst result = await agent.prompt(\"What files are in this project?\");\n\nconsole.log(result.text);\nconsole.log(\n  `Turns: ${result.num_turns}, Tokens: ${result.usage.input_tokens + result.usage.output_tokens}`,\n);\n```\n\n### OpenAI / GPT models\n\n```typescript\nimport { createAgent } from \"@claudebuddy/claudebuddy-agent-sdk\";\n\nconst agent = createAgent({\n  apiType: \"openai-completions\",\n  model: \"gpt-4o\",\n  apiKey: \"sk-...\",\n  baseURL: \"https://api.openai.com/v1\",\n});\n\nconst result = await agent.prompt(\"What files are in this project?\");\nconsole.log(result.text);\n```\n\nThe `apiType` is auto-detected from model name — models containing `gpt-`, `o1`, `o3`, `deepseek`, `qwen`, `mistral`, etc. automatically use `openai-completions`.\n\n### Scheduled prompts\n\n```typescript\nconst agent = createAgent({\n  scheduler: { enabled: true, timeZone: \"Asia/Shanghai\" },\n});\n\nawait agent.createSchedule({\n  name: \"daily review\",\n  prompt: \"Review the project and report actionable problems.\",\n  cron: \"0 9 * * *\",\n});\n\nawait agent.close();\n```\n\nSchedules are recoverable when session persistence is enabled, do not overlap the\nsame job, and run only while the owning process is alive. See\n[session scheduler](./docs/scheduler.md) for lifecycle and recovery semantics.\n\n### Multi-turn conversation\n\n```typescript\nimport { createAgent } from \"@claudebuddy/claudebuddy-agent-sdk\";\n\nconst agent = createAgent({ maxTurns: 5 });\n\nconst r1 = await agent.prompt(\n  'Create a file /tmp/hello.txt with \"Hello World\"',\n);\nconsole.log(r1.text);\n\nconst r2 = await agent.prompt(\"Read back the file you just created\");\nconsole.log(r2.text);\n\nconsole.log(`Session messages: ${agent.getMessages().length}`);\n```\n\n### Custom tools (Zod schema)\n\n```typescript\nimport { z } from \"zod\";\nimport { query, tool, createSdkMcpServer } from \"@claudebuddy/claudebuddy-agent-sdk\";\n\nconst getWeather = tool(\n  \"get_weather\",\n  \"Get the temperature for a city\",\n  { city: z.string().describe(\"City name\") },\n  async ({ city }) => ({\n    content: [{ type: \"text\", text: `${city}: 22°C, sunny` }],\n  }),\n);\n\nconst server = createSdkMcpServer({ name: \"weather\", tools: [getWeather] });\n\nfor await (const msg of query({\n  prompt: \"What is the weather in Tokyo?\",\n  options: { mcpServers: { weather: server } },\n})) {\n  if (msg.type === \"result\")\n    console.log(`Done: $${msg.total_cost_usd?.toFixed(4)}`);\n}\n```\n\n### Custom tools (low-level)\n\n```typescript\nimport {\n  createAgent,\n  getAllBaseTools,\n  defineTool,\n} from \"@claudebuddy/claudebuddy-agent-sdk\";\n\nconst calculator = defineTool({\n  name: \"Calculator\",\n  description: \"Evaluate a math expression\",\n  inputSchema: {\n    type: \"object\",\n    properties: { expression: { type: \"string\" } },\n    required: [\"expression\"],\n  },\n  isReadOnly: true,\n  async call(input) {\n    const result = Function(`'use strict'; return (${input.expression})`)();\n    return `${input.expression} = ${result}`;\n  },\n});\n\nconst agent = createAgent({ tools: [...getAllBaseTools(), calculator] });\nconst r = await agent.prompt(\"Calculate 2**10 * 3\");\nconsole.log(r.text);\n```\n\n### Skills\n\nSkills are reusable prompt templates that extend agent capabilities. Five bundled skills are included: `simplify`, `commit`, `review`, `debug`, `test`.\n\n```typescript\nimport {\n  createAgent,\n  registerSkill,\n  getAllSkills,\n} from \"@claudebuddy/claudebuddy-agent-sdk\";\n\n// Register a custom skill\nregisterSkill({\n  name: \"explain\",\n  description: \"Explain a concept in simple terms\",\n  userInvocable: true,\n  async getPrompt(args) {\n    return [\n      {\n        type: \"text\",\n        text: `Explain in simple terms: ${args || \"Ask what to explain.\"}`,\n      },\n    ];\n  },\n});\n\nconsole.log(`${getAllSkills().length} skills registered`);\n\n// The model can invoke skills via the Skill tool\nconst agent = createAgent();\nconst result = await agent.prompt('Use the \"explain\" skill to explain git rebase');\nconsole.log(result.text);\n```\n\n### Hooks (lifecycle events)\n\n```typescript\nimport { createAgent, createHookRegistry } from \"@claudebuddy/claudebuddy-agent-sdk\";\n\nconst hooks = createHookRegistry({\n  PreToolUse: [\n    {\n      handler: async (input) => {\n        console.log(`About to use: ${input.toolName}`);\n        // Return { block: true } to prevent tool execution\n      },\n    },\n  ],\n  PostToolUse: [\n    {\n      handler: async (input) => {\n        console.log(`Tool ${input.toolName} completed`);\n      },\n    },\n  ],\n});\n```\n\n20 lifecycle events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `SessionStart`, `SessionEnd`, `Stop`, `SubagentStart`, `SubagentStop`, `UserPromptSubmit`, `PermissionRequest`, `PermissionDenied`, `TaskCreated`, `TaskCompleted`, `ConfigChange`, `CwdChanged`, `FileChanged`, `Notification`, `PreCompact`, `PostCompact`, `TeammateIdle`.\n\n### MCP server integration\n\n```typescript\nimport { createAgent } from \"@claudebuddy/claudebuddy-agent-sdk\";\n\nconst agent = createAgent({\n  mcpServers: {\n    filesystem: {\n      command: \"npx\",\n      args: [\"-y\", \"@modelcontextprotocol/server-filesystem\", \"/tmp\"],\n    },\n  },\n});\n\nconst result = await agent.prompt(\"List files in /tmp\");\nconsole.log(result.text);\nawait agent.close();\n```\n\n### Subagents\n\n```typescript\nimport { query } from \"@claudebuddy/claudebuddy-agent-sdk\";\n\nfor await (const msg of query({\n  prompt: \"Use the code-reviewer agent to review src/index.ts\",\n  options: {\n    agents: {\n      \"code-reviewer\": {\n        description: \"Expert code reviewer\",\n        prompt: \"Analyze code quality. Focus on security and performance.\",\n        tools: [\"Read\", \"Glob\", \"Grep\"],\n      },\n    },\n  },\n})) {\n  if (msg.type === \"result\") console.log(\"Done\");\n}\n```\n\n### Permissions\n\n```typescript\nimport { query } from \"@claudebuddy/claudebuddy-agent-sdk\";\n\n// Read-only agent — can only analyze, not modify\nfor await (const msg of query({\n  prompt: \"Review the code in src/ for best practices.\",\n  options: {\n    allowedTools: [\"Read\", \"Glob\", \"Grep\"],\n    permissionMode: \"dontAsk\",\n  },\n})) {\n  // ...\n}\n```\n\n### Web UI\n\nA built-in web chat interface is included for testing:\n\n```bash\nnpx tsx examples/web/server.ts\n# Open http://localhost:8081\n```\n\n## API reference\n\n### Top-level functions\n\n| Function                              | Description                                                    |\n| ------------------------------------- | -------------------------------------------------------------- |\n| `query({ prompt, options })`          | One-shot streaming query, returns `AsyncGenerator<SDKMessage>` |\n| `createAgent(options)`                | Create a reusable agent with session persistence               |\n| `tool(name, desc, schema, handler)`   | Create a tool with Zod schema validation                       |\n| `createSdkMcpServer({ name, tools })` | Bundle tools into an in-process MCP server                     |\n| `defineTool(config)`                  | Low-level tool definition helper                               |\n| `getAllBaseTools()`                   | Get all 35+ built-in tools                                     |\n| `registerSkill(definition)`           | Register a custom skill                                        |\n| `getAllSkills()`                       | Get all registered skills                                      |\n| `createProvider(apiType, opts)`        | Create an LLM provider directly                                |\n| `createHookRegistry(config)`          | Create a hook registry for lifecycle events                    |\n| `listSessions()`                      | List persisted sessions                                        |\n| `forkSession(id)`                     | Fork a session for branching                                   |\n\n### Agent methods\n\n| Method                          | Description                                           |\n| ------------------------------- | ----------------------------------------------------- |\n| `agent.query(prompt)`           | Streaming query, returns `AsyncGenerator<SDKMessage>` |\n| `agent.prompt(text)`            | Blocking query, returns `Promise<QueryResult>`        |\n| `agent.getMessages()`           | Get conversation history                              |\n| `agent.clear()`                 | Reset session                                         |\n| `agent.interrupt()`             | Abort current query                                   |\n| `agent.setModel(model)`         | Change model mid-session                              |\n| `agent.setPermissionMode(mode)` | Change permission mode                                |\n| `agent.getApiType()`            | Get current API type                                  |\n| `agent.close()`                 | Close MCP connections, persist session                |\n\n### Options\n\n| Option               | Type                                    | Default                | Description                                                          |\n| -------------------- | --------------------------------------- | ---------------------- | -------------------------------------------------------------------- |\n| `apiType`            | `string`                                | auto-detected          | `'anthropic-messages'` or `'openai-completions'`                     |\n| `model`              | `string`                                | `claude-sonnet-4-6`    | LLM model ID                                                         |\n| `apiKey`             | `string`                                | `CLAUDEBUDDY_API_KEY`      | API key                                                              |\n| `baseURL`            | `string`                                | —                      | Custom API endpoint                                                  |\n| `cwd`                | `string`                                | `process.cwd()`        | Working directory                                                    |\n| `systemPrompt`       | `string`                                | —                      | System prompt override                                               |\n| `appendSystemPrompt` | `string`                                | —                      | Append to default system prompt                                      |\n| `tools`              | `ToolDefinition[]`                      | All built-in           | Available tools                                                      |\n| `allowedTools`       | `string[]`                              | —                      | Tool allow-list                                                      |\n| `disallowedTools`    | `string[]`                              | —                      | Tool deny-list                                                       |\n| `permissionMode`     | `string`                                | `bypassPermissions`    | `default` / `acceptEdits` / `dontAsk` / `bypassPermissions` / `plan` |\n| `canUseTool`         | `function`                              | —                      | Custom permission callback                                           |\n| `maxTurns`           | `number`                                | `10`                   | Max agentic turns                                                    |\n| `maxBudgetUsd`       | `number`                                | —                      | Spending cap                                                         |\n| `thinking`           | `ThinkingConfig`                        | `{ type: 'adaptive' }` | Extended thinking                                                    |\n| `effort`             | `string`                                | `high`                 | Reasoning effort: `low` / `medium` / `high` / `max`                  |\n| `mcpServers`         | `Record<string, McpServerConfig>`       | —                      | MCP server connections                                               |\n| `agents`             | `Record<string, AgentDefinition>`       | —                      | Subagent definitions                                                 |\n| `hooks`              | `Record<string, HookCallbackMatcher[]>` | —                      | Lifecycle hooks                                                      |\n| `resume`             | `string`                                | —                      | Resume session by ID                                                 |\n| `continue`           | `boolean`                               | `false`                | Continue most recent session                                         |\n| `persistSession`     | `boolean`                               | `true`                 | Persist session to disk                                              |\n| `sessionId`          | `string`                                | auto                   | Explicit session ID                                                  |\n| `outputFormat`       | `{ type: 'json_schema', schema }`       | —                      | Structured output                                                    |\n| `sandbox`            | `SandboxSettings`                       | —                      | Filesystem/network sandbox                                           |\n| `settingSources`     | `SettingSource[]`                       | —                      | Load AGENT.md, project settings                                      |\n| `env`                | `Record<string, string>`                | —                      | Environment variables                                                |\n| `abortController`    | `AbortController`                       | —                      | Cancellation controller                                              |\n\n### Environment variables\n\n| Variable             | Description                                              |\n| -------------------- | -------------------------------------------------------- |\n| `CLAUDEBUDDY_API_KEY`    | API key (required)                                       |\n| `CLAUDEBUDDY_API_TYPE`   | `anthropic-messages` (default) or `openai-completions`   |\n| `CLAUDEBUDDY_MODEL`      | Default model override                                   |\n| `CLAUDEBUDDY_BASE_URL`   | Custom API endpoint                                      |\n| `CLAUDEBUDDY_AUTH_TOKEN` | Alternative auth token                                   |\n\n## Built-in tools\n\n| Tool                                       | Description                                  |\n| ------------------------------------------ | -------------------------------------------- |\n| **Bash**                                   | Execute shell commands                       |\n| **Read**                                   | Read files with line numbers                 |\n| **Write**                                  | Create / overwrite files                     |\n| **Edit**                                   | Precise string replacement in files          |\n| **Glob**                                   | Find files by pattern                        |\n| **Grep**                                   | Search file contents with regex              |\n| **WebFetch**                               | Fetch and parse web content                  |\n| **WebSearch**                              | Search the web                               |\n| **NotebookEdit**                           | Edit Jupyter notebook cells                  |\n| **Agent**                                  | Spawn subagents for parallel work            |\n| **Skill**                                  | Invoke registered skills                     |\n| **TaskCreate/List/Update/Get/Stop/Output** | Task management system                       |\n| **TeamCreate/Delete**                      | Multi-agent team coordination                |\n| **SendMessage**                            | Inter-agent messaging                        |\n| **EnterWorktree/ExitWorktree**             | Git worktree isolation                       |\n| **EnterPlanMode/ExitPlanMode**             | Structured planning workflow                 |\n| **AskUserQuestion**                        | Ask the user for input                       |\n| **ToolSearch**                             | Discover lazy-loaded tools                   |\n| **ListMcpResources/ReadMcpResource**       | MCP resource access                          |\n| **CronCreate/Delete/List**                 | Scheduled task management                    |\n| **RemoteTrigger**                          | Remote agent triggers                        |\n| **LSP**                                    | Language Server Protocol (code intelligence) |\n| **Config**                                 | Dynamic configuration                        |\n| **TodoWrite**                              | Session todo list                            |\n\n## Bundled skills\n\n| Skill        | Description                                                    |\n| ------------ | -------------------------------------------------------------- |\n| `simplify`   | Review changed code for reuse, quality, and efficiency         |\n| `commit`     | Create a git commit with a well-crafted message                |\n| `review`     | Review code changes for correctness, security, and performance |\n| `debug`      | Systematic debugging using structured investigation            |\n| `test`       | Run tests and analyze failures                                 |\n\nRegister custom skills with `registerSkill()`.\n\n## Architecture\n\n```\n┌──────────────────────────────────────────────────────┐\n│                   Your Application                    │\n│                                                       │\n│   import { createAgent } from '@claudebuddy/claudebuddy-agent-sdk' │\n└────────────────────────┬─────────────────────────────┘\n                         │\n              ┌──────────▼──────────┐\n              │       Agent         │  Session state, tool pool,\n              │  query() / prompt() │  MCP connections, hooks\n              └──────────┬──────────┘\n                         │\n              ┌──────────▼──────────┐\n              │    QueryEngine      │  Agentic loop:\n              │   submitMessage()   │  API call → tools → repeat\n              └──────────┬──────────┘\n                         │\n         ┌───────────────┼───────────────┐\n         │               │               │\n   ┌─────▼─────┐  ┌─────▼─────┐  ┌─────▼─────┐\n   │  Provider  │  │  35 Tools │  │    MCP     │\n   │ Anthropic  │  │ Bash,Read │  │  Servers   │\n   │  OpenAI    │  │ Edit,...  │  │ stdio/SSE/ │\n   │ DeepSeek   │  │ + Skills  │  │ HTTP/SDK   │\n   └───────────┘  └───────────┘  └───────────┘\n```\n\n**Key internals:**\n\n| Component             | Description                                                        |\n| --------------------- | ------------------------------------------------------------------ |\n| **Provider layer**    | Abstracts Anthropic / OpenAI API differences                       |\n| **QueryEngine**       | Core agentic loop with auto-compact, retry, tool orchestration     |\n| **Skill system**      | Reusable prompt templates with 5 bundled skills                    |\n| **Hook system**       | 20 lifecycle events integrated into the engine                     |\n| **Auto-compact**      | Summarizes conversation when context window fills up               |\n| **Micro-compact**     | Truncates oversized tool results                                   |\n| **Retry**             | Exponential backoff for rate limits and transient errors            |\n| **Token estimation**  | Rough token counting with pricing for Claude, GPT, DeepSeek models |\n| **File cache**        | LRU cache (100 entries, 25 MB) for file reads                      |\n| **Session storage**   | Persist / resume / fork sessions on disk                           |\n| **Context injection** | Git status + AGENT.md automatically injected into system prompt    |\n\n## Examples\n\n| #   | File                                  | Description                            |\n| --- | ------------------------------------- | -------------------------------------- |\n| 01  | `examples/01-simple-query.ts`         | Streaming query with event handling    |\n| 02  | `examples/02-multi-tool.ts`           | Multi-tool orchestration (Glob + Bash) |\n| 03  | `examples/03-multi-turn.ts`           | Multi-turn session persistence         |\n| 04  | `examples/04-prompt-api.ts`           | Blocking `prompt()` API                |\n| 05  | `examples/05-custom-system-prompt.ts` | Custom system prompt                   |\n| 06  | `examples/06-mcp-server.ts`           | MCP server integration                 |\n| 07  | `examples/07-custom-tools.ts`         | Custom tools with `defineTool()`       |\n| 08  | `examples/08-official-api-compat.ts`  | `query()` API pattern                  |\n| 09  | `examples/09-subagents.ts`            | Subagent delegation                    |\n| 10  | `examples/10-permissions.ts`          | Read-only agent with tool restrictions |\n| 11  | `examples/11-custom-mcp-tools.ts`     | `tool()` + `createSdkMcpServer()`      |\n| 12  | `examples/12-skills.ts`              | Skill system usage                     |\n| 13  | `examples/13-hooks.ts`               | Lifecycle hooks                        |\n| 14  | `examples/14-openai-compat.ts`       | OpenAI / DeepSeek models               |\n| web | `examples/web/`                       | Web chat UI for testing                |\n\nRun any example:\n\n```bash\nnpx tsx examples/01-simple-query.ts\n```\n\nStart the web UI:\n\n```bash\nnpx tsx examples/web/server.ts\n```\n\n## Execution-time interaction\n\nUse `agent.sendMessage(text)` to queue steering instructions during an active query.\nEnable `interactive: true` to receive question events and answer them with\n`agent.answerQuestion(id, answer)`. Existing multi-turn queries and question callbacks\nremain supported. See [runtime interaction](docs/runtime-interaction.md) for receipts,\nUI integration, timeouts, cancellation and persistence limits.\n\n## Background tasks\n\n`Bash` and `Agent` support `run_in_background: true`, returning a `task_id` for\n`TaskOutput` and `TaskStop`. Tasks execute within the current query; the engine\njoins them before its final result and cancels them on interruption. See\n[background execution](docs/background-tasks.md) for output, cancellation and\nlifecycle details. Scheduler placeholders are currently excluded from model tools.\n\n## Streaming and recovery\n\nSet `includePartialMessages: true` to receive real text/tool argument deltas from\nAnthropic and OpenAI-compatible transports. The final `assistant` event contains the\ncomplete response. Tool calls execute only after completion; adjacent explicitly\nsafe reads may run concurrently, preserving mutation barriers.\n\nWith persistence enabled, progress is checkpointed during execution and semantic\nevents can be replayed with `readSessionEvents(sessionId, afterId?)`. Unknown tool\noutcomes are marked on resume and are not automatically replayed. See\n[streaming, scheduling and recovery](docs/runtime-progress.md) for usage, failure\nsemantics and the single-writer storage requirement.\n\n## Runtime reliability and compatibility\n\nEach `Agent` owns its conversation and built-in tool state. Only one query or goal\nmay run on an Agent at a time; use separate Agents for concurrent conversations.\nChildren intentionally share the parent session state, cancellation signal and\nexecution budget, while inheriting its available tools and permission policy.\n`clear()` clears conversation and tool state, retaining connected MCP servers.\nConfigure session-specific helpers with the Agent's state handle, for example\n`setQuestionHandler(handler, agent.getToolState())`. Helpers called without a state\nhandle retain legacy standalone behavior and do not configure Agent instances.\n\nTool allow/deny lists apply to built-in, MCP and replacement tools. Query overrides\ncan narrow the constructor's lists; `allowedTools: []` exposes no tools. Denials win.\n\n| Permission mode | Execution policy |\n| --- | --- |\n| `bypassPermissions` (default) | Available tools are permitted; a supplied `canUseTool` callback may still deny. |\n| `plan` | Only tools declaring `isReadOnly() === true`; callbacks cannot permit mutations. |\n| `default`, `auto` | Read-only or explicitly allowed tools are preapproved; other tools require an allowing callback. `auto` currently uses this deterministic policy. |\n| `dontAsk` | Read-only or explicitly allowed tools only. |\n| `acceptEdits` | Also preapproves the built-in file and notebook edit/write tools; other mutations require an allowing callback. |\n\nA supplied callback is still consulted for preapproved tools. Tool metadata and\ncustom tool implementations are trusted host code. These policies do not provide\nOS isolation: requesting sandbox enforcement throws an explicit unsupported error.\nGoal runs additionally expose their internal goal-reporting tool.\n\n`prompt()` returns `subtype`, `is_error`, `errors` and `total_cost_usd` alongside text\nand usage. Check `is_error` before treating text as a completed answer. Provider\nfailures, cancellation, exhausted turns and budget limits remain observable.\nInvalid configuration and overlapping runs throw. Goal execution emits one final\naggregate result and stops on provider failure, cancellation or a budget limit.\n\n`maxBudgetUsd` covers one ordinary query, or all rounds of one goal, including child\nagents and compaction summaries. Usage and costs accumulate in the same ledger.\nThe limit checks whether another request may start; an in-flight request can exceed\nit. Cost is estimated from configured pricing and reported token usage.\n\nCancellation propagates to Anthropic/OpenAI transports, retry waits, compaction,\nchild agents and MCP requests. Custom tools/providers must cooperate with the\nsupplied abort signal; cancellation cannot undo completed side effects. Breaking\nout of a query iterator preserves conversation history and releases its run lock.\n\nRun offline regression tests and compile the SDK:\n\n```bash\nnpm run test:all\n```\n\n`npm run test:examples` executes the examples separately; these may use live model\nAPIs and require credentials.\n\n## Star History\n\n<a href=\"https://www.star-history.com/?repos=claudebuddy%2Fclaudebuddy-agent-sdk&type=timeline&legend=top-left\">\n <picture>\n   <source media=\"(prefers-color-scheme: dark)\" srcset=\"https://api.star-history.com/image?repos=claudebuddy/claudebuddy-agent-sdk&type=timeline&theme=dark&legend=top-left\" />\n   <source media=\"(prefers-color-scheme: light)\" srcset=\"https://api.star-history.com/image?repos=claudebuddy/claudebuddy-agent-sdk&type=timeline&legend=top-left\" />\n   <img alt=\"Star History Chart\" src=\"https://api.star-history.com/image?repos=claudebuddy/claudebuddy-agent-sdk&type=timeline&legend=top-left\" />\n </picture>\n</a>\n\n## License\n\nMIT\n","readmeFilename":"README.md"}