@codeany/open-agent-sdk 0.1.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 (57) hide show
  1. package/.env.example +8 -0
  2. package/LICENSE +21 -0
  3. package/README.md +388 -0
  4. package/examples/01-simple-query.ts +43 -0
  5. package/examples/02-multi-tool.ts +44 -0
  6. package/examples/03-multi-turn.ts +39 -0
  7. package/examples/04-prompt-api.ts +29 -0
  8. package/examples/05-custom-system-prompt.ts +26 -0
  9. package/examples/06-mcp-server.ts +49 -0
  10. package/examples/07-custom-tools.ts +87 -0
  11. package/examples/08-official-api-compat.ts +38 -0
  12. package/examples/09-subagents.ts +48 -0
  13. package/examples/10-permissions.ts +40 -0
  14. package/examples/11-custom-mcp-tools.ts +101 -0
  15. package/examples/web/index.html +365 -0
  16. package/examples/web/server.ts +157 -0
  17. package/package.json +60 -0
  18. package/src/agent.ts +425 -0
  19. package/src/engine.ts +520 -0
  20. package/src/hooks.ts +261 -0
  21. package/src/index.ts +376 -0
  22. package/src/mcp/client.ts +150 -0
  23. package/src/sdk-mcp-server.ts +78 -0
  24. package/src/session.ts +227 -0
  25. package/src/tool-helper.ts +127 -0
  26. package/src/tools/agent-tool.ts +153 -0
  27. package/src/tools/ask-user.ts +79 -0
  28. package/src/tools/bash.ts +75 -0
  29. package/src/tools/config-tool.ts +89 -0
  30. package/src/tools/cron-tools.ts +153 -0
  31. package/src/tools/edit.ts +74 -0
  32. package/src/tools/glob.ts +77 -0
  33. package/src/tools/grep.ts +168 -0
  34. package/src/tools/index.ts +232 -0
  35. package/src/tools/lsp-tool.ts +163 -0
  36. package/src/tools/mcp-resource-tools.ts +125 -0
  37. package/src/tools/notebook-edit.ts +93 -0
  38. package/src/tools/plan-tools.ts +88 -0
  39. package/src/tools/read.ts +73 -0
  40. package/src/tools/send-message.ts +96 -0
  41. package/src/tools/task-tools.ts +290 -0
  42. package/src/tools/team-tools.ts +128 -0
  43. package/src/tools/todo-tool.ts +112 -0
  44. package/src/tools/tool-search.ts +87 -0
  45. package/src/tools/types.ts +62 -0
  46. package/src/tools/web-fetch.ts +66 -0
  47. package/src/tools/web-search.ts +86 -0
  48. package/src/tools/worktree-tools.ts +140 -0
  49. package/src/tools/write.ts +42 -0
  50. package/src/types.ts +459 -0
  51. package/src/utils/compact.ts +206 -0
  52. package/src/utils/context.ts +191 -0
  53. package/src/utils/fileCache.ts +148 -0
  54. package/src/utils/messages.ts +196 -0
  55. package/src/utils/retry.ts +140 -0
  56. package/src/utils/tokens.ts +122 -0
  57. package/tsconfig.json +19 -0
