@rozek/nanoclaw 1.2.17
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.
- package/.claude/settings.json +1 -0
- package/.claude/skills/add-compact/SKILL.md +135 -0
- package/.claude/skills/add-discord/SKILL.md +203 -0
- package/.claude/skills/add-gmail/SKILL.md +220 -0
- package/.claude/skills/add-image-vision/SKILL.md +94 -0
- package/.claude/skills/add-ollama-tool/SKILL.md +153 -0
- package/.claude/skills/add-parallel/SKILL.md +290 -0
- package/.claude/skills/add-pdf-reader/SKILL.md +104 -0
- package/.claude/skills/add-reactions/SKILL.md +117 -0
- package/.claude/skills/add-slack/SKILL.md +207 -0
- package/.claude/skills/add-telegram/SKILL.md +222 -0
- package/.claude/skills/add-telegram-swarm/SKILL.md +384 -0
- package/.claude/skills/add-voice-transcription/SKILL.md +148 -0
- package/.claude/skills/add-whatsapp/SKILL.md +372 -0
- package/.claude/skills/convert-to-apple-container/SKILL.md +175 -0
- package/.claude/skills/customize/SKILL.md +110 -0
- package/.claude/skills/debug/SKILL.md +349 -0
- package/.claude/skills/get-qodo-rules/SKILL.md +122 -0
- package/.claude/skills/get-qodo-rules/references/output-format.md +41 -0
- package/.claude/skills/get-qodo-rules/references/pagination.md +33 -0
- package/.claude/skills/get-qodo-rules/references/repository-scope.md +26 -0
- package/.claude/skills/qodo-pr-resolver/SKILL.md +326 -0
- package/.claude/skills/qodo-pr-resolver/resources/providers.md +329 -0
- package/.claude/skills/setup/SKILL.md +218 -0
- package/.claude/skills/update-nanoclaw/SKILL.md +235 -0
- package/.claude/skills/update-skills/SKILL.md +130 -0
- package/.claude/skills/use-local-whisper/SKILL.md +152 -0
- package/.claude/skills/x-integration/SKILL.md +417 -0
- package/.claude/skills/x-integration/agent.ts +243 -0
- package/.claude/skills/x-integration/host.ts +159 -0
- package/.claude/skills/x-integration/lib/browser.ts +148 -0
- package/.claude/skills/x-integration/lib/config.ts +62 -0
- package/.claude/skills/x-integration/scripts/like.ts +56 -0
- package/.claude/skills/x-integration/scripts/post.ts +66 -0
- package/.claude/skills/x-integration/scripts/quote.ts +80 -0
- package/.claude/skills/x-integration/scripts/reply.ts +74 -0
- package/.claude/skills/x-integration/scripts/retweet.ts +62 -0
- package/.claude/skills/x-integration/scripts/setup.ts +87 -0
- package/.env.example +1 -0
- package/.github/CODEOWNERS +10 -0
- package/.github/PULL_REQUEST_TEMPLATE.md +14 -0
- package/.github/workflows/bump-version.yml +32 -0
- package/.github/workflows/ci.yml +25 -0
- package/.github/workflows/merge-forward-skills.yml +160 -0
- package/.github/workflows/update-tokens.yml +42 -0
- package/.husky/pre-commit +1 -0
- package/.mcp.json +3 -0
- package/.nvmrc +1 -0
- package/.prettierrc +3 -0
- package/CHANGELOG.md +8 -0
- package/CLAUDE.md +64 -0
- package/CONTRIBUTING.md +23 -0
- package/CONTRIBUTORS.md +15 -0
- package/LICENSE +21 -0
- package/NanoClaw_with_Web-Support.md +290 -0
- package/README.md +261 -0
- package/README_zh.md +200 -0
- package/assets/nanoclaw-favicon.png +0 -0
- package/assets/nanoclaw-icon.png +0 -0
- package/assets/nanoclaw-logo-dark.png +0 -0
- package/assets/nanoclaw-logo.png +0 -0
- package/assets/nanoclaw-profile.jpeg +0 -0
- package/assets/nanoclaw-sales.png +0 -0
- package/assets/social-preview.jpg +0 -0
- package/config-examples/mount-allowlist.json +25 -0
- package/container/Dockerfile +70 -0
- package/container/agent-runner/package-lock.json +1524 -0
- package/container/agent-runner/package.json +21 -0
- package/container/agent-runner/src/index.ts +558 -0
- package/container/agent-runner/src/ipc-mcp-stdio.ts +338 -0
- package/container/agent-runner/tsconfig.json +15 -0
- package/container/build.sh +23 -0
- package/container/skills/agent-browser/SKILL.md +159 -0
- package/container/skills/capabilities/SKILL.md +100 -0
- package/container/skills/status/SKILL.md +104 -0
- package/dist/channels/index.d.ts +2 -0
- package/dist/channels/index.d.ts.map +1 -0
- package/dist/channels/index.js +9 -0
- package/dist/channels/index.js.map +1 -0
- package/dist/channels/registry.d.ts +13 -0
- package/dist/channels/registry.d.ts.map +1 -0
- package/dist/channels/registry.js +11 -0
- package/dist/channels/registry.js.map +1 -0
- package/dist/channels/registry.test.d.ts +2 -0
- package/dist/channels/registry.test.d.ts.map +1 -0
- package/dist/channels/registry.test.js +32 -0
- package/dist/channels/registry.test.js.map +1 -0
- package/dist/channels/web.d.ts +2 -0
- package/dist/channels/web.d.ts.map +1 -0
- package/dist/channels/web.js +1738 -0
- package/dist/channels/web.js.map +1 -0
- package/dist/cli.d.ts +11 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +182 -0
- package/dist/cli.js.map +1 -0
- package/dist/config.d.ts +19 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +36 -0
- package/dist/config.js.map +1 -0
- package/dist/container-runner.d.ts +44 -0
- package/dist/container-runner.d.ts.map +1 -0
- package/dist/container-runner.js +467 -0
- package/dist/container-runner.js.map +1 -0
- package/dist/container-runner.test.d.ts +2 -0
- package/dist/container-runner.test.d.ts.map +1 -0
- package/dist/container-runner.test.js +150 -0
- package/dist/container-runner.test.js.map +1 -0
- package/dist/container-runtime.d.ts +22 -0
- package/dist/container-runtime.d.ts.map +1 -0
- package/dist/container-runtime.js +96 -0
- package/dist/container-runtime.js.map +1 -0
- package/dist/container-runtime.test.d.ts +2 -0
- package/dist/container-runtime.test.d.ts.map +1 -0
- package/dist/container-runtime.test.js +93 -0
- package/dist/container-runtime.test.js.map +1 -0
- package/dist/credential-proxy.d.ts +21 -0
- package/dist/credential-proxy.d.ts.map +1 -0
- package/dist/credential-proxy.js +95 -0
- package/dist/credential-proxy.js.map +1 -0
- package/dist/credential-proxy.test.d.ts +2 -0
- package/dist/credential-proxy.test.d.ts.map +1 -0
- package/dist/credential-proxy.test.js +134 -0
- package/dist/credential-proxy.test.js.map +1 -0
- package/dist/db.d.ts +115 -0
- package/dist/db.d.ts.map +1 -0
- package/dist/db.js +549 -0
- package/dist/db.js.map +1 -0
- package/dist/db.test.d.ts +2 -0
- package/dist/db.test.d.ts.map +1 -0
- package/dist/db.test.js +360 -0
- package/dist/db.test.js.map +1 -0
- package/dist/env.d.ts +8 -0
- package/dist/env.d.ts.map +1 -0
- package/dist/env.js +42 -0
- package/dist/env.js.map +1 -0
- package/dist/formatting.test.d.ts +2 -0
- package/dist/formatting.test.d.ts.map +1 -0
- package/dist/formatting.test.js +183 -0
- package/dist/formatting.test.js.map +1 -0
- package/dist/group-folder.d.ts +5 -0
- package/dist/group-folder.d.ts.map +1 -0
- package/dist/group-folder.js +44 -0
- package/dist/group-folder.js.map +1 -0
- package/dist/group-folder.test.d.ts +2 -0
- package/dist/group-folder.test.d.ts.map +1 -0
- package/dist/group-folder.test.js +29 -0
- package/dist/group-folder.test.js.map +1 -0
- package/dist/group-queue.d.ts +34 -0
- package/dist/group-queue.d.ts.map +1 -0
- package/dist/group-queue.js +263 -0
- package/dist/group-queue.js.map +1 -0
- package/dist/group-queue.test.d.ts +2 -0
- package/dist/group-queue.test.d.ts.map +1 -0
- package/dist/group-queue.test.js +341 -0
- package/dist/group-queue.test.js.map +1 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +518 -0
- package/dist/index.js.map +1 -0
- package/dist/ipc-auth.test.d.ts +2 -0
- package/dist/ipc-auth.test.d.ts.map +1 -0
- package/dist/ipc-auth.test.js +434 -0
- package/dist/ipc-auth.test.js.map +1 -0
- package/dist/ipc.d.ts +32 -0
- package/dist/ipc.d.ts.map +1 -0
- package/dist/ipc.js +311 -0
- package/dist/ipc.js.map +1 -0
- package/dist/logger.d.ts +3 -0
- package/dist/logger.d.ts.map +1 -0
- package/dist/logger.js +14 -0
- package/dist/logger.js.map +1 -0
- package/dist/mount-security.d.ts +34 -0
- package/dist/mount-security.d.ts.map +1 -0
- package/dist/mount-security.js +325 -0
- package/dist/mount-security.js.map +1 -0
- package/dist/remote-control.d.ts +32 -0
- package/dist/remote-control.d.ts.map +1 -0
- package/dist/remote-control.js +185 -0
- package/dist/remote-control.js.map +1 -0
- package/dist/remote-control.test.d.ts +2 -0
- package/dist/remote-control.test.d.ts.map +1 -0
- package/dist/remote-control.test.js +321 -0
- package/dist/remote-control.test.js.map +1 -0
- package/dist/router.d.ts +8 -0
- package/dist/router.d.ts.map +1 -0
- package/dist/router.js +37 -0
- package/dist/router.js.map +1 -0
- package/dist/routing.test.d.ts +2 -0
- package/dist/routing.test.d.ts.map +1 -0
- package/dist/routing.test.js +81 -0
- package/dist/routing.test.js.map +1 -0
- package/dist/sender-allowlist.d.ts +14 -0
- package/dist/sender-allowlist.d.ts.map +1 -0
- package/dist/sender-allowlist.js +79 -0
- package/dist/sender-allowlist.js.map +1 -0
- package/dist/sender-allowlist.test.d.ts +2 -0
- package/dist/sender-allowlist.test.d.ts.map +1 -0
- package/dist/sender-allowlist.test.js +186 -0
- package/dist/sender-allowlist.test.js.map +1 -0
- package/dist/session-commands.d.ts +47 -0
- package/dist/session-commands.d.ts.map +1 -0
- package/dist/session-commands.js +102 -0
- package/dist/session-commands.js.map +1 -0
- package/dist/session-commands.test.d.ts +2 -0
- package/dist/session-commands.test.d.ts.map +1 -0
- package/dist/session-commands.test.js +190 -0
- package/dist/session-commands.test.js.map +1 -0
- package/dist/task-scheduler.d.ts +22 -0
- package/dist/task-scheduler.d.ts.map +1 -0
- package/dist/task-scheduler.js +210 -0
- package/dist/task-scheduler.js.map +1 -0
- package/dist/task-scheduler.test.d.ts +2 -0
- package/dist/task-scheduler.test.d.ts.map +1 -0
- package/dist/task-scheduler.test.js +107 -0
- package/dist/task-scheduler.test.js.map +1 -0
- package/dist/timezone.d.ts +6 -0
- package/dist/timezone.d.ts.map +1 -0
- package/dist/timezone.js +17 -0
- package/dist/timezone.js.map +1 -0
- package/dist/timezone.test.d.ts +2 -0
- package/dist/timezone.test.d.ts.map +1 -0
- package/dist/timezone.test.js +23 -0
- package/dist/timezone.test.js.map +1 -0
- package/dist/types.d.ts +78 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/docs/APPLE-CONTAINER-NETWORKING.md +90 -0
- package/docs/DEBUG_CHECKLIST.md +143 -0
- package/docs/REQUIREMENTS.md +196 -0
- package/docs/SDK_DEEP_DIVE.md +643 -0
- package/docs/SECURITY.md +122 -0
- package/docs/SPEC.md +785 -0
- package/docs/docker-sandboxes.md +359 -0
- package/docs/nanoclaw-architecture-final.md +1063 -0
- package/docs/nanorepo-architecture.md +168 -0
- package/docs/skills-as-branches.md +662 -0
- package/groups/global/CLAUDE.md +58 -0
- package/groups/main/CLAUDE.md +246 -0
- package/launchd/com.nanoclaw.plist +32 -0
- package/package.json +45 -0
- package/repo-tokens/README.md +113 -0
- package/repo-tokens/action.yml +186 -0
- package/repo-tokens/badge.svg +23 -0
- package/repo-tokens/examples/green.svg +14 -0
- package/repo-tokens/examples/red.svg +14 -0
- package/repo-tokens/examples/yellow-green.svg +14 -0
- package/repo-tokens/examples/yellow.svg +14 -0
- package/scripts/run-migrations.ts +105 -0
- package/setup/container.ts +144 -0
- package/setup/environment.test.ts +121 -0
- package/setup/environment.ts +94 -0
- package/setup/groups.ts +229 -0
- package/setup/index.ts +58 -0
- package/setup/mounts.ts +115 -0
- package/setup/platform.test.ts +120 -0
- package/setup/platform.ts +132 -0
- package/setup/register.test.ts +257 -0
- package/setup/register.ts +177 -0
- package/setup/service.test.ts +187 -0
- package/setup/service.ts +362 -0
- package/setup/status.ts +16 -0
- package/setup/verify.ts +192 -0
- package/setup.sh +161 -0
- package/src/channels/index.ts +12 -0
- package/src/channels/registry.test.ts +42 -0
- package/src/channels/registry.ts +32 -0
- package/src/channels/web.ts +1856 -0
- package/src/cli.ts +209 -0
- package/src/config.ts +73 -0
- package/src/container-runner.test.ts +210 -0
- package/src/container-runner.ts +707 -0
- package/src/container-runtime.test.ts +149 -0
- package/src/container-runtime.ts +127 -0
- package/src/credential-proxy.test.ts +192 -0
- package/src/credential-proxy.ts +125 -0
- package/src/db.test.ts +484 -0
- package/src/db.ts +803 -0
- package/src/env.ts +42 -0
- package/src/formatting.test.ts +256 -0
- package/src/group-folder.test.ts +43 -0
- package/src/group-folder.ts +44 -0
- package/src/group-queue.test.ts +484 -0
- package/src/group-queue.ts +365 -0
- package/src/index.ts +731 -0
- package/src/ipc-auth.test.ts +679 -0
- package/src/ipc.ts +461 -0
- package/src/logger.ts +16 -0
- package/src/mount-security.ts +419 -0
- package/src/remote-control.test.ts +397 -0
- package/src/remote-control.ts +224 -0
- package/src/router.ts +52 -0
- package/src/routing.test.ts +170 -0
- package/src/sender-allowlist.test.ts +216 -0
- package/src/sender-allowlist.ts +128 -0
- package/src/session-commands.test.ts +247 -0
- package/src/session-commands.ts +163 -0
- package/src/task-scheduler.test.ts +129 -0
- package/src/task-scheduler.ts +295 -0
- package/src/timezone.test.ts +29 -0
- package/src/timezone.ts +16 -0
- package/src/types.ts +107 -0
- package/tsconfig.json +20 -0
- package/vitest.config.ts +7 -0
- package/vitest.skills.config.ts +7 -0
|
@@ -0,0 +1,643 @@
|
|
|
1
|
+
# Claude Agent SDK Deep Dive
|
|
2
|
+
|
|
3
|
+
Findings from reverse-engineering `@anthropic-ai/claude-agent-sdk` v0.2.29–0.2.34 to understand how `query()` works, why agent teams subagents were being killed, and how to fix it. Supplemented with official SDK reference docs.
|
|
4
|
+
|
|
5
|
+
## Architecture
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
Agent Runner (our code)
|
|
9
|
+
└── query() → SDK (sdk.mjs)
|
|
10
|
+
└── spawns CLI subprocess (cli.js)
|
|
11
|
+
└── Claude API calls, tool execution
|
|
12
|
+
└── Task tool → spawns subagent subprocesses
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
The SDK spawns `cli.js` as a child process with `--output-format stream-json --input-format stream-json --print --verbose` flags. Communication happens via JSON-lines on stdin/stdout.
|
|
16
|
+
|
|
17
|
+
`query()` returns a `Query` object extending `AsyncGenerator<SDKMessage, void>`. Internally:
|
|
18
|
+
|
|
19
|
+
- SDK spawns CLI as a child process, communicates via stdin/stdout JSON lines
|
|
20
|
+
- SDK's `readMessages()` reads from CLI stdout, enqueues into internal stream
|
|
21
|
+
- `readSdkMessages()` async generator yields from that stream
|
|
22
|
+
- `[Symbol.asyncIterator]` returns `readSdkMessages()`
|
|
23
|
+
- Iterator returns `done: true` only when CLI closes stdout
|
|
24
|
+
|
|
25
|
+
Both V1 (`query()`) and V2 (`createSession`/`send`/`stream`) use the exact same three-layer architecture:
|
|
26
|
+
|
|
27
|
+
```
|
|
28
|
+
SDK (sdk.mjs) CLI Process (cli.js)
|
|
29
|
+
-------------- --------------------
|
|
30
|
+
XX Transport ------> stdin reader (bd1)
|
|
31
|
+
(spawn cli.js) |
|
|
32
|
+
$X Query <------ stdout writer
|
|
33
|
+
(JSON-lines) |
|
|
34
|
+
EZ() recursive generator
|
|
35
|
+
|
|
|
36
|
+
Anthropic Messages API
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## The Core Agent Loop (EZ)
|
|
40
|
+
|
|
41
|
+
Inside the CLI, the agentic loop is a **recursive async generator called `EZ()`**, not an iterative while loop:
|
|
42
|
+
|
|
43
|
+
```
|
|
44
|
+
EZ({ messages, systemPrompt, canUseTool, maxTurns, turnCount=1, ... })
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Each invocation = one API call to Claude (one "turn").
|
|
48
|
+
|
|
49
|
+
### Flow per turn:
|
|
50
|
+
|
|
51
|
+
1. **Prepare messages** — trim context, run compaction if needed
|
|
52
|
+
2. **Call the Anthropic API** (via `mW1` streaming function)
|
|
53
|
+
3. **Extract tool_use blocks** from the response
|
|
54
|
+
4. **Branch:**
|
|
55
|
+
- If **no tool_use blocks** → stop (run stop hooks, return)
|
|
56
|
+
- If **tool_use blocks present** → execute tools, increment turnCount, recurse
|
|
57
|
+
|
|
58
|
+
All complex logic — the agent loop, tool execution, background tasks, teammate orchestration — runs inside the CLI subprocess. `query()` is a thin transport wrapper.
|
|
59
|
+
|
|
60
|
+
## query() Options
|
|
61
|
+
|
|
62
|
+
Full `Options` type from the official docs:
|
|
63
|
+
|
|
64
|
+
| Property | Type | Default | Description |
|
|
65
|
+
|----------|------|---------|-------------|
|
|
66
|
+
| `abortController` | `AbortController` | `new AbortController()` | Controller for cancelling operations |
|
|
67
|
+
| `additionalDirectories` | `string[]` | `[]` | Additional directories Claude can access |
|
|
68
|
+
| `agents` | `Record<string, AgentDefinition>` | `undefined` | Programmatically define subagents (not agent teams — no orchestration) |
|
|
69
|
+
| `allowDangerouslySkipPermissions` | `boolean` | `false` | Required when using `permissionMode: 'bypassPermissions'` |
|
|
70
|
+
| `allowedTools` | `string[]` | All tools | List of allowed tool names |
|
|
71
|
+
| `betas` | `SdkBeta[]` | `[]` | Beta features (e.g., `['context-1m-2025-08-07']` for 1M context) |
|
|
72
|
+
| `canUseTool` | `CanUseTool` | `undefined` | Custom permission function for tool usage |
|
|
73
|
+
| `continue` | `boolean` | `false` | Continue the most recent conversation |
|
|
74
|
+
| `cwd` | `string` | `process.cwd()` | Current working directory |
|
|
75
|
+
| `disallowedTools` | `string[]` | `[]` | List of disallowed tool names |
|
|
76
|
+
| `enableFileCheckpointing` | `boolean` | `false` | Enable file change tracking for rewinding |
|
|
77
|
+
| `env` | `Dict<string>` | `process.env` | Environment variables |
|
|
78
|
+
| `executable` | `'bun' \| 'deno' \| 'node'` | Auto-detected | JavaScript runtime |
|
|
79
|
+
| `fallbackModel` | `string` | `undefined` | Model to use if primary fails |
|
|
80
|
+
| `forkSession` | `boolean` | `false` | When resuming, fork to a new session ID instead of continuing original |
|
|
81
|
+
| `hooks` | `Partial<Record<HookEvent, HookCallbackMatcher[]>>` | `{}` | Hook callbacks for events |
|
|
82
|
+
| `includePartialMessages` | `boolean` | `false` | Include partial message events (streaming) |
|
|
83
|
+
| `maxBudgetUsd` | `number` | `undefined` | Maximum budget in USD for the query |
|
|
84
|
+
| `maxThinkingTokens` | `number` | `undefined` | Maximum tokens for thinking process |
|
|
85
|
+
| `maxTurns` | `number` | `undefined` | Maximum conversation turns |
|
|
86
|
+
| `mcpServers` | `Record<string, McpServerConfig>` | `{}` | MCP server configurations |
|
|
87
|
+
| `model` | `string` | Default from CLI | Claude model to use |
|
|
88
|
+
| `outputFormat` | `{ type: 'json_schema', schema: JSONSchema }` | `undefined` | Structured output format |
|
|
89
|
+
| `pathToClaudeCodeExecutable` | `string` | Uses built-in | Path to Claude Code executable |
|
|
90
|
+
| `permissionMode` | `PermissionMode` | `'default'` | Permission mode |
|
|
91
|
+
| `plugins` | `SdkPluginConfig[]` | `[]` | Load custom plugins from local paths |
|
|
92
|
+
| `resume` | `string` | `undefined` | Session ID to resume |
|
|
93
|
+
| `resumeSessionAt` | `string` | `undefined` | Resume session at a specific message UUID |
|
|
94
|
+
| `sandbox` | `SandboxSettings` | `undefined` | Sandbox behavior configuration |
|
|
95
|
+
| `settingSources` | `SettingSource[]` | `[]` (none) | Which filesystem settings to load. Must include `'project'` to load CLAUDE.md |
|
|
96
|
+
| `stderr` | `(data: string) => void` | `undefined` | Callback for stderr output |
|
|
97
|
+
| `systemPrompt` | `string \| { type: 'preset'; preset: 'claude_code'; append?: string }` | `undefined` | System prompt. Use preset to get Claude Code's prompt, with optional `append` |
|
|
98
|
+
| `tools` | `string[] \| { type: 'preset'; preset: 'claude_code' }` | `undefined` | Tool configuration |
|
|
99
|
+
|
|
100
|
+
### PermissionMode
|
|
101
|
+
|
|
102
|
+
```typescript
|
|
103
|
+
type PermissionMode = 'default' | 'acceptEdits' | 'bypassPermissions' | 'plan';
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
### SettingSource
|
|
107
|
+
|
|
108
|
+
```typescript
|
|
109
|
+
type SettingSource = 'user' | 'project' | 'local';
|
|
110
|
+
// 'user' → ~/.claude/settings.json
|
|
111
|
+
// 'project' → .claude/settings.json (version controlled)
|
|
112
|
+
// 'local' → .claude/settings.local.json (gitignored)
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
When omitted, SDK loads NO filesystem settings (isolation by default). Precedence: local > project > user. Programmatic options always override filesystem settings.
|
|
116
|
+
|
|
117
|
+
### AgentDefinition
|
|
118
|
+
|
|
119
|
+
Programmatic subagents (NOT agent teams — these are simpler, no inter-agent coordination):
|
|
120
|
+
|
|
121
|
+
```typescript
|
|
122
|
+
type AgentDefinition = {
|
|
123
|
+
description: string; // When to use this agent
|
|
124
|
+
tools?: string[]; // Allowed tools (inherits all if omitted)
|
|
125
|
+
prompt: string; // Agent's system prompt
|
|
126
|
+
model?: 'sonnet' | 'opus' | 'haiku' | 'inherit';
|
|
127
|
+
}
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
### McpServerConfig
|
|
131
|
+
|
|
132
|
+
```typescript
|
|
133
|
+
type McpServerConfig =
|
|
134
|
+
| { type?: 'stdio'; command: string; args?: string[]; env?: Record<string, string> }
|
|
135
|
+
| { type: 'sse'; url: string; headers?: Record<string, string> }
|
|
136
|
+
| { type: 'http'; url: string; headers?: Record<string, string> }
|
|
137
|
+
| { type: 'sdk'; name: string; instance: McpServer } // in-process
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
### SdkBeta
|
|
141
|
+
|
|
142
|
+
```typescript
|
|
143
|
+
type SdkBeta = 'context-1m-2025-08-07';
|
|
144
|
+
// Enables 1M token context window for Opus 4.6, Sonnet 4.5, Sonnet 4
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
### CanUseTool
|
|
148
|
+
|
|
149
|
+
```typescript
|
|
150
|
+
type CanUseTool = (
|
|
151
|
+
toolName: string,
|
|
152
|
+
input: ToolInput,
|
|
153
|
+
options: { signal: AbortSignal; suggestions?: PermissionUpdate[] }
|
|
154
|
+
) => Promise<PermissionResult>;
|
|
155
|
+
|
|
156
|
+
type PermissionResult =
|
|
157
|
+
| { behavior: 'allow'; updatedInput: ToolInput; updatedPermissions?: PermissionUpdate[] }
|
|
158
|
+
| { behavior: 'deny'; message: string; interrupt?: boolean };
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
## SDKMessage Types
|
|
162
|
+
|
|
163
|
+
`query()` can yield 16 message types. The official docs show a simplified union of 7, but `sdk.d.ts` has the full set:
|
|
164
|
+
|
|
165
|
+
| Type | Subtype | Purpose |
|
|
166
|
+
|------|---------|---------|
|
|
167
|
+
| `system` | `init` | Session initialized, contains session_id, tools, model |
|
|
168
|
+
| `system` | `task_notification` | Background agent completed/failed/stopped |
|
|
169
|
+
| `system` | `compact_boundary` | Conversation was compacted |
|
|
170
|
+
| `system` | `status` | Status change (e.g. compacting) |
|
|
171
|
+
| `system` | `hook_started` | Hook execution started |
|
|
172
|
+
| `system` | `hook_progress` | Hook progress output |
|
|
173
|
+
| `system` | `hook_response` | Hook completed |
|
|
174
|
+
| `system` | `files_persisted` | Files saved |
|
|
175
|
+
| `assistant` | — | Claude's response (text + tool calls) |
|
|
176
|
+
| `user` | — | User message (internal) |
|
|
177
|
+
| `user` (replay) | — | Replayed user message on resume |
|
|
178
|
+
| `result` | `success` / `error_*` | Final result of a prompt processing round |
|
|
179
|
+
| `stream_event` | — | Partial streaming (when includePartialMessages) |
|
|
180
|
+
| `tool_progress` | — | Long-running tool progress |
|
|
181
|
+
| `auth_status` | — | Authentication state changes |
|
|
182
|
+
| `tool_use_summary` | — | Summary of preceding tool uses |
|
|
183
|
+
|
|
184
|
+
### SDKTaskNotificationMessage (sdk.d.ts:1507)
|
|
185
|
+
|
|
186
|
+
```typescript
|
|
187
|
+
type SDKTaskNotificationMessage = {
|
|
188
|
+
type: 'system';
|
|
189
|
+
subtype: 'task_notification';
|
|
190
|
+
task_id: string;
|
|
191
|
+
status: 'completed' | 'failed' | 'stopped';
|
|
192
|
+
output_file: string;
|
|
193
|
+
summary: string;
|
|
194
|
+
uuid: UUID;
|
|
195
|
+
session_id: string;
|
|
196
|
+
};
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
### SDKResultMessage (sdk.d.ts:1375)
|
|
200
|
+
|
|
201
|
+
Two variants with shared fields:
|
|
202
|
+
|
|
203
|
+
```typescript
|
|
204
|
+
// Shared fields on both variants:
|
|
205
|
+
// uuid, session_id, duration_ms, duration_api_ms, is_error, num_turns,
|
|
206
|
+
// total_cost_usd, usage: NonNullableUsage, modelUsage, permission_denials
|
|
207
|
+
|
|
208
|
+
// Success:
|
|
209
|
+
type SDKResultSuccess = {
|
|
210
|
+
type: 'result';
|
|
211
|
+
subtype: 'success';
|
|
212
|
+
result: string;
|
|
213
|
+
structured_output?: unknown;
|
|
214
|
+
// ...shared fields
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
// Error:
|
|
218
|
+
type SDKResultError = {
|
|
219
|
+
type: 'result';
|
|
220
|
+
subtype: 'error_during_execution' | 'error_max_turns' | 'error_max_budget_usd' | 'error_max_structured_output_retries';
|
|
221
|
+
errors: string[];
|
|
222
|
+
// ...shared fields
|
|
223
|
+
};
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
Useful fields on result: `total_cost_usd`, `duration_ms`, `num_turns`, `modelUsage` (per-model breakdown with `costUSD`, `inputTokens`, `outputTokens`, `contextWindow`).
|
|
227
|
+
|
|
228
|
+
### SDKAssistantMessage
|
|
229
|
+
|
|
230
|
+
```typescript
|
|
231
|
+
type SDKAssistantMessage = {
|
|
232
|
+
type: 'assistant';
|
|
233
|
+
uuid: UUID;
|
|
234
|
+
session_id: string;
|
|
235
|
+
message: APIAssistantMessage; // From Anthropic SDK
|
|
236
|
+
parent_tool_use_id: string | null; // Non-null when from subagent
|
|
237
|
+
};
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
### SDKSystemMessage (init)
|
|
241
|
+
|
|
242
|
+
```typescript
|
|
243
|
+
type SDKSystemMessage = {
|
|
244
|
+
type: 'system';
|
|
245
|
+
subtype: 'init';
|
|
246
|
+
uuid: UUID;
|
|
247
|
+
session_id: string;
|
|
248
|
+
apiKeySource: ApiKeySource;
|
|
249
|
+
cwd: string;
|
|
250
|
+
tools: string[];
|
|
251
|
+
mcp_servers: { name: string; status: string }[];
|
|
252
|
+
model: string;
|
|
253
|
+
permissionMode: PermissionMode;
|
|
254
|
+
slash_commands: string[];
|
|
255
|
+
output_style: string;
|
|
256
|
+
};
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
## Turn Behavior: When the Agent Stops vs Continues
|
|
260
|
+
|
|
261
|
+
### When the Agent STOPS (no more API calls)
|
|
262
|
+
|
|
263
|
+
**1. No tool_use blocks in response (THE PRIMARY CASE)**
|
|
264
|
+
|
|
265
|
+
Claude responded with text only — it decided it has completed the task. The API's `stop_reason` will be `"end_turn"`. The SDK does NOT make this decision — it's entirely driven by Claude's model output.
|
|
266
|
+
|
|
267
|
+
**2. Max turns exceeded** — Results in `SDKResultError` with `subtype: "error_max_turns"`.
|
|
268
|
+
|
|
269
|
+
**3. Abort signal** — User interruption via `abortController`.
|
|
270
|
+
|
|
271
|
+
**4. Budget exceeded** — `totalCost >= maxBudgetUsd` → `"error_max_budget_usd"`.
|
|
272
|
+
|
|
273
|
+
**5. Stop hook prevents continuation** — Hook returns `{preventContinuation: true}`.
|
|
274
|
+
|
|
275
|
+
### When the Agent CONTINUES (makes another API call)
|
|
276
|
+
|
|
277
|
+
**1. Response contains tool_use blocks (THE PRIMARY CASE)** — Execute tools, increment turnCount, recurse into EZ.
|
|
278
|
+
|
|
279
|
+
**2. max_output_tokens recovery** — Up to 3 retries with a "break your work into smaller pieces" context message.
|
|
280
|
+
|
|
281
|
+
**3. Stop hook blocking errors** — Errors fed back as context messages, loop continues.
|
|
282
|
+
|
|
283
|
+
**4. Model fallback** — Retry with fallback model (one-time).
|
|
284
|
+
|
|
285
|
+
### Decision Table
|
|
286
|
+
|
|
287
|
+
| Condition | Action | Result Type |
|
|
288
|
+
|-----------|--------|-------------|
|
|
289
|
+
| Response has `tool_use` blocks | Execute tools, recurse into `EZ` | continues |
|
|
290
|
+
| Response has NO `tool_use` blocks | Run stop hooks, return | `success` |
|
|
291
|
+
| `turnCount > maxTurns` | Yield max_turns_reached | `error_max_turns` |
|
|
292
|
+
| `totalCost >= maxBudgetUsd` | Yield budget error | `error_max_budget_usd` |
|
|
293
|
+
| `abortController.signal.aborted` | Yield interrupted msg | depends on context |
|
|
294
|
+
| `stop_reason === "max_tokens"` (output) | Retry up to 3x with recovery prompt | continues |
|
|
295
|
+
| Stop hook `preventContinuation` | Return immediately | `success` |
|
|
296
|
+
| Stop hook blocking error | Feed error back, recurse | continues |
|
|
297
|
+
| Model fallback error | Retry with fallback model (one-time) | continues |
|
|
298
|
+
|
|
299
|
+
## Subagent Execution Modes
|
|
300
|
+
|
|
301
|
+
### Case 1: Synchronous Subagents (`run_in_background: false`) — BLOCKS
|
|
302
|
+
|
|
303
|
+
Parent agent calls Task tool → `VR()` runs `EZ()` for subagent → parent waits for full result → tool result returned to parent → parent continues.
|
|
304
|
+
|
|
305
|
+
The subagent runs the full recursive EZ loop. The parent's tool execution is suspended via `await`. There is a mid-execution "promotion" mechanism: a synchronous subagent can be promoted to background via `Promise.race()` against a `backgroundSignal` promise.
|
|
306
|
+
|
|
307
|
+
### Case 2: Background Tasks (`run_in_background: true`) — DOES NOT WAIT
|
|
308
|
+
|
|
309
|
+
- **Bash tool:** Command spawned, tool returns immediately with empty result + `backgroundTaskId`
|
|
310
|
+
- **Task/Agent tool:** Subagent launched in fire-and-forget wrapper (`g01()`), tool returns immediately with `status: "async_launched"` + `outputFile` path
|
|
311
|
+
|
|
312
|
+
Zero "wait for background tasks" logic before emitting the `type: "result"` message. When a background task completes, an `SDKTaskNotificationMessage` is emitted separately.
|
|
313
|
+
|
|
314
|
+
### Case 3: Agent Teams (TeammateTool / SendMessage) — RESULT FIRST, THEN POLLING
|
|
315
|
+
|
|
316
|
+
The team leader runs its normal EZ loop, which includes spawning teammates. When the leader's EZ loop finishes, `type: "result"` is emitted. Then the leader enters a post-result polling loop:
|
|
317
|
+
|
|
318
|
+
```javascript
|
|
319
|
+
while (true) {
|
|
320
|
+
// Check if no active teammates AND no running tasks → break
|
|
321
|
+
// Check for unread messages from teammates → re-inject as new prompt, restart EZ loop
|
|
322
|
+
// If stdin closed with active teammates → inject shutdown prompt
|
|
323
|
+
// Poll every 500ms
|
|
324
|
+
}
|
|
325
|
+
```
|
|
326
|
+
|
|
327
|
+
From the SDK consumer's perspective: you receive the initial `type: "result"`, but the AsyncGenerator may continue yielding more messages as the team leader processes teammate responses and re-enters the agent loop. The generator only truly finishes when all teammates have shut down.
|
|
328
|
+
|
|
329
|
+
## The isSingleUserTurn Problem
|
|
330
|
+
|
|
331
|
+
From sdk.mjs:
|
|
332
|
+
|
|
333
|
+
```javascript
|
|
334
|
+
QK = typeof X === "string" // isSingleUserTurn = true when prompt is a string
|
|
335
|
+
```
|
|
336
|
+
|
|
337
|
+
When `isSingleUserTurn` is true and the first `result` message arrives:
|
|
338
|
+
|
|
339
|
+
```javascript
|
|
340
|
+
if (this.isSingleUserTurn) {
|
|
341
|
+
this.transport.endInput(); // closes stdin to CLI
|
|
342
|
+
}
|
|
343
|
+
```
|
|
344
|
+
|
|
345
|
+
This triggers a chain reaction:
|
|
346
|
+
|
|
347
|
+
1. SDK closes CLI stdin
|
|
348
|
+
2. CLI detects stdin close
|
|
349
|
+
3. Polling loop sees `D = true` (stdin closed) with active teammates
|
|
350
|
+
4. Injects shutdown prompt → leader sends `shutdown_request` to all teammates
|
|
351
|
+
5. **Teammates get killed mid-research**
|
|
352
|
+
|
|
353
|
+
The shutdown prompt (found via `BGq` variable in minified cli.js):
|
|
354
|
+
|
|
355
|
+
```
|
|
356
|
+
You are running in non-interactive mode and cannot return a response
|
|
357
|
+
to the user until your team is shut down.
|
|
358
|
+
|
|
359
|
+
You MUST shut down your team before preparing your final response:
|
|
360
|
+
1. Use requestShutdown to ask each team member to shut down gracefully
|
|
361
|
+
2. Wait for shutdown approvals
|
|
362
|
+
3. Use the cleanup operation to clean up the team
|
|
363
|
+
4. Only then provide your final response to the user
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
### The practical problem
|
|
367
|
+
|
|
368
|
+
With V1 `query()` + string prompt + agent teams:
|
|
369
|
+
|
|
370
|
+
1. Leader spawns teammates, they start researching
|
|
371
|
+
2. Leader's EZ loop ends ("I've dispatched the team, they're working on it")
|
|
372
|
+
3. `type: "result"` emitted
|
|
373
|
+
4. SDK sees `isSingleUserTurn = true` → closes stdin immediately
|
|
374
|
+
5. Polling loop detects stdin closed + active teammates → injects shutdown prompt
|
|
375
|
+
6. Leader sends `shutdown_request` to all teammates
|
|
376
|
+
7. **Teammates could be 10 seconds into a 5-minute research task and they get told to stop**
|
|
377
|
+
|
|
378
|
+
## The Fix: Streaming Input Mode
|
|
379
|
+
|
|
380
|
+
Instead of passing a string prompt (which sets `isSingleUserTurn = true`), pass an `AsyncIterable<SDKUserMessage>`:
|
|
381
|
+
|
|
382
|
+
```typescript
|
|
383
|
+
// Before (broken for agent teams):
|
|
384
|
+
query({ prompt: "do something" })
|
|
385
|
+
|
|
386
|
+
// After (keeps CLI alive):
|
|
387
|
+
query({ prompt: asyncIterableOfMessages })
|
|
388
|
+
```
|
|
389
|
+
|
|
390
|
+
When prompt is an `AsyncIterable`:
|
|
391
|
+
- `isSingleUserTurn = false`
|
|
392
|
+
- SDK does NOT close stdin after first result
|
|
393
|
+
- CLI stays alive, continues processing
|
|
394
|
+
- Background agents keep running
|
|
395
|
+
- `task_notification` messages flow through the iterator
|
|
396
|
+
- We control when to end the iterable
|
|
397
|
+
|
|
398
|
+
### Additional Benefit: Streaming New Messages
|
|
399
|
+
|
|
400
|
+
With the async iterable approach, we can push new incoming WhatsApp messages into the iterable while the agent is still working. Instead of queuing messages until the container exits and spawning a new container, we stream them directly into the running session.
|
|
401
|
+
|
|
402
|
+
### Intended Lifecycle with Agent Teams
|
|
403
|
+
|
|
404
|
+
With the async iterable fix (`isSingleUserTurn = false`), stdin stays open so the CLI never hits the teammate check or shutdown prompt injection:
|
|
405
|
+
|
|
406
|
+
```
|
|
407
|
+
1. system/init → session initialized
|
|
408
|
+
2. assistant/user → Claude reasoning, tool calls, tool results
|
|
409
|
+
3. ... → more assistant/user turns (spawning subagents, etc.)
|
|
410
|
+
4. result #1 → lead agent's first response (capture)
|
|
411
|
+
5. task_notification(s) → background agents complete/fail/stop
|
|
412
|
+
6. assistant/user → lead agent continues (processing subagent results)
|
|
413
|
+
7. result #2 → lead agent's follow-up response (capture)
|
|
414
|
+
8. [iterator done] → CLI closed stdout, all done
|
|
415
|
+
```
|
|
416
|
+
|
|
417
|
+
All results are meaningful — capture every one, not just the first.
|
|
418
|
+
|
|
419
|
+
## V1 vs V2 API
|
|
420
|
+
|
|
421
|
+
### V1: `query()` — One-shot async generator
|
|
422
|
+
|
|
423
|
+
```typescript
|
|
424
|
+
const q = query({ prompt: "...", options: {...} });
|
|
425
|
+
for await (const msg of q) { /* process events */ }
|
|
426
|
+
```
|
|
427
|
+
|
|
428
|
+
- When `prompt` is a string: `isSingleUserTurn = true` → stdin auto-closes after first result
|
|
429
|
+
- For multi-turn: must pass an `AsyncIterable<SDKUserMessage>` and manage coordination yourself
|
|
430
|
+
|
|
431
|
+
### V2: `createSession()` + `send()` / `stream()` — Persistent session
|
|
432
|
+
|
|
433
|
+
```typescript
|
|
434
|
+
await using session = unstable_v2_createSession({ model: "..." });
|
|
435
|
+
await session.send("first message");
|
|
436
|
+
for await (const msg of session.stream()) { /* events */ }
|
|
437
|
+
await session.send("follow-up");
|
|
438
|
+
for await (const msg of session.stream()) { /* events */ }
|
|
439
|
+
```
|
|
440
|
+
|
|
441
|
+
- `isSingleUserTurn = false` always → stdin stays open
|
|
442
|
+
- `send()` enqueues into an async queue (`QX`)
|
|
443
|
+
- `stream()` yields from the same message generator, stopping on `result` type
|
|
444
|
+
- Multi-turn is natural — just alternate `send()` / `stream()`
|
|
445
|
+
- V2 does NOT call V1 `query()` internally — both independently create Transport + Query
|
|
446
|
+
|
|
447
|
+
### Comparison Table
|
|
448
|
+
|
|
449
|
+
| Aspect | V1 | V2 |
|
|
450
|
+
|--------|----|----|
|
|
451
|
+
| `isSingleUserTurn` | `true` for string prompt | always `false` |
|
|
452
|
+
| Multi-turn | Requires managing `AsyncIterable` | Just call `send()`/`stream()` |
|
|
453
|
+
| stdin lifecycle | Auto-closes after first result | Stays open until `close()` |
|
|
454
|
+
| Agentic loop | Identical `EZ()` | Identical `EZ()` |
|
|
455
|
+
| Stop conditions | Same | Same |
|
|
456
|
+
| Session persistence | Must pass `resume` to new `query()` | Built-in via session object |
|
|
457
|
+
| API stability | Stable | Unstable preview (`unstable_v2_*` prefix) |
|
|
458
|
+
|
|
459
|
+
**Key finding: Zero difference in turn behavior.** Both use the same CLI process, the same `EZ()` recursive generator, and the same decision logic.
|
|
460
|
+
|
|
461
|
+
## Hook Events
|
|
462
|
+
|
|
463
|
+
```typescript
|
|
464
|
+
type HookEvent =
|
|
465
|
+
| 'PreToolUse' // Before tool execution
|
|
466
|
+
| 'PostToolUse' // After successful tool execution
|
|
467
|
+
| 'PostToolUseFailure' // After failed tool execution
|
|
468
|
+
| 'Notification' // Notification messages
|
|
469
|
+
| 'UserPromptSubmit' // User prompt submitted
|
|
470
|
+
| 'SessionStart' // Session started (startup/resume/clear/compact)
|
|
471
|
+
| 'SessionEnd' // Session ended
|
|
472
|
+
| 'Stop' // Agent stopping
|
|
473
|
+
| 'SubagentStart' // Subagent spawned
|
|
474
|
+
| 'SubagentStop' // Subagent stopped
|
|
475
|
+
| 'PreCompact' // Before conversation compaction
|
|
476
|
+
| 'PermissionRequest'; // Permission being requested
|
|
477
|
+
```
|
|
478
|
+
|
|
479
|
+
### Hook Configuration
|
|
480
|
+
|
|
481
|
+
```typescript
|
|
482
|
+
interface HookCallbackMatcher {
|
|
483
|
+
matcher?: string; // Optional tool name matcher
|
|
484
|
+
hooks: HookCallback[];
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
type HookCallback = (
|
|
488
|
+
input: HookInput,
|
|
489
|
+
toolUseID: string | undefined,
|
|
490
|
+
options: { signal: AbortSignal }
|
|
491
|
+
) => Promise<HookJSONOutput>;
|
|
492
|
+
```
|
|
493
|
+
|
|
494
|
+
### Hook Return Values
|
|
495
|
+
|
|
496
|
+
```typescript
|
|
497
|
+
type HookJSONOutput = AsyncHookJSONOutput | SyncHookJSONOutput;
|
|
498
|
+
|
|
499
|
+
type AsyncHookJSONOutput = { async: true; asyncTimeout?: number };
|
|
500
|
+
|
|
501
|
+
type SyncHookJSONOutput = {
|
|
502
|
+
continue?: boolean;
|
|
503
|
+
suppressOutput?: boolean;
|
|
504
|
+
stopReason?: string;
|
|
505
|
+
decision?: 'approve' | 'block';
|
|
506
|
+
systemMessage?: string;
|
|
507
|
+
reason?: string;
|
|
508
|
+
hookSpecificOutput?:
|
|
509
|
+
| { hookEventName: 'PreToolUse'; permissionDecision?: 'allow' | 'deny' | 'ask'; updatedInput?: Record<string, unknown> }
|
|
510
|
+
| { hookEventName: 'UserPromptSubmit'; additionalContext?: string }
|
|
511
|
+
| { hookEventName: 'SessionStart'; additionalContext?: string }
|
|
512
|
+
| { hookEventName: 'PostToolUse'; additionalContext?: string };
|
|
513
|
+
};
|
|
514
|
+
```
|
|
515
|
+
|
|
516
|
+
### Subagent Hooks (from sdk.d.ts)
|
|
517
|
+
|
|
518
|
+
```typescript
|
|
519
|
+
type SubagentStartHookInput = BaseHookInput & {
|
|
520
|
+
hook_event_name: 'SubagentStart';
|
|
521
|
+
agent_id: string;
|
|
522
|
+
agent_type: string;
|
|
523
|
+
};
|
|
524
|
+
|
|
525
|
+
type SubagentStopHookInput = BaseHookInput & {
|
|
526
|
+
hook_event_name: 'SubagentStop';
|
|
527
|
+
stop_hook_active: boolean;
|
|
528
|
+
agent_id: string;
|
|
529
|
+
agent_transcript_path: string;
|
|
530
|
+
agent_type: string;
|
|
531
|
+
};
|
|
532
|
+
|
|
533
|
+
// BaseHookInput = { session_id, transcript_path, cwd, permission_mode? }
|
|
534
|
+
```
|
|
535
|
+
|
|
536
|
+
## Query Interface Methods
|
|
537
|
+
|
|
538
|
+
The `Query` object (sdk.d.ts:931). Official docs list these public methods:
|
|
539
|
+
|
|
540
|
+
```typescript
|
|
541
|
+
interface Query extends AsyncGenerator<SDKMessage, void> {
|
|
542
|
+
interrupt(): Promise<void>; // Stop current execution (streaming input mode only)
|
|
543
|
+
rewindFiles(userMessageUuid: string): Promise<void>; // Restore files to state at message (needs enableFileCheckpointing)
|
|
544
|
+
setPermissionMode(mode: PermissionMode): Promise<void>; // Change permissions (streaming input mode only)
|
|
545
|
+
setModel(model?: string): Promise<void>; // Change model (streaming input mode only)
|
|
546
|
+
setMaxThinkingTokens(max: number | null): Promise<void>; // Change thinking tokens (streaming input mode only)
|
|
547
|
+
supportedCommands(): Promise<SlashCommand[]>; // Available slash commands
|
|
548
|
+
supportedModels(): Promise<ModelInfo[]>; // Available models
|
|
549
|
+
mcpServerStatus(): Promise<McpServerStatus[]>; // MCP server connection status
|
|
550
|
+
accountInfo(): Promise<AccountInfo>; // Authenticated user info
|
|
551
|
+
}
|
|
552
|
+
```
|
|
553
|
+
|
|
554
|
+
Found in sdk.d.ts but NOT in official docs (may be internal):
|
|
555
|
+
- `streamInput(stream)` — stream additional user messages
|
|
556
|
+
- `close()` — forcefully end the query
|
|
557
|
+
- `setMcpServers(servers)` — dynamically add/remove MCP servers
|
|
558
|
+
|
|
559
|
+
## Sandbox Configuration
|
|
560
|
+
|
|
561
|
+
```typescript
|
|
562
|
+
type SandboxSettings = {
|
|
563
|
+
enabled?: boolean;
|
|
564
|
+
autoAllowBashIfSandboxed?: boolean;
|
|
565
|
+
excludedCommands?: string[];
|
|
566
|
+
allowUnsandboxedCommands?: boolean;
|
|
567
|
+
network?: {
|
|
568
|
+
allowLocalBinding?: boolean;
|
|
569
|
+
allowUnixSockets?: string[];
|
|
570
|
+
allowAllUnixSockets?: boolean;
|
|
571
|
+
httpProxyPort?: number;
|
|
572
|
+
socksProxyPort?: number;
|
|
573
|
+
};
|
|
574
|
+
ignoreViolations?: {
|
|
575
|
+
file?: string[];
|
|
576
|
+
network?: string[];
|
|
577
|
+
};
|
|
578
|
+
};
|
|
579
|
+
```
|
|
580
|
+
|
|
581
|
+
When `allowUnsandboxedCommands` is true, the model can set `dangerouslyDisableSandbox: true` in Bash tool input, which falls back to the `canUseTool` permission handler.
|
|
582
|
+
|
|
583
|
+
## MCP Server Helpers
|
|
584
|
+
|
|
585
|
+
### tool()
|
|
586
|
+
|
|
587
|
+
Creates type-safe MCP tool definitions with Zod schemas:
|
|
588
|
+
|
|
589
|
+
```typescript
|
|
590
|
+
function tool<Schema extends ZodRawShape>(
|
|
591
|
+
name: string,
|
|
592
|
+
description: string,
|
|
593
|
+
inputSchema: Schema,
|
|
594
|
+
handler: (args: z.infer<ZodObject<Schema>>, extra: unknown) => Promise<CallToolResult>
|
|
595
|
+
): SdkMcpToolDefinition<Schema>
|
|
596
|
+
```
|
|
597
|
+
|
|
598
|
+
### createSdkMcpServer()
|
|
599
|
+
|
|
600
|
+
Creates an in-process MCP server (we use stdio instead for subagent inheritance):
|
|
601
|
+
|
|
602
|
+
```typescript
|
|
603
|
+
function createSdkMcpServer(options: {
|
|
604
|
+
name: string;
|
|
605
|
+
version?: string;
|
|
606
|
+
tools?: Array<SdkMcpToolDefinition<any>>;
|
|
607
|
+
}): McpSdkServerConfigWithInstance
|
|
608
|
+
```
|
|
609
|
+
|
|
610
|
+
## Internals Reference
|
|
611
|
+
|
|
612
|
+
### Key minified identifiers (sdk.mjs)
|
|
613
|
+
|
|
614
|
+
| Minified | Purpose |
|
|
615
|
+
|----------|---------|
|
|
616
|
+
| `s_` | V1 `query()` export |
|
|
617
|
+
| `e_` | `unstable_v2_createSession` |
|
|
618
|
+
| `Xx` | `unstable_v2_resumeSession` |
|
|
619
|
+
| `Qx` | `unstable_v2_prompt` |
|
|
620
|
+
| `U9` | V2 Session class (`send`/`stream`/`close`) |
|
|
621
|
+
| `XX` | ProcessTransport (spawns cli.js) |
|
|
622
|
+
| `$X` | Query class (JSON-line routing, async iterable) |
|
|
623
|
+
| `QX` | AsyncQueue (input stream buffer) |
|
|
624
|
+
|
|
625
|
+
### Key minified identifiers (cli.js)
|
|
626
|
+
|
|
627
|
+
| Minified | Purpose |
|
|
628
|
+
|----------|---------|
|
|
629
|
+
| `EZ` | Core recursive agentic loop (async generator) |
|
|
630
|
+
| `_t4` | Stop hook handler (runs when no tool_use blocks) |
|
|
631
|
+
| `PU1` | Streaming tool executor (parallel during API response) |
|
|
632
|
+
| `TP6` | Standard tool executor (after API response) |
|
|
633
|
+
| `GU1` | Individual tool executor |
|
|
634
|
+
| `lTq` | SDK session runner (calls EZ directly) |
|
|
635
|
+
| `bd1` | stdin reader (JSON-lines from transport) |
|
|
636
|
+
| `mW1` | Anthropic API streaming caller |
|
|
637
|
+
|
|
638
|
+
## Key Files
|
|
639
|
+
|
|
640
|
+
- `sdk.d.ts` — All type definitions (1777 lines)
|
|
641
|
+
- `sdk-tools.d.ts` — Tool input schemas
|
|
642
|
+
- `sdk.mjs` — SDK runtime (minified, 376KB)
|
|
643
|
+
- `cli.js` — CLI executable (minified, runs as subprocess)
|