coding-agents-sdk 0.18.0 → 0.21.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 (90) hide show
  1. package/README.md +292 -7
  2. package/dist/Agent-BsDJsgJa.mjs +4 -0
  3. package/dist/SdkAgent-jwighP_b.mjs +1 -0
  4. package/dist/adapters/antigravity-cli/index.d.mts +2 -0
  5. package/dist/adapters/antigravity-cli/index.mjs +2 -0
  6. package/dist/adapters/claude-code-cli/index.d.mts +2 -2
  7. package/dist/adapters/claude-code-cli/index.mjs +1 -1
  8. package/dist/adapters/claude-code-cli-pty/index.d.mts +2 -2
  9. package/dist/adapters/claude-code-cli-pty/index.mjs +5 -5
  10. package/dist/adapters/claude-code-sdk/index.d.mts +1 -1
  11. package/dist/adapters/claude-code-sdk/index.mjs +4 -4
  12. package/dist/adapters/codex-cli/index.d.mts +1 -1
  13. package/dist/adapters/codex-cli/index.mjs +4 -2
  14. package/dist/adapters/codex-sdk/index.d.mts +1 -1
  15. package/dist/adapters/codex-sdk/index.mjs +1 -1
  16. package/dist/adapters/cursor-cli/index.d.mts +1 -1
  17. package/dist/adapters/cursor-cli/index.mjs +1 -1
  18. package/dist/adapters/cursor-sdk/index.d.mts +1 -1
  19. package/dist/adapters/cursor-sdk/index.mjs +1 -1
  20. package/dist/adapters/drac-cli/index.d.mts +2 -0
  21. package/dist/adapters/drac-cli/index.mjs +1 -0
  22. package/dist/adapters/gemini-cli/index.d.mts +1 -1
  23. package/dist/adapters/gemini-cli/index.mjs +1 -1
  24. package/dist/adapters/opencode-cli/index.d.mts +1 -1
  25. package/dist/adapters/opencode-cli/index.mjs +1 -1
  26. package/dist/adapters/pi-cli/index.d.mts +1 -1
  27. package/dist/adapters/pi-cli/index.mjs +1 -1
  28. package/dist/classify-error-_WNZMhMY.mjs +8 -0
  29. package/dist/container/index.d.mts +2 -2
  30. package/dist/container/index.mjs +1 -1
  31. package/dist/container-BlsSoBe1.mjs +1 -0
  32. package/dist/container-C7oWwLGK.mjs +1 -0
  33. package/dist/container-DUoj_mnh.mjs +1 -0
  34. package/dist/container-DXQ92RVu.mjs +1 -0
  35. package/dist/container-MazMFZg8.mjs +1 -0
  36. package/dist/control-requests-DtjV0e4o.mjs +1 -0
  37. package/dist/core/process/index.d.mts +2 -2
  38. package/dist/core/process/index.mjs +1 -1
  39. package/dist/diff-CMWH9a0d.mjs +1 -0
  40. package/dist/{errors-aYGbvsaq.mjs → errors-BauhTL3l.mjs} +1 -1
  41. package/dist/{events-BxEB6zHt.d.mts → events-DmlAPVpd.d.mts} +172 -5
  42. package/dist/{index-DH2vDD3l.d.mts → index-5XiyFBcK.d.mts} +5 -9
  43. package/dist/index-BimeR91j.d.mts +6 -0
  44. package/dist/{index-DWv7tLOX.d.mts → index-Bl9DtOcy.d.mts} +4 -10
  45. package/dist/{index-BWAsLSN3.d.mts → index-Brx5CEx7.d.mts} +4 -10
  46. package/dist/{index-DB0fLwpu.d.mts → index-CCsw4G4N.d.mts} +1 -5
  47. package/dist/{index-CmRm10Lo.d.mts → index-CZiWvyn3.d.mts} +3 -7
  48. package/dist/{index-CPhcEEAp.d.mts → index-DQYRy7xl.d.mts} +4 -10
  49. package/dist/index-DUTtolch.d.mts +63 -0
  50. package/dist/{index-DCQu5ZAu.d.mts → index-DilMV_1s.d.mts} +182 -36
  51. package/dist/{index-DpPNo3dX.d.mts → index-DpG9mouj.d.mts} +33 -18
  52. package/dist/{index-Ssb7kE6D.d.mts → index-DqNl8zYj.d.mts} +1 -5
  53. package/dist/index-Du99OLj6.d.mts +65 -0
  54. package/dist/{index-DWmHDEQL.d.mts → index-Q5jNyQHD.d.mts} +88 -25
  55. package/dist/{index-BrFs4M0Z.d.mts → index-X-W5isMp.d.mts} +3 -7
  56. package/dist/{index-BEEVpHOg.d.mts → index-oUIMXZIp.d.mts} +4 -10
  57. package/dist/index.d.mts +28 -21
  58. package/dist/index.mjs +1 -1
  59. package/dist/oci-t88M5ODN.mjs +2 -0
  60. package/dist/parser-BY3CZGmc.mjs +2 -0
  61. package/dist/permission-updates-CkFvevWQ.mjs +1 -0
  62. package/dist/permissions-BjNU9GCH.mjs +1 -0
  63. package/dist/questions-CaEwN4JQ.mjs +1 -0
  64. package/dist/sandbox/index.d.mts +1 -1
  65. package/dist/sandbox/index.mjs +1 -1
  66. package/dist/{sandbox-CYA69miM.mjs → sandbox-BemAIoIo.mjs} +2 -2
  67. package/dist/schemas/index.d.mts +2 -2
  68. package/dist/schemas/index.mjs +1 -1
  69. package/dist/schemas-CzJM9p-0.mjs +1 -0
  70. package/dist/spawner-CYAQQABs.mjs +1 -0
  71. package/dist/{types-COmjfh8B.d.mts → types-BetgZysV.d.mts} +0 -2
  72. package/dist/{types-D0ejXDa9.d.mts → types-D_QP9PC-.d.mts} +98 -17
  73. package/dist/util-CCXryPDO.mjs +1 -0
  74. package/package.json +20 -10
  75. package/dist/Agent-WqGee5TR.mjs +0 -4
  76. package/dist/SdkAgent-BjdSrtFe.mjs +0 -1
  77. package/dist/classify-error-DK2WpxiL.mjs +0 -8
  78. package/dist/container-Bdb90GJb.mjs +0 -1
  79. package/dist/container-DMFxf-kn.mjs +0 -1
  80. package/dist/container-Dvr-p53c.mjs +0 -1
  81. package/dist/container-dCRMBvQw.mjs +0 -1
  82. package/dist/container-w0rl1QMH.mjs +0 -1
  83. package/dist/diff-Dqyk2cdt.mjs +0 -1
  84. package/dist/index-DvwVRB7K.d.mts +0 -10
  85. package/dist/oci-DTNwW-WH.mjs +0 -1
  86. package/dist/parser-jSS5vOTN.mjs +0 -2
  87. package/dist/schemas-CkdQXAep.mjs +0 -1
  88. package/dist/session-markers-BHsJLWJk.mjs +0 -1
  89. package/dist/spawner-CgfyvnR4.mjs +0 -1
  90. package/dist/util-B4HTdOSc.mjs +0 -1
package/README.md CHANGED
@@ -28,6 +28,7 @@ bun add e2b
28
28
 
29
29
  Before you call `await createAgent(...)`, make sure the runtime for that adapter is available.
30
30
 
31
+ - `antigravity-cli` runs Antigravity CLI's ACP server, `agy acp`.
31
32
  - `claude-code-cli` runs Claude Code CLI.
32
33
  - `claude-code-cli-pty` runs interactive Claude Code behind a PTY and requires `socat` on `PATH`.
33
34
  - `claude-code-sdk` uses `@anthropic-ai/claude-agent-sdk` and launches Claude Code locally.
@@ -35,6 +36,7 @@ Before you call `await createAgent(...)`, make sure the runtime for that adapter
35
36
  - `codex-sdk` uses `@openai/codex-sdk` and launches Codex locally.
36
37
  - `cursor-cli` runs Cursor CLI.
37
38
  - `cursor-sdk` uses `@cursor/sdk` and launches Cursor locally.
39
+ - `drac-cli` runs Drac's headless command, `drac exec`, attended: Drac asks the adapter for approvals and answers and takes input during a run.
38
40
  - `gemini-cli` runs Gemini CLI.
39
41
  - `opencode-cli` runs OpenCode CLI.
40
42
  - `pi-cli` runs Pi CLI.
