coding-agents-sdk 0.16.0 → 0.17.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.
package/README.md CHANGED
@@ -17,6 +17,9 @@ bun add @anthropic-ai/claude-agent-sdk
17
17
  # for codex-sdk
18
18
  bun add @openai/codex-sdk
19
19
 
20
+ # for cursor-sdk
21
+ bun add @cursor/sdk
22
+
20
23
  # for createContainer({ type: "e2b", ... })
21
24
  bun add e2b
22
25
  ```
@@ -38,7 +41,11 @@ Before you call `await createAgent(...)`, make sure the runtime for that adapter
38
41
 
39
42
  SDK adapters and the `e2b` container provider are optional peer dependencies. Install only the ones you use.
40
43
 
41
- If one is missing, `createAgent()`, `createContainer()`, or the first `run()` surfaces an error that tells you which package to install.
44
+ Missing SDK peers reject `createAgent()` with an installation hint. A missing `e2b` peer rejects `createContainer()`. Missing CLI binaries are generally reported by the first `run()` as a failed result.
45
+
46
+ For `cursor-sdk`, pass `apiKey` explicitly and supply a `model` for a new local agent; `sessionId` resumes an existing one. It does not accept this library's `container` or `sandbox` options, nor `env` or `propagateEnv`.
47
+
48
+ The package supports TypeScript `^6.0.3 || ^7.0.0`. The examples use ESM, top-level `await`, and `await using`; use Bun or a Node setup that supports those features.
42
49
 
43
50
  Set `cwd` when the agent should run somewhere other than the current working directory.
44
51
 
@@ -46,7 +53,7 @@ Use `agent.capabilities` when you need to branch on features at runtime.
46
53
 
47
54
  Option names shared across adapters (like `permissionMode`) take adapter-specific values — check the adapter's `*RunOptions` type for the valid set.
48
55
 
49
- Claude and Codex CLI both keep automatic review separate from dangerous bypass:
56
+ Claude and Codex CLI both keep automatic review separate from dangerous bypass. The Claude SDK adapter defaults `permissionMode` to `"default"` when omitted, rather than opting into the upstream runtime's automatic mode.
50
57
 
51
58
  - Claude `"auto"` and Codex CLI `"auto-approve"` use model-based review to approve or deny permission requests; Codex uses its `workspace-write` sandbox
52
59
  - Claude `"bypassPermissions"` and Codex CLI `"bypass-sandbox"` disable permission checks; the Codex mode also disables its sandbox
@@ -187,6 +194,13 @@ Useful bits:
187
194
  - pass `sessionId` to `await createAgent(type, { sessionId })` to resume one explicitly
188
195
  - `reset()` forgets the stored session
189
196
  - Claude adapters and `pi-cli` support `fork()`
197
+ - `opencode-cli` supports `forkSession: true` on a run, not a `fork()` method
198
+
199
+ ## Permission requests
200
+
201
+ The Claude adapters support `onPermissionRequest()`. Register a handler before the run and return `{ decision: "allow" }` or `{ decision: "deny", message }`. An allow decision can include `updatedInput` to replace the tool input. Check `agent.capabilities.permissionRequests` before relying on a handler with another adapter.
202
+
203
+ `claude-code-cli-pty` uses a run-local hook for permission requests. Its callback bridge is not supported inside a container.
190
204
 
191
205
  ## Events
192
206
 
@@ -246,7 +260,7 @@ const spawner: ProcessSpawner = {
246
260
  };
247
261
  ```
248
262
 
249
- Pass `spawner` when creating a CLI agent. For `claude-code-cli` and `codex-cli`, the returned process must provide `stdin.write` and `stdin.end`.
263
+ Pass `spawner` when creating a non-PTY CLI agent. `claude-code-cli-pty` instead accepts a `pty` backend override. For `claude-code-cli` and `codex-cli`, the returned process must provide `stdin.write` and `stdin.end`.
250
264
 
251
265
  Stdin methods may complete synchronously or return `Promise<void>`; agents await their completion. Built-in spawners observe rejected write/EOF promises and retain the failure for `wait()`, so ignoring an operation's return value does not create a separate unhandled rejection.
252
266
 
@@ -262,13 +276,15 @@ This wrapper exposes MCP configuration directly on:
262
276
  - `claude-code-cli-pty`: `mcpConfig`, `mcpServers`
263
277
  - `claude-code-sdk`: `mcpServers`
264
278
  - `codex-cli`: `mcpConfig`, `mcpServers`
