@claudebuddy/claudebuddy-agent-sdk 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (223) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +501 -0
  3. package/dist/agent.d.ts +137 -0
  4. package/dist/agent.d.ts.map +1 -0
  5. package/dist/agent.js +573 -0
  6. package/dist/agent.js.map +1 -0
  7. package/dist/engine.d.ts +70 -0
  8. package/dist/engine.d.ts.map +1 -0
  9. package/dist/engine.js +552 -0
  10. package/dist/engine.js.map +1 -0
  11. package/dist/hooks.d.ts +111 -0
  12. package/dist/hooks.d.ts.map +1 -0
  13. package/dist/hooks.js +179 -0
  14. package/dist/hooks.js.map +1 -0
  15. package/dist/index.d.ts +70 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +141 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/mcp/client.d.ts +19 -0
  20. package/dist/mcp/client.d.ts.map +1 -0
  21. package/dist/mcp/client.js +126 -0
  22. package/dist/mcp/client.js.map +1 -0
  23. package/dist/providers/anthropic.d.ts +17 -0
  24. package/dist/providers/anthropic.d.ts.map +1 -0
  25. package/dist/providers/anthropic.js +47 -0
  26. package/dist/providers/anthropic.js.map +1 -0
  27. package/dist/providers/index.d.ts +20 -0
  28. package/dist/providers/index.d.ts.map +1 -0
  29. package/dist/providers/index.js +26 -0
  30. package/dist/providers/index.js.map +1 -0
  31. package/dist/providers/openai.d.ts +26 -0
  32. package/dist/providers/openai.d.ts.map +1 -0
  33. package/dist/providers/openai.js +243 -0
  34. package/dist/providers/openai.js.map +1 -0
  35. package/dist/providers/types.d.ts +84 -0
  36. package/dist/providers/types.d.ts.map +1 -0
  37. package/dist/providers/types.js +11 -0
  38. package/dist/providers/types.js.map +1 -0
  39. package/dist/sdk-mcp-server.d.ts +52 -0
  40. package/dist/sdk-mcp-server.d.ts.map +1 -0
  41. package/dist/sdk-mcp-server.js +57 -0
  42. package/dist/sdk-mcp-server.js.map +1 -0
  43. package/dist/session.d.ts +73 -0
  44. package/dist/session.d.ts.map +1 -0
  45. package/dist/session.js +159 -0
  46. package/dist/session.js.map +1 -0
  47. package/dist/skills/bundled/commit.d.ts +7 -0
  48. package/dist/skills/bundled/commit.d.ts.map +1 -0
  49. package/dist/skills/bundled/commit.js +35 -0
  50. package/dist/skills/bundled/commit.js.map +1 -0
  51. package/dist/skills/bundled/debug.d.ts +7 -0
  52. package/dist/skills/bundled/debug.d.ts.map +1 -0
  53. package/dist/skills/bundled/debug.js +46 -0
  54. package/dist/skills/bundled/debug.js.map +1 -0
  55. package/dist/skills/bundled/index.d.ts +11 -0
  56. package/dist/skills/bundled/index.d.ts.map +1 -0
  57. package/dist/skills/bundled/index.js +26 -0
  58. package/dist/skills/bundled/index.js.map +1 -0
  59. package/dist/skills/bundled/review.d.ts +7 -0
  60. package/dist/skills/bundled/review.d.ts.map +1 -0
  61. package/dist/skills/bundled/review.js +38 -0
  62. package/dist/skills/bundled/review.js.map +1 -0
  63. package/dist/skills/bundled/simplify.d.ts +8 -0
  64. package/dist/skills/bundled/simplify.d.ts.map +1 -0
  65. package/dist/skills/bundled/simplify.js +48 -0
  66. package/dist/skills/bundled/simplify.js.map +1 -0
  67. package/dist/skills/bundled/test.d.ts +7 -0
  68. package/dist/skills/bundled/test.d.ts.map +1 -0
  69. package/dist/skills/bundled/test.js +40 -0
  70. package/dist/skills/bundled/test.js.map +1 -0
  71. package/dist/skills/index.d.ts +7 -0
  72. package/dist/skills/index.d.ts.map +1 -0
  73. package/dist/skills/index.js +8 -0
  74. package/dist/skills/index.js.map +1 -0
  75. package/dist/skills/registry.d.ts +43 -0
  76. package/dist/skills/registry.d.ts.map +1 -0
  77. package/dist/skills/registry.js +111 -0
  78. package/dist/skills/registry.js.map +1 -0
  79. package/dist/skills/types.d.ts +83 -0
  80. package/dist/skills/types.d.ts.map +1 -0
  81. package/dist/skills/types.js +8 -0
  82. package/dist/skills/types.js.map +1 -0
  83. package/dist/tool-helper.d.ts +73 -0
  84. package/dist/tool-helper.d.ts.map +1 -0
  85. package/dist/tool-helper.js +86 -0
  86. package/dist/tool-helper.js.map +1 -0
  87. package/dist/tools/agent-tool.d.ts +17 -0
  88. package/dist/tools/agent-tool.d.ts.map +1 -0
  89. package/dist/tools/agent-tool.js +150 -0
  90. package/dist/tools/agent-tool.js.map +1 -0
  91. package/dist/tools/ask-user.d.ts +18 -0
  92. package/dist/tools/ask-user.d.ts.map +1 -0
  93. package/dist/tools/ask-user.js +72 -0
  94. package/dist/tools/ask-user.js.map +1 -0
  95. package/dist/tools/bash.d.ts +5 -0
  96. package/dist/tools/bash.d.ts.map +1 -0
  97. package/dist/tools/bash.js +67 -0
  98. package/dist/tools/bash.js.map +1 -0
  99. package/dist/tools/config-tool.d.ts +20 -0
  100. package/dist/tools/config-tool.d.ts.map +1 -0
  101. package/dist/tools/config-tool.js +83 -0
  102. package/dist/tools/config-tool.js.map +1 -0
  103. package/dist/tools/cron-tools.d.ts +33 -0
  104. package/dist/tools/cron-tools.d.ts.map +1 -0
  105. package/dist/tools/cron-tools.js +128 -0
  106. package/dist/tools/cron-tools.js.map +1 -0
  107. package/dist/tools/edit.d.ts +5 -0
  108. package/dist/tools/edit.d.ts.map +1 -0
  109. package/dist/tools/edit.js +70 -0
  110. package/dist/tools/edit.js.map +1 -0
  111. package/dist/tools/glob.d.ts +5 -0
  112. package/dist/tools/glob.d.ts.map +1 -0
  113. package/dist/tools/glob.js +75 -0
  114. package/dist/tools/glob.js.map +1 -0
  115. package/dist/tools/grep.d.ts +5 -0
  116. package/dist/tools/grep.d.ts.map +1 -0
  117. package/dist/tools/grep.js +168 -0
  118. package/dist/tools/grep.js.map +1 -0
  119. package/dist/tools/index.d.ts +45 -0
  120. package/dist/tools/index.d.ts.map +1 -0
  121. package/dist/tools/index.js +162 -0
  122. package/dist/tools/index.js.map +1 -0
  123. package/dist/tools/lsp-tool.d.ts +9 -0
  124. package/dist/tools/lsp-tool.d.ts.map +1 -0
  125. package/dist/tools/lsp-tool.js +137 -0
  126. package/dist/tools/lsp-tool.js.map +1 -0
  127. package/dist/tools/mcp-resource-tools.d.ts +14 -0
  128. package/dist/tools/mcp-resource-tools.d.ts.map +1 -0
  129. package/dist/tools/mcp-resource-tools.js +117 -0
  130. package/dist/tools/mcp-resource-tools.js.map +1 -0
  131. package/dist/tools/notebook-edit.d.ts +5 -0
  132. package/dist/tools/notebook-edit.d.ts.map +1 -0
  133. package/dist/tools/notebook-edit.js +85 -0
  134. package/dist/tools/notebook-edit.js.map +1 -0
  135. package/dist/tools/plan-tools.d.ts +12 -0
  136. package/dist/tools/plan-tools.d.ts.map +1 -0
  137. package/dist/tools/plan-tools.js +77 -0
  138. package/dist/tools/plan-tools.js.map +1 -0
  139. package/dist/tools/read.d.ts +5 -0
  140. package/dist/tools/read.d.ts.map +1 -0
  141. package/dist/tools/read.js +66 -0
  142. package/dist/tools/read.js.map +1 -0
  143. package/dist/tools/send-message.d.ts +31 -0
  144. package/dist/tools/send-message.d.ts.map +1 -0
  145. package/dist/tools/send-message.js +77 -0
  146. package/dist/tools/send-message.js.map +1 -0
  147. package/dist/tools/skill-tool.d.ts +9 -0
  148. package/dist/tools/skill-tool.d.ts.map +1 -0
  149. package/dist/tools/skill-tool.js +115 -0
  150. package/dist/tools/skill-tool.js.map +1 -0
  151. package/dist/tools/task-tools.d.ts +48 -0
  152. package/dist/tools/task-tools.d.ts.map +1 -0
  153. package/dist/tools/task-tools.js +242 -0
  154. package/dist/tools/task-tools.js.map +1 -0
  155. package/dist/tools/team-tools.d.ts +34 -0
  156. package/dist/tools/team-tools.d.ts.map +1 -0
  157. package/dist/tools/team-tools.js +103 -0
  158. package/dist/tools/team-tools.js.map +1 -0
  159. package/dist/tools/todo-tool.d.ts +22 -0
  160. package/dist/tools/todo-tool.d.ts.map +1 -0
  161. package/dist/tools/todo-tool.js +93 -0
  162. package/dist/tools/todo-tool.js.map +1 -0
  163. package/dist/tools/tool-search.d.ts +13 -0
  164. package/dist/tools/tool-search.d.ts.map +1 -0
  165. package/dist/tools/tool-search.js +76 -0
  166. package/dist/tools/tool-search.js.map +1 -0
  167. package/dist/tools/types.d.ts +29 -0
  168. package/dist/tools/types.d.ts.map +1 -0
  169. package/dist/tools/types.js +52 -0
  170. package/dist/tools/types.js.map +1 -0
  171. package/dist/tools/update-goal.d.ts +38 -0
  172. package/dist/tools/update-goal.d.ts.map +1 -0
  173. package/dist/tools/update-goal.js +109 -0
  174. package/dist/tools/update-goal.js.map +1 -0
  175. package/dist/tools/web-fetch.d.ts +5 -0
  176. package/dist/tools/web-fetch.d.ts.map +1 -0
  177. package/dist/tools/web-fetch.js +60 -0
  178. package/dist/tools/web-fetch.js.map +1 -0
  179. package/dist/tools/web-search.d.ts +5 -0
  180. package/dist/tools/web-search.d.ts.map +1 -0
  181. package/dist/tools/web-search.js +77 -0
  182. package/dist/tools/web-search.js.map +1 -0
  183. package/dist/tools/worktree-tools.d.ts +10 -0
  184. package/dist/tools/worktree-tools.d.ts.map +1 -0
  185. package/dist/tools/worktree-tools.js +130 -0
  186. package/dist/tools/worktree-tools.js.map +1 -0
  187. package/dist/tools/write.d.ts +5 -0
  188. package/dist/tools/write.d.ts.map +1 -0
  189. package/dist/tools/write.js +40 -0
  190. package/dist/tools/write.js.map +1 -0
  191. package/dist/types.d.ts +485 -0
  192. package/dist/types.d.ts.map +1 -0
  193. package/dist/types.js +5 -0
  194. package/dist/types.js.map +1 -0
  195. package/dist/utils/compact.d.ts +44 -0
  196. package/dist/utils/compact.d.ts.map +1 -0
  197. package/dist/utils/compact.js +162 -0
  198. package/dist/utils/compact.js.map +1 -0
  199. package/dist/utils/context.d.ts +35 -0
  200. package/dist/utils/context.d.ts.map +1 -0
  201. package/dist/utils/context.js +174 -0
  202. package/dist/utils/context.js.map +1 -0
  203. package/dist/utils/fileCache.d.ts +64 -0
  204. package/dist/utils/fileCache.d.ts.map +1 -0
  205. package/dist/utils/fileCache.js +117 -0
  206. package/dist/utils/fileCache.js.map +1 -0
  207. package/dist/utils/messages.d.ts +57 -0
  208. package/dist/utils/messages.d.ts.map +1 -0
  209. package/dist/utils/messages.js +152 -0
  210. package/dist/utils/messages.js.map +1 -0
  211. package/dist/utils/retry.d.ts +48 -0
  212. package/dist/utils/retry.d.ts.map +1 -0
  213. package/dist/utils/retry.js +111 -0
  214. package/dist/utils/retry.js.map +1 -0
  215. package/dist/utils/spill.d.ts +100 -0
  216. package/dist/utils/spill.d.ts.map +1 -0
  217. package/dist/utils/spill.js +126 -0
  218. package/dist/utils/spill.js.map +1 -0
  219. package/dist/utils/tokens.d.ts +60 -0
  220. package/dist/utils/tokens.d.ts.map +1 -0
  221. package/dist/utils/tokens.js +140 -0
  222. package/dist/utils/tokens.js.map +1 -0
  223. package/package.json +71 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 CodeAny (https://codeany.ai)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,501 @@
1
+ # Open Agent SDK (TypeScript)
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@claudebuddy/claudebuddy-agent-sdk)](https://www.npmjs.com/package/@claudebuddy/claudebuddy-agent-sdk)
4
+ [![Node.js](https://img.shields.io/badge/node-%3E%3D18-brightgreen)](https://nodejs.org)
5
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue)](./LICENSE)
6
+
7
+ Open-source 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.
8
+
9
+ Also available in **Go**: [open-agent-sdk-go](https://github.com/claudebuddy/claudebuddy-agent-sdk)
10
+
11
+ ## Get started
12
+
13
+ ```bash
14
+ npm install @claudebuddy/claudebuddy-agent-sdk
15
+ ```
16
+
17
+ Set your API key:
18
+
19
+ ```bash
20
+ export CLAUDEBUDDY_API_KEY=your-api-key
21
+ ```
22
+
23
+ ### OpenAI-compatible models
24
+
25
+ Works with OpenAI, DeepSeek, Qwen, Mistral, or any OpenAI-compatible endpoint:
26
+
27
+ ```bash
28
+ export CLAUDEBUDDY_API_TYPE=openai-completions
29
+ export CLAUDEBUDDY_API_KEY=sk-...
30
+ export CLAUDEBUDDY_BASE_URL=https://api.openai.com/v1
31
+ export CLAUDEBUDDY_MODEL=gpt-4o
32
+ ```
33
+
34
+ ### Third-party Anthropic-compatible providers
35
+
36
+ ```bash
37
+ export CLAUDEBUDDY_BASE_URL=https://openrouter.ai/api
38
+ export CLAUDEBUDDY_API_KEY=sk-or-...
39
+ export CLAUDEBUDDY_MODEL=anthropic/claude-sonnet-4
40
+ ```
41
+
42
+ ## Quick start
43
+
44
+ ### One-shot query (streaming)
45
+
46
+ ```typescript
47
+ import { query } from "@claudebuddy/claudebuddy-agent-sdk";
48
+
49
+ for await (const message of query({
50
+ prompt: "Read package.json and tell me the project name.",
51
+ options: {
52
+ allowedTools: ["Read", "Glob"],
53
+ permissionMode: "bypassPermissions",
54
+ },
55
+ })) {
56
+ if (message.type === "assistant") {
57
+ for (const block of message.message.content) {
58
+ if ("text" in block) console.log(block.text);
59
+ }
60
+ }
61
+ }
62
+ ```
63
+
64
+ ### Simple blocking prompt
65
+
66
+ ```typescript
67
+ import { createAgent } from "@claudebuddy/claudebuddy-agent-sdk";
68
+
69
+ const agent = createAgent({ model: "claude-sonnet-4-6" });
70
+ const result = await agent.prompt("What files are in this project?");
71
+
72
+ console.log(result.text);
73
+ console.log(
74
+ `Turns: ${result.num_turns}, Tokens: ${result.usage.input_tokens + result.usage.output_tokens}`,
75
+ );
76
+ ```
77
+
78
+ ### OpenAI / GPT models
79
+
80
+ ```typescript
81
+ import { createAgent } from "@claudebuddy/claudebuddy-agent-sdk";
82
+
83
+ const agent = createAgent({
84
+ apiType: "openai-completions",
85
+ model: "gpt-4o",
86
+ apiKey: "sk-...",
87
+ baseURL: "https://api.openai.com/v1",
88
+ });
89
+
90
+ const result = await agent.prompt("What files are in this project?");
91
+ console.log(result.text);
92
+ ```
93
+
94
+ The `apiType` is auto-detected from model name — models containing `gpt-`, `o1`, `o3`, `deepseek`, `qwen`, `mistral`, etc. automatically use `openai-completions`.
95
+
96
+ ### Multi-turn conversation
97
+
98
+ ```typescript
99
+ import { createAgent } from "@claudebuddy/claudebuddy-agent-sdk";
100
+
101
+ const agent = createAgent({ maxTurns: 5 });
102
+
103
+ const r1 = await agent.prompt(
104
+ 'Create a file /tmp/hello.txt with "Hello World"',
105
+ );
106
+ console.log(r1.text);
107
+
108
+ const r2 = await agent.prompt("Read back the file you just created");
109
+ console.log(r2.text);
110
+
111
+ console.log(`Session messages: ${agent.getMessages().length}`);
112
+ ```
113
+
114
+ ### Custom tools (Zod schema)
115
+
116
+ ```typescript
117
+ import { z } from "zod";
118
+ import { query, tool, createSdkMcpServer } from "@claudebuddy/claudebuddy-agent-sdk";
119
+
120
+ const getWeather = tool(
121
+ "get_weather",
122
+ "Get the temperature for a city",
123
+ { city: z.string().describe("City name") },
124
+ async ({ city }) => ({
125
+ content: [{ type: "text", text: `${city}: 22°C, sunny` }],
126
+ }),
127
+ );
128
+
129
+ const server = createSdkMcpServer({ name: "weather", tools: [getWeather] });
130
+
131
+ for await (const msg of query({
132
+ prompt: "What is the weather in Tokyo?",
133
+ options: { mcpServers: { weather: server } },
134
+ })) {
135
+ if (msg.type === "result")
136
+ console.log(`Done: $${msg.total_cost_usd?.toFixed(4)}`);
137
+ }
138
+ ```
139
+
140
+ ### Custom tools (low-level)
141
+
142
+ ```typescript
143
+ import {
144
+ createAgent,
145
+ getAllBaseTools,
146
+ defineTool,
147
+ } from "@claudebuddy/claudebuddy-agent-sdk";
148
+
149
+ const calculator = defineTool({
150
+ name: "Calculator",
151
+ description: "Evaluate a math expression",
152
+ inputSchema: {
153
+ type: "object",
154
+ properties: { expression: { type: "string" } },
155
+ required: ["expression"],
156
+ },
157
+ isReadOnly: true,
158
+ async call(input) {
159
+ const result = Function(`'use strict'; return (${input.expression})`)();
160
+ return `${input.expression} = ${result}`;
161
+ },
162
+ });
163
+
164
+ const agent = createAgent({ tools: [...getAllBaseTools(), calculator] });
165
+ const r = await agent.prompt("Calculate 2**10 * 3");
166
+ console.log(r.text);
167
+ ```
168
+
169
+ ### Skills
170
+
171
+ Skills are reusable prompt templates that extend agent capabilities. Five bundled skills are included: `simplify`, `commit`, `review`, `debug`, `test`.
172
+
173
+ ```typescript
174
+ import {
175
+ createAgent,
176
+ registerSkill,
177
+ getAllSkills,
178
+ } from "@claudebuddy/claudebuddy-agent-sdk";
179
+
180
+ // Register a custom skill
181
+ registerSkill({
182
+ name: "explain",
183
+ description: "Explain a concept in simple terms",
184
+ userInvocable: true,
185
+ async getPrompt(args) {
186
+ return [
187
+ {
188
+ type: "text",
189
+ text: `Explain in simple terms: ${args || "Ask what to explain."}`,
190
+ },
191
+ ];
192
+ },
193
+ });
194
+
195
+ console.log(`${getAllSkills().length} skills registered`);
196
+
197
+ // The model can invoke skills via the Skill tool
198
+ const agent = createAgent();
199
+ const result = await agent.prompt('Use the "explain" skill to explain git rebase');
200
+ console.log(result.text);
201
+ ```
202
+
203
+ ### Hooks (lifecycle events)
204
+
205
+ ```typescript
206
+ import { createAgent, createHookRegistry } from "@claudebuddy/claudebuddy-agent-sdk";
207
+
208
+ const hooks = createHookRegistry({
209
+ PreToolUse: [
210
+ {
211
+ handler: async (input) => {
212
+ console.log(`About to use: ${input.toolName}`);
213
+ // Return { block: true } to prevent tool execution
214
+ },
215
+ },
216
+ ],
217
+ PostToolUse: [
218
+ {
219
+ handler: async (input) => {
220
+ console.log(`Tool ${input.toolName} completed`);
221
+ },
222
+ },
223
+ ],
224
+ });
225
+ ```
226
+
227
+ 20 lifecycle events: `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `SessionStart`, `SessionEnd`, `Stop`, `SubagentStart`, `SubagentStop`, `UserPromptSubmit`, `PermissionRequest`, `PermissionDenied`, `TaskCreated`, `TaskCompleted`, `ConfigChange`, `CwdChanged`, `FileChanged`, `Notification`, `PreCompact`, `PostCompact`, `TeammateIdle`.
228
+
229
+ ### MCP server integration
230
+
231
+ ```typescript
232
+ import { createAgent } from "@claudebuddy/claudebuddy-agent-sdk";
233
+
234
+ const agent = createAgent({
235
+ mcpServers: {
236
+ filesystem: {
237
+ command: "npx",
238
+ args: ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
239
+ },
240
+ },
241
+ });
242
+
243
+ const result = await agent.prompt("List files in /tmp");
244
+ console.log(result.text);
245
+ await agent.close();
246
+ ```
247
+
248
+ ### Subagents
249
+
250
+ ```typescript
251
+ import { query } from "@claudebuddy/claudebuddy-agent-sdk";
252
+
253
+ for await (const msg of query({
254
+ prompt: "Use the code-reviewer agent to review src/index.ts",
255
+ options: {
256
+ agents: {
257
+ "code-reviewer": {
258
+ description: "Expert code reviewer",
259
+ prompt: "Analyze code quality. Focus on security and performance.",
260
+ tools: ["Read", "Glob", "Grep"],
261
+ },
262
+ },
263
+ },
264
+ })) {
265
+ if (msg.type === "result") console.log("Done");
266
+ }
267
+ ```
268
+
269
+ ### Permissions
270
+
271
+ ```typescript
272
+ import { query } from "@claudebuddy/claudebuddy-agent-sdk";
273
+
274
+ // Read-only agent — can only analyze, not modify
275
+ for await (const msg of query({
276
+ prompt: "Review the code in src/ for best practices.",
277
+ options: {
278
+ allowedTools: ["Read", "Glob", "Grep"],
279
+ permissionMode: "dontAsk",
280
+ },
281
+ })) {
282
+ // ...
283
+ }
284
+ ```
285
+
286
+ ### Web UI
287
+
288
+ A built-in web chat interface is included for testing:
289
+
290
+ ```bash
291
+ npx tsx examples/web/server.ts
292
+ # Open http://localhost:8081
293
+ ```
294
+
295
+ ## API reference
296
+
297
+ ### Top-level functions
298
+
299
+ | Function | Description |
300
+ | ------------------------------------- | -------------------------------------------------------------- |
301
+ | `query({ prompt, options })` | One-shot streaming query, returns `AsyncGenerator<SDKMessage>` |
302
+ | `createAgent(options)` | Create a reusable agent with session persistence |
303
+ | `tool(name, desc, schema, handler)` | Create a tool with Zod schema validation |
304
+ | `createSdkMcpServer({ name, tools })` | Bundle tools into an in-process MCP server |
305
+ | `defineTool(config)` | Low-level tool definition helper |
306
+ | `getAllBaseTools()` | Get all 35+ built-in tools |
307
+ | `registerSkill(definition)` | Register a custom skill |
308
+ | `getAllSkills()` | Get all registered skills |
309
+ | `createProvider(apiType, opts)` | Create an LLM provider directly |
310
+ | `createHookRegistry(config)` | Create a hook registry for lifecycle events |
311
+ | `listSessions()` | List persisted sessions |
312
+ | `forkSession(id)` | Fork a session for branching |
313
+
314
+ ### Agent methods
315
+
316
+ | Method | Description |
317
+ | ------------------------------- | ----------------------------------------------------- |
318
+ | `agent.query(prompt)` | Streaming query, returns `AsyncGenerator<SDKMessage>` |
319
+ | `agent.prompt(text)` | Blocking query, returns `Promise<QueryResult>` |
320
+ | `agent.getMessages()` | Get conversation history |
321
+ | `agent.clear()` | Reset session |
322
+ | `agent.interrupt()` | Abort current query |
323
+ | `agent.setModel(model)` | Change model mid-session |
324
+ | `agent.setPermissionMode(mode)` | Change permission mode |
325
+ | `agent.getApiType()` | Get current API type |
326
+ | `agent.close()` | Close MCP connections, persist session |
327
+
328
+ ### Options
329
+
330
+ | Option | Type | Default | Description |
331
+ | -------------------- | --------------------------------------- | ---------------------- | -------------------------------------------------------------------- |
332
+ | `apiType` | `string` | auto-detected | `'anthropic-messages'` or `'openai-completions'` |
333
+ | `model` | `string` | `claude-sonnet-4-6` | LLM model ID |
334
+ | `apiKey` | `string` | `CLAUDEBUDDY_API_KEY` | API key |
335
+ | `baseURL` | `string` | — | Custom API endpoint |
336
+ | `cwd` | `string` | `process.cwd()` | Working directory |
337
+ | `systemPrompt` | `string` | — | System prompt override |
338
+ | `appendSystemPrompt` | `string` | — | Append to default system prompt |
339
+ | `tools` | `ToolDefinition[]` | All built-in | Available tools |
340
+ | `allowedTools` | `string[]` | — | Tool allow-list |
341
+ | `disallowedTools` | `string[]` | — | Tool deny-list |
342
+ | `permissionMode` | `string` | `bypassPermissions` | `default` / `acceptEdits` / `dontAsk` / `bypassPermissions` / `plan` |
343
+ | `canUseTool` | `function` | — | Custom permission callback |
344
+ | `maxTurns` | `number` | `10` | Max agentic turns |
345
+ | `maxBudgetUsd` | `number` | — | Spending cap |
346
+ | `thinking` | `ThinkingConfig` | `{ type: 'adaptive' }` | Extended thinking |
347
+ | `effort` | `string` | `high` | Reasoning effort: `low` / `medium` / `high` / `max` |
348
+ | `mcpServers` | `Record<string, McpServerConfig>` | — | MCP server connections |
349
+ | `agents` | `Record<string, AgentDefinition>` | — | Subagent definitions |
350
+ | `hooks` | `Record<string, HookCallbackMatcher[]>` | — | Lifecycle hooks |
351
+ | `resume` | `string` | — | Resume session by ID |
352
+ | `continue` | `boolean` | `false` | Continue most recent session |
353
+ | `persistSession` | `boolean` | `true` | Persist session to disk |
354
+ | `sessionId` | `string` | auto | Explicit session ID |
355
+ | `outputFormat` | `{ type: 'json_schema', schema }` | — | Structured output |
356
+ | `sandbox` | `SandboxSettings` | — | Filesystem/network sandbox |
357
+ | `settingSources` | `SettingSource[]` | — | Load AGENT.md, project settings |
358
+ | `env` | `Record<string, string>` | — | Environment variables |
359
+ | `abortController` | `AbortController` | — | Cancellation controller |
360
+
361
+ ### Environment variables
362
+
363
+ | Variable | Description |
364
+ | -------------------- | -------------------------------------------------------- |
365
+ | `CLAUDEBUDDY_API_KEY` | API key (required) |
366
+ | `CLAUDEBUDDY_API_TYPE` | `anthropic-messages` (default) or `openai-completions` |
367
+ | `CLAUDEBUDDY_MODEL` | Default model override |
368
+ | `CLAUDEBUDDY_BASE_URL` | Custom API endpoint |
369
+ | `CLAUDEBUDDY_AUTH_TOKEN` | Alternative auth token |
370
+
371
+ ## Built-in tools
372
+
373
+ | Tool | Description |
374
+ | ------------------------------------------ | -------------------------------------------- |
375
+ | **Bash** | Execute shell commands |
376
+ | **Read** | Read files with line numbers |
377
+ | **Write** | Create / overwrite files |
378
+ | **Edit** | Precise string replacement in files |
379
+ | **Glob** | Find files by pattern |
380
+ | **Grep** | Search file contents with regex |
381
+ | **WebFetch** | Fetch and parse web content |
382
+ | **WebSearch** | Search the web |
383
+ | **NotebookEdit** | Edit Jupyter notebook cells |
384
+ | **Agent** | Spawn subagents for parallel work |
385
+ | **Skill** | Invoke registered skills |
386
+ | **TaskCreate/List/Update/Get/Stop/Output** | Task management system |
387
+ | **TeamCreate/Delete** | Multi-agent team coordination |
388
+ | **SendMessage** | Inter-agent messaging |
389
+ | **EnterWorktree/ExitWorktree** | Git worktree isolation |
390
+ | **EnterPlanMode/ExitPlanMode** | Structured planning workflow |
391
+ | **AskUserQuestion** | Ask the user for input |
392
+ | **ToolSearch** | Discover lazy-loaded tools |
393
+ | **ListMcpResources/ReadMcpResource** | MCP resource access |
394
+ | **CronCreate/Delete/List** | Scheduled task management |
395
+ | **RemoteTrigger** | Remote agent triggers |
396
+ | **LSP** | Language Server Protocol (code intelligence) |
397
+ | **Config** | Dynamic configuration |
398
+ | **TodoWrite** | Session todo list |
399
+
400
+ ## Bundled skills
401
+
402
+ | Skill | Description |
403
+ | ------------ | -------------------------------------------------------------- |
404
+ | `simplify` | Review changed code for reuse, quality, and efficiency |
405
+ | `commit` | Create a git commit with a well-crafted message |
406
+ | `review` | Review code changes for correctness, security, and performance |
407
+ | `debug` | Systematic debugging using structured investigation |
408
+ | `test` | Run tests and analyze failures |
409
+
410
+ Register custom skills with `registerSkill()`.
411
+
412
+ ## Architecture
413
+
414
+ ```
415
+ ┌──────────────────────────────────────────────────────┐
416
+ │ Your Application │
417
+ │ │
418
+ │ import { createAgent } from '@claudebuddy/claudebuddy-agent-sdk' │
419
+ └────────────────────────┬─────────────────────────────┘
420
+
421
+ ┌──────────▼──────────┐
422
+ │ Agent │ Session state, tool pool,
423
+ │ query() / prompt() │ MCP connections, hooks
424
+ └──────────┬──────────┘
425
+
426
+ ┌──────────▼──────────┐
427
+ │ QueryEngine │ Agentic loop:
428
+ │ submitMessage() │ API call → tools → repeat
429
+ └──────────┬──────────┘
430
+
431
+ ┌───────────────┼───────────────┐
432
+ │ │ │
433
+ ┌─────▼─────┐ ┌─────▼─────┐ ┌─────▼─────┐
434
+ │ Provider │ │ 35 Tools │ │ MCP │
435
+ │ Anthropic │ │ Bash,Read │ │ Servers │
436
+ │ OpenAI │ │ Edit,... │ │ stdio/SSE/ │
437
+ │ DeepSeek │ │ + Skills │ │ HTTP/SDK │
438
+ └───────────┘ └───────────┘ └───────────┘
439
+ ```
440
+
441
+ **Key internals:**
442
+
443
+ | Component | Description |
444
+ | --------------------- | ------------------------------------------------------------------ |
445
+ | **Provider layer** | Abstracts Anthropic / OpenAI API differences |
446
+ | **QueryEngine** | Core agentic loop with auto-compact, retry, tool orchestration |
447
+ | **Skill system** | Reusable prompt templates with 5 bundled skills |
448
+ | **Hook system** | 20 lifecycle events integrated into the engine |
449
+ | **Auto-compact** | Summarizes conversation when context window fills up |
450
+ | **Micro-compact** | Truncates oversized tool results |
451
+ | **Retry** | Exponential backoff for rate limits and transient errors |
452
+ | **Token estimation** | Rough token counting with pricing for Claude, GPT, DeepSeek models |
453
+ | **File cache** | LRU cache (100 entries, 25 MB) for file reads |
454
+ | **Session storage** | Persist / resume / fork sessions on disk |
455
+ | **Context injection** | Git status + AGENT.md automatically injected into system prompt |
456
+
457
+ ## Examples
458
+
459
+ | # | File | Description |
460
+ | --- | ------------------------------------- | -------------------------------------- |
461
+ | 01 | `examples/01-simple-query.ts` | Streaming query with event handling |
462
+ | 02 | `examples/02-multi-tool.ts` | Multi-tool orchestration (Glob + Bash) |
463
+ | 03 | `examples/03-multi-turn.ts` | Multi-turn session persistence |
464
+ | 04 | `examples/04-prompt-api.ts` | Blocking `prompt()` API |
465
+ | 05 | `examples/05-custom-system-prompt.ts` | Custom system prompt |
466
+ | 06 | `examples/06-mcp-server.ts` | MCP server integration |
467
+ | 07 | `examples/07-custom-tools.ts` | Custom tools with `defineTool()` |
468
+ | 08 | `examples/08-official-api-compat.ts` | `query()` API pattern |
469
+ | 09 | `examples/09-subagents.ts` | Subagent delegation |
470
+ | 10 | `examples/10-permissions.ts` | Read-only agent with tool restrictions |
471
+ | 11 | `examples/11-custom-mcp-tools.ts` | `tool()` + `createSdkMcpServer()` |
472
+ | 12 | `examples/12-skills.ts` | Skill system usage |
473
+ | 13 | `examples/13-hooks.ts` | Lifecycle hooks |
474
+ | 14 | `examples/14-openai-compat.ts` | OpenAI / DeepSeek models |
475
+ | web | `examples/web/` | Web chat UI for testing |
476
+
477
+ Run any example:
478
+
479
+ ```bash
480
+ npx tsx examples/01-simple-query.ts
481
+ ```
482
+
483
+ Start the web UI:
484
+
485
+ ```bash
486
+ npx tsx examples/web/server.ts
487
+ ```
488
+
489
+ ## Star History
490
+
491
+ <a href="https://www.star-history.com/?repos=claudebuddy%2Fclaudebuddy-agent-sdk&type=timeline&legend=top-left">
492
+ <picture>
493
+ <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" />
494
+ <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/image?repos=claudebuddy/claudebuddy-agent-sdk&type=timeline&legend=top-left" />
495
+ <img alt="Star History Chart" src="https://api.star-history.com/image?repos=claudebuddy/claudebuddy-agent-sdk&type=timeline&legend=top-left" />
496
+ </picture>
497
+ </a>
498
+
499
+ ## License
500
+
501
+ MIT
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Agent - High-level API
3
+ *
4
+ * Provides createAgent() and query() interfaces compatible with
5
+ * open-agent-sdk.
6
+ *
7
+ * Usage:
8
+ * import { createAgent } from 'open-agent-sdk'
9
+ * const agent = createAgent({ model: 'claude-sonnet-4-6' })
10
+ * for await (const event of agent.query('Hello')) { ... }
11
+ *
12
+ * // OpenAI-compatible models
13
+ * const agent = createAgent({
14
+ * apiType: 'openai-completions',
15
+ * model: 'gpt-4o',
16
+ * apiKey: 'sk-...',
17
+ * baseURL: 'https://api.openai.com/v1',
18
+ * })
19
+ */
20
+ import type { AgentOptions, QueryResult, SDKMessage, Message, PermissionMode } from './types.js';
21
+ import { type ApiType } from './providers/index.js';
22
+ export declare class Agent {
23
+ private cfg;
24
+ private toolPool;
25
+ private modelId;
26
+ private apiType;
27
+ private apiCredentials;
28
+ private provider;
29
+ private mcpLinks;
30
+ private history;
31
+ private messageLog;
32
+ private setupDone;
33
+ private sid;
34
+ private abortCtrl;
35
+ private currentEngine;
36
+ private hookRegistry;
37
+ constructor(options?: AgentOptions);
38
+ /**
39
+ * Resolve API type from options, env, or model name heuristic.
40
+ */
41
+ private resolveApiType;
42
+ /** Pick API key and base URL from options or CLAUDEBUDDY_* env vars. */
43
+ private pickCredentials;
44
+ /**
45
+ * Read an env var by its short key using the CLAUDEBUDDY_ prefix.
46
+ * e.g. readEnv('MODEL') checks CLAUDEBUDDY_MODEL.
47
+ */
48
+ private readEnv;
49
+ /** Read a value from the options `env` map using the CLAUDEBUDDY_ prefix. */
50
+ private envMapValue;
51
+ /** Assemble the available tool set based on options. */
52
+ private buildToolPool;
53
+ /**
54
+ * Async initialization: connect MCP servers, register agents, resume sessions.
55
+ */
56
+ private setup;
57
+ /**
58
+ * Run a query with streaming events.
59
+ */
60
+ query(prompt: string | any[], overrides?: Partial<AgentOptions>): AsyncGenerator<SDKMessage, void>;
61
+ /**
62
+ * Convenience method: send a prompt and collect the final answer as a single object.
63
+ * Internally iterates through the streaming query and aggregates the outcome.
64
+ */
65
+ prompt(text: string, overrides?: Partial<AgentOptions>): Promise<QueryResult>;
66
+ /**
67
+ * Goal-driven autonomous loop.
68
+ *
69
+ * Runs the agent toward `goal` over up to `maxRounds` rounds. Unlike a single
70
+ * `query`, the agent keeps working ("give it a task and let it run until done")
71
+ * and only stops when:
72
+ * - it calls the injected `update_goal` tool with goal_status="complete", or
73
+ * - it reports goal_status="blocked", or
74
+ * - `maxRounds` is exhausted (returns with a helpful error event), or
75
+ * - it is aborted.
76
+ *
77
+ * The `update_goal` internal tool is injected into the tool pool and a
78
+ * goal-mode system prompt is appended, so the agent knows it should keep
79
+ * working autonomously and how to signal completion.
80
+ */
81
+ runGoal(goal: string, overrides?: {
82
+ maxGoalRounds?: number;
83
+ turnsPerRound?: number;
84
+ }): AsyncGenerator<SDKMessage, void>;
85
+ /**
86
+ * Get conversation messages.
87
+ */
88
+ getMessages(): Message[];
89
+ /**
90
+ * Reset conversation history.
91
+ */
92
+ clear(): void;
93
+ /**
94
+ * Interrupt the current query.
95
+ */
96
+ interrupt(): Promise<void>;
97
+ /**
98
+ * Change the model during a session.
99
+ */
100
+ setModel(model?: string): Promise<void>;
101
+ /**
102
+ * Change the permission mode during a session.
103
+ */
104
+ setPermissionMode(mode: PermissionMode): Promise<void>;
105
+ /**
106
+ * Set maximum thinking tokens.
107
+ */
108
+ setMaxThinkingTokens(maxThinkingTokens: number | null): Promise<void>;
109
+ /**
110
+ * Get the session ID.
111
+ */
112
+ getSessionId(): string;
113
+ /**
114
+ * Get the current API type.
115
+ */
116
+ getApiType(): ApiType;
117
+ /**
118
+ * Stop a background task.
119
+ */
120
+ stopTask(taskId: string): Promise<void>;
121
+ /**
122
+ * Close MCP connections and clean up.
123
+ * Optionally persist session to disk.
124
+ */
125
+ close(): Promise<void>;
126
+ }
127
+ /** Factory: shorthand for `new Agent(options)`. */
128
+ export declare function createAgent(options?: AgentOptions): Agent;
129
+ /**
130
+ * Execute a single agentic query without managing an Agent instance.
131
+ * The agent is created, used, and cleaned up automatically.
132
+ */
133
+ export declare function query(params: {
134
+ prompt: string | any[];
135
+ options?: AgentOptions;
136
+ }): AsyncGenerator<SDKMessage, void>;
137
+ //# sourceMappingURL=agent.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,KAAK,EACV,YAAY,EACZ,WAAW,EACX,UAAU,EAGV,OAAO,EACP,cAAc,EACf,MAAM,YAAY,CAAA;AAYnB,OAAO,EAAoC,KAAK,OAAO,EAAE,MAAM,sBAAsB,CAAA;AAarF,qBAAa,KAAK;IAChB,OAAO,CAAC,GAAG,CAAc;IACzB,OAAO,CAAC,QAAQ,CAAkB;IAClC,OAAO,CAAC,OAAO,CAAQ;IACvB,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,cAAc,CAAoC;IAC1D,OAAO,CAAC,QAAQ,CAAa;IAC7B,OAAO,CAAC,QAAQ,CAAsB;IACtC,OAAO,CAAC,OAAO,CAA+B;IAC9C,OAAO,CAAC,UAAU,CAAgB;IAClC,OAAO,CAAC,SAAS,CAAe;IAChC,OAAO,CAAC,GAAG,CAAQ;IACnB,OAAO,CAAC,SAAS,CAA+B;IAChD,OAAO,CAAC,aAAa,CAA2B;IAChD,OAAO,CAAC,YAAY,CAAc;gBAEtB,OAAO,GAAE,YAAiB;IAkDtC;;OAEG;IACH,OAAO,CAAC,cAAc;IAgCtB,wEAAwE;IACxE,OAAO,CAAC,eAAe;IAevB;;;OAGG;IACH,OAAO,CAAC,OAAO;IAIf,6EAA6E;IAC7E,OAAO,CAAC,WAAW;IAInB,wDAAwD;IACxD,OAAO,CAAC,aAAa;IAerB;;OAEG;YACW,KAAK;IA2CnB;;OAEG;IACI,KAAK,CACV,MAAM,EAAE,MAAM,GAAG,GAAG,EAAE,EACtB,SAAS,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,GAChC,cAAc,CAAC,UAAU,EAAE,IAAI,CAAC;IAuInC;;;OAGG;IACG,MAAM,CACV,IAAI,EAAE,MAAM,EACZ,SAAS,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,GAChC,OAAO,CAAC,WAAW,CAAC;IA+BvB;;;;;;;;;;;;;;OAcG;IACI,OAAO,CACZ,IAAI,EAAE,MAAM,EACZ,SAAS,CAAC,EAAE;QAAE,aAAa,CAAC,EAAE,MAAM,CAAC;QAAC,aAAa,CAAC,EAAE,MAAM,CAAA;KAAE,GAC7D,cAAc,CAAC,UAAU,EAAE,IAAI,CAAC;IAyFnC;;OAEG;IACH,WAAW,IAAI,OAAO,EAAE;IAIxB;;OAEG;IACH,KAAK,IAAI,IAAI;IAKb;;OAEG;IACG,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC;IAIhC;;OAEG;IACG,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAO7C;;OAEG;IACG,iBAAiB,CAAC,IAAI,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IAI5D;;OAEG;IACG,oBAAoB,CAAC,iBAAiB,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAQ3E;;OAEG;IACH,YAAY,IAAI,MAAM;IAItB;;OAEG;IACH,UAAU,IAAI,OAAO;IAIrB;;OAEG;IACG,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAQ7C;;;OAGG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAmB7B;AAMD,mDAAmD;AACnD,wBAAgB,WAAW,CAAC,OAAO,GAAE,YAAiB,GAAG,KAAK,CAE7D;AAMD;;;GAGG;AACH,wBAAuB,KAAK,CAAC,MAAM,EAAE;IACnC,MAAM,EAAE,MAAM,GAAG,GAAG,EAAE,CAAA;IACtB,OAAO,CAAC,EAAE,YAAY,CAAA;CACvB,GAAG,cAAc,CAAC,UAAU,EAAE,IAAI,CAAC,CAOnC"}