@@ -170,7 +172,7 @@ if (result.status === "completed") {
170
172
 
171
173
  If you want to pass Zod schemas, depend on `zod` in your app.
172
174
 
173
- `schema` accepts a raw JSON Schema object or a Zod schema. This wrapper validates only the Zod path. `cursor-cli`, `cursor-sdk`, `gemini-cli`, `opencode-cli`, and `pi-cli` do not support structured output.
175
+ `schema` accepts a raw JSON Schema object or a Zod schema. This wrapper validates only the Zod path. `antigravity-cli`, `cursor-cli`, `cursor-sdk`, `gemini-cli`, `opencode-cli`, and `pi-cli` do not support structured output.
174
176
 
175
177
  If you need to name these shapes in your own helpers, import `RunRequest`, `JsonSchemaRunRequest`, `ZodRunRequest`, `RunResult`, or `CompletedRunResult` from the package.
176
178
 
@@ -194,16 +196,221 @@ Useful bits:
194
196
  - pass `sessionId` to `await createAgent(type, { sessionId })` to resume one explicitly
195
197
  - `reset()` forgets the stored session
196
198
  - Claude adapters and `pi-cli` support `fork()`
197
- - `opencode-cli` supports `forkSession: true` on a run, not a `fork()` method
199
+ - `opencode-cli` and `codex-cli` with `transport: "app-server"` support `forkSession: true` on a run, not a `fork()` method
198
200
 
199
201
  ## Permission requests
200
202
 
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.
203
+ The Claude adapters, `antigravity-cli`, `codex-cli` with `transport: "app-server"`, and `drac-cli` support `onPermissionRequest()`. Register a handler before the run and return `{ decision: "allow" }` or `{ decision: "deny", message }`. Check `agent.capabilities.permissionRequests` before relying on a handler with another adapter. On `antigravity-cli`, the model sees a denial without its `message`, because Antigravity's permission answer names only the option chosen.
202
204
 
203
- `claude-code-cli` answers permission requests over stdin and keeps a run with a handler open until Claude reports the session idle, so background work started during the run can still ask. It stops waiting if the session is still busy 10 minutes after the last result or answered permission request.
205
+ `drac-cli` also brings its plan mode to the same handler. Run with `startsInPlanMode: true` and Drac plans without changing anything; when the plan is ready, the handler gets a request for the tool `exit_plan_mode` whose input holds `plan`, `planFile`, and `mode`. Allowing it starts the implementation in the same run, in the run's `permissionMode` (named by `mode`); the allow must carry neither `updatedInput` nor `permissionMode`. Denying it keeps Drac planning: with a `message`, Drac revises the plan and asks again, and without one it stops and the run ends with the plan unapproved. Without a handler, when the handler throws, or when its allow carries either field, Drac is told that nobody can decide, and the run ends with the plan. `startsInPlanMode` applies to one run: a later run of the session without it leaves plan mode when it passes a `permissionMode`.
206
+
207
+ On the Claude adapters, an allow decision can also include `updatedInput` to replace the tool input, and `permissionMode` to change the session's permission mode from that point on, for example to `"acceptEdits"` after approving the first edit. The other adapters cannot apply either field, so the tool call does not run when an allow carries one: `drac-cli` denies it with a reason saying that Drac cannot make such changes, and `antigravity-cli` and `codex-cli` reject the request, which Antigravity reports as a denial by the user. Set these fields only when the agent is a Claude adapter.
208
+
209
+ `claude-code-cli` answers permission requests over stdin and keeps a run with a handler open until Claude reports the session idle, so background work started during the run can still ask. After a result, it stops waiting if the busy session prints nothing for 10 minutes; time spent waiting on a permission request does not count.
204
210
 
205
211
  `claude-code-cli-pty` uses a run-local hook for permission requests. Its callback bridge is not supported inside a container.
206
212
 
213
+ ### Codex app-server transport
214
+
215
+ For Codex, opt into the native app-server transport when a person or application must decide permission requests:
216
+
217
+ ```ts
218
+ await using agent = await createAgent("codex-cli", {
219
+ transport: "app-server",
220
+ sandboxMode: "workspace-write",
221
+ extraArgs: ["-c", 'approval_policy="on-request"', "-c", 'approvals_reviewer="user"'],
222
+ });
223
+ agent.onPermissionRequest(decideToolPermission);
224
+ await agent.run({ input: "Make the requested change." });
225
+ ```
226
+
227
+ The default `transport: "exec"` does not bridge permission or question requests, accepts no input during a run, and streams no text. The app-server transport keeps the configured command, environment, execution target, MCP configuration, normalized events, and structured-output contract. Its `extraArgs` must be flags that `codex app-server` accepts, such as `-c` and `--profile`, not `codex exec` flags, and `skipGitRepoCheck` has no effect because app-server does not require a Git repository.
228
+
229
+ Permission review and the filesystem sandbox are separate settings: `permissionMode: "auto-approve"` selects automatic review with workspace-write, while `"bypass-sandbox"` disables both approval prompts and the sandbox.
230
+
231
+ A handler receives command, file-change, additional-permission, and tagged native MCP-tool approval requests. Its decisions work like this:
232
+
233
+ - allow and deny answer one outstanding request; they do not save command rules or session-wide approvals
234
+ - Codex does not accept rewritten inputs or permission-mode changes in an allow decision; returning either rejects the request
235
+ - Codex's native command and file approval protocol does not carry a custom denial message back to the model
236
+ - approving an additional-permissions request grants the requested profile for the current turn, not just one command; the request's `description` states that duration so applications can display it alongside the decision
237
+ - a request without a handler is denied
238
+ - a withdrawn request or stopped run aborts its request signal, and a later handler response is discarded
239
+
240
+ `toolUseId` tells outstanding requests apart:
241
+
242
+ - for command, file-change, and additional-permission requests, it is the ID of the Codex item the request belongs to; for a command or file change that is the `toolCallId` of its `tool-call` and `tool-result` events
243
+ - when Codex asks more than once for one item, such as for a sub-command, it is that item ID followed by `:` and Codex's ID for the request, so each outstanding request stays distinct
244
+ - an MCP-tool approval has no item ID and gets a unique ID of its own
245
+
246
+ Native user questions and general MCP elicitation are not permission requests, and the adapter never treats either as permission to use a tool. It hands native user questions to a registered question handler, as described under [Question requests](#question-requests), rejects them when no question handler is registered, and cancels general elicitation.
247
+
248
+ The app-server transport resumes `sessionId` normally. Two run options require it:
249
+
250
+ - `forkSession: true` forks the session before the run; it also requires an existing session ID
251
+ - `collaborationMode: "plan"` starts the turn in native plan mode
252
+
253
+ When a plan-mode turn proposes a plan, that plan is the run's `text` and a `message` event, and any text Codex writes outside the plan arrives as a separate `message` event. A plan-mode turn that proposes no plan returns Codex's last message as its `text`, like any other turn.
254
+
255
+ The app-server transport rejects `ephemeral: true` on a resume before launching Codex. To continue an existing session without saving the new history, set both `ephemeral: true` and `forkSession: true`; the fork gets a new session ID and leaves the saved source session unchanged. Codex does not save an ephemeral session, so its ID is reported on that run's result but does not become `agent.sessionId`. Later runs keep using the saved session, or start a new one when the agent has none.
256
+
257
+ ## Question requests
258
+
259
+ `antigravity-cli`, `claude-code-cli`, `codex-cli` with `transport: "app-server"`, and `drac-cli` hand the questions the agent asks through its question tool (`AskUserQuestion` on Claude, `request_user_input` on Codex, either on Drac, and Antigravity's own question tool on Antigravity) to a handler registered with `onQuestionRequest()`. Register the handler before the run and return the answers. Check `agent.capabilities.questionRequests` before relying on a handler with another adapter.
260
+
261
+ ```ts
262
+ import { createAgent, type QuestionAnswers } from "coding-agents-sdk";
263
+
264
+ await using agent = await createAgent("claude-code-cli");
265
+
266
+ agent.onQuestionRequest(async ({ questions, signal }) => {
267
+ const answers: QuestionAnswers = {};
268
+
269
+ for (const question of questions) {
270
+ answers[question.id] = await askUser(question, signal);
271
+ }
272
+
273
+ return answers;
274
+ });
275
+
276
+ await agent.run({ input: "Ask me which test runner to set up, then set it up." });
277
+ ```
278
+
279
+ A request carries one or more questions. It works like this:
280
+
281
+ - each question has an `id`, its `text`, a short `header`, its `options` (each with a `label` and a `description`), and `allowsMultiple`, which is `true` when more than one option may be selected
282
+ - the handler returns answers keyed by question `id`; each answer lists the labels of the selected options, free-form text, or both, and a question without an entry stays unanswered
283
+ - `toolUseId` tells outstanding requests apart; on `claude-code-cli` and `drac-cli` it is the `toolCallId` of the question tool's `tool-call` event, on `codex-cli` it is Codex's ID for the question tool call, which has no such events, and on `antigravity-cli` it is the ID of the tool call Antigravity asks for, or a generated ID when Antigravity names none
284
+ - an agent has one question handler: registering another replaces it, and the function `onQuestionRequest()` returns removes it
285
+ - if the handler throws, the question stays unanswered and the run continues; `claude-code-cli` tells the agent so with the error's message, `codex-cli` gives the model no answer and reports the error's message only in a `stderr` event, `drac-cli` tells Drac the question went unanswered, and `antigravity-cli` answers Antigravity with the error; `drac-cli` and `antigravity-cli` also write the error to the agent's `logPath` log
286
+ - `signal` aborts when the run is cancelled or the provider withdraws the request, and a later handler response is discarded
287
+
288
+ Registering a question handler is optional. Without one, a question tool call on `claude-code-cli` reaches a registered permission handler like any other tool call, with `toolName: "AskUserQuestion"`. On `codex-cli`, a question that arrives with no question handler registered is rejected, and Codex continues the turn without an answer. On `drac-cli`, Drac is told the question went unanswered. `antigravity-cli` does not offer Antigravity its question form without a question handler, and declines a question Antigravity still sends.
289
+
290
+ Codex offers its question tool in plan mode (`collaborationMode: "plan"`). In default mode it offers the tool only when Codex's `default_mode_request_user_input` feature is on. A Codex question never allows multiple selections, its `id` is the ID Codex gave the question, and a question Codex asks without options has an empty `options` list and expects free-form text.
291
+
292
+ `claude-code-cli` asks over the same stdin channel as permission requests, so a run with a question handler stays open until Claude reports the session idle, as described under [Permission requests](#permission-requests). The two handlers are separate: questions go to the question handler and every other tool request to the permission handler. With a question handler but no permission handler, the adapter answers Claude Code's other permission requests with an error: Claude Code does not run the tool and tells the model that the permission request failed. Register both handlers when the permission mode lets Claude ask before using a tool.
293
+
294
+ ## Input during a run
295
+
296
+ `sendInput()` delivers user input into the run that is active, without waiting for it to finish. `claude-code-cli` supports it on an agent created with `keepInputOpen: true`, `codex-cli` on an agent created with `transport: "app-server"`, and `antigravity-cli` and `drac-cli` on every agent. Check `agent.capabilities.midRunInput` before calling it with another adapter.
297
+
298
+ ```ts
299
+ await using agent = await createAgent("claude-code-cli", { keepInputOpen: true });
300
+
301
+ const unsubscribe = agent.onEvent((event) => {
302
+ if (event.type !== "session-start") return;
303
+
304
+ showInputBox((text) => agent.sendInput(text));
305
+ });
306
+
307
+ const result = await agent.run({ input: "Refactor the parser module." });
308
+ unsubscribe();
309
+ ```
310
+
311
+ `sendInput()` takes the same input as `run()`: a string or content parts. It resolves once the input is handed to the provider, not when the model has read it, and the run's result still arrives from `run()`.
312
+
313
+ It rejects with `AgentValidationError` in these cases:
314
+
315
+ - the agent does not report `capabilities.midRunInput`
316
+ - no run is active, or the run is stopping after `stop()`, an abort, or its timeout
317
+ - the input is empty or holds a part the adapter does not support, such as an image on `claude-code-cli`
318
+ - the run is not accepting input: on `claude-code-cli`, before the run has set up Claude Code's input, which it does before the `session-start` event, or after that input has closed, which happens once Claude has answered every input and reports the session idle; on `codex-cli`, before Codex has started the turn, after the turn has ended, or when Codex refuses the input; on `antigravity-cli`, before Antigravity has started the turn or after the turn has ended; on `drac-cli`, before Drac has started, when Drac refuses the input, such as when no turn is running, or when the run ends before Drac takes it
319
+
320
+ `claude-code-cli` writes the input to Claude Code's stdin as a user message, and Claude Code queues it. What happens next depends on when it arrives:
321
+
322
+ - while tool calls are running, the model receives it when they have finished, before its next step, and the run continues as one turn
323
+ - while the model is writing the turn's last reply, or just after the turn has ended, Claude answers it in another turn of the same run: the earlier reply arrives as a `message` event, `run()` resolves after the last turn, its `text` is the last turn's reply, and its `stats` cover every turn
324
+
325
+ No event reports the input itself or the moment the model receives it.
326
+
327
+ `codex-cli` steers the turn in progress. Codex does not interrupt the step it is working on, such as a running command; the model reads the input at its next step, in the same turn and the same run. `sendInput()` resolves once Codex has accepted the input. Codex accepts input from the start of the turn, which follows `session-start` by a moment and which the `turn.started` [provider event](#provider-events) announces.
328
+
329
+ `antigravity-cli` sends the input to Antigravity as a new prompt in the same session. Antigravity ends the turn in progress and goes on with the new prompt, in the same run, whose `text` is the reply to the last prompt.
330
+
331
+ `drac-cli` hands the input to Drac for the running turn, and `sendInput()` resolves once Drac has taken it.
332
+
333
+ ## Control requests
334
+
335
+ `claude-code-cli` can send Claude Code control requests while a run is active, for example to stop one subagent and let the rest of the run continue. Create the agent with `keepInputOpen: true` so Claude Code reads stream-json input for the whole run; a registered permission or question handler keeps the input open the same way. As in a run with a permission handler, the input closes once Claude reports the session idle after the result, or when the run stops.
336
+
337
+ Connect a handler like this to your application's task-stop action before starting the run. Call it only after a `task_started` [provider event](#provider-events) supplies the task's ID, not immediately after calling `run()`.
338
+
339
+ ```ts
340
+ import { ClaudeControlRequestError, createClaudeCodeCliAgent } from "coding-agents-sdk/adapters/claude-code-cli";
341
+
342
+ await using claude = createClaudeCodeCliAgent({ keepInputOpen: true });
343
+
344
+ const handleStopTask = async (taskId: string) => {
345
+ try {
346
+ await claude.stopTask(taskId);
347
+ } catch (error) {
348
+ if (!(error instanceof ClaudeControlRequestError)) throw error;
349
+
350
+ console.error(error.reason, error.message);
351
+ }
352
+ };
353
+
354
+ claude.onProviderEvent(({ event }) => {
355
+ if (event.type !== "system" || event.subtype !== "task_started") return;
356
+ if (event.task_id === undefined) return;
357
+
358
+ showStopAction(event.task_id, handleStopTask);
359
+ });
360
+
361
+ await claude.run({ input: "Inspect each part with a subagent." });
362
+ ```
363
+
364
+ - `stopTask(taskId)` sends `{ subtype: "stop_task", task_id }`
365
+ - `sendControlRequest(request)` sends any other control request and resolves with the `response` of Claude Code's success answer
366
+ - both reject with `ClaudeControlRequestError`, whose `reason` is `"no-open-input"` when no run of the agent has its input open, `"input-closed"` when the run ends before Claude Code answers, and `"refused"` when Claude Code answers with an error
367
+ - with `backgroundTasks: "keep-running"`, both also reach the Claude Code process the agent keeps between runs, as described under [Background tasks](#background-tasks)
368
+
369
+ Claude Code announces each task it starts, such as a subagent, with a `system` provider event whose `subtype` is `"task_started"`. Pass that event's `task_id` to `stopTask()`, not its `tool_use_id`. Normalized events don't include it, so subscribe with `onProviderEvent()`.
370
+
371
+ A resolved `stopTask()` does not confirm that a task stopped, because Claude Code can answer success for a task ID it does not know. Claude Code reports a stopped task with a `system` provider event whose `subtype` is `"task_notification"`.
372
+
373
+ ## Background tasks
374
+
375
+ Claude Code can leave a command running in the background, such as a dev server the model starts with the Bash tool's `run_in_background`, and go on working. `claude-code-cli` reports these tasks to `onBackgroundTask()` handlers: a `started` change with the task's ID, description, and command, and an `ended` change whose `status` is `"completed"`, `"failed"`, or `"stopped"` and whose `summary`, Claude Code's own words, can include the exit code. A command that runs in the foreground is not reported.
376
+
377
+ A subagent started in the background with the Agent tool is a background task too. While it works, also between runs, handlers receive `progressed` changes whose `progress` holds the tool calls it made so far (`toolUses`), the tokens it used (`totalTokens`), and Claude Code's `lastToolName` and `summary`. Its `ended` change carries the work it did in all as `usage`. Between runs the agent emits no events. The events of what Claude Code reports between runs, such as the subagent's messages, reasoning, tool calls, and tool results, or a rate limit, reach the next run instead, also a run Claude Code starts by itself: before that run's own events, in the order Claude Code reported them, and with the times Claude Code reported them as their `timestamp`. A result whose call an earlier run received arrives alone. While the subagent works between runs, progress is what reaches you as it happens. When no run follows, the agent drops what it holds when it is disposed.
378
+
379
+ By default a run lasts until Claude Code exits, and Claude Code exits only after its background tasks have ended: a run whose agent started a server never ends. Create the agent with `backgroundTasks: "keep-running"` to end each run at its reply instead:
380
+
381
+ ```ts
382
+ await using claude = createClaudeCodeCliAgent({ backgroundTasks: "keep-running" });
383
+
384
+ claude.onBackgroundTask((change) => {
385
+ if (change.kind === "started") {
386
+ showTask(change.task, () => claude.stopTask(change.task.taskId));
387
+
388
+ return;
389
+ }
390
+
391
+ if (change.kind === "ended") {
392
+ markTaskEnded(change.task.taskId, change.task.status);
393
+ }
394
+ });
395
+
396
+ claude.onAgentRun((run) => {
397
+ run.result.then((result) => showFollowUp(run.endedTasks, result));
398
+ });
399
+
400
+ await claude.run({ input: "Start the dev server in the background." });
401
+ await claude.run({ input: "Open the home page and check its title." });
402
+ ```
403
+
404
+ With this option:
405
+
406
+ - While background tasks run, `run()` resolves at the result that answers its input, and the agent keeps Claude Code's process with its input open: the next `run()` writes its input to that process instead of starting Claude Code again.
407
+ - When a task completes or fails while no run is active, Claude Code starts a turn by itself to tell the model. The agent delivers that turn to `onAgentRun()` handlers as a run, before its first event and before the task's `ended` change. A `run()` call made during that run starts when it has ended. The run answers permission and question requests with the handlers registered when the `onAgentRun()` handlers have run, so they can replace them; Claude Code asks over its input only when a handler was registered when it started, so register one before the first run.
408
+ - `stop()` interrupts the run's turn and leaves the background tasks running. `stopTask()` ends one task, also between runs. `dispose()` ends Claude Code's process with its tasks, which are reported as `stopped`.
409
+ - `reset()` also ends Claude Code's process with its tasks, which are reported as `stopped`, because they belong to the session it clears; the next run starts a fresh session in a new process. As during any run, `reset()` throws `AgentValidationError` while a run Claude Code started by itself is active.
410
+ - Once no task runs, the agent closes Claude Code's input when Claude Code reports itself idle after the turn, and the run ends when Claude Code exits, as without the option. A turn Claude Code goes on to before it reports itself idle belongs to the run.
411
+ - `onProviderEvent()` handlers also receive what Claude Code reports between runs, such as a task's end before the turn it starts. Those events carry the run ID of Claude Code's process, which no `run()` call or `onAgentRun()` handler gave you.
412
+ - A run that continues in Claude Code's process switches it to the run's `permissionMode` before writing its input. When the run's turn ends while tasks run, or the run stops first, the agent switches Claude Code back to its own `permissionMode`, so turns Claude Code starts by itself run in that mode; an agent without a `permissionMode` leaves Claude Code in the last run's mode. Claude Code reads other options, such as `schema`, `model`, and `forkSession`, and whether the agent has a permission or question handler, only when it starts: while its process runs background tasks, `run()` rejects a run with other such options with `AgentValidationError`. When the tasks start while the run waits for a run Claude Code started by itself, the run resolves as `failed` with a `process` error instead.
413
+
207
414
  ## Events
208
415
 
209
416
  Use `onEvent()` to subscribe to the normalized event stream.
@@ -222,11 +429,69 @@ await agent.run({
222
429
  unsubscribe();
223
430
  ```
224
431
 
225
- All adapters emit `session-start` and `session-end`. Depending on the backend, you may also see `message`, `reasoning`, `tool-call`, `tool-result`, and `stderr`.
432
+ All adapters emit `session-start` and `session-end`. Depending on the backend, you may also see `message`, `reasoning`, `tool-call`, `tool-result`, `stderr`, `rate-limit`, and `notice`.
433
+
434
+ On `claude-code-cli`, the `message`, `reasoning`, `tool-call`, and `tool-result` events of a subagent's work, and its `message-delta` and `reasoning-delta` events, carry `parentToolCallId`: the `toolCallId` of the Agent tool call that started the subagent. The main agent's own events have none, so a consumer can group a subagent's work under the call that started it.
435
+
436
+ On `claude-code-cli`, every `tool-result` follows its `tool-call` and carries the call's `toolName` and `input`, also when it arrives in a later run than the call, as a background subagent's result can. A result whose call Claude Code never reported is left out.
437
+
438
+ On `codex-cli`, a file change Codex makes arrives as a `tool-call` and a `tool-result` event with `toolName: "apply_patch"`, the name Codex gives its file-editing tool:
439
+
440
+ - the `tool-call` input is `{ changes }`, one entry per file with its `path` and its `kind` of change, `"add"`, `"delete"`, or `"update"`; on the app-server transport each entry also has the `diff`, and a moved file has its destination as `movePath`
441
+ - the `tool-result` output is Codex's status for the change, `"completed"` or `"failed"`, and `isError` is `true` when the change failed or a permission handler denied it
442
+ - on the app-server transport, the `tool-call` event arrives when Codex proposes the change, before its permission request; on the default `exec` transport, Codex reports a file change only once it has been applied, so both events arrive together
443
+
444
+ ### Usage limits and notices
445
+
446
+ A `rate-limit` event reports how much of one of the provider account's usage limits is used. `status` is `"allowed"`, `"warning"` when the provider warns that the limit is close, or `"rejected"` when it refuses requests until `resetsAt`. `utilization` is the used share, from 0 to 1.
447
+
448
+ - `claude-code-cli` and `claude-code-sdk` report the limit that applies to the run, named by `limitType`, such as `"five_hour"` or `"seven_day"`, with Claude's extra-usage fields `overageStatus`, `isUsingOverage`, and `overageDisabledReason`. A status the adapter does not know arrives as a system `message` instead.
449
+ - `codex-cli` on the app-server transport reports the more used of Codex's two limit windows whenever Codex sends an update, with the window's length as `windowMinutes`. A rounded utilization of 100% alone does not indicate refusal: `status` stays `"allowed"` unless Codex reports a reached limit or fails the turn with `usageLimitExceeded`. A reported limit name becomes `reason`; a terminal refusal without a limit name uses `"usageLimitExceeded"` and has no window or reset time. When Codex names a reached limit while no window is used up, `resetsAt` is left out, because that refusal does not end when a window resets.
450
+
451
+ A `notice` event reports something that failed around the run without failing it. On `claude-code-cli` and `claude-code-sdk`:
452
+
453
+ - `{ kind: "mcp-server-failed", server }` is an MCP server that did not start, so the agent lacks its tools
454
+ - `{ kind: "hook-failed", hook, exitCode }` is a hook whose command failed; Claude Code reports the results of only some hooks, such as `SessionStart` hooks
455
+
456
+ ### Streamed text
457
+
458
+ `message` and `reasoning` events carry a whole text. To also receive text while the model generates it, create the agent with `streamText: true`. `antigravity-cli`, `claude-code-cli`, `codex-cli` with `transport: "app-server"`, and `drac-cli` support this option; an agent reports `capabilities.textStreaming` only when it was created with it.
459
+
460
+ ```ts
461
+ await using agent = await createAgent("claude-code-cli", { streamText: true });
462
+
463
+ const partialTextsByMessageId = new Map<string, string>();
464
+
465
+ agent.onEvent((event) => {
466
+ if (event.type === "message-delta") {
467
+ const partialText = (partialTextsByMessageId.get(event.messageId) ?? "") + event.text;
468
+ partialTextsByMessageId.set(event.messageId, partialText);
469
+ renderMessage(event.messageId, partialText);
470
+ }
471
+
472
+ if (event.type === "message") {
473
+ partialTextsByMessageId.delete(event.id);
474
+ renderMessage(event.id, event.text);
475
+ }
476
+ });
477
+
478
+ await agent.run({ input: "Explain the package layout." });
479
+ ```
480
+
481
+ - a `message-delta` event carries the `text` generated since the previous delta and the `messageId` of the message it belongs to; a `reasoning-delta` event does the same with `reasoningId`
482
+ - the `message` or `reasoning` event that follows has that ID as its `id` and carries the whole text; it is authoritative, so replace the text accumulated from deltas with it
483
+ - a text whose generation is cut short, for example by stopping the run, gets no `message` or `reasoning` event
484
+ - deltas are stored in `RunResult.events` like every other normalized event
485
+ - an agent created without `streamText` emits no delta events
486
+ - on `codex-cli`, a plan proposed in plan mode streams as `message-delta` events of the `message` event that carries the plan, reasoning deltas carry Codex's reasoning summaries, and `streamText` has no effect on the default `exec` transport
487
+
488
+ For every `drac-cli` run, including when `streamText` is `false`, the `drac` binary must include `blockId` in JSONL content records and a `blockIds` array aligned with the content parts of each assistant record. The adapter uses these IDs to match streamed text to its completed message, including after retries.
489
+
490
+ Current Claude models send a non-interactive Claude Code run no thinking text unless it asks for a summary, so by default `claude-code-cli` emits `reasoning` events with empty text and no `reasoning-delta` events. To receive summarized thinking, as deltas and in the whole events, create the agent with `extraArgs: ["--thinking-display", "summarized"]`. Claude Code accepts that flag but does not list it in `--help`.
226
491
 
227
492
  ### Provider events
228
493
 
229
- Use `onProviderEvent()` on `claude-code-cli` or `codex-cli` for provider-specific details not included in normalized events.
494
+ Use `onProviderEvent()` on `claude-code-cli` or `codex-cli` for provider-specific details not included in normalized events. On the app-server transport, Codex notifications arrive translated into the same event shapes the Codex CLI emits; JSON-RPC control messages are not provider events.
230
495
 
231
496
  ```ts
232
497
  import { createClaudeCodeCliAgent } from "coding-agents-sdk/adapters/claude-code-cli";
@@ -242,6 +507,8 @@ await claude.run({ input: "Explain the package layout." });
242
507
  unsubscribe();
243
508
  ```
244
509
 
510
+ Claude `system` events arrive for every `subtype` Claude Code emits, such as `task_progress` and `task_notification`, with all their fields. Fields the adapter doesn't declare are typed `unknown`, so check them before use.
511
+
245
512
  For Codex, import `createCodexCliAgent` from `coding-agents-sdk/adapters/codex-cli`.
246
513
 
247
514
  Provider events are not stored in `RunResult.events`; collect them in your callback if needed. Subscriptions persist across runs and `reset()`. Subscribe separately on forked agents.
@@ -280,7 +547,7 @@ This wrapper exposes MCP configuration directly on:
280
547
  - `codex-cli`: `mcpConfig`, `mcpServers`
281
548
  - `cursor-sdk`: `mcpServers` using `CursorSdkMcpServerConfig`
282
549
 
283
- 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`.
550
+ 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. `antigravity-cli`, `drac-cli`, and `pi-cli` report `mcp: false`.
284
551
 
285
552
  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.
286
553
 
@@ -336,6 +603,22 @@ Your image needs the runtime for the adapter you picked available inside the con
336
603
 
337
604
  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.
338
605
 
606
+ To use a Docker or Podman container that already exists, attach to it by ID or name:
607
+
608
+ ```ts
609
+ import { attachContainer } from "coding-agents-sdk";
610
+
611
+ const container = await attachContainer({
612
+ type: "docker",
613
+ containerId: "my-workspace",
614
+ workdir: "/workspace",
615
+ });
616
+ ```
617
+
618
+ An attached container has the same methods as a created one, except `getMappedPort`, and can be passed as `container` to a CLI adapter. `attachContainer()` does not start a stopped container; call `start()`, or let the agent start it before a run. A missing container rejects with `ContainerNotFoundError`, and any other failure with `ContainerAttachError`.
619
+
620
+ Disposing an attached container neither stops nor removes it. Call `stop()` to stop it, or `remove()` to stop it and remove it from the engine together with its anonymous volumes. `remove()` succeeds when the container is already gone, leaves the container's image and named volumes in place, and rejects with `ContainerRemoveError` when the engine could not remove the container.
621
+
339
622
  Use `snapshotWorkdir()`, `diffWorkdir()`, and `releaseWorkdirSnapshot()` when you need a before/after file diff. Start the container before taking the first snapshot.
340
623
 
341
624
  `propagateEnv` defaults depend on the execution target:
@@ -346,6 +629,8 @@ Use `snapshotWorkdir()`, `diffWorkdir()`, and `releaseWorkdirSnapshot()` when yo
346
629
  - `env` still applies in every case
347
630
  - set `propagateEnv: true` on a container-backed agent only when you intentionally want host env passed through to `docker exec` / `podman exec` / `nerdctl exec`
348
631
 
632
+ The `docker`, `podman`, and `nerdctl` providers never put environment values on the engine's command line, where other users of the host could read them in the process list. The container's `env`, an `exec()` call's `env`, and an agent's environment reach the engine through a file only your user can read, deleted once the engine command ends. That file format holds one variable per line, and the engines read lines of at most 65,536 bytes, `NAME=value` and its newline together (measured with Docker 29.9.2 and Podman 6.1.4; nerdctl's source uses the same line reader). A value is therefore refused, before the engine runs, when it contains a line break, a carriage return, or a NUL character, or when its line would be longer than that, so a value can be up to 65,534 bytes minus the length of its name. A name is refused when it is empty, starts with `#`, or contains whitespace or `=`. With nerdctl, which trims whitespace from each line, a value that ends in whitespace is refused too. A refused value makes `createContainer()` reject with `ContainerCreateError` and `exec()` reject with `ContainerExecError`, and makes the container's `spawner` throw `ContainerExecError`. The error names the variable, and for a value that is too long it gives the value's size and the most it can be.
633
+
349
634
  Notes:
350
635
 
351
636
  - `nerdctl` reuses the same OCI-backed behavior as `docker` and `podman`, but it depends on a working containerd and BuildKit setup on the host; the bundled `nerdctl` examples use `network: "host"` to avoid rootless CNI/firewall differences across hosts
@@ -0,0 +1,4 @@
1
+ import{i as e,l as t,n,o as r,t as i}from"./classify-error-_WNZMhMY.mjs";import{t as a}from"./env-Cb8MIvH7.mjs";import{t as o}from"./errors-BauhTL3l.mjs";import{t as s}from"./spawner-CYAQQABs.mjs";import{t as c}from"./util-CCXryPDO.mjs";import{dirname as l}from"node:path";import{createWriteStream as u,mkdirSync as d}from"node:fs";async function*f(e){let t=new TextDecoder,n=``;for await(let r of e){let e=t.decode(r,{stream:!0});n+=e;let i=n.split(`
2
+ `);n=i.pop()??``;for(let e of i){let t=e.trim();t&&(yield t)}}let r=t.decode();r&&(n+=r);let i=n.trim();i&&(yield i)}const p=Symbol(`process exited`),m=e=>e.status===`rejected`?c(e.reason):void 0,h=(e,t)=>{if(e.stopReason)return;if(t.processResult.status===`rejected`){let e=t.processResult.reason;return{kind:e instanceof o?`process`:`spawn`,message:c(e)}}let n=m(t.stdinResult);if(n)return{kind:`process`,message:n};let i=m(t.stdoutResult);if(i)return{kind:`process`,message:i};let a=m(t.stderrResult);if(a)return{kind:`process`,message:a};if(!e.status&&!e.error){let t=e.processResult,n=e.stderrLines.join(`
3
+ `);if(t&&t.exitCode!==null&&t.exitCode!==0)return{kind:`process`,message:n||`Process exited with code ${t.exitCode}.`};if(!r(e)&&e.stderrLines.length>0)return{kind:`process`,message:n}}},g=async(e,t,n)=>{let r=e.stdin;if(!r?.write)throw Error(`The process spawner must provide a stdin writer for this adapter.`);let i=n.then(()=>p,()=>p),a=t[Symbol.asyncIterator]();for(;;){let e=await Promise.race([a.next(),i]);if(e===p){a.return?.();return}if(e.done)break;if(await Promise.race([r.write(e.value),i])===p)return}await Promise.race([r.end(),i])},_=e=>{let t=i(e);return t.kind===`provider`?{kind:`process`,message:t.message}:t};var v=class extends n{spawner;defaults;executionTargetRef;providerHandlers=/* @__PURE__ */ new Set;logStream;sigkillTimer;constructor(e){super({type:e.type,capabilities:e.capabilities,sessionId:e.defaults?.sessionId,onEvent:e.onEvent}),this.spawner=e.spawner??s,this.defaults=e.defaults??{},this.executionTargetRef=e.executionTarget,e.onProviderEvent&&this.onProviderEvent(e.onProviderEvent),e.logPath&&this.initLogStream(e.logPath)}onProviderEvent(e){return this.providerHandlers.add(e),()=>{this.providerHandlers.delete(e)}}get hasProviderEventListeners(){return this.providerHandlers.size>0}emitProviderEvent(e,t,n=t.sessionId){if(!this.hasProviderEventListeners)return;let r={agentType:this.type,runId:t.runId,sessionId:n,timestamp:/* @__PURE__ */ new Date,event:e};for(let e of this.providerHandlers)try{e(r)}catch(e){this.onHandlerError(e)}}getStdinInput(e){}onParseError(e,t){this.appendRawLog(`[parse-error] ${c(t)} ${e.slice(0,200)}`)}buildDefaultEnv(e){let t=a({propagateEnv:e});return t.CI=t.CI??`true`,this.defaults.env&&Object.assign(t,this.defaults.env),t}async executeRunCore(e,t){let n=this.setupRunLifecycle(e);try{if(n.abortedBeforeStart)return this.buildResult(e,/* @__PURE__ */ new Date);try{await this.onBeforeRun(e);let n={...t,...e.normalizedRequest},r=this.buildArgs(n,e),i=this.buildEnv(n,e),a=this.defaults.command?.[0]??`claude`,o=[...this.defaults.command?.slice(1)??[],...r];if(e.stopReason)return this.buildResult(e,/* @__PURE__ */ new Date);e.sessionId&&this.emitSessionStart(e),e.process=this.spawner.spawn(a,o,{cwd:e.normalizedRequest.cwd,env:i,stdio:[`pipe`,`pipe`,`pipe`]});let s=e.process.wait(),[c,l,u,d]=await Promise.allSettled([this.watchStdout(e),this.watchStderr(e),s,this.deliverInput(e.process,this.getStdinInput(n),s)]);u.status===`fulfilled`&&(e.processResult=u.value);let f=h(e,{stdoutResult:c,stderrResult:l,processResult:u,stdinResult:d});f&&(e.error=f),this.onProcessSettled(e)}catch(t){!e.stopReason&&!e.error&&(e.error=_(t))}return this.buildResult(e,/* @__PURE__ */ new Date)}finally{n.cleanup(),this.sigkillTimer&&=(clearTimeout(this.sigkillTimer),void 0);try{await this.onRunFinished(e)}catch(e){this.appendRawLog(`[cleanup-error] ${c(e)}`)}}}async watchStdout(e){let t=e.process?.stdout;if(t)for await(let n of f(t))this.appendLog(`stdout`,n),this.processLine(e,n)}async deliverInput(e,t,n){try{if(typeof t==`object`){await g(e,t,n);return}if(t!==void 0){if(!e.stdin?.write)throw Error(`The process spawner must provide a stdin writer for this adapter.`);await e.stdin.write(t)}await e.stdin?.end()}catch(t){throw e.kill(`SIGKILL`),t}}async watchStderr(e){let t=e.process?.stderr;if(t)for await(let n of f(t))this.appendLog(`stderr`,n),this.recordStderrLine(e,n)}recordStderrLine(e,n){e.stderrLines.push(n),this.emit(e,t(e.runId,`stderr`,{sessionId:e.sessionId,text:n}))}processLine(t,n){let r;try{r=JSON.parse(n)}catch(e){this.onParseError(n,e);return}let i;try{i=this.mapRawEvent(r,e(t))}catch(e){this.onParseError(n,e);return}this.applyBatch(t,i)}get runRequestDefaults(){return this.defaults}onHandlerError(e){this.appendRawLog(`[handler-error] ${c(e)}`)}async onDispose(){this.providerHandlers.clear();let e=this.logStream;this.logStream=void 0,e&&await new Promise(t=>{e.end(t)})}onStopRequested(e){e.process?.kill(),this.sigkillTimer=setTimeout(()=>{e.process?.kill(`SIGKILL`)},5e3),this.sigkillTimer.unref?.()}onBeforeRun(e){return this.ensureExecutionTarget()}onProcessSettled(e){}async onRunFinished(e){}appendRawLog(e){if(!this.logStream)return;let t=typeof e==`string`?e:JSON.stringify(e);this.logStream.write(`${t}\n`)}initLogStream(e){try{d(l(e),{recursive:!0}),this.logStream=u(e,{flags:`a`}),this.logStream.write(`\n--- ${(/* @__PURE__ */ new Date()).toISOString()} ---\n`)}catch{this.logStream=void 0}}appendLog(e,t){if(!this.logStream||!t)return;let n=e===`stderr`?`STDERR`:`STDOUT`,r=(/* @__PURE__ */ new Date()).toISOString();for(let e of t.split(`
4
+ `))e&&this.logStream.write(`[${r}] ${n} ${e}\n`)}async ensureExecutionTarget(){this.executionTargetRef&&this.executionTargetRef.status!==`running`&&await this.executionTargetRef.start()}};export{v as t};
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./classify-error-_WNZMhMY.mjs";var n=class extends e{currentAbortController;cleanupSdkResources(){}onStopRequested(e){this.currentAbortController?.abort()}async executeRunCore(e,n){let r=new AbortController;this.currentAbortController=r;let i=this.setupRunLifecycle(e);try{return i.abortedBeforeStart||e.stopReason||(e.sessionId&&this.emitSessionStart(e),await this.executeSdkRun(e,n,r)),this.buildResult(e,/* @__PURE__ */ new Date)}catch(n){return!e.stopReason&&!e.error&&(e.error=t(n)),this.buildResult(e,/* @__PURE__ */ new Date)}finally{i.cleanup();try{await this.cleanupSdkResources()}catch{}this.currentAbortController===r&&(this.currentAbortController=void 0)}}};export{n as t};
@@ -0,0 +1,2 @@
1
+ import { a as AntigravityMode, i as AntigravityCliRunOptions, n as AntigravityCliAgent, o as AntigravityThoughtLevel, r as AntigravityCliAgentOptions, s as AntigravityProviderEvent, t as createAntigravityCliAgent } from "../../index-DUTtolch.mjs";
2
+ export { type AntigravityCliAgent, type AntigravityCliAgentOptions, type AntigravityCliRunOptions, type AntigravityMode, type AntigravityProviderEvent, type AntigravityThoughtLevel, createAntigravityCliAgent };
@@ -0,0 +1,2 @@
1
+ import{t as e}from"../../Agent-BsDJsgJa.mjs";import{t}from"../../execution-target-CdlYXh6Z.mjs";import{f as n,l as r,p as i,s as a}from"../../classify-error-_WNZMhMY.mjs";import{a as o,i as s,n as c,t as l}from"../../util-CCXryPDO.mjs";import{a as u,i as d,n as f,o as p,r as m}from"../../permissions-BjNU9GCH.mjs";import{n as h,t as g}from"../../questions-CaEwN4JQ.mjs";import{z as _}from"zod/v4";const v=_.union([_.string(),_.number().int()]),y=_.object({id:v.optional(),method:_.string().optional(),params:_.unknown().optional(),result:_.unknown().optional(),error:_.looseObject({message:_.string()}).optional()}),b=_.looseObject({sessionUpdate:_.string()}),x=_.object({sessionId:_.string(),update:b}),ee=_.object({sessionId:_.string().optional(),models:_.object({currentModelId:_.string().optional()}).nullable().optional()}),S=_.looseObject({type:_.string(),text:_.string().optional()}),C=_.object({content:S}),w=_.enum([`pending`,`in_progress`,`completed`,`failed`]),T=_.looseObject({toolCallId:_.string(),name:_.string().nullish(),title:_.string().nullish(),kind:_.string().nullish(),status:w.nullish(),args:_.unknown().optional(),rawInput:_.unknown().optional(),rawOutput:_.unknown().optional(),content:_.array(_.looseObject({type:_.string(),content:S.optional()})).nullable().optional()}),te=_.object({inputTokens:_.number(),outputTokens:_.number(),cachedReadTokens:_.number().optional(),cachedWriteTokens:_.number().optional(),thoughtTokens:_.number().optional()}),E=_.object({stopReason:_.string(),usage:te.optional()}),D=_.object({sessionId:_.string(),toolCall:T,options:_.array(_.object({optionId:_.string(),name:_.string().optional(),kind:_.string()}))}),O=_.object({const:_.string(),title:_.string().optional()}),k=_.object({oneOf:_.array(O).optional(),anyOf:_.array(O).optional(),enum:_.array(_.string()).optional(),enumNames:_.array(_.string()).optional()}),A=k.extend({type:_.string().optional(),title:_.string().optional(),description:_.string().optional(),items:k.optional()}),j=_.object({sessionId:_.string(),toolCallId:_.string().optional(),mode:_.string().optional(),message:_.string().optional(),requestedSchema:_.object({properties:_.record(_.string(),A)})}),M=/* @__PURE__ */ new Set([`completed`,`failed`]),N=e=>{let{content:t}=C.parse(e);return t.type===`text`?t.text??``:``},P=({name:e,title:t,kind:n})=>e??t??n??`tool`,ne=({rawOutput:e,content:t})=>{let n=c(e)?e.output:void 0;if(typeof n==`string`)return n;let r=(t??[]).flatMap(e=>{let t=e.content?.text;return t===void 0?[]:[t]});return r.length>0?r.join(`
2
+ `):e??``},F=e=>typeof e!=`string`||e===``?`The tool call failed.`:e,I=(e,t)=>s(...e.map(t)),L=(e,t)=>{let n=I(e,e=>e.inputTokens),r=I(e,e=>e.cachedReadTokens),i=I(e,e=>e.cachedWriteTokens),a=I(e,e=>e.outputTokens);return{turns:1,costUsd:0,inputTokens:n,cacheReadInputTokens:r,cacheCreationInputTokens:i,outputTokens:a,reasoningOutputTokens:I(e,e=>e.thoughtTokens),totalTokens:s(n,r,i,a),...t===void 0?{}:{models:[t]}}},R=({readModel:e,streamsText:t})=>{let n,a,o,s=/* @__PURE__ */ new Set,c=/* @__PURE__ */ new Set,l=({text:e})=>!(t&&e!==``)&&e.trim()===``,u=t=>{let a=n;return n=void 0,a===void 0||l(a)?[]:(a.text.trim()!==``&&(o=a.text),[r(t.runId,`message`,{id:a.id,sessionId:t.sessionId,model:e()??null,role:`assistant`,content:[i(a.text)],text:a.text})])},d=t=>{let n=a;return a=void 0,n===void 0||l(n)?[]:[r(t.runId,`reasoning`,{id:n.id,sessionId:t.sessionId,model:e()??null,content:[i(n.text)],text:n.text})]},f=e=>[...d(e),...u(e)],p=()=>{n=void 0,a=void 0},m=(e,i)=>{let a=d(i);return n??={id:crypto.randomUUID(),text:``},n.text+=e,t&&e!==``?[...a,r(i.runId,`message-delta`,{sessionId:i.sessionId,messageId:n.id,text:e})]:a},h=(e,n)=>{let i=u(n);return a??={id:crypto.randomUUID(),text:``},a.text+=e,t&&e!==``?[...i,r(n.runId,`reasoning-delta`,{sessionId:n.sessionId,reasoningId:a.id,text:e})]:i},g=(t,n)=>{let i=T.parse(t),{toolCallId:a}=i,o=P(i),l=i.rawInput??i.args,u=i.status!=null&&M.has(i.status),d={events:f(n),toolCalls:[{toolCallId:a,toolName:o,input:l}]};if((l!=null||u)&&!s.has(a)&&(s.add(a),d.events.push(r(n.runId,`tool-call`,{sessionId:n.sessionId,model:e()??null,toolCallId:a,toolName:o,input:l}))),!u||c.has(a))return d;c.add(a);let p=ne(i),m=i.status===`failed`;return d.events.push(r(n.runId,`tool-result`,{sessionId:n.sessionId,toolCallId:a,toolName:o,input:l,output:p,...m?{isError:!0,error:F(p)}:{}})),d};return{mapUpdate:(e,t)=>{switch(e.sessionUpdate){case`agent_message_chunk`:return{events:m(N(e),t)};case`agent_thought_chunk`:return{events:h(N(e),t)};case`tool_call`:case`tool_call_update`:return g(e,t);default:return{events:[]}}},flushText:f,discardText:p,readLastMessage:()=>o}},z=`_other`,B=e=>{let t=e.oneOf??e.anyOf;return t===void 0?(e.enum??[]).map((t,n)=>({value:t,label:e.enumNames?.[n]??t})):t.map(e=>({value:e.const,label:e.title??e.const}))},V=e=>e.type===`array`?e.items===void 0?[]:B(e.items):B(e),H=(e,t)=>e.endsWith(z)&&t[e.slice(0,-6)]!==void 0,U=({requestedSchema:{properties:e}})=>Object.entries(e).filter(([t])=>!H(t,e)),W=e=>U(e).map(([t,n])=>({id:t,text:n.title??n.description??e.message??t,header:``,options:V(n).map(({label:e})=>({label:e,description:``})),allowsMultiple:n.type===`array`})),G=({name:e,property:t,answers:n,properties:r})=>{let i=V(t),a=/* @__PURE__ */ new Map;for(let{label:e,value:t}of i)a.has(e)||a.set(e,t);let o=n.flatMap(e=>{let t=a.get(e);return t===void 0?[]:[t]}),{freeFormText:s}=g(n,i.map(({label:e})=>e)),c=[];if(t.type===`array`?c.push([e,o]):o[0]!==void 0&&c.push([e,o[0]]),s===``)return c;let l=`${e}${z}`;return r[l]===void 0?i.length===0&&c.push([e,s]):c.push([l,s]),c},K=(e,t)=>{let{properties:n}=e.requestedSchema,r=U(e).flatMap(([e,r])=>{let i=t[e];return i===void 0||i.length===0?[]:G({name:e,property:r,answers:i,properties:n})});return{action:`accept`,content:Object.fromEntries(r)}},q=e=>{if(!u(e))return[{type:`text`,text:n(e)}];let t=[];for(let n of e){if(n.type===`text`){n.text!==``&&t.push({type:`text`,text:n.text});continue}let{data:e,mediaType:r}=p(n);t.push({type:`image`,data:e,mimeType:r})}return t},J=`initialize`,Y=`session`,X=`prompt-`,re={allow:`allow_once`,deny:`reject_once`},ie=e=>JSON.stringify([typeof e,e]),ae=({rawInput:e,args:t})=>{let n=e??t;return c(n)?n:n===void 0?{}:{input:n}},oe=({options:e},t)=>{let n=e.find(({kind:e})=>e===re[t]);if(n===void 0)throw Error(`Antigravity offered no option to ${t} the tool call.`);return{outcome:{outcome:`selected`,optionId:n.optionId}}},Z={outcome:{outcome:`cancelled`}},Q={action:`cancel`},se={action:`decline`},$=/* @__PURE__ */ new Map([[`session/request_permission`,Z],[`elicitation/create`,Q]]);var ce=class{options;channel=h();pendingRequestsByKey=/* @__PURE__ */ new Map;toolCallsById=/* @__PURE__ */ new Map;setupRequests=[];usages=[];initialPromptBlocks=[];sessionId;promptCount=0;activePromptId;hasCancelled=!1;constructor(e){this.options=e}get hasTerminated(){return this.channel.isClosed}async*lines(e){this.initialPromptBlocks=q(e),this.send({id:J,method:`initialize`,params:{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,...this.options.questionHandler===void 0?{}:{elicitation:{form:{}}}},clientInfo:{name:`coding-agents-sdk`,version:`1`}}}),yield*this.channel.lines}close(){this.channel.isClosed||(this.channel.close(),this.abortPendingRequests(),this.pendingRequestsByKey.clear(),this.toolCallsById.clear())}steer(e){if(this.activePromptId===void 0||this.channel.isClosed)throw a(`Antigravity has no turn in progress.`);this.sendPromptBlocks(q(e))}cancel(){this.channel.isClosed||this.hasCancelled||(this.hasCancelled=!0,this.activePromptId===void 0?this.close():(this.send({method:`session/cancel`,params:{sessionId:this.sessionId}}),this.abortPendingRequests()))}observe(e){try{return this.readMessage(e)}catch(e){return this.close(),{kind:`failed`,message:l(e)}}}abortPendingRequests(){for(let e of this.pendingRequestsByKey.values())e.abort()}readMessage(e){let t=y.parse(e);if(t.method!==void 0&&t.id!==void 0)this.answerRequest(t.id,t.method,t.params);else{if(t.method!==void 0)return this.readNotification(t.method,t.params);if(t.id!==void 0)return this.isPromptId(t.id)&&t.id!==this.activePromptId?(this.recordUsage(t.result),{kind:`prompt-superseded`}):t.error===void 0?this.readResponse(t.id,t.result):(this.close(),{kind:`failed`,message:t.error.message})}}readNotification(e,t){if(e!==`session/update`)return;let n=x.parse(t);if(n.sessionId!==this.sessionId)return;let r=n.update;return r.sessionUpdate!==`tool_call`&&r.sessionUpdate!==`tool_call_update`?{kind:`update`,update:r,rawUpdate:r}:{kind:`update`,update:{...this.mergeToolCall(T.parse(r)),sessionUpdate:r.sessionUpdate},rawUpdate:r}}mergeToolCall(e){let t=this.toolCallsById.get(e.toolCallId),n={...t,...e,name:e.name??t?.name,title:e.title??t?.title,kind:e.kind??t?.kind,status:e.status??t?.status,args:e.args??t?.args,rawInput:e.rawInput??t?.rawInput,rawOutput:e.rawOutput??t?.rawOutput,content:e.content??t?.content};return this.toolCallsById.set(e.toolCallId,structuredClone(n)),n}readResponse(e,t){if(e===J)this.openSession();else{if(e===Y){let e=ee.parse(t),n=e.sessionId??this.options.sessionId;if(n===void 0)throw Error(`Antigravity opened a session without an ID.`);return this.sessionId=n,this.queueSetup(n),this.sendNextSetupRequest(),{kind:`session`,sessionId:n,model:this.options.model??e.models?.currentModelId}}if(e===this.activePromptId){let{stopReason:e}=E.parse(t);return this.recordUsage(t),this.activePromptId=void 0,this.close(),{kind:`turn-ended`,stopReason:e,usages:[...this.usages]}}this.sendNextSetupRequest()}}openSession(){let{sessionId:e,cwd:t}=this.options,n=e===void 0?`session/new`:`session/resume`;this.send({id:Y,method:n,params:{...e===void 0?{}:{sessionId:e},cwd:t,mcpServers:[]}})}queueSetup(e){let{model:t,thoughtLevel:n,mode:r}=this.options;t!==void 0&&this.setupRequests.push({id:`set-model`,method:`session/set_model`,params:{sessionId:e,modelId:t}}),n!==void 0&&this.setupRequests.push({id:`set-thought-level`,method:`session/set_config_option`,params:{sessionId:e,configId:`thought_level`,value:n}}),r!==void 0&&this.setupRequests.push({id:`set-mode`,method:`session/set_mode`,params:{sessionId:e,modeId:r}})}sendNextSetupRequest(){let e=this.setupRequests.shift();e===void 0?this.sendPromptBlocks(this.initialPromptBlocks):this.send(e)}sendPromptBlocks(e){this.promptCount+=1;let t=`${X}${this.promptCount}`;this.activePromptId=t,this.send({id:t,method:`session/prompt`,params:{sessionId:this.sessionId,prompt:e}})}isPromptId(e){return typeof e==`string`&&e.startsWith(X)}recordUsage(e){let t=E.safeParse(e);t.success&&t.data.usage!==void 0&&this.usages.push(t.data.usage)}async answerRequest(e,t,n){if(this.channel.isClosed)return;if(this.hasCancelled){this.sendRequestResult(e,t,$.get(t));return}let r=ie(e),i=new AbortController;try{if(this.pendingRequestsByKey.has(r))throw Error(`Antigravity reused a pending request ID.`);this.pendingRequestsByKey.set(r,i);let a=await this.decideRequest(t,n,i.signal);this.sendRequestResult(e,t,a)}catch(n){if(i.signal.aborted){let n=$.get(t);n!==void 0&&this.send({id:e,result:n});return}this.options.onHandlerError(n),this.send({id:e,error:{code:-32602,message:l(n)}})}finally{this.pendingRequestsByKey.get(r)===i&&this.pendingRequestsByKey.delete(r)}}async decideRequest(e,t,n){switch(e){case`session/request_permission`:{let e=D.parse(t),r=await this.decideToolCall(e,n);return n.aborted?Z:oe(e,r.decision)}case`elicitation/create`:{let e=j.parse(t),r=this.options.questionHandler;if(r===void 0||e.mode!==`form`)return se;let i=await r({toolUseId:e.toolCallId??crypto.randomUUID(),questions:W(e),signal:n});return n.aborted?Q:K(e,i)}default:return}}sendRequestResult(e,t,n){n===void 0?this.send({id:e,error:{code:-32601,message:`Unsupported ACP request: ${t}`}}):this.send({id:e,result:n})}async decideToolCall(e,t){let n=this.mergeToolCall(e.toolCall),r=await m(this.options.permissionHandler,{toolName:P(n),toolUseId:n.toolCallId,input:ae(n),signal:t,...n.title==null?{}:{title:n.title}});if(f(r))throw Error(d(`Antigravity permission requests`));return r}send(e){this.channel.send({jsonrpc:`2.0`,...e})}};const le={structuredOutput:!1,sessionResume:!0,imageInput:!0,mcp:!1,eventStreaming:!0,permissionRequests:!0,midRunInput:!0,questionRequests:!0},ue={max_tokens:`Antigravity's model reached its output limit, so the response is incomplete.`,max_turn_requests:`Antigravity reached its limit on model requests for the turn, so the work is incomplete.`,refusal:`Antigravity refused to continue the turn.`},de=e=>{let t=ue[e];return t===void 0?`Antigravity ended the turn with the stop reason "${e}".`:t},fe=e=>e===`end_turn`?{status:`completed`}:e===`cancelled`?{status:`cancelled`}:{status:`failed`,error:{kind:`provider`,message:de(e)}};var pe=class extends e{type=`antigravity-cli`;creationOptions;runDefaults;activeRun;stopTimer;constructor(e={}){super({type:`antigravity-cli`,capabilities:{...le,textStreaming:e.streamText===!0},defaults:{cwd:e.cwd,env:e.env,command:o(e.command??`agy`),sessionId:e.sessionId,model:e.model},spawner:e.spawner,executionTarget:e.container??e.sandbox,logPath:e.logPath,onEvent:e.onEvent,onProviderEvent:e.onProviderEvent}),this.creationOptions=e,this.runDefaults={mode:e.mode,thoughtLevel:e.thoughtLevel,extraArgs:e.extraArgs?[...e.extraArgs]:void 0}}buildArgs(e,t){let n=[`acp`];this.creationOptions.skipPermissions===!0&&n.push(`--dangerously-skip-permissions`),n.push(...e.extraArgs??this.runDefaults.extraArgs??[]);let r={session:new ce({cwd:e.cwd??process.cwd(),sessionId:t.requestedSessionId,model:e.model,thoughtLevel:e.thoughtLevel??this.runDefaults.thoughtLevel,mode:e.mode??this.runDefaults.mode,permissionHandler:this.getPermissionHandler(),questionHandler:this.getQuestionHandler(),onHandlerError:e=>this.onHandlerError(e)}),model:e.model,mapper:R({readModel:()=>r.model,streamsText:this.capabilities.textStreaming===!0})};return this.activeRun=r,n}buildEnv(){return this.buildDefaultEnv(this.creationOptions.propagateEnv)}getStdinInput(e){return this.activeRun===void 0?n(e.input):this.activeRun.session.lines(e.input)}mapRawEvent(e,t){this.appendRawLog(e);let n=this.activeRun;if(n===void 0)return{events:[]};let r=n.session.observe(e);return r===void 0?{events:[]}:this.mapObservation(n,r,t)}mapObservation(e,t,n){switch(t.kind){case`session`:return e.model??=t.model,{events:[],sessionId:t.sessionId};case`update`:return this.emitProviderEvent(t.rawUpdate,n),e.mapper.mapUpdate(t.update,n);case`prompt-superseded`:return{events:e.mapper.flushText(n)};case`turn-ended`:{let r=fe(t.stopReason);r.status!==`completed`&&e.mapper.discardText();let i=e.mapper.flushText(n),a=e.mapper.readLastMessage();return{events:i,state:{...r,stats:L(t.usages,e.model),...a===void 0?{}:{output:{text:a}}}}}case`failed`:return e.mapper.discardText(),{events:[],state:{status:`failed`,error:{kind:`provider`,message:t.message}}};default:throw Error(`Unhandled ACP observation: ${JSON.stringify(t)}`)}}async sendRunInput(e,t){let n=this.activeRun?.session;if(n===void 0)throw a(`Antigravity has not started.`);n.steer(t)}onStopRequested(e){let t=this.activeRun?.session;t===void 0?super.onStopRequested(e):(t.cancel(),this.stopTimer=setTimeout(()=>{t.close(),super.onStopRequested(e)},5e3),this.stopTimer.unref?.())}onProcessSettled(e){this.activeRun===void 0||this.activeRun.session.hasTerminated||e.stopReason!==void 0||e.error!==void 0||this.applyBatch(e,{events:[],state:{status:`failed`,error:{kind:`process`,message:`Antigravity closed before the turn completed.`}}})}async onRunFinished(e){await super.onRunFinished(e),clearTimeout(this.stopTimer),this.stopTimer=void 0,this.activeRun?.session.close(),this.activeRun=void 0}};const me=e=>new pe(t(e));export{me as createAntigravityCliAgent};
@@ -1,2 +1,2 @@
1
- import { a as ClaudeCodeCliRunOptions, c as ClaudeProviderEvent, d as ClaudeSystemEvent, f as ClaudeUserEvent, i as ClaudeCodeCliPermissionMode, l as ClaudeRateLimitEvent, n as ClaudeCodeCliAgent, o as ClaudeAssistantEvent, r as ClaudeCodeCliAgentOptions, s as ClaudeEvent, t as createClaudeCodeCliAgent, u as ClaudeResultEvent } from "../../index-DCQu5ZAu.mjs";
2
- export { type ClaudeAssistantEvent, type ClaudeCodeCliAgent, type ClaudeCodeCliAgentOptions, type ClaudeCodeCliPermissionMode, type ClaudeCodeCliRunOptions, type ClaudeEvent, type ClaudeProviderEvent, type ClaudeRateLimitEvent, type ClaudeResultEvent, type ClaudeSystemEvent, type ClaudeUserEvent, createClaudeCodeCliAgent };
1
+ import { C as ClaudeControlRequestPayload, S as ClaudeControlRequestFailure, _ as ClaudeRateLimitEvent, a as ClaudeBackgroundTaskChange, b as ClaudeUserEvent, c as ClaudeBackgroundTaskStatus, d as ClaudeCodeCliAgentOptions, f as ClaudeCodeCliPermissionMode, g as ClaudeProviderEvent, h as ClaudeEvent, i as ClaudeBackgroundTask, l as ClaudeBackgroundTaskUsage, m as ClaudeAssistantEvent, n as ClaudeAgentRun, o as ClaudeBackgroundTaskEnd, p as ClaudeCodeCliRunOptions, r as ClaudeBackgroundSubagent, s as ClaudeBackgroundTaskProgress, t as createClaudeCodeCliAgent, u as ClaudeCodeCliAgent, v as ClaudeResultEvent, x as ClaudeControlRequestError, y as ClaudeSystemEvent } from "../../index-DilMV_1s.mjs";
2
+ export { type ClaudeAgentRun, type ClaudeAssistantEvent, type ClaudeBackgroundSubagent, type ClaudeBackgroundTask, type ClaudeBackgroundTaskChange, type ClaudeBackgroundTaskEnd, type ClaudeBackgroundTaskProgress, type ClaudeBackgroundTaskStatus, type ClaudeBackgroundTaskUsage, type ClaudeCodeCliAgent, type ClaudeCodeCliAgentOptions, type ClaudeCodeCliPermissionMode, type ClaudeCodeCliRunOptions, ClaudeControlRequestError, type ClaudeControlRequestFailure, type ClaudeControlRequestPayload, type ClaudeEvent, type ClaudeProviderEvent, type ClaudeRateLimitEvent, type ClaudeResultEvent, type ClaudeSystemEvent, type ClaudeUserEvent, createClaudeCodeCliAgent };
@@ -1 +1 @@
1
- import{n as e}from"../../types-B72tDMEZ.mjs";import{a as t,t as n}from"../../util-B4HTdOSc.mjs";import{t as r}from"../../env-Cb8MIvH7.mjs";import{l as i}from"../../classify-error-DK2WpxiL.mjs";import{t as a}from"../../execution-target-CdlYXh6Z.mjs";import{a as o,n as s,r as c,t as l}from"../../session-markers-BHsJLWJk.mjs";import{a as u,i as d,n as f,o as p,r as m,s as h,t as g}from"../../parser-jSS5vOTN.mjs";import{t as _}from"../../Agent-WqGee5TR.mjs";import{join as v}from"node:path";import{mkdtempSync as y,rmSync as b,writeFileSync as x}from"node:fs";import{tmpdir as S}from"node:os";import{rm as C}from"node:fs/promises";const w=e=>`${JSON.stringify(e)}\n`;var T=class{handler;abortController=new AbortController;pendingLines=[];pendingRequests=/* @__PURE__ */ new Map;wakeReader;sessionState;hasReceivedResult=!1;idleWaitTimer;constructor(e){this.handler=e}get isClosed(){return this.abortController.signal.aborted}async*lines(e){for(yield w({type:`user`,message:{role:`user`,content:e},parent_tool_use_id:null});;){let e=this.pendingLines.shift();if(e!==void 0){yield e;continue}if(this.isClosed)return;await new Promise(e=>{this.wakeReader=e})}}close(){clearTimeout(this.idleWaitTimer),this.abortController.abort(),this.wakeReader?.()}observeEvent(e){let t=u.safeParse(e);if(!t.success)return;let n=t.data;if(n.type===`result`){this.hasReceivedResult=!0,this.sessionState===void 0||this.sessionState===`idle`?this.close():this.sessionState!==`requires_action`&&this.armIdleWaitCeiling();return}if(this.sessionState=n.state,n.state===`requires_action`){clearTimeout(this.idleWaitTimer);return}if(this.hasReceivedResult){if(n.state===`idle`){this.close();return}this.armIdleWaitCeiling()}}async answerControlRequest({request_id:e,request:t}){if(t.subtype!==`can_use_tool`){this.sendError(e,`Unsupported control request subtype: ${t.subtype}`);return}let n=f.safeParse(t);if(!n.success){this.sendError(e,`Invalid can_use_tool request.`);return}let r=new AbortController;this.pendingRequests.set(e,r);let i=await this.decide(n.data,AbortSignal.any([this.abortController.signal,r.signal]));this.pendingRequests.delete(e),!r.signal.aborted&&this.send({type:`control_response`,response:{subtype:`success`,request_id:e,response:i}})}cancelControlRequest(e){this.pendingRequests.get(e)?.abort(),this.pendingRequests.delete(e)}armIdleWaitCeiling(){clearTimeout(this.idleWaitTimer),this.idleWaitTimer=setTimeout(()=>this.close(),6e5),this.idleWaitTimer.unref?.()}async decide(e,t){try{let n=await this.handler({toolName:e.tool_name,input:e.input,toolUseId:e.tool_use_id,signal:t,reason:e.decision_reason,blockedPath:e.blocked_path,title:e.title,description:e.description});return n.decision===`allow`?{behavior:`allow`,updatedInput:n.updatedInput??e.input}:{behavior:`deny`,message:n.message??`Tool call denied.`}}catch(e){return{behavior:`deny`,message:n(e)}}}sendError(e,t){this.send({type:`control_response`,response:{subtype:`error`,request_id:e,error:t}})}send(e){this.isClosed||(this.pendingLines.push(w(e)),this.wakeReader?.())}};const E=[`--resume`,`-r`,`--continue`,`-c`,`--fork-session`,`--session-id`],D=(e,t)=>e===t||e.startsWith(`${t}=`),O=e=>e.some(e=>E.some(t=>D(e,t))),k={structuredOutput:!0,sessionResume:!0,imageInput:!1,mcp:!0,eventStreaming:!0,sessionFork:!0,permissionRequests:!0};var A=class n extends _{type=`claude-code-cli`;creationOptions;runDefaults;forkOnNextRun;recordedSessionTotals;mcpTempDir;activeSession;runStats=/* @__PURE__ */ new Map;constructor(e={}){super({type:`claude-code-cli`,capabilities:k,defaults:{cwd:e.cwd,env:e.env,command:e.command?t(e.command):void 0,sessionId:e.sessionId,model:e.model,systemPrompt:e.systemPrompt},spawner:e.spawner,executionTarget:e.container??e.sandbox,logPath:e.logPath,onEvent:e.onEvent,onProviderEvent:e.onProviderEvent}),this.creationOptions={...e,command:e.command?[...t(e.command)]:void 0,env:e.env?{...e.env}:void 0,allowedTools:e.allowedTools?[...e.allowedTools]:void 0,disallowedTools:e.disallowedTools?[...e.disallowedTools]:void 0,mcpConfig:Array.isArray(e.mcpConfig)?[...e.mcpConfig]:e.mcpConfig,mcpServers:e.mcpServers?{...e.mcpServers}:void 0,extraArgs:e.extraArgs?[...e.extraArgs]:void 0},this.runDefaults={allowedTools:e.allowedTools?[...e.allowedTools]:void 0,disallowedTools:e.disallowedTools?[...e.disallowedTools]:void 0,appendSystemPrompt:e.appendSystemPrompt,permissionMode:e.permissionMode,mcpConfig:Array.isArray(e.mcpConfig)?[...e.mcpConfig]:e.mcpConfig,mcpServers:e.mcpServers?{...e.mcpServers}:void 0,forkSession:e.forkSession,extraArgs:e.extraArgs?[...e.extraArgs]:void 0},this.forkOnNextRun=e.forkOnNextRun??!1,this.recordedSessionTotals=e.recordedSessionTotals}fork(){if(!this.sessionId)throw new e(`Cannot fork a Claude Code CLI agent before it has a sessionId.`);return new n({...this.creationOptions,sessionId:this.sessionId,forkSession:void 0,forkOnNextRun:!0,recordedSessionTotals:this.recordedSessionTotals,onProviderEvent:void 0})}onValidateRun(t,n){if((t.forkSession??this.runDefaults.forkSession??this.forkOnNextRun)&&!this.sessionId)throw new e(`forkSession requires an existing sessionId on the agent.`)}async onBeforeRun(e){await super.onBeforeRun(e);let t=this.getPermissionHandler();t&&(this.activeSession=new T(t))}onStopRequested(e){super.onStopRequested(e),this.activeSession?.close()}async onRunFinished(e){await super.onRunFinished(e),this.recordedSessionTotals=this.runStats.get(e.runId)?.sessionTotals??this.recordedSessionTotals,this.runStats.delete(e.runId),this.activeSession?.close(),this.activeSession=void 0,await this.cleanupMcpTempDir()}async onDispose(){await super.onDispose(),await this.cleanupMcpTempDir()}async cleanupMcpTempDir(){if(this.mcpTempDir){let e=this.mcpTempDir;this.mcpTempDir=void 0,await C(e,{recursive:!0,force:!0}).catch(()=>{})}}ensureMcpTempFile(e){this.mcpTempDir&&=(b(this.mcpTempDir,{recursive:!0,force:!0}),void 0),this.mcpTempDir=y(v(S(),`cw-mcp-`));let t=v(this.mcpTempDir,`mcp.json`);return x(t,JSON.stringify({mcpServers:e}),{encoding:`utf8`,mode:384}),t}buildArgs(e,n){let r=[`--verbose`,`--output-format`,`stream-json`],i=e.permissionMode??this.runDefaults.permissionMode,a=e.appendSystemPrompt??this.runDefaults.appendSystemPrompt,l=e.allowedTools??this.runDefaults.allowedTools,u=o(e.disallowedTools??this.runDefaults.disallowedTools),d=e.mcpConfig??this.runDefaults.mcpConfig,f=e.mcpServers??this.runDefaults.mcpServers,p=e.extraArgs??this.runDefaults.extraArgs,m=e.forkSession??this.runDefaults.forkSession??this.forkOnNextRun,h=this.defaults.command?.slice(1)??[];if(this.runStats.set(n.runId,new c({requestedSessionId:n.requestedSessionId,recordedSessionTotals:this.recordedSessionTotals,mayResumeUntrackedSession:O([...h,...p??[]])})),e.model&&r.push(`--model`,e.model),e.systemPrompt&&r.push(`--system-prompt`,e.systemPrompt),a&&r.push(`--append-system-prompt`,a),i&&r.push(`--permission-mode`,i),l&&l.length>0&&r.push(`--allowed-tools`,l.join(`,`)),r.push(`--disallowed-tools`,u.join(`,`)),d)for(let e of t(d))r.push(`--mcp-config`,e);return f&&r.push(`--mcp-config`,this.ensureMcpTempFile(f)),this.activeSession&&r.push(`--permission-prompt-tool`,`stdio`),e.schema.kind!==`none`&&r.push(`--json-schema`,JSON.stringify(s(e.schema.jsonSchema))),n.requestedSessionId&&(r.push(`--resume`,n.requestedSessionId),m&&r.push(`--fork-session`)),p&&p.length>0&&r.push(...p),r.push(`--input-format`,this.activeSession?`stream-json`:`text`,`--print`),r}buildEnv(e,t){let n=r({propagateEnv:this.creationOptions.propagateEnv});return this.creationOptions.ci!==!1&&(n.CI=n.CI??`true`),this.defaults.env&&Object.assign(n,this.defaults.env),this.activeSession&&(n.CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS??=`1`),l(n),n}mapRawEvent(e,t){this.appendRawLog(e);let n=m.safeParse(e);if(n.success)return n.data.type===`control_request`?this.activeSession?.answerControlRequest(n.data):n.data.type===`control_cancel_request`&&this.activeSession?.cancelControlRequest(n.data.request_id),{events:[]};if(this.hasProviderEventListeners){let n=d.safeParse(e);n.success&&this.emitProviderEvent(n.data,t,n.data.session_id??t.sessionId)}this.activeSession?.observeEvent(e);let r=g(e);if(!r)return this.onParseError(JSON.stringify(e).slice(0,200),/* @__PURE__ */ Error(`schema validation failed`)),{events:[]};let i=p(r)??t.sessionId;this.forkOnNextRun&&t.requestedSessionId&&i&&i!==t.requestedSessionId&&(this.forkOnNextRun=!1);let a=h(r,{...t,sessionId:i},{statsAccumulator:this.runStats.get(t.runId)});return i&&a.sessionId===void 0&&(a.sessionId=i),a}getStdinInput(e){let t=i(e.input);return this.activeSession?this.activeSession.lines(t):t}};const j=e=>new A(a(e));export{j as createClaudeCodeCliAgent};
1
+ import{t as e}from"../../Agent-BsDJsgJa.mjs";import{t}from"../../execution-target-CdlYXh6Z.mjs";import{a as n,o as r,t as i}from"../../permissions-BjNU9GCH.mjs";import{a,f as o,i as s,l as c,s as l}from"../../classify-error-_WNZMhMY.mjs";import{n as u}from"../../types-B72tDMEZ.mjs";import{t as ee}from"../../env-Cb8MIvH7.mjs";import{a as d,n as f,t as p}from"../../util-CCXryPDO.mjs";import{_ as m,a as h,c as g,d as _,f as v,g as y,h as te,i as ne,l as b,m as re,n as ie,o as x,p as S,r as C,s as w,t as T,u as E,v as D,y as O}from"../../parser-BY3CZGmc.mjs";import{c as k,n as A,o as j,r as M,t as N}from"../../permission-updates-CkFvevWQ.mjs";import{t as P}from"../../control-requests-DtjV0e4o.mjs";import{join as F}from"node:path";import{mkdtempSync as I,rmSync as L,writeFileSync as R}from"node:fs";import{tmpdir as z}from"node:os";import{z as B}from"zod/v4";import{rm as ae}from"node:fs/promises";const V=/* @__PURE__ */ new Set([`local_agent`,`remote_agent`,`in_process_teammate`]),H=(e,t)=>{if(!f(e))return;let n=e[t];if(typeof n==`string`)return n},U=(e,t,n)=>{if(e!==void 0&&V.has(e))return{type:t,name:H(n,`name`)}},W=({tool_uses:e,total_tokens:t})=>({toolUses:e,totalTokens:t}),G=e=>e===`completed`||e===`failed`?e:`stopped`,K=e=>({...e,subagent:e.subagent===void 0?void 0:{...e.subagent}});var q=class{tasksById=/* @__PURE__ */ new Map;get hasRunning(){return this.tasksById.size>0}observe(e,t){if(!(f(e)&&e.type===`system`))return;let n=S.safeParse(e);if(n.success){if(n.data.is_backgrounded!==!0)return;let{task_id:e,tool_use_id:r,description:i,task_type:a,subagent_type:o,parent_task_id:s}=n.data,c=r===void 0?void 0:t(r)?.input,l={taskId:e,toolCallId:r,description:i,command:H(c,`command`),subagent:U(a,o,c),parentTaskId:s};return this.tasksById.set(e,l),{kind:`started`,task:K(l)}}let r=v.safeParse(e);if(r.success){let e=this.tasksById.get(r.data.task_id);if(e===void 0)return;let{usage:t,last_tool_name:n,summary:i}=r.data;return{kind:`progressed`,task:K(e),progress:{...W(t),lastToolName:n,summary:i}}}let i=_.safeParse(e);if(!i.success)return;let a=this.tasksById.get(i.data.task_id);if(a===void 0)return;this.tasksById.delete(i.data.task_id);let{status:o,summary:s,usage:c}=i.data;return{kind:`ended`,task:{...K(a),status:G(o),summary:s,usage:c===void 0?void 0:W(c)}}}endAll(){let e=[...this.tasksById.values()].map(e=>({kind:`ended`,task:{...K(e),status:`stopped`}}));return this.tasksById.clear(),e}},J=class{callsById=/* @__PURE__ */ new Map;heldEvents=[];get toolCalls(){return this.callsById}hold(e){this.heldEvents.push(...this.admit(e).events)}release(e){let t=this.heldEvents.map(t=>({...t,runId:e}));return this.heldEvents=[],{events:t,toolCalls:t.flatMap(e=>e.type===`tool-call`?[{toolCallId:e.toolCallId,toolName:e.toolName,input:e.input}]:[])}}admit(e){let t=[];for(let n of e.events){if(n.type===`tool-call`)this.callsById.set(n.toolCallId,{toolName:n.toolName,input:n.input});else if(n.type===`tool-result`&&!this.callsById.delete(n.toolCallId))continue;t.push(n)}return{...e,events:t}}forgetCalls(){this.callsById.clear()}clear(){this.callsById.clear(),this.heldEvents=[]}};const oe=B.object({questions:B.array(B.object({question:B.string(),header:B.string(),options:B.array(B.object({label:B.string(),description:B.string()})),multiSelect:B.boolean()}))}),se=e=>{if(e.tool_name!==`AskUserQuestion`)return;let t=oe.safeParse(e.input);if(t.success)return t.data.questions.map((e,t)=>({id:String(t),text:e.question,header:e.header,options:e.options,allowsMultiple:e.multiSelect}))},ce=(e,t,n)=>{let r=t.flatMap(e=>{let t=n[e.id];return t===void 0?[]:[[e.text,t.join(`, `)]]});return{...e,answers:Object.fromEntries(r)}},Y=e=>`${JSON.stringify(e)}\n`,le=e=>{if(!n(e))return o(e);let t=[];for(let n of e){if(n.type===`text`){n.text!==``&&t.push({type:`text`,text:n.text});continue}let{data:e,mediaType:i}=r(n);t.push({type:`image`,source:{type:`base64`,media_type:i,data:e}})}return t},ue=(e,t)=>({type:`user`,message:{role:`user`,content:le(e)},parent_tool_use_id:null,uuid:t});var X=class{readHandlers;onInputsAnswered;onPermissionModeChange;abortController=new AbortController;pendingLines=[];pendingRequests=/* @__PURE__ */ new Map;sentRequestsById=/* @__PURE__ */ new Map;wakeReader;sessionState;hasReceivedResult=!1;silenceLimitTimer;unansweredInputIds=/* @__PURE__ */ new Set;hasSeenAnsweredInputIds=!1;constructor({readHandlers:e,onInputsAnswered:t,onPermissionModeChange:n}){this.readHandlers=e,this.onInputsAnswered=t,this.onPermissionModeChange=n}get isClosed(){return this.abortController.signal.aborted}get answersToolRequests(){let{permissionHandler:e,questionHandler:t}=this.readHandlers();return e!==void 0||t!==void 0}async*lines(e){for(yield Y(this.createTrackedUserMessage(e));;){let e=this.pendingLines.shift();if(e!==void 0)yield e;else{if(this.isClosed)return;await new Promise(e=>{this.wakeReader=e})}}}close(){clearTimeout(this.silenceLimitTimer),this.abortController.abort(),this.wakeReader?.();for(let e of this.sentRequestsById.values())e.reject(new P(`input-closed`,`Claude Code's input closed before it answered the control request.`));this.sentRequestsById.clear()}sendControlRequest(e){if(this.isClosed)return Promise.reject(new P(`input-closed`,`Claude Code's input is closed; the run has ended.`));let t=`req_${crypto.randomUUID()}`,{promise:n,resolve:r,reject:i}=Promise.withResolvers();return this.sentRequestsById.set(t,{resolve:r,reject:i}),this.send({type:`control_request`,request_id:t,request:e}),n}sendUserMessage(e){this.send(this.createTrackedUserMessage(e))}receiveControlResponse(e){let t=x.safeParse(e);if(!t.success)return;let{response:n}=t.data,r=this.sentRequestsById.get(n.request_id);r!==void 0&&(this.sentRequestsById.delete(n.request_id),n.subtype===`error`?r.reject(new P(`refused`,n.error)):r.resolve(n.response))}observeEvent(e){if(this.onInputsAnswered!==void 0){this.reportAnsweredInputs(e,this.onInputsAnswered);return}let t=b.safeParse(e);if(!t.success){this.hasReceivedResult&&this.sessionState===`running`&&!this.isClosed&&this.restartSilenceLimit();return}let n=t.data;n.type===`result`?(this.hasReceivedResult=!0,this.removeAnsweredInputs(n.user_message_uuids),this.sessionState===void 0||this.sessionState===`idle`?this.close():this.sessionState!==`requires_action`&&this.restartSilenceLimit()):(this.sessionState=n.state,n.state===`requires_action`?clearTimeout(this.silenceLimitTimer):this.hasReceivedResult&&(n.state===`idle`&&this.hasAnsweredEveryInput?this.close():this.restartSilenceLimit()))}async answerControlRequest({request_id:e,request:t}){if(t.subtype!==`can_use_tool`){this.sendError(e,`Unsupported control request subtype: ${t.subtype}`);return}let n=ie.safeParse(t);if(!n.success){this.sendError(e,`Invalid can_use_tool request.`);return}let r=this.selectResponder(n.data);if(r===void 0){this.sendError(e,i);return}let a=new AbortController;this.pendingRequests.set(e,a);let{response:o,permissionMode:s}=await r(AbortSignal.any([this.abortController.signal,a.signal]));this.pendingRequests.delete(e),a.signal.aborted||(this.send({type:`control_response`,response:{subtype:`success`,request_id:e,response:o}}),s===void 0||this.isClosed||this.onPermissionModeChange?.(s))}cancelControlRequest(e){this.pendingRequests.get(e)?.abort(),this.pendingRequests.delete(e)}reportAnsweredInputs(e,t){let n=b.safeParse(e);if(!n.success)return;let r=n.data;if(r.type!==`result`)return;let i=r.user_message_uuids;i===void 0?this.hasSeenAnsweredInputIds||this.removeAnsweredInputs(void 0):(this.hasSeenAnsweredInputIds=!0,this.removeAnsweredInputs(i)),this.hasAnsweredEveryInput&&t()}get hasAnsweredEveryInput(){return this.unansweredInputIds.size===0}createTrackedUserMessage(e){let t=crypto.randomUUID(),n=ue(e,t);return this.unansweredInputIds.add(t),n}removeAnsweredInputs(e){if(e===void 0)this.unansweredInputIds.clear();else for(let t of e)this.unansweredInputIds.delete(t)}restartSilenceLimit(){clearTimeout(this.silenceLimitTimer),this.silenceLimitTimer=setTimeout(()=>this.close(),6e5),this.silenceLimitTimer.unref?.()}selectResponder(e){let{permissionHandler:t,questionHandler:n}=this.readHandlers();if(n!==void 0){let t=se(e);if(t!==void 0)return r=>this.ask(n,e,{toolUseId:e.tool_use_id,questions:t,signal:r})}if(t!==void 0)return n=>this.decide(t,e,n)}async ask(e,t,n){try{let r=await e(n);return{response:{behavior:`allow`,updatedInput:ce(t.input,n.questions,r)}}}catch(e){return{response:{behavior:`deny`,message:p(e)}}}}async decide(e,t,n){try{let r=await e({toolName:t.tool_name,input:t.input,toolUseId:t.tool_use_id,signal:n,reason:t.decision_reason,blockedPath:t.blocked_path,title:t.title,description:t.description});if(r.decision===`allow`){let e=N(r);return{response:{behavior:`allow`,updatedInput:r.updatedInput??t.input,...e===void 0?{}:{updatedPermissions:e}},permissionMode:r.permissionMode}}return{response:{behavior:`deny`,message:r.message??`Tool call denied.`}}}catch(e){return{response:{behavior:`deny`,message:p(e)}}}}sendError(e,t){this.send({type:`control_response`,response:{subtype:`error`,request_id:e,error:t}})}send(e){this.isClosed||(this.pendingLines.push(Y(e)),this.wakeReader?.())}};const Z=(e,t,n)=>{let r=`${e.apiMessageId}:${n}`,i=e.reservedEventIdsByType[t];return i.at(-1)!==r&&i.push(r),r};var de=class{streamedMessagesByParentToolCallId=/* @__PURE__ */ new Map;mapStreamEvent({event:e,session_id:t,parent_tool_use_id:n},r){let i=n??void 0;if(e.type===`message_start`){let{message:t}=w.parse(e);return this.streamedMessagesByParentToolCallId.set(i,{apiMessageId:t.id,reservedEventIdsByType:{message:[],reasoning:[]},hasStopped:!1}),{events:[]}}if(e.type===`message_stop`){let e=this.streamedMessagesByParentToolCallId.get(i);return e!==void 0&&(e.hasStopped=!0,this.releaseIfFinished(i,e)),{events:[]}}if(e.type!==`content_block_delta`)return{events:[]};let a=this.streamedMessagesByParentToolCallId.get(i);if(a===void 0)return{events:[]};let{index:o,delta:s}=ne.parse(e);switch(s.type){case`text_delta`:{let{text:e}=re.parse(s);if(e===``)return{events:[]};let n=Z(a,`message`,o);return{events:[c(r.runId,`message-delta`,{sessionId:t,parentToolCallId:i,messageId:n,text:e})]}}case`thinking_delta`:{let{thinking:e}=te.parse(s);if(e===``)return{events:[]};let n=Z(a,`reasoning`,o);return{events:[c(r.runId,`reasoning-delta`,{sessionId:t,parentToolCallId:i,reasoningId:n,text:e})]}}default:return{events:[]}}}clear(){this.streamedMessagesByParentToolCallId.clear()}takeReservedEventId(e,t,n){let r=this.streamedMessagesByParentToolCallId.get(n);if(r?.apiMessageId!==t)return;let i=r.reservedEventIdsByType[e].shift();return this.releaseIfFinished(n,r),i}releaseIfFinished(e,t){let{message:n,reasoning:r}=t.reservedEventIdsByType;t.hasStopped&&n.length===0&&r.length===0&&this.streamedMessagesByParentToolCallId.delete(e)}};const fe=[`--resume`,`-r`,`--continue`,`-c`,`--fork-session`,`--session-id`],pe=(e,t)=>e===t||e.startsWith(`${t}=`),me=e=>e.some(e=>fe.some(t=>pe(e,t))),Q={structuredOutput:!0,sessionResume:!0,imageInput:!0,mcp:!0,eventStreaming:!0,sessionFork:!0,permissionRequests:!0,questionRequests:!0},$=`This run needs Claude Code started with other options, such as another output schema, but the agent's Claude Code process still runs background tasks. Stop the background tasks first.`,he=e=>{let t=b.safeParse(e);if(t.success&&t.data.type===`system`)return t.data.state};var ge=class t extends e{type=`claude-code-cli`;creationOptions;runDefaults;forkOnNextRun;recordedSessionTotals;mcpTempDir;activeSession;textStream;runStats=/* @__PURE__ */ new Map;backgroundTasksMode;backgroundTasks=new q;outputAcrossRuns=new J;backgroundTaskHandlers=/* @__PURE__ */ new Set;agentRunHandlers=/* @__PURE__ */ new Set;processContexts=/* @__PURE__ */ new WeakSet;stopWakersByRunId=/* @__PURE__ */ new Map;keptProcess;turnRun;deferredTaskEnds=[];taskEndsSinceIdle=[];hasReportedSessionState=!1;keptPermissionMode;isDisposing=!1;constructor(e={}){super({type:`claude-code-cli`,capabilities:{...Q,textStreaming:e.streamText===!0,midRunInput:e.keepInputOpen===!0},defaults:{cwd:e.cwd,env:e.env,command:e.command?d(e.command):void 0,sessionId:e.sessionId,model:e.model,systemPrompt:e.systemPrompt},spawner:e.spawner,executionTarget:e.container??e.sandbox,logPath:e.logPath,onEvent:e.onEvent,onProviderEvent:e.onProviderEvent}),this.creationOptions={...e,command:e.command?[...d(e.command)]:void 0,env:e.env?{...e.env}:void 0,allowedTools:e.allowedTools?[...e.allowedTools]:void 0,disallowedTools:e.disallowedTools?[...e.disallowedTools]:void 0,mcpConfig:Array.isArray(e.mcpConfig)?[...e.mcpConfig]:e.mcpConfig,mcpServers:e.mcpServers?{...e.mcpServers}:void 0,extraArgs:e.extraArgs?[...e.extraArgs]:void 0},this.runDefaults={allowedTools:e.allowedTools?[...e.allowedTools]:void 0,disallowedTools:e.disallowedTools?[...e.disallowedTools]:void 0,appendSystemPrompt:e.appendSystemPrompt,permissionMode:e.permissionMode,mcpConfig:Array.isArray(e.mcpConfig)?[...e.mcpConfig]:e.mcpConfig,mcpServers:e.mcpServers?{...e.mcpServers}:void 0,forkSession:e.forkSession,extraArgs:e.extraArgs?[...e.extraArgs]:void 0},this.forkOnNextRun=e.forkOnNextRun??!1,this.recordedSessionTotals=e.recordedSessionTotals,this.textStream=e.streamText?new de:void 0,this.backgroundTasksMode=e.backgroundTasks??`wait`}fork(){if(!this.sessionId)throw new u(`Cannot fork a Claude Code CLI agent before it has a sessionId.`);return new t({...this.creationOptions,sessionId:this.sessionId,forkSession:void 0,forkOnNextRun:!0,recordedSessionTotals:this.recordedSessionTotals,onProviderEvent:void 0})}onBackgroundTask(e){return this.backgroundTaskHandlers.add(e),()=>{this.backgroundTaskHandlers.delete(e)}}onAgentRun(e){return this.agentRunHandlers.add(e),()=>{this.agentRunHandlers.delete(e)}}onValidateRun(e,t){if((e.forkSession??this.runDefaults.forkSession??this.forkOnNextRun)&&!this.sessionId)throw new u(`forkSession requires an existing sessionId on the agent.`);let n=this.keptProcess;if(n!==void 0&&this.backgroundTasks.hasRunning&&this.requiresNewProcess(n,e,this.describeProcessOptions(e,t)))throw new u($)}async onBeforeRun(e){if(await super.onBeforeRun(e),this.processContexts.has(e))return;let t=this.readToolRequestHandlers();(t.permissionHandler!==void 0||t.questionHandler!==void 0||this.creationOptions.keepInputOpen===!0||n(e.normalizedRequest.input))&&(this.activeSession=new X({readHandlers:()=>t}))}executeRunCore(e,t){return this.backgroundTasksMode===`wait`?super.executeRunCore(e,t):this.executeKeptRun(e,t)}async executeKeptRun(e,t){let n=this.setupRunLifecycle(e);try{let n=await this.startKeptTurn(e,t);switch(n.state){case`started`:await n.turnRun.finished.promise;break;case`failed`:e.error=n.error;break;case`stopped`:break;default:throw Error(`Unhandled kept turn start: ${JSON.stringify(n)}`)}return this.buildResult(e,/* @__PURE__ */ new Date)}finally{n.cleanup()}}async startKeptTurn(e,t){let n=this.describeProcessOptions(t,e.normalizedRequest),r=t.permissionMode??this.runDefaults.permissionMode;for(;e.stopReason===void 0;){if(this.isDisposing){this.requestStop(e,`user`);break}let i=this.turnRun;if(i!==void 0){await this.waitUnlessStopped(i.finished.promise,e);continue}let a=this.keptProcess;if(a===void 0)return{state:`started`,turnRun:this.beginKeptTurn(e,t)};let o=this.requiresNewProcess(a,t,n);if(o||a.session.isClosed){if(o&&this.backgroundTasks.hasRunning)return{state:`failed`,error:{kind:`process`,message:$}};a.session.close(),await this.waitUnlessStopped(a.ended,e);continue}if(r===void 0||this.keptPermissionMode===r)return{state:`started`,turnRun:this.beginKeptTurn(e,t)};let s=await this.waitUnlessStopped(this.trySetPermissionMode(a,r),e);if(s!==void 0)return{state:`failed`,error:s}}return this.restoreDefaultPermissionMode(),{state:`stopped`}}async trySetPermissionMode(e,t){try{await this.sendPermissionMode(e.session,t);return}catch(e){if(!(e instanceof P))throw e;return e.reason===`input-closed`?void 0:{kind:`process`,message:`Claude Code did not switch to permission mode ${t}: ${e.message}`}}}beginKeptTurn(e,t){this.flushDeferredTaskEnds(),this.taskEndsSinceIdle=[];let n=this.keptProcess,r=this.beginTurnRun(e,n?.extraArgs??t.extraArgs??this.runDefaults.extraArgs);return e.sessionId&&this.emitSessionStart(e),this.applyBatch(e,this.outputAcrossRuns.release(e.runId)),n===void 0?this.startProcess(e,t):n.session.sendUserMessage(e.normalizedRequest.input),r}async waitUnlessStopped(e,t){let n=Promise.withResolvers();this.stopWakersByRunId.set(t.runId,()=>n.resolve(void 0));try{return await Promise.race([e,n.promise])}finally{this.stopWakersByRunId.delete(t.runId)}}startProcess(e,t){let{input:n,schema:r,cwd:i,model:o,systemPrompt:s}=e.normalizedRequest,c=a({requestedSessionId:e.requestedSessionId,sessionId:e.sessionId,normalizedRequest:{input:n,schema:r,cwd:i,model:o,systemPrompt:s}});this.processContexts.add(c);let l=new X({readHandlers:()=>this.readToolRequestHandlers(),onInputsAnswered:()=>this.finishKeptTurn(l),onPermissionModeChange:e=>{this.keptProcess?.session===l&&(this.keptPermissionMode=e)}});this.activeSession=l,this.keptPermissionMode=t.permissionMode??this.runDefaults.permissionMode,this.keptProcess={context:c,session:l,optionsKey:this.describeProcessOptions(t,e.normalizedRequest),extraArgs:t.extraArgs??this.runDefaults.extraArgs,ended:super.executeRunCore(c,t),isSessionCleared:!1}}startAgentRun(e){let t=a({requestedSessionId:this.sessionId,sessionId:this.sessionId,normalizedRequest:{input:[],schema:{kind:`none`}}}),n=this.beginTurnRun(t,e.extraArgs).finished.promise.then(()=>this.buildResult(t,/* @__PURE__ */ new Date)),r={runId:t.runId,endedTasks:[...this.taskEndsSinceIdle,...this.deferredTaskEnds.map(e=>structuredClone(e.task))],result:n,stop:()=>(this.requestStop(t,`user`),n)};this.taskEndsSinceIdle=[],this.notifyHandlers(this.agentRunHandlers,r),this.applyBatch(t,this.outputAcrossRuns.release(t.runId)),this.flushDeferredTaskEnds()}beginTurnRun(e,t){this.trackRunStats(e,t);let n={context:e,finished:Promise.withResolvers(),hasAnsweredInputs:!1};return this.turnRun=n,n}finishTurnRun(e){this.turnRun===e&&(this.turnRun=void 0,this.recordSessionTotals(e.context.runId),e.finished.resolve())}finishKeptTurn(e){let t=this.turnRun;t!==void 0&&(this.backgroundTasks.hasRunning?(this.finishTurnRun(t),this.restoreDefaultPermissionMode()):this.hasReportedSessionState?t.hasAnsweredInputs=!0:e.close())}restoreDefaultPermissionMode(){if(!this.backgroundTasks.hasRunning)return;let e=this.keptProcess;if(e===void 0)return;let t=this.runDefaults.permissionMode;t!==void 0&&this.keptPermissionMode!==t&&this.sendPermissionMode(e.session,t).catch(e=>{e instanceof P&&e.reason===`input-closed`||this.onHandlerError(e)})}async sendPermissionMode(e,t){this.keptPermissionMode=t;try{await e.sendControlRequest({subtype:`set_permission_mode`,mode:t})}catch(e){throw this.keptPermissionMode=void 0,e}}endKeptProcess(e){let t=this.keptProcess;if(t?.context!==e)return;this.keptProcess=void 0,this.activeSession=void 0,t.session.close(),this.flushDeferredTaskEnds(),this.endBackgroundTasks(),this.forgetProcessOutput(),t.isSessionCleared&&this.outputAcrossRuns.clear();let n=this.turnRun;if(n===void 0)return;let{context:r}=n;r.processResult=e.processResult,r.status===void 0&&r.error===void 0&&(r.error=e.error),this.finishTurnRun(n)}stopKeptTurn(e){this.stopWakersByRunId.get(e.runId)?.();let t=this.keptProcess;t!==void 0&&this.turnRun?.context===e&&(!this.backgroundTasks.hasRunning||this.isDisposing||t.session.isClosed?this.requestStop(t.context,`user`):t.session.sendControlRequest({subtype:`interrupt`}).catch(()=>{this.requestStop(t.context,`user`)}))}requiresNewProcess(e,t,n){return(t.forkSession??this.runDefaults.forkSession??!1)||e.optionsKey!==n}describeProcessOptions(e,{cwd:t,model:n,systemPrompt:r,schema:i}){let{permissionHandler:a,questionHandler:o}=this.readToolRequestHandlers();return JSON.stringify({cwd:t,model:n,systemPrompt:r,schema:i.kind===`none`?void 0:i.jsonSchema,appendSystemPrompt:e.appendSystemPrompt??this.runDefaults.appendSystemPrompt,allowedTools:e.allowedTools??this.runDefaults.allowedTools,disallowedTools:e.disallowedTools??this.runDefaults.disallowedTools,mcpConfig:e.mcpConfig??this.runDefaults.mcpConfig,mcpServers:e.mcpServers??this.runDefaults.mcpServers,extraArgs:e.extraArgs??this.runDefaults.extraArgs,answersToolRequests:a!==void 0||o!==void 0})}readToolRequestHandlers(){return{permissionHandler:this.getPermissionHandler(),questionHandler:this.getQuestionHandler()}}trackRunStats(e,t){let n=this.defaults.command?.slice(1)??[];this.runStats.set(e.runId,new j({requestedSessionId:e.requestedSessionId,recordedSessionTotals:this.recordedSessionTotals,mayResumeUntrackedSession:me([...n,...t??[]])}))}recordSessionTotals(e){this.recordedSessionTotals=this.runStats.get(e)?.sessionTotals??this.recordedSessionTotals,this.runStats.delete(e)}observeBackgroundTask(e,t){let n=this.backgroundTasks.observe(e,e=>t.toolCalls.get(e)??this.outputAcrossRuns.toolCalls.get(e));if(n===void 0)return;let r=this.backgroundTasksMode===`keep-running`&&n.kind===`ended`&&n.task.status!==`stopped`;r&&this.turnRun===void 0?this.deferredTaskEnds.push(n):(r&&this.taskEndsSinceIdle.push(structuredClone(n.task)),this.notifyHandlers(this.backgroundTaskHandlers,n))}flushDeferredTaskEnds(){let e=this.deferredTaskEnds;this.deferredTaskEnds=[];for(let t of e)this.notifyHandlers(this.backgroundTaskHandlers,t)}endBackgroundTasks(){for(let e of this.backgroundTasks.endAll())this.notifyHandlers(this.backgroundTaskHandlers,e)}notifyHandlers(e,t){for(let n of e)try{n(t)}catch(e){this.onHandlerError(e)}}async sendRunInput(e,t){if(this.backgroundTasksMode===`keep-running`&&this.turnRun?.context!==e)throw l(`its turn has not started in Claude Code yet.`);let n=this.activeSession;if(n===void 0||n.isClosed)throw l(`Claude Code's input is not open.`);n.sendUserMessage(t)}sendControlRequest(e){return this.activeSession?this.activeSession.sendControlRequest(e):Promise.reject(new P(`no-open-input`,`No run of this agent has Claude Code's input open. Create the agent with keepInputOpen: true and send control requests while a run is active.`))}async stopTask(e){await this.sendControlRequest({subtype:`stop_task`,task_id:e})}onStopRequested(e){this.backgroundTasksMode===`keep-running`&&!this.processContexts.has(e)?this.stopKeptTurn(e):(super.onStopRequested(e),this.activeSession?.close())}async onRunFinished(e){await super.onRunFinished(e),this.processContexts.has(e)?this.endKeptProcess(e):(this.recordSessionTotals(e.runId),this.activeSession?.close(),this.activeSession=void 0,this.endBackgroundTasks(),this.forgetProcessOutput()),await this.cleanupMcpTempDir()}forgetProcessOutput(){this.outputAcrossRuns.forgetCalls(),this.textStream?.clear()}hasRunInFlight(){return super.hasRunInFlight()||this.turnRun!==void 0}reset(){super.reset();let e=this.keptProcess;e!==void 0&&(e.isSessionCleared=!0,this.requestStop(e.context,`user`))}async dispose(){this.isDisposing=!0;let e=this.keptProcess;if(e!==void 0){let t=this.turnRun;t!==void 0&&this.requestStop(t.context,`user`),this.requestStop(e.context,`user`),await e.ended}await super.dispose()}async onDispose(){await super.onDispose(),this.outputAcrossRuns.clear(),await this.cleanupMcpTempDir()}async cleanupMcpTempDir(){if(this.mcpTempDir){let e=this.mcpTempDir;this.mcpTempDir=void 0,await ae(e,{recursive:!0,force:!0}).catch(()=>{})}}ensureMcpTempFile(e){this.mcpTempDir&&=(L(this.mcpTempDir,{recursive:!0,force:!0}),void 0),this.mcpTempDir=I(F(z(),`cw-mcp-`));let t=F(this.mcpTempDir,`mcp.json`);return R(t,JSON.stringify({mcpServers:e}),{encoding:`utf8`,mode:384}),t}buildArgs(e,t){let n=[`--verbose`,`--output-format`,`stream-json`],r=e.permissionMode??this.runDefaults.permissionMode,i=e.appendSystemPrompt??this.runDefaults.appendSystemPrompt,a=e.allowedTools??this.runDefaults.allowedTools,o=k(e.disallowedTools??this.runDefaults.disallowedTools),s=e.mcpConfig??this.runDefaults.mcpConfig,c=e.mcpServers??this.runDefaults.mcpServers,l=e.extraArgs??this.runDefaults.extraArgs,u=e.forkSession??this.runDefaults.forkSession??this.forkOnNextRun;if(this.processContexts.has(t)||this.trackRunStats(t,l),e.model&&n.push(`--model`,e.model),e.systemPrompt&&n.push(`--system-prompt`,e.systemPrompt),i&&n.push(`--append-system-prompt`,i),r&&n.push(`--permission-mode`,r),a&&a.length>0&&n.push(`--allowed-tools`,a.join(`,`)),n.push(`--disallowed-tools`,o.join(`,`)),s)for(let e of d(s))n.push(`--mcp-config`,e);return c&&n.push(`--mcp-config`,this.ensureMcpTempFile(c)),this.activeSession?.answersToolRequests&&n.push(`--permission-prompt-tool`,`stdio`),this.textStream!==void 0&&n.push(`--include-partial-messages`),e.schema.kind!==`none`&&n.push(`--json-schema`,JSON.stringify(M(e.schema.jsonSchema))),t.requestedSessionId&&(n.push(`--resume`,t.requestedSessionId),u&&n.push(`--fork-session`)),l&&l.length>0&&n.push(...l),n.push(`--input-format`,this.activeSession?`stream-json`:`text`,`--print`),n}buildEnv(e,t){let n=ee({propagateEnv:this.creationOptions.propagateEnv});return this.creationOptions.ci!==!1&&(n.CI=n.CI??`true`),this.defaults.env&&Object.assign(n,this.defaults.env),this.activeSession&&(n.CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS??=`1`),A(n),n}mapRawEvent(e,t){if(this.appendRawLog(e),this.answerControlMessage(e))return{events:[]};let n=this.keptProcess;return n?.context.runId===t.runId?(this.routeKeptProcessEvent(e,n),{events:[]}):(this.forwardProviderEvent(e,t),this.observeBackgroundTask(e,t),this.activeSession?.observeEvent(e),this.outputAcrossRuns.admit(this.toEventBatch(e,t)))}emit(e,t){this.processContexts.has(e)||super.emit(e,t)}recordStderrLine(e,t){if(!this.processContexts.has(e)){super.recordStderrLine(e,t);return}e.stderrLines.push(t);let n=this.turnRun;n!==void 0&&super.recordStderrLine(n.context,t)}answerControlMessage(e){let t=h.safeParse(e);return t.success?(t.data.type===`control_request`?this.activeSession?.answerControlRequest(t.data):t.data.type===`control_cancel_request`?this.activeSession?.cancelControlRequest(t.data.request_id):this.activeSession?.receiveControlResponse(t.data),!0):!1}forwardProviderEvent(e,t){if(!this.hasProviderEventListeners)return;let n=g.safeParse(e);n.success&&this.emitProviderEvent(n.data,t,n.data.session_id??t.sessionId)}routeKeptProcessEvent(e,t){let n=he(e);n!==void 0&&(this.hasReportedSessionState=!0),this.turnRun===void 0&&(n===`running`||y.safeParse(e).success)&&this.startAgentRun(t);let r=this.turnRun,i=s(r?.context??t.context);this.forwardProviderEvent(e,i),this.observeBackgroundTask(e,i);let a=this.toEventBatch(e,i);if(r===void 0?this.outputAcrossRuns.hold(a):this.applyBatch(r.context,this.outputAcrossRuns.admit(a)),t.session.observeEvent(e),n!==`idle`)return;this.taskEndsSinceIdle=[];let o=this.turnRun;o===void 0?this.releaseIdleProcess(t):o.hasAnsweredInputs&&t.session.close()}releaseIdleProcess(e){this.flushDeferredTaskEnds(),this.backgroundTasks.hasRunning||e.session.close()}toEventBatch(e,t){if(this.textStream!==void 0){let n=E.safeParse(e);if(n.success)return this.textStream.mapStreamEvent(n.data,t)}if(C.safeParse(e).success)return{events:[]};let n=T(e);if(!n)return m.safeParse(e).success||this.onParseError(JSON.stringify(e).slice(0,200),/* @__PURE__ */ Error(`schema validation failed`)),{events:[]};let r=D(n)??t.sessionId;this.forkOnNextRun&&t.requestedSessionId&&r&&r!==t.requestedSessionId&&(this.forkOnNextRun=!1);let i=O(n,{...t,sessionId:r,toolCalls:this.outputAcrossRuns.toolCalls},{statsAccumulator:this.runStats.get(t.runId),textStream:this.textStream});return r&&i.sessionId===void 0&&(i.sessionId=r),i}getStdinInput(e){return this.activeSession===void 0?o(e.input):this.activeSession.lines(e.input)}};const _e=e=>new ge(t(e));export{P as ClaudeControlRequestError,_e as createClaudeCodeCliAgent};
@@ -1,3 +1,3 @@
1
- import { d as ClaudeSystemEvent, f as ClaudeUserEvent, l as ClaudeRateLimitEvent, o as ClaudeAssistantEvent, s as ClaudeEvent, u as ClaudeResultEvent } from "../../index-DCQu5ZAu.mjs";
2
- import { a as ClaudeCodeCliPtyPermissionMode, i as ClaudeCodeCliPtyModule, n as ClaudeCodeCliPtyAgent, o as ClaudeCodeCliPtyProcess, r as ClaudeCodeCliPtyAgentOptions, s as ClaudeCodeCliPtyRunOptions, t as createClaudeCodeCliPtyAgent } from "../../index-DH2vDD3l.mjs";
1
+ import { _ as ClaudeRateLimitEvent, b as ClaudeUserEvent, h as ClaudeEvent, m as ClaudeAssistantEvent, v as ClaudeResultEvent, y as ClaudeSystemEvent } from "../../index-DilMV_1s.mjs";
2
+ import { a as ClaudeCodeCliPtyPermissionMode, i as ClaudeCodeCliPtyModule, n as ClaudeCodeCliPtyAgent, o as ClaudeCodeCliPtyProcess, r as ClaudeCodeCliPtyAgentOptions, s as ClaudeCodeCliPtyRunOptions, t as createClaudeCodeCliPtyAgent } from "../../index-5XiyFBcK.mjs";
3
3
  export { type ClaudeAssistantEvent, type ClaudeCodeCliPtyAgent, type ClaudeCodeCliPtyAgentOptions, type ClaudeCodeCliPtyModule, type ClaudeCodeCliPtyPermissionMode, type ClaudeCodeCliPtyProcess, type ClaudeCodeCliPtyRunOptions, type ClaudeEvent, type ClaudeRateLimitEvent, type ClaudeResultEvent, type ClaudeSystemEvent, type ClaudeUserEvent, createClaudeCodeCliPtyAgent };