265
- - `opencode-cli`: MCP is supported by the runtime (configure via opencode's own settings)
279
+ - `cursor-sdk`: `mcpServers` using `CursorSdkMcpServerConfig`
266
280
 
267
- For `codex-sdk`, `gemini-cli`, and `pi-cli`, use the runtime's own MCP setup. This wrapper does not add separate MCP config options for them.
281
+ For `codex-sdk`, `cursor-cli`, `gemini-cli`, and `opencode-cli`, use the runtime's own MCP setup. This wrapper does not add dedicated MCP configuration options for them. `pi-cli` reports `mcp: false`.
282
+
283
+ Claude CLI adapters pass `mcpConfig` paths to the CLI, so those files must be visible inside the execution target. `codex-cli` reads its single `mcpConfig` JSON file in the host process and converts its `mcpServers` entries to CLI configuration arguments; use a host-readable path there.
268
284
 
269
285
  ## Containers
270
286
 
271
- Containers are supported on the CLI adapters: `claude-code-cli`, `claude-code-cli-pty`, `codex-cli`, `gemini-cli`, `opencode-cli`, and `pi-cli`.
287
+ Containers are supported on every CLI adapter, including `cursor-cli`. SDK adapters launch their vendor runtimes locally and do not support this library's `container` or `sandbox` options.
272
288
  Built-in container providers are:
273
289
 
274
290
  - `docker`
@@ -316,7 +332,9 @@ if (result.status === "completed") {
316
332
 
317
333
  Your image needs the runtime for the adapter you picked available inside the container. For `claude-code-cli-pty`, install both `claude` and `socat` in the image; the Stop hook also expects `sh` and `cat`.
318
334
 
319
- If you omit `cwd`, the agent uses `container.workdir`. The container is started automatically on the first run. Use `snapshotWorkdir()`, `diffWorkdir()`, and `releaseWorkdirSnapshot()` when you need a reliable before/after file diff.
335
+ If you omit `cwd`, the agent uses `container.workdir`. The agent starts a stopped or created execution target before a run. E2B creates or connects to its remote sandbox during `createContainer()`. Dispose the container separately from the agent; `await using` handles that when declared in the order shown above.
336
+
337
+ Use `snapshotWorkdir()`, `diffWorkdir()`, and `releaseWorkdirSnapshot()` when you need a before/after file diff. Start the container before taking the first snapshot.
320
338
 
321
339
  `propagateEnv` defaults depend on the execution target:
322
340
 
@@ -341,6 +359,7 @@ import { createAgent, createSandbox } from "coding-agents-sdk";
341
359
  await using sandbox = await createSandbox({
342
360
  type: "bubblewrap",
343
361
  workdir: process.cwd(),
362
+ shareNetwork: true,
344
363
  setEnv: {
345
364
  OPENAI_API_KEY: process.env.OPENAI_API_KEY ?? "",
346
365
  },
@@ -364,8 +383,8 @@ Notes:
364
383
  - `codex-cli`'s `sandboxMode` sets the Codex CLI `--sandbox` policy only when `permissionMode` is omitted or `"default"`; it is independent of the `sandbox` execution target option
365
384
  - if you omit `cwd`, the agent uses `sandbox.workdir`
366
385
  - keep network access enabled when the sandboxed CLI still needs to reach a hosted model API
367
- - `firejail` and `nsjail` are Linux-only and depend on the corresponding host binaries and kernel features being available
368
- - `nsjail` preserves `PATH` by default so relative adapter commands still launch, but other host env vars remain cleared unless you opt back in with `clearEnv: false`
369
- - `bubblewrap` and `nsjail` commonly use a private or remounted `/tmp`; if the host process writes helper files that the sandboxed CLI must read, you probably want to bind-mount `/tmp` or another host temp directory there
386
+ - all built-in sandbox providers require Linux and the corresponding host binary (`bwrap`, `firejail`, or `nsjail`); [Bubblewrap's documentation](https://github.com/containers/bubblewrap) describes its Linux namespace requirements
387
+ - `nsjail` clears its base environment and preserves `PATH` by default, then merges `setEnv` and the agent's process environment; suppress host variables with `propagateEnv: false` on the agent as well as the sandbox's default `clearEnv: true`
388
+ - `bubblewrap` and `nsjail` use a private `/tmp` by default; expose host-generated helper files through a bind mount or a shared temporary directory. For an exact `/tmp` bind with `nsjail`, also set `tmpfs: []` so its private tmpfs does not suppress the bind
370
389
  - `firejail` is more host-dependent than `bubblewrap`; `readOnly` plus `readWrite` tune path permissions inside Firejail's base filesystem, while allowlist-style confinement needs explicit `whitelist` / `blacklist` rules. Setting a synthetic `HOME` only redirects CLI state files; it does not hide the real host home by itself
371
390
  - in particular, `codex-cli` structured output (`schema`) and `claude-code-cli` `mcpServers` create helper files that should live on a sandbox-visible `/tmp`
@@ -1,4 +1,4 @@
1
1
  import{n as e}from"../../types-B72tDMEZ.mjs";import{i as t,n,r}from"../../util-B4HTdOSc.mjs";import{t as i}from"../../env-Cb8MIvH7.mjs";import{i as a,l as o,s,u as c}from"../../classify-error-DOqkMCcy.mjs";import{i as l,n as u,r as d,t as f}from"../../session-markers-Dt7TWdKY.mjs";import{t as p}from"../../SdkAgent-Dtsr8Ycr.mjs";import{query as m}from"@anthropic-ai/claude-agent-sdk";const h=(e,t)=>{if(n(e)&&typeof e[t]==`string`)return e[t]},g=(e,t)=>{if(n(e)&&typeof e[t]==`number`)return e[t]},_=e=>n(e)&&e.type===`text`&&typeof e.text==`string`,v=e=>n(e)&&e.type===`thinking`&&typeof e.thinking==`string`,y=e=>n(e)&&e.type===`tool_use`&&typeof e.id==`string`&&typeof e.name==`string`,b=e=>n(e)&&e.type===`tool_result`&&typeof e.tool_use_id==`string`,x=e=>{let t=n(e.message)?e.message.content:void 0;return Array.isArray(t)?t:[]},S=(e,t)=>h(e.message,`model`)??t.model??null,C=e=>{let t=n(e.message)?e.message.content:void 0;return typeof t==`string`?[t]:Array.isArray(t)?t:[]},w=e=>{if(typeof e==`string`||!Array.isArray(e))return e;let t=e.flatMap(e=>_(e)?[e.text]:[]);return t.length===e.length?t.join(`
2
2
  `):e},T=e=>{if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return}},E=e=>{let n=g(e.usage,`input_tokens`),r=g(e.usage,`cache_creation_input_tokens`),i=g(e.usage,`cache_read_input_tokens`),a=g(e.usage,`output_tokens`),o=t(n,r,i,a);return{durationMs:e.duration_ms,apiDurationMs:e.duration_api_ms,turns:e.num_turns,costUsd:e.total_cost_usd,inputTokens:n,cacheCreationInputTokens:r,cacheReadInputTokens:i,outputTokens:a,totalTokens:o}},D=e=>{if(`errors`in e&&Array.isArray(e.errors)){let t=e.errors.filter(e=>typeof e==`string`&&e.trim()!==``);if(t.length>0)return t.join(`
3
- `)}return e.subtype===`error_max_structured_output_retries`?`Structured output retries were exhausted.`:e.subtype},O=e=>`session_id`in e?e.session_id:void 0,k=(e,t,n)=>s(e,`message`,{sessionId:t,model:null,role:`system`,content:[c(n)],text:n}),A=(e,t,n)=>{let r=[],i=[],a=S(e,n);for(let n of x(e)){if(_(n)){r.push(s(t.runId,`message`,{sessionId:t.sessionId,model:a,role:`assistant`,content:[c(n.text)],text:n.text}));continue}if(v(n)){r.push(s(t.runId,`reasoning`,{sessionId:t.sessionId,model:a,content:[c(n.thinking)],text:n.thinking}));continue}y(n)&&(i.push({toolCallId:n.id,toolName:n.name,input:n.input}),r.push(s(t.runId,`tool-call`,{sessionId:t.sessionId,model:a,toolCallId:n.id,toolName:n.name,input:n.input})))}return{events:r,toolCalls:i}},j=(e,t)=>{let n=[];for(let r of C(e)){if(typeof r==`string`){n.push(s(t.runId,`message`,{sessionId:t.sessionId,model:null,role:`user`,content:[c(r)],text:r}));continue}if(_(r)){n.push(s(t.runId,`message`,{sessionId:t.sessionId,model:null,role:`user`,content:[c(r.text)],text:r.text}));continue}if(b(r)){let e=t.toolCalls.get(r.tool_use_id),i=w(r.content);n.push(s(t.runId,`tool-result`,{sessionId:t.sessionId,toolCallId:r.tool_use_id,toolName:e?.toolName,input:e?.input,output:i,isError:r.is_error,error:r.is_error?T(i):void 0}))}}return{events:n}},M=(e,t,n)=>t.toolCalls.has(e.tool_use_id)?{events:[]}:{events:[s(t.runId,`tool-call`,{sessionId:t.sessionId,model:n.model??null,toolCallId:e.tool_use_id,toolName:e.tool_name,input:void 0})],toolCalls:[{toolCallId:e.tool_use_id,toolName:e.tool_name}]},N=e=>{switch(e.subtype){case`init`:return;case`status`:return`status: ${e.status??`idle`}`;case`local_command_output`:return e.content;case`hook_started`:return`[hook_started] ${e.hook_name}`;case`hook_progress`:return`[hook_progress] ${e.hook_name}`;case`hook_response`:return`[hook_response] ${e.hook_name}: ${e.outcome}`;case`task_started`:return`[task_started] ${e.description}`;case`task_progress`:return`[task_progress] ${e.summary??e.description}`;case`task_notification`:return`[task_${e.status}] ${e.summary}`;case`compact_boundary`:return`[compact_boundary] ${e.compact_metadata.trigger}`;case`files_persisted`:return`[files_persisted] ${e.files.length} file${e.files.length===1?``:`s`}`;default:return}},P=(e,t)=>{let n=N(e);return n?{events:[k(t.runId,t.sessionId,n)]}:{events:[]}},F=(e,t)=>{switch(e.type){case`auth_status`:{let n=`authenticated`;return e.error?n=`auth error: ${e.error}`:e.isAuthenticating&&(n=`authenticating`),{events:[k(t.runId,t.sessionId,n)]}}case`prompt_suggestion`:return{events:[k(t.runId,t.sessionId,`prompt suggestion: ${e.suggestion}`)]};case`rate_limit_event`:return{events:[k(t.runId,t.sessionId,`rate limited: ${e.rate_limit_info.status}`)]};case`tool_use_summary`:return{events:[k(t.runId,t.sessionId,e.summary)]};default:return{events:[]}}},I=(e,t)=>{let n={stats:E(e)},i=`result`in e?e.result:void 0,a=e.subtype===`success`&&!e.is_error;typeof i==`string`&&(n.output={...n.output,text:i});let o=d(`structured_output`in e?e.structured_output:void 0,t,{isSuccess:a},`Structured output was requested but Claude Agent SDK did not return structured_output.`);if(o.value===void 0&&a&&t.schemaRequested&&typeof i==`string`)try{o.value=r(i),o.error=void 0}catch{}return o.value!==void 0&&(n.output={...n.output,value:o.value}),o.error&&(n.status=`failed`,n.error=o.error),a?n.error||(n.status=`completed`):(n.status=`failed`,n.error={kind:`provider`,message:D(e)}),{events:[],state:n}},L=(e,t,n={})=>{let r;switch(e.type){case`assistant`:r=A(e,t,n);break;case`result`:r=I(e,t);break;case`system`:r=P(e,t);break;case`tool_progress`:r=M(e,t,n);break;case`user`:r=j(e,t);break;case`auth_status`:case`prompt_suggestion`:case`rate_limit_event`:case`tool_use_summary`:r=F(e,t);break;default:r={events:[]}}let i=O(e);return i&&r.sessionId===void 0&&(r.sessionId=i),r},R={structuredOutput:!0,sessionResume:!0,imageInput:!1,mcp:!0,eventStreaming:!0,sessionFork:!0,permissionRequests:!0},z=e=>async(t,n,r)=>{let i=await e({toolName:t,input:n,toolUseId:r.toolUseID,signal:r.signal,reason:r.decisionReason,blockedPath:r.blockedPath,title:r.title,description:r.description});return i.decision===`allow`?{behavior:`allow`,updatedInput:i.updatedInput??n}:{behavior:`deny`,message:i.message??`Tool call denied.`}},B=(e,t)=>e?t?`${e}\n\n${t}`:e:t?{type:`preset`,preset:`claude_code`,append:t}:void 0,V=({prompt:e,options:t})=>m({prompt:e,options:t}),H=t=>{if(t===void 0||typeof t==`string`)return t;if(Array.isArray(t))throw new e(`settings must be an object or a path string.`);return t},U=(t,n)=>{if(n.command){if(n.url)throw new e(`mcpServers.${t} cannot set both command and url.`);if(n.headers)throw new e(`mcpServers.${t}.headers is only supported with url transports.`);if(n.cwd)throw new e(`mcpServers.${t}.cwd is not supported by claude-code-sdk.`);return{type:`stdio`,command:n.command,args:n.args,env:n.env}}if(n.url){if(n.args)throw new e(`mcpServers.${t}.args is only supported with command transports.`);if(n.env)throw new e(`mcpServers.${t}.env is only supported with command transports.`);if(n.cwd)throw new e(`mcpServers.${t}.cwd is not supported by claude-code-sdk.`);return{type:`http`,url:n.url,headers:n.headers}}throw new e(`mcpServers.${t} must set either command or url.`)},W=e=>{if(e)return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,U(e,t)]))};var G=class t extends p{type=`claude-code-sdk`;defaults;creationOptions;runDefaults;createQueryFn;command;forkOnNextRun;currentQuery;constructor(e={}){super({type:`claude-code-sdk`,capabilities:R,sessionId:e.sessionId,onEvent:e.onEvent}),this.command=e.command,this.defaults={cwd:e.cwd,model:e.model,systemPrompt:e.systemPrompt},this.creationOptions={...e,command:e.command,env:e.env?{...e.env}:void 0,executableArgs:e.executableArgs?[...e.executableArgs]:void 0,mcpServers:e.mcpServers?{...e.mcpServers}:void 0,settingSources:e.settingSources?[...e.settingSources]:void 0},this.runDefaults={allowedTools:e.allowedTools?[...e.allowedTools]:void 0,disallowedTools:e.disallowedTools?[...e.disallowedTools]:void 0,appendSystemPrompt:e.appendSystemPrompt,permissionMode:e.permissionMode,mcpServers:e.mcpServers?{...e.mcpServers}:void 0,forkSession:e.forkSession,maxTurns:e.maxTurns},this.createQueryFn=e.createQuery??V,this.forkOnNextRun=e.forkOnNextRun??!1}fork(){if(!this.sessionId)throw new e(`Cannot fork a Claude Code SDK agent before it has a sessionId.`);return new t({...this.creationOptions,sessionId:this.sessionId,forkSession:void 0,forkOnNextRun:!0})}get runRequestDefaults(){return this.defaults}onValidateRun(t,n){if((t.forkSession??this.runDefaults.forkSession??this.forkOnNextRun)&&!this.sessionId)throw new e(`forkSession requires an existing sessionId on the agent.`);if(t.maxTurns!==void 0&&(!Number.isInteger(t.maxTurns)||t.maxTurns<=0))throw new e(`maxTurns must be a positive integer.`)}onStopRequested(e){this.currentQuery?.interrupt?.().catch(()=>{}),super.onStopRequested(e)}async onDispose(){this.cleanupSdkResources()}cleanupSdkResources(){this.currentQuery?.close?.(),this.currentQuery=void 0}async executeSdkRun(e,t,n){let r=this.createQueryFn({prompt:o(e.normalizedRequest.input),options:this.buildQueryOptions(t,e,n)});this.currentQuery=r;for await(let t of r){let n=O(t)??e.sessionId;n&&e.sessionId!==n&&(e.sessionId=n,this.setSessionId(n),this.forkOnNextRun&&e.requestedSessionId&&n!==e.requestedSessionId&&(this.forkOnNextRun=!1));let r=L(t,a(e),{model:e.normalizedRequest.model});this.applyBatch(e,r)}}buildQueryOptions(e,t,n){let r=e.permissionMode??this.runDefaults.permissionMode,a=e.forkSession??this.runDefaults.forkSession??this.forkOnNextRun,o=e.appendSystemPrompt??this.runDefaults.appendSystemPrompt,c=i({propagateEnv:this.creationOptions.propagateEnv});this.creationOptions.env&&Object.assign(c,this.creationOptions.env),f(c);let d=this.getPermissionHandler();return{abortController:n,canUseTool:d?z(d):void 0,cwd:t.normalizedRequest.cwd,model:t.normalizedRequest.model,systemPrompt:B(t.normalizedRequest.systemPrompt,o),allowedTools:e.allowedTools??this.runDefaults.allowedTools,disallowedTools:l(e.disallowedTools??this.runDefaults.disallowedTools),mcpServers:W(e.mcpServers??this.runDefaults.mcpServers),maxTurns:e.maxTurns??this.runDefaults.maxTurns,outputFormat:t.normalizedRequest.schema.kind===`none`?void 0:{type:`json_schema`,schema:u(t.normalizedRequest.schema.jsonSchema)},permissionMode:r,allowDangerouslySkipPermissions:r===`bypassPermissions`||void 0,resume:t.requestedSessionId,forkSession:t.requestedSessionId?a:void 0,env:c,executable:this.creationOptions.executable,executableArgs:this.creationOptions.executableArgs,pathToClaudeCodeExecutable:this.command,settings:H(this.creationOptions.settings),settingSources:this.creationOptions.settingSources,stderr:e=>{for(let n of e.split(`
3
+ `)}return e.subtype===`error_max_structured_output_retries`?`Structured output retries were exhausted.`:e.subtype},O=e=>`session_id`in e?e.session_id:void 0,k=(e,t,n)=>s(e,`message`,{sessionId:t,model:null,role:`system`,content:[c(n)],text:n}),A=(e,t,n)=>{let r=[],i=[],a=S(e,n);for(let n of x(e)){if(_(n)){r.push(s(t.runId,`message`,{sessionId:t.sessionId,model:a,role:`assistant`,content:[c(n.text)],text:n.text}));continue}if(v(n)){r.push(s(t.runId,`reasoning`,{sessionId:t.sessionId,model:a,content:[c(n.thinking)],text:n.thinking}));continue}y(n)&&(i.push({toolCallId:n.id,toolName:n.name,input:n.input}),r.push(s(t.runId,`tool-call`,{sessionId:t.sessionId,model:a,toolCallId:n.id,toolName:n.name,input:n.input})))}return{events:r,toolCalls:i}},j=(e,t)=>{let n=[];for(let r of C(e)){if(typeof r==`string`){n.push(s(t.runId,`message`,{sessionId:t.sessionId,model:null,role:`user`,content:[c(r)],text:r}));continue}if(_(r)){n.push(s(t.runId,`message`,{sessionId:t.sessionId,model:null,role:`user`,content:[c(r.text)],text:r.text}));continue}if(b(r)){let e=t.toolCalls.get(r.tool_use_id),i=w(r.content);n.push(s(t.runId,`tool-result`,{sessionId:t.sessionId,toolCallId:r.tool_use_id,toolName:e?.toolName,input:e?.input,output:i,isError:r.is_error,error:r.is_error?T(i):void 0}))}}return{events:n}},M=(e,t,n)=>t.toolCalls.has(e.tool_use_id)?{events:[]}:{events:[s(t.runId,`tool-call`,{sessionId:t.sessionId,model:n.model??null,toolCallId:e.tool_use_id,toolName:e.tool_name,input:void 0})],toolCalls:[{toolCallId:e.tool_use_id,toolName:e.tool_name}]},N=e=>{switch(e.subtype){case`init`:return;case`status`:return`status: ${e.status??`idle`}`;case`local_command_output`:return e.content;case`hook_started`:return`[hook_started] ${e.hook_name}`;case`hook_progress`:return`[hook_progress] ${e.hook_name}`;case`hook_response`:return`[hook_response] ${e.hook_name}: ${e.outcome}`;case`task_started`:return`[task_started] ${e.description}`;case`task_progress`:return`[task_progress] ${e.summary??e.description}`;case`task_notification`:return`[task_${e.status}] ${e.summary}`;case`compact_boundary`:return`[compact_boundary] ${e.compact_metadata.trigger}`;case`files_persisted`:return`[files_persisted] ${e.files.length} file${e.files.length===1?``:`s`}`;default:return}},P=(e,t)=>{let n=N(e);return n?{events:[k(t.runId,t.sessionId,n)]}:{events:[]}},F=(e,t)=>{switch(e.type){case`auth_status`:{let n=`authenticated`;return e.error?n=`auth error: ${e.error}`:e.isAuthenticating&&(n=`authenticating`),{events:[k(t.runId,t.sessionId,n)]}}case`prompt_suggestion`:return{events:[k(t.runId,t.sessionId,`prompt suggestion: ${e.suggestion}`)]};case`rate_limit_event`:return{events:[k(t.runId,t.sessionId,`rate limited: ${e.rate_limit_info.status}`)]};case`tool_use_summary`:return{events:[k(t.runId,t.sessionId,e.summary)]};default:return{events:[]}}},I=(e,t)=>{let n={stats:E(e)},i=`result`in e?e.result:void 0,a=e.subtype===`success`&&!e.is_error;typeof i==`string`&&(n.output={...n.output,text:i});let o=d(`structured_output`in e?e.structured_output:void 0,t,{isSuccess:a},`Structured output was requested but Claude Agent SDK did not return structured_output.`);if(o.value===void 0&&a&&t.schemaRequested&&typeof i==`string`)try{o.value=r(i),o.error=void 0}catch{}return o.value!==void 0&&(n.output={...n.output,value:o.value}),o.error&&(n.status=`failed`,n.error=o.error),a?n.error||(n.status=`completed`):(n.status=`failed`,n.error={kind:`provider`,message:D(e)}),{events:[],state:n}},L=(e,t,n={})=>{let r;switch(e.type){case`assistant`:r=A(e,t,n);break;case`result`:r=I(e,t);break;case`system`:r=P(e,t);break;case`tool_progress`:r=M(e,t,n);break;case`user`:r=j(e,t);break;case`auth_status`:case`prompt_suggestion`:case`rate_limit_event`:case`tool_use_summary`:r=F(e,t);break;default:r={events:[]}}let i=O(e);return i&&r.sessionId===void 0&&(r.sessionId=i),r},R={structuredOutput:!0,sessionResume:!0,imageInput:!1,mcp:!0,eventStreaming:!0,sessionFork:!0,permissionRequests:!0},z=e=>async(t,n,r)=>{let i=await e({toolName:t,input:n,toolUseId:r.toolUseID,signal:r.signal,reason:r.decisionReason,blockedPath:r.blockedPath,title:r.title,description:r.description});return i.decision===`allow`?{behavior:`allow`,updatedInput:i.updatedInput??n}:{behavior:`deny`,message:i.message??`Tool call denied.`}},B=(e,t)=>e?t?`${e}\n\n${t}`:e:t?{type:`preset`,preset:`claude_code`,append:t}:void 0,V=({prompt:e,options:t})=>m({prompt:e,options:t}),H=t=>{if(t===void 0||typeof t==`string`)return t;if(Array.isArray(t))throw new e(`settings must be an object or a path string.`);return t},U=(t,n)=>{if(n.command){if(n.url)throw new e(`mcpServers.${t} cannot set both command and url.`);if(n.headers)throw new e(`mcpServers.${t}.headers is only supported with url transports.`);if(n.cwd)throw new e(`mcpServers.${t}.cwd is not supported by claude-code-sdk.`);return{type:`stdio`,command:n.command,args:n.args,env:n.env}}if(n.url){if(n.args)throw new e(`mcpServers.${t}.args is only supported with command transports.`);if(n.env)throw new e(`mcpServers.${t}.env is only supported with command transports.`);if(n.cwd)throw new e(`mcpServers.${t}.cwd is not supported by claude-code-sdk.`);return{type:`http`,url:n.url,headers:n.headers}}throw new e(`mcpServers.${t} must set either command or url.`)},W=e=>{if(e)return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,U(e,t)]))};var G=class t extends p{type=`claude-code-sdk`;defaults;creationOptions;runDefaults;createQueryFn;command;forkOnNextRun;currentQuery;constructor(e={}){super({type:`claude-code-sdk`,capabilities:R,sessionId:e.sessionId,onEvent:e.onEvent}),this.command=e.command,this.defaults={cwd:e.cwd,model:e.model,systemPrompt:e.systemPrompt},this.creationOptions={...e,command:e.command,env:e.env?{...e.env}:void 0,executableArgs:e.executableArgs?[...e.executableArgs]:void 0,mcpServers:e.mcpServers?{...e.mcpServers}:void 0,settingSources:e.settingSources?[...e.settingSources]:void 0},this.runDefaults={allowedTools:e.allowedTools?[...e.allowedTools]:void 0,disallowedTools:e.disallowedTools?[...e.disallowedTools]:void 0,appendSystemPrompt:e.appendSystemPrompt,permissionMode:e.permissionMode,mcpServers:e.mcpServers?{...e.mcpServers}:void 0,forkSession:e.forkSession,maxTurns:e.maxTurns},this.createQueryFn=e.createQuery??V,this.forkOnNextRun=e.forkOnNextRun??!1}fork(){if(!this.sessionId)throw new e(`Cannot fork a Claude Code SDK agent before it has a sessionId.`);return new t({...this.creationOptions,sessionId:this.sessionId,forkSession:void 0,forkOnNextRun:!0})}get runRequestDefaults(){return this.defaults}onValidateRun(t,n){if((t.forkSession??this.runDefaults.forkSession??this.forkOnNextRun)&&!this.sessionId)throw new e(`forkSession requires an existing sessionId on the agent.`);if(t.maxTurns!==void 0&&(!Number.isInteger(t.maxTurns)||t.maxTurns<=0))throw new e(`maxTurns must be a positive integer.`)}onStopRequested(e){this.currentQuery?.interrupt?.().catch(()=>{}),super.onStopRequested(e)}async onDispose(){this.cleanupSdkResources()}cleanupSdkResources(){this.currentQuery?.close?.(),this.currentQuery=void 0}async executeSdkRun(e,t,n){let r=this.createQueryFn({prompt:o(e.normalizedRequest.input),options:this.buildQueryOptions(t,e,n)});this.currentQuery=r;for await(let t of r){let n=O(t)??e.sessionId;n&&e.sessionId!==n&&(e.sessionId=n,this.setSessionId(n),this.forkOnNextRun&&e.requestedSessionId&&n!==e.requestedSessionId&&(this.forkOnNextRun=!1));let r=L(t,a(e),{model:e.normalizedRequest.model});this.applyBatch(e,r)}}buildQueryOptions(e,t,n){let r=e.permissionMode??this.runDefaults.permissionMode??`default`,a=e.forkSession??this.runDefaults.forkSession??this.forkOnNextRun,o=e.appendSystemPrompt??this.runDefaults.appendSystemPrompt,c=i({propagateEnv:this.creationOptions.propagateEnv});this.creationOptions.env&&Object.assign(c,this.creationOptions.env),f(c);let d=this.getPermissionHandler();return{abortController:n,canUseTool:d?z(d):void 0,cwd:t.normalizedRequest.cwd,model:t.normalizedRequest.model,systemPrompt:B(t.normalizedRequest.systemPrompt,o),allowedTools:e.allowedTools??this.runDefaults.allowedTools,disallowedTools:l(e.disallowedTools??this.runDefaults.disallowedTools),mcpServers:W(e.mcpServers??this.runDefaults.mcpServers),maxTurns:e.maxTurns??this.runDefaults.maxTurns,outputFormat:t.normalizedRequest.schema.kind===`none`?void 0:{type:`json_schema`,schema:u(t.normalizedRequest.schema.jsonSchema)},permissionMode:r,allowDangerouslySkipPermissions:r===`bypassPermissions`||void 0,resume:t.requestedSessionId,forkSession:t.requestedSessionId?a:void 0,env:c,executable:this.creationOptions.executable,executableArgs:this.creationOptions.executableArgs,pathToClaudeCodeExecutable:this.command,settings:H(this.creationOptions.settings),settingSources:this.creationOptions.settingSources,stderr:e=>{for(let n of e.split(`
4
4
  `))n&&(t.stderrLines.push(n),this.emit(t,s(t.runId,`stderr`,{sessionId:t.sessionId,text:n})))}}}};const K=e=>new G(e);export{K as createClaudeCodeSdkAgent};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "coding-agents-sdk",
3
- "version": "0.16.0",
4
- "description": "Run coding agents (Claude Code, Codex, Cursor, Gemini, OpenCode, Pi — CLI and SDK) behind one uniform TypeScript interface, with optional container and sandbox execution.",
3
+ "version": "0.17.0",
4
+ "description": "Run coding agents behind one uniform TypeScript interface, with optional container and sandbox execution.",
5
5
  "keywords": [
6
6
  "coding-agent",
7
7
  "ai-agent",
@@ -91,8 +91,8 @@
91
91
  "scripts": {
92
92
  "build": "bun run typecheck && tsdown && bun run test:package",
93
93
  "start": "bun run examples/claude-code-cli/simple.ts",
94
- "test": "bun test",
95
- "test:agent": "bun test ./tests",
94
+ "test": "bun test ./src",
95
+ "test:agent": "bun test ./tests/features",
96
96
  "test:package": "bun run test:package:runtime",
97
97
  "test:package:runtime": "bun test ./tests/package-exports.smoke.ts",
98
98
  "test:agent:claude-code-cli-pty": "ADAPTERS=claude-code-cli-pty bun run test:agent",
@@ -110,13 +110,13 @@
110
110
  "typecheck": "bun run tsc"
111
111
  },
112
112
  "devDependencies": {
113
- "@anthropic-ai/claude-agent-sdk": "^0.3.280",
114
- "@cursor/sdk": "^1.0.32",
115
- "@openai/codex-sdk": "^0.156.1",
113
+ "@anthropic-ai/claude-agent-sdk": "^0.3.288",
114
+ "@cursor/sdk": "^1.0.35",
115
+ "@openai/codex-sdk": "^0.160.0",
116
116
  "@types/bun": "^1.4.2",
117
- "@types/node": "^26.6.2",
118
- "e2b": "^2.51.0",
119
- "knip": "^6.35.1",
117
+ "@types/node": "^26.6.4",
118
+ "e2b": "^2.52.0",
119
+ "knip": "^6.39.0",
120
120
  "picoprint": "^2.2.2",
121
121
  "tsdown": "^0.23.0",
122
122
  "typescript": "^7.0.2"
@@ -124,7 +124,7 @@
124
124
  "peerDependencies": {
125
125
  "@anthropic-ai/claude-agent-sdk": "^0.3.170",
126
126
  "@cursor/sdk": "^1.0.12",
127
- "@openai/codex-sdk": ">=0.150.0 <0.157.0",
127
+ "@openai/codex-sdk": ">=0.150.0 <0.161.0",
128
128
  "e2b": "^2.28.0",
129
129
  "typescript": "^6.0.3 || ^7.0.0"
130
130
  },