package/.env.example ADDED
@@ -0,0 +1,8 @@
1
+ # Required: your LLM API key
2
+ CODEANY_API_KEY=sk-or-...
3
+
4
+ # Optional: override model
5
+ # CODEANY_MODEL=anthropic/claude-sonnet-4
6
+
7
+ # Optional: custom API endpoint (e.g. third-party proxy)
8
+ # CODEANY_BASE_URL=https://openrouter.ai/api
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,388 @@
1
+ # Open Agent SDK (TypeScript)
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@codeany/open-agent-sdk)](https://www.npmjs.com/package/@codeany/open-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. Deploy anywhere: cloud, serverless, Docker, CI/CD.
8
+
9
+ Also available in **Go**: [open-agent-sdk-go](https://github.com/codeany-ai/open-agent-sdk-go)
10
+
11
+ ## Get started
12
+
13
+ ```bash
14
+ npm install @codeany/open-agent-sdk
15
+ ```
16
+
17
+ Set your API key:
18
+
19
+ ```bash
20
+ export CODEANY_API_KEY=your-api-key
21
+ ```
22
+
23
+ Third-party providers (e.g. OpenRouter) are supported via `CODEANY_BASE_URL`:
24
+
25
+ ```bash
26
+ export CODEANY_BASE_URL=https://openrouter.ai/api
27
+ export CODEANY_API_KEY=sk-or-...
28
+ export CODEANY_MODEL=anthropic/claude-sonnet-4
29
+ ```
30
+
31
+ ## Quick start
32
+
33
+ ### One-shot query (streaming)
34
+
35
+ ```typescript
36
+ import { query } from "@codeany/open-agent-sdk";
37
+
38
+ for await (const message of query({
39
+ prompt: "Read package.json and tell me the project name.",
40
+ options: {
41
+ allowedTools: ["Read", "Glob"],
42
+ permissionMode: "bypassPermissions",
43
+ },
44
+ })) {
45
+ if (message.type === "assistant") {
46
+ for (const block of message.message.content) {
47
+ if ("text" in block) console.log(block.text);
48
+ }
49
+ }
50
+ }
51
+ ```
52
+
53
+ ### Simple blocking prompt
54
+
55
+ ```typescript
56
+ import { createAgent } from "@codeany/open-agent-sdk";
57
+
58
+ const agent = createAgent({ model: "claude-sonnet-4-6" });
59
+ const result = await agent.prompt("What files are in this project?");
60
+
61
+ console.log(result.text);
62
+ console.log(
63
+ `Turns: ${result.num_turns}, Tokens: ${result.usage.input_tokens + result.usage.output_tokens}`,
64
+ );
65
+ ```
66
+
67
+ ### Multi-turn conversation
68
+
69
+ ```typescript
70
+ import { createAgent } from "@codeany/open-agent-sdk";
71
+
72
+ const agent = createAgent({ maxTurns: 5 });
73
+
74
+ const r1 = await agent.prompt(
75
+ 'Create a file /tmp/hello.txt with "Hello World"',
76
+ );
77
+ console.log(r1.text);
78
+
79
+ const r2 = await agent.prompt("Read back the file you just created");
80
+ console.log(r2.text);
81
+
82
+ console.log(`Session messages: ${agent.getMessages().length}`);
83
+ ```
84
+
85
+ ### Custom tools (Zod schema)
86
+
87
+ ```typescript
88
+ import { z } from "zod";
89
+ import { query, tool, createSdkMcpServer } from "@codeany/open-agent-sdk";
90
+
91
+ const getWeather = tool(
92
+ "get_weather",
93
+ "Get the temperature for a city",
94
+ { city: z.string().describe("City name") },
95
+ async ({ city }) => ({
96
+ content: [{ type: "text", text: `${city}: 22°C, sunny` }],
97
+ }),
98
+ );
99
+
100
+ const server = createSdkMcpServer({ name: "weather", tools: [getWeather] });
101
+
102
+ for await (const msg of query({
103
+ prompt: "What is the weather in Tokyo?",
104
+ options: { mcpServers: { weather: server } },
105
+ })) {
106
+ if (msg.type === "result")
107
+ console.log(`Done: $${msg.total_cost_usd?.toFixed(4)}`);
108
+ }
109
+ ```
110
+
111
+ ### Custom tools (low-level)
112
+
113
+ ```typescript
114
+ import {
115
+ createAgent,
116
+ getAllBaseTools,
117
+ defineTool,
118
+ } from "@codeany/open-agent-sdk";
119
+
120
+ const calculator = defineTool({
121
+ name: "Calculator",
122
+ description: "Evaluate a math expression",
123
+ inputSchema: {
124
+ type: "object",
125
+ properties: { expression: { type: "string" } },
126
+ required: ["expression"],
127
+ },
128
+ isReadOnly: true,
129
+ async call(input) {
130
+ const result = Function(`'use strict'; return (${input.expression})`)();
131
+ return `${input.expression} = ${result}`;
132
+ },
133
+ });
134
+
135
+ const agent = createAgent({ tools: [...getAllBaseTools(), calculator] });
136
+ const r = await agent.prompt("Calculate 2**10 * 3");
137
+ console.log(r.text);
138
+ ```
139
+
140
+ ### MCP server integration
141
+
142
+ ```typescript
143
+ import { createAgent } from "@codeany/open-agent-sdk";
144
+
145
+ const agent = createAgent({
146
+ mcpServers: {
147
+ filesystem: {
148
+ command: "npx",
149
+ args: ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
150
+ },
151
+ },
152
+ });
153
+
154
+ const result = await agent.prompt("List files in /tmp");
155
+ console.log(result.text);
156
+ await agent.close();
157
+ ```
158
+
159
+ ### Subagents
160
+
161
+ ```typescript
162
+ import { query } from "@codeany/open-agent-sdk";
163
+
164
+ for await (const msg of query({
165
+ prompt: "Use the code-reviewer agent to review src/index.ts",
166
+ options: {
167
+ agents: {
168
+ "code-reviewer": {
169
+ description: "Expert code reviewer",
170
+ prompt: "Analyze code quality. Focus on security and performance.",
171
+ tools: ["Read", "Glob", "Grep"],
172
+ },
173
+ },
174
+ },
175
+ })) {
176
+ if (msg.type === "result") console.log("Done");
177
+ }
178
+ ```
179
+
180
+ ### Permissions
181
+
182
+ ```typescript
183
+ import { query } from "@codeany/open-agent-sdk";
184
+
185
+ // Read-only agent — can only analyze, not modify
186
+ for await (const msg of query({
187
+ prompt: "Review the code in src/ for best practices.",
188
+ options: {
189
+ allowedTools: ["Read", "Glob", "Grep"],
190
+ permissionMode: "dontAsk",
191
+ },
192
+ })) {
193
+ // ...
194
+ }
195
+ ```
196
+
197
+ ### Web UI
198
+
199
+ A built-in web chat interface is included for testing:
200
+
201
+ ```bash
202
+ npx tsx examples/web/server.ts
203
+ # Open http://localhost:8081
204
+ ```
205
+
206
+ ## API reference
207
+
208
+ ### Top-level functions
209
+
210
+ | Function | Description |
211
+ | ------------------------------------- | -------------------------------------------------------------- |
212
+ | `query({ prompt, options })` | One-shot streaming query, returns `AsyncGenerator<SDKMessage>` |
213
+ | `createAgent(options)` | Create a reusable agent with session persistence |
214
+ | `tool(name, desc, schema, handler)` | Create a tool with Zod schema validation |
215
+ | `createSdkMcpServer({ name, tools })` | Bundle tools into an in-process MCP server |
216
+ | `defineTool(config)` | Low-level tool definition helper |
217
+ | `getAllBaseTools()` | Get all 34 built-in tools |
218
+ | `listSessions()` | List persisted sessions |
219
+ | `getSessionMessages(id)` | Retrieve messages from a session |
220
+ | `forkSession(id)` | Fork a session for branching |
221
+
222
+ ### Agent methods
223
+
224
+ | Method | Description |
225
+ | ------------------------------- | ----------------------------------------------------- |
226
+ | `agent.query(prompt)` | Streaming query, returns `AsyncGenerator<SDKMessage>` |
227
+ | `agent.prompt(text)` | Blocking query, returns `Promise<QueryResult>` |
228
+ | `agent.getMessages()` | Get conversation history |
229
+ | `agent.clear()` | Reset session |
230
+ | `agent.interrupt()` | Abort current query |
231
+ | `agent.setModel(model)` | Change model mid-session |
232
+ | `agent.setPermissionMode(mode)` | Change permission mode |
233
+ | `agent.close()` | Close MCP connections, persist session |
234
+
235
+ ### Options
236
+
237
+ | Option | Type | Default | Description |
238
+ | -------------------- | --------------------------------------- | ---------------------- | -------------------------------------------------------------------- |
239
+ | `model` | `string` | `claude-sonnet-4-6` | LLM model ID |
240
+ | `apiKey` | `string` | `CODEANY_API_KEY` | API key |
241
+ | `baseURL` | `string` | — | Custom API endpoint |
242
+ | `cwd` | `string` | `process.cwd()` | Working directory |
243
+ | `systemPrompt` | `string` | — | System prompt override |
244
+ | `appendSystemPrompt` | `string` | — | Append to default system prompt |
245
+ | `tools` | `ToolDefinition[]` | All built-in | Available tools |
246
+ | `allowedTools` | `string[]` | — | Tool allow-list |
247
+ | `disallowedTools` | `string[]` | — | Tool deny-list |
248
+ | `permissionMode` | `string` | `bypassPermissions` | `default` / `acceptEdits` / `dontAsk` / `bypassPermissions` / `plan` |
249
+ | `canUseTool` | `function` | — | Custom permission callback |
250
+ | `maxTurns` | `number` | `10` | Max agentic turns |
251
+ | `maxBudgetUsd` | `number` | — | Spending cap |
252
+ | `thinking` | `ThinkingConfig` | `{ type: 'adaptive' }` | Extended thinking |
253
+ | `effort` | `string` | `high` | Reasoning effort: `low` / `medium` / `high` / `max` |
254
+ | `mcpServers` | `Record<string, McpServerConfig>` | — | MCP server connections |
255
+ | `agents` | `Record<string, AgentDefinition>` | — | Subagent definitions |
256
+ | `hooks` | `Record<string, HookCallbackMatcher[]>` | — | Lifecycle hooks |
257
+ | `resume` | `string` | — | Resume session by ID |
258
+ | `continue` | `boolean` | `false` | Continue most recent session |
259
+ | `persistSession` | `boolean` | `true` | Persist session to disk |
260
+ | `sessionId` | `string` | auto | Explicit session ID |
261
+ | `outputFormat` | `{ type: 'json_schema', schema }` | — | Structured output |
262
+ | `sandbox` | `SandboxSettings` | — | Filesystem/network sandbox |
263
+ | `settingSources` | `SettingSource[]` | — | Load AGENT.md, project settings |
264
+ | `env` | `Record<string, string>` | — | Environment variables |
265
+ | `abortController` | `AbortController` | — | Cancellation controller |
266
+
267
+ ### Environment variables
268
+
269
+ | Variable | Description |
270
+ | -------------------- | ---------------------- |
271
+ | `CODEANY_API_KEY` | API key (required) |
272
+ | `CODEANY_MODEL` | Default model override |
273
+ | `CODEANY_BASE_URL` | Custom API endpoint |
274
+ | `CODEANY_AUTH_TOKEN` | Alternative auth token |
275
+
276
+ ## Built-in tools
277
+
278
+ | Tool | Description |
279
+ | ------------------------------------------ | -------------------------------------------- |
280
+ | **Bash** | Execute shell commands |
281
+ | **Read** | Read files with line numbers |
282
+ | **Write** | Create / overwrite files |
283
+ | **Edit** | Precise string replacement in files |
284
+ | **Glob** | Find files by pattern |
285
+ | **Grep** | Search file contents with regex |
286
+ | **WebFetch** | Fetch and parse web content |
287
+ | **WebSearch** | Search the web |
288
+ | **NotebookEdit** | Edit Jupyter notebook cells |
289
+ | **Agent** | Spawn subagents for parallel work |
290
+ | **TaskCreate/List/Update/Get/Stop/Output** | Task management system |
291
+ | **TeamCreate/Delete** | Multi-agent team coordination |
292
+ | **SendMessage** | Inter-agent messaging |
293
+ | **EnterWorktree/ExitWorktree** | Git worktree isolation |
294
+ | **EnterPlanMode/ExitPlanMode** | Structured planning workflow |
295
+ | **AskUserQuestion** | Ask the user for input |
296
+ | **ToolSearch** | Discover lazy-loaded tools |
297
+ | **ListMcpResources/ReadMcpResource** | MCP resource access |
298
+ | **CronCreate/Delete/List** | Scheduled task management |
299
+ | **RemoteTrigger** | Remote agent triggers |
300
+ | **LSP** | Language Server Protocol (code intelligence) |
301
+ | **Config** | Dynamic configuration |
302
+ | **TodoWrite** | Session todo list |
303
+
304
+ ## Architecture
305
+
306
+ ```
307
+ ┌──────────────────────────────────────────────────────┐
308
+ │ Your Application │
309
+ │ │
310
+ │ import { createAgent } from '@codeany/open-agent-sdk' │
311
+ └────────────────────────┬─────────────────────────────┘
312
+
313
+ ┌──────────▼──────────┐
314
+ │ Agent │ Session state, tool pool,
315
+ │ query() / prompt() │ MCP connections
316
+ └──────────┬──────────┘
317
+
318
+ ┌──────────▼──────────┐
319
+ │ QueryEngine │ Agentic loop:
320
+ │ submitMessage() │ API call → tools → repeat
321
+ └──────────┬──────────┘
322
+
323
+ ┌───────────────┼───────────────┐
324
+ │ │ │
325
+ ┌─────▼─────┐ ┌─────▼─────┐ ┌─────▼─────┐
326
+ │ LLM API │ │ 34 Tools │ │ MCP │
327
+ │ Client │ │ Bash,Read │ │ Servers │
328
+ │ (streaming)│ │ Edit,... │ │ stdio/SSE/ │
329
+ └───────────┘ └───────────┘ │ HTTP/SDK │
330
+ └───────────┘
331
+ ```
332
+
333
+ **Key internals:**
334
+
335
+ | Component | Description |
336
+ | --------------------- | ---------------------------------------------------------------- |
337
+ | **QueryEngine** | Core agentic loop with auto-compact, retry, tool orchestration |
338
+ | **Auto-compact** | Summarizes conversation when context window fills up |
339
+ | **Micro-compact** | Truncates oversized tool results |
340
+ | **Retry** | Exponential backoff for rate limits and transient errors |
341
+ | **Token estimation** | Rough token counting for budget and compaction thresholds |
342
+ | **File cache** | LRU cache (100 entries, 25 MB) for file reads |
343
+ | **Hook system** | 20 lifecycle events (PreToolUse, PostToolUse, SessionStart, ...) |
344
+ | **Session storage** | Persist / resume / fork sessions on disk |
345
+ | **Context injection** | Git status + AGENT.md automatically injected into system prompt |
346
+
347
+ ## Examples
348
+
349
+ | # | File | Description |
350
+ | --- | ------------------------------------- | -------------------------------------- |
351
+ | 01 | `examples/01-simple-query.ts` | Streaming query with event handling |
352
+ | 02 | `examples/02-multi-tool.ts` | Multi-tool orchestration (Glob + Bash) |
353
+ | 03 | `examples/03-multi-turn.ts` | Multi-turn session persistence |
354
+ | 04 | `examples/04-prompt-api.ts` | Blocking `prompt()` API |
355
+ | 05 | `examples/05-custom-system-prompt.ts` | Custom system prompt |
356
+ | 06 | `examples/06-mcp-server.ts` | MCP server integration |
357
+ | 07 | `examples/07-custom-tools.ts` | Custom tools with `defineTool()` |
358
+ | 08 | `examples/08-official-api-compat.ts` | `query()` API pattern |
359
+ | 09 | `examples/09-subagents.ts` | Subagent delegation |
360
+ | 10 | `examples/10-permissions.ts` | Read-only agent with tool restrictions |
361
+ | 11 | `examples/11-custom-mcp-tools.ts` | `tool()` + `createSdkMcpServer()` |
362
+ | web | `examples/web/` | Web chat UI for testing |
363
+
364
+ Run any example:
365
+
366
+ ```bash
367
+ npx tsx examples/01-simple-query.ts
368
+ ```
369
+
370
+ Start the web UI:
371
+
372
+ ```bash
373
+ npx tsx examples/web/server.ts
374
+ ```
375
+
376
+ ## Star History
377
+
378
+ <a href="https://www.star-history.com/?repos=shipany-ai%2Fopen-agent-sdk&type=timeline&legend=top-left">
379
+ <picture>
380
+ <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/image?repos=shipany-ai/open-agent-sdk&type=timeline&theme=dark&legend=top-left" />
381
+ <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/image?repos=shipany-ai/open-agent-sdk&type=timeline&legend=top-left" />
382
+ <img alt="Star History Chart" src="https://api.star-history.com/image?repos=shipany-ai/open-agent-sdk&type=timeline&legend=top-left" />
383
+ </picture>
384
+ </a>
385
+
386
+ ## License
387
+
388
+ MIT
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Example 1: Simple Query with Streaming
3
+ *
4
+ * Demonstrates the basic createAgent() + query() flow with
5
+ * real-time event streaming.
6
+ *
7
+ * Run: npx tsx examples/01-simple-query.ts
8
+ */
9
+ import { createAgent } from '../src/index.js'
10
+
11
+ async function main() {
12
+ console.log('--- Example 1: Simple Query ---\n')
13
+
14
+ const agent = createAgent({
15
+ model: process.env.CODEANY_MODEL || 'claude-sonnet-4-6',
16
+ maxTurns: 10,
17
+ })
18
+
19
+ for await (const event of agent.query(
20
+ 'Read package.json and tell me the project name and version in one sentence.',
21
+ )) {
22
+ const msg = event as any
23
+
24
+ if (msg.type === 'assistant') {
25
+ // Print tool calls
26
+ for (const block of msg.message?.content || []) {
27
+ if (block.type === 'tool_use') {
28
+ console.log(`[Tool] ${block.name}(${JSON.stringify(block.input).slice(0, 80)})`)
29
+ }
30
+ if (block.type === 'text') {
31
+ console.log(`\nAssistant: ${block.text}`)
32
+ }
33
+ }
34
+ }
35
+
36
+ if (msg.type === 'result') {
37
+ console.log(`\n--- Result: ${msg.subtype} ---`)
38
+ console.log(`Tokens: ${msg.usage?.input_tokens} in / ${msg.usage?.output_tokens} out`)
39
+ }
40
+ }
41
+ }
42
+
43
+ main().catch(console.error)
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Example 2: Multi-Tool Orchestration
3
+ *
4
+ * The agent autonomously uses Glob, Bash, and Read tools to
5
+ * accomplish a multi-step task.
6
+ *
7
+ * Run: npx tsx examples/02-multi-tool.ts
8
+ */
9
+ import { createAgent } from '../src/index.js'
10
+
11
+ async function main() {
12
+ console.log('--- Example 2: Multi-Tool Orchestration ---\n')
13
+
14
+ const agent = createAgent({
15
+ model: process.env.CODEANY_MODEL || 'claude-sonnet-4-6',
16
+ maxTurns: 15,
17
+ })
18
+
19
+ for await (const event of agent.query(
20
+ 'Do these steps: ' +
21
+ '1) Use Glob to find all .ts files in src/ (pattern "src/*.ts"). ' +
22
+ '2) Use Bash to count lines in src/agent.ts with `wc -l`. ' +
23
+ '3) Give a brief summary.',
24
+ )) {
25
+ const msg = event as any
26
+
27
+ if (msg.type === 'assistant') {
28
+ for (const block of msg.message?.content || []) {
29
+ if (block.type === 'tool_use') {
30
+ console.log(`[${block.name}] ${JSON.stringify(block.input).slice(0, 100)}`)
31
+ }
32
+ if (block.type === 'text' && block.text.trim()) {
33
+ console.log(`\n${block.text}`)
34
+ }
35
+ }
36
+ }
37
+
38
+ if (msg.type === 'result') {
39
+ console.log(`\n--- ${msg.subtype} | ${msg.usage?.input_tokens}/${msg.usage?.output_tokens} tokens ---`)
40
+ }
41
+ }
42
+ }
43
+
44
+ main().catch(console.error)
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Example 3: Multi-Turn Conversation
3
+ *
4
+ * Demonstrates session persistence across multiple turns.
5
+ * The agent remembers context from previous interactions.
6
+ *
7
+ * Run: npx tsx examples/03-multi-turn.ts
8
+ */
9
+ import { createAgent } from '../src/index.js'
10
+
11
+ async function main() {
12
+ console.log('--- Example 3: Multi-Turn Conversation ---\n')
13
+
14
+ const agent = createAgent({
15
+ model: process.env.CODEANY_MODEL || 'claude-sonnet-4-6',
16
+ maxTurns: 5,
17
+ })
18
+
19
+ // Turn 1: Create a file
20
+ console.log('> Turn 1: Create a file')
21
+ const r1 = await agent.prompt(
22
+ 'Use Bash to run: echo "Hello Open Agent SDK" > /tmp/oas-test.txt. Confirm briefly.',
23
+ )
24
+ console.log(` ${r1.text}\n`)
25
+
26
+ // Turn 2: Read back (should remember context)
27
+ console.log('> Turn 2: Read the file back')
28
+ const r2 = await agent.prompt('Read the file you just created and tell me its contents.')
29
+ console.log(` ${r2.text}\n`)
30
+
31
+ // Turn 3: Clean up
32
+ console.log('> Turn 3: Cleanup')
33
+ const r3 = await agent.prompt('Delete that file with Bash. Confirm.')
34
+ console.log(` ${r3.text}\n`)
35
+
36
+ console.log(`Session history: ${agent.getMessages().length} messages`)
37
+ }
38
+
39
+ main().catch(console.error)
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Example 4: Simple Prompt API
3
+ *
4
+ * Uses the blocking prompt() method for quick one-shot queries.
5
+ * No need to iterate over streaming events.
6
+ *
7
+ * Run: npx tsx examples/04-prompt-api.ts
8
+ */
9
+ import { createAgent } from '../src/index.js'
10
+
11
+ async function main() {
12
+ console.log('--- Example 4: Simple Prompt API ---\n')
13
+
14
+ const agent = createAgent({
15
+ model: process.env.CODEANY_MODEL || 'claude-sonnet-4-6',
16
+ maxTurns: 5,
17
+ })
18
+
19
+ const result = await agent.prompt(
20
+ 'Use Bash to run `node --version` and `npm --version`, then tell me the versions.',
21
+ )
22
+
23
+ console.log(`Answer: ${result.text}`)
24
+ console.log(`Turns: ${result.num_turns}`)
25
+ console.log(`Tokens: ${result.usage.input_tokens} in / ${result.usage.output_tokens} out`)
26
+ console.log(`Duration: ${result.duration_ms}ms`)
27
+ }
28
+
29
+ main().catch(console.error)
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Example 5: Custom System Prompt
3
+ *
4
+ * Shows how to customize the agent's behavior with a system prompt.
5
+ *
6
+ * Run: npx tsx examples/05-custom-system-prompt.ts
7
+ */
8
+ import { createAgent } from '../src/index.js'
9
+
10
+ async function main() {
11
+ console.log('--- Example 5: Custom System Prompt ---\n')
12
+
13
+ const agent = createAgent({
14
+ model: process.env.CODEANY_MODEL || 'claude-sonnet-4-6',
15
+ maxTurns: 5,
16
+ systemPrompt:
17
+ 'You are a senior code reviewer. When asked to review code, focus on: ' +
18
+ '1) Security issues, 2) Performance concerns, 3) Maintainability. ' +
19
+ 'Be concise and use bullet points.',
20
+ })
21
+
22
+ const result = await agent.prompt('Read src/agent.ts and give a brief code review.')
23
+ console.log(result.text)
24
+ }
25
+
26
+ main().catch(console.error)
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Example 6: MCP Server Integration
3
+ *
4
+ * Connects to an MCP (Model Context Protocol) server and uses
5
+ * its tools through the agent. This example uses the filesystem
6
+ * MCP server as a demonstration.
7
+ *
8
+ * Prerequisites:
9
+ * npm install -g @modelcontextprotocol/server-filesystem
10
+ *
11
+ * Run: npx tsx examples/06-mcp-server.ts
12
+ */
13
+ import { createAgent } from '../src/index.js'
14
+
15
+ async function main() {
16
+ console.log('--- Example 6: MCP Server Integration ---\n')
17
+
18
+ const agent = createAgent({
19
+ model: process.env.CODEANY_MODEL || 'claude-sonnet-4-6',
20
+ maxTurns: 10,
21
+ mcpServers: {
22
+ filesystem: {
23
+ command: 'npx',
24
+ args: ['-y', '@modelcontextprotocol/server-filesystem', '/tmp'],
25
+ },
26
+ },
27
+ })
28
+
29
+ console.log('Connecting to MCP filesystem server...\n')
30
+
31
+ const result = await agent.prompt(
32
+ 'Use the filesystem MCP tools to list files in /tmp. Be brief.',
33
+ )
34
+
35
+ console.log(`Answer: ${result.text}`)
36
+ console.log(`Turns: ${result.num_turns}`)
37
+
38
+ await agent.close()
39
+ }
40
+
41
+ main().catch(e => {
42
+ console.error('Error:', e.message)
43
+ if (e.message.includes('ENOENT') || e.message.includes('not found')) {
44
+ console.error(
45
+ '\nMCP server not found. Install it with:\n' +
46
+ ' npm install -g @modelcontextprotocol/server-filesystem\n',
47
+ )
48
+ }
49
+ })