coding-agents-sdk 0.20.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 (60) hide show
  1. package/README.md +81 -13
  2. package/dist/{Agent-DjrM6eSk.mjs → Agent-BsDJsgJa.mjs} +3 -3
  3. package/dist/{SdkAgent-DYmXd2QH.mjs → SdkAgent-jwighP_b.mjs} +1 -1
  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 +3 -3
  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 -4
  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 +1 -1
  30. package/dist/{events-DoTNE9UF.d.mts → events-DmlAPVpd.d.mts} +109 -1
  31. package/dist/{index-BUsykYQW.d.mts → index-5XiyFBcK.d.mts} +5 -5
  32. package/dist/{index--TbBtTi8.d.mts → index-Bl9DtOcy.d.mts} +3 -3
  33. package/dist/{index-B6HqsIFZ.d.mts → index-Brx5CEx7.d.mts} +3 -3
  34. package/dist/{index-BOpfjzkT.d.mts → index-CCsw4G4N.d.mts} +1 -1
  35. package/dist/{index-BA-SATzW.d.mts → index-CZiWvyn3.d.mts} +2 -2
  36. package/dist/{index-Bs2PNdMx.d.mts → index-DQYRy7xl.d.mts} +3 -3
  37. package/dist/index-DUTtolch.d.mts +63 -0
  38. package/dist/{index-DoVEbwlx.d.mts → index-DilMV_1s.d.mts} +128 -21
  39. package/dist/{index-_lsNncl5.d.mts → index-DpG9mouj.d.mts} +8 -4
  40. package/dist/{index-DP-w59TG.d.mts → index-DqNl8zYj.d.mts} +1 -1
  41. package/dist/index-Du99OLj6.d.mts +65 -0
  42. package/dist/{index-DOsWiOqK.d.mts → index-Q5jNyQHD.d.mts} +1 -1
  43. package/dist/{index-CDN7Re-3.d.mts → index-X-W5isMp.d.mts} +2 -2
  44. package/dist/{index-DmzP2soo.d.mts → index-oUIMXZIp.d.mts} +3 -3
  45. package/dist/index.d.mts +26 -17
  46. package/dist/index.mjs +1 -1
  47. package/dist/parser-BY3CZGmc.mjs +2 -0
  48. package/dist/permission-updates-CkFvevWQ.mjs +1 -0
  49. package/dist/permissions-BjNU9GCH.mjs +1 -0
  50. package/dist/questions-CaEwN4JQ.mjs +1 -0
  51. package/dist/sandbox/index.d.mts +1 -1
  52. package/dist/schemas/index.d.mts +2 -2
  53. package/dist/schemas/index.mjs +1 -1
  54. package/dist/schemas-CzJM9p-0.mjs +1 -0
  55. package/dist/{types-1ueeWtwd.d.mts → types-D_QP9PC-.d.mts} +35 -14
  56. package/package.json +11 -1
  57. package/dist/classify-error-DJq_uoy2.mjs +0 -8
  58. package/dist/parser-D-7JMlQr.mjs +0 -2
  59. package/dist/permission-updates-lGl8T2lW.mjs +0 -1
  60. package/dist/schemas-CF1pu_vW.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
 
@@ -198,9 +200,11 @@ Useful bits:
198
200
 
199
201
  ## Permission requests
200
202
 
201
- The Claude adapters and `codex-cli` with `transport: "app-server"` 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.
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
- 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.
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.
204
208
 
205
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.
206
210
 
@@ -252,7 +256,7 @@ The app-server transport rejects `ephemeral: true` on a resume before launching
252
256
 
253
257
  ## Question requests
254
258
 
255
- `claude-code-cli` and `codex-cli` with `transport: "app-server"` hand the questions the agent asks through its question tool (`AskUserQuestion` on Claude, `request_user_input` on Codex) 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.
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.
256
260
 
257
261
  ```ts
258
262
  import { createAgent, type QuestionAnswers } from "coding-agents-sdk";
@@ -276,12 +280,12 @@ A request carries one or more questions. It works like this:
276
280
 
277
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
278
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
279
- - `toolUseId` tells outstanding requests apart; on `claude-code-cli` it is the `toolCallId` of the question tool's `tool-call` and `tool-result` events, and on `codex-cli` it is Codex's ID for the question tool call, which has no such events
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
280
284
  - an agent has one question handler: registering another replaces it, and the function `onQuestionRequest()` returns removes it
281
- - if the handler throws, the question stays unanswered and the run continues; `claude-code-cli` tells the agent so with the error's message, while `codex-cli` gives the model no answer and reports the error's message only in a `stderr` event
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
282
286
  - `signal` aborts when the run is cancelled or the provider withdraws the request, and a later handler response is discarded
283
287
 
284
- 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.
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.
285
289
 
286
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.
287
291
 
@@ -289,7 +293,7 @@ Codex offers its question tool in plan mode (`collaborationMode: "plan"`). In de
289
293
 
290
294
  ## Input during a run
291
295
 
292
- `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`, and `codex-cli` on an agent created with `transport: "app-server"`. Check `agent.capabilities.midRunInput` before calling it with another adapter.
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.
293
297
 
294
298
  ```ts
295
299
  await using agent = await createAgent("claude-code-cli", { keepInputOpen: true });
@@ -309,9 +313,9 @@ unsubscribe();
309
313
  It rejects with `AgentValidationError` in these cases:
310
314
 
311
315
  - the agent does not report `capabilities.midRunInput`
312
- - no run is active
316
+ - no run is active, or the run is stopping after `stop()`, an abort, or its timeout
313
317
  - the input is empty or holds a part the adapter does not support, such as an image on `claude-code-cli`
314
- - 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
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
315
319
 
316
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:
317
321
 
@@ -322,6 +326,10 @@ No event reports the input itself or the moment the model receives it.
322
326
 
323
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.
324
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
+
325
333
  ## Control requests
326
334
 
327
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.
@@ -356,11 +364,53 @@ await claude.run({ input: "Inspect each part with a subagent." });
356
364
  - `stopTask(taskId)` sends `{ subtype: "stop_task", task_id }`
357
365
  - `sendControlRequest(request)` sends any other control request and resolves with the `response` of Claude Code's success answer
358
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)
359
368
 
360
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()`.
361
370
 
362
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"`.
363
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
+
364
414
  ## Events
365
415
 
366
416
  Use `onEvent()` to subscribe to the normalized event stream.
@@ -379,7 +429,11 @@ await agent.run({
379
429
  unsubscribe();
380
430
  ```
381
431
 
382
- 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.
383
437
 
384
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:
385
439
 
@@ -387,9 +441,21 @@ On `codex-cli`, a file change Codex makes arrives as a `tool-call` and a `tool-r
387
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
388
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
389
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
+
390
456
  ### Streamed text
391
457
 
392
- `message` and `reasoning` events carry a whole text. To also receive text while the model generates it, create the agent with `streamText: true`. `claude-code-cli` and `codex-cli` with `transport: "app-server"` support this option; an agent reports `capabilities.textStreaming` only when it was created with it.
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.
393
459
 
394
460
  ```ts
395
461
  await using agent = await createAgent("claude-code-cli", { streamText: true });
@@ -419,6 +485,8 @@ await agent.run({ input: "Explain the package layout." });
419
485
  - an agent created without `streamText` emits no delta events
420
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
421
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
+
422
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`.
423
491
 
424
492
  ### Provider events
@@ -479,7 +547,7 @@ This wrapper exposes MCP configuration directly on:
479
547
  - `codex-cli`: `mcpConfig`, `mcpServers`
480
548
  - `cursor-sdk`: `mcpServers` using `CursorSdkMcpServerConfig`
481
549
 
482
- 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`.
483
551
 
484
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.
485
553
 
@@ -1,4 +1,4 @@
1
- import{a as e,c as t,i as n,n as r,t as i}from"./classify-error-DJq_uoy2.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=(t,n)=>{if(t.stopReason)return;if(n.processResult.status===`rejected`){let e=n.processResult.reason;return{kind:e instanceof o?`process`:`spawn`,message:c(e)}}let r=m(n.stdinResult);if(r)return{kind:`process`,message:r};let i=m(n.stdoutResult);if(i)return{kind:`process`,message:i};let a=m(n.stderrResult);if(a)return{kind:`process`,message:a};if(!t.status&&!t.error){let n=t.processResult,r=t.stderrLines.join(`
3
- `);if(n&&n.exitCode!==null&&n.exitCode!==0)return{kind:`process`,message:r||`Process exited with code ${n.exitCode}.`};if(!e(t)&&t.stderrLines.length>0)return{kind:`process`,message:r}}},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 r{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 n=e.process?.stderr;if(n)for await(let r of f(n))this.appendLog(`stderr`,r),e.stderrLines.push(r),this.emit(e,t(e.runId,`stderr`,{sessionId:e.sessionId,text:r}))}processLine(e,t){let r;try{r=JSON.parse(t)}catch(e){this.onParseError(t,e);return}let i;try{i=this.mapRawEvent(r,n(e))}catch(e){this.onParseError(t,e);return}this.applyBatch(e,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(`
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
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};
@@ -1 +1 @@
1
- import{n as e,t}from"./classify-error-DJq_uoy2.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};
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, h as ClaudeControlRequestPayload, i as ClaudeCodeCliPermissionMode, l as ClaudeRateLimitEvent, m as ClaudeControlRequestFailure, n as ClaudeCodeCliAgent, o as ClaudeAssistantEvent, p as ClaudeControlRequestError, r as ClaudeCodeCliAgentOptions, s as ClaudeEvent, t as createClaudeCodeCliAgent, u as ClaudeResultEvent } from "../../index-DoVEbwlx.mjs";
2
- export { type ClaudeAssistantEvent, 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
+ 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{t as e}from"../../Agent-DjrM6eSk.mjs";import{t}from"../../execution-target-CdlYXh6Z.mjs";import{c as n,o as r,u as i}from"../../classify-error-DJq_uoy2.mjs";import{n as a}from"../../types-B72tDMEZ.mjs";import{t as o}from"../../env-Cb8MIvH7.mjs";import{a as s,t as c}from"../../util-CCXryPDO.mjs";import{i as l,n as u,o as d,r as f,t as p}from"../../permission-updates-lGl8T2lW.mjs";import{t as m}from"../../control-requests-DtjV0e4o.mjs";import{a as h,c as g,d as _,f as v,h as y,i as b,l as x,m as S,n as C,o as w,p as T,r as E,s as D,t as O,u as k}from"../../parser-D-7JMlQr.mjs";import{join as A}from"node:path";import{mkdtempSync as j,rmSync as M,writeFileSync as N}from"node:fs";import{tmpdir as P}from"node:os";import{z as F}from"zod/v4";import{rm as I}from"node:fs/promises";const L=F.object({questions:F.array(F.object({question:F.string(),header:F.string(),options:F.array(F.object({label:F.string(),description:F.string()})),multiSelect:F.boolean()}))}),R=e=>{if(e.tool_name!==`AskUserQuestion`)return;let t=L.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}))},z=(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)}},B=e=>`${JSON.stringify(e)}\n`,V=(e,t)=>({type:`user`,message:{role:`user`,content:e},parent_tool_use_id:null,uuid:t});var H=class{permissionHandler;questionHandler;abortController=new AbortController;pendingLines=[];pendingRequests=/* @__PURE__ */ new Map;sentRequestsById=/* @__PURE__ */ new Map;wakeReader;sessionState;hasReceivedResult=!1;silenceLimitTimer;unansweredInputIds=/* @__PURE__ */ new Set;constructor({permissionHandler:e,questionHandler:t}){this.permissionHandler=e,this.questionHandler=t}get isClosed(){return this.abortController.signal.aborted}get answersToolRequests(){return this.permissionHandler!==void 0||this.questionHandler!==void 0}async*lines(e){for(yield B(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 m(`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 m(`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=w.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 m(`refused`,n.error)):r.resolve(n.response))}observeEvent(e){let t=x.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=C.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,`No permission handler is registered.`);return}let i=new AbortController;this.pendingRequests.set(e,i);let a=await r(AbortSignal.any([this.abortController.signal,i.signal]));this.pendingRequests.delete(e),i.signal.aborted||this.send({type:`control_response`,response:{subtype:`success`,request_id:e,response:a}})}cancelControlRequest(e){this.pendingRequests.get(e)?.abort(),this.pendingRequests.delete(e)}get hasAnsweredEveryInput(){return this.unansweredInputIds.size===0}createTrackedUserMessage(e){let t=crypto.randomUUID();return this.unansweredInputIds.add(t),V(e,t)}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 t=this.questionHandler;if(t!==void 0){let n=R(e);if(n!==void 0)return r=>this.ask(t,e,{toolUseId:e.tool_use_id,questions:n,signal:r})}let n=this.permissionHandler;if(n!==void 0)return t=>this.decide(n,e,t)}async ask(e,t,n){try{let r=await e(n);return{behavior:`allow`,updatedInput:z(t.input,n.questions,r)}}catch(e){return{behavior:`deny`,message:c(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=p(r);return{behavior:`allow`,updatedInput:r.updatedInput??t.input,...e===void 0?{}:{updatedPermissions:e}}}return{behavior:`deny`,message:r.message??`Tool call denied.`}}catch(e){return{behavior:`deny`,message:c(e)}}}sendError(e,t){this.send({type:`control_response`,response:{subtype:`error`,request_id:e,error:t}})}send(e){this.isClosed||(this.pendingLines.push(B(e)),this.wakeReader?.())}};const U=(e,t,n)=>{let r=`${e.apiMessageId}:${n}`,i=e.reservedEventIdsByType[t];return i.at(-1)!==r&&i.push(r),r};var W=class{streamedMessage;mapStreamEvent({event:e,session_id:t},r){if(e.type===`message_start`){let{message:t}=D.parse(e);return this.streamedMessage={apiMessageId:t.id,reservedEventIdsByType:{message:[],reasoning:[]}},{events:[]}}if(e.type!==`content_block_delta`)return{events:[]};let i=this.streamedMessage;if(i===void 0)return{events:[]};let{index:a,delta:o}=b.parse(e);switch(o.type){case`text_delta`:{let{text:e}=_.parse(o);if(e===``)return{events:[]};let s=U(i,`message`,a);return{events:[n(r.runId,`message-delta`,{sessionId:t,messageId:s,text:e})]}}case`thinking_delta`:{let{thinking:e}=v.parse(o);if(e===``)return{events:[]};let s=U(i,`reasoning`,a);return{events:[n(r.runId,`reasoning-delta`,{sessionId:t,reasoningId:s,text:e})]}}default:return{events:[]}}}takeReservedEventId(e,t){if(this.streamedMessage?.apiMessageId===t)return this.streamedMessage.reservedEventIdsByType[e].shift()}};const G=[`--resume`,`-r`,`--continue`,`-c`,`--fork-session`,`--session-id`],K=(e,t)=>e===t||e.startsWith(`${t}=`),q=e=>e.some(e=>G.some(t=>K(e,t))),J={structuredOutput:!0,sessionResume:!0,imageInput:!1,mcp:!0,eventStreaming:!0,sessionFork:!0,permissionRequests:!0,questionRequests:!0};var Y=class t extends e{type=`claude-code-cli`;creationOptions;runDefaults;forkOnNextRun;recordedSessionTotals;mcpTempDir;activeSession;textStream;runStats=/* @__PURE__ */ new Map;constructor(e={}){super({type:`claude-code-cli`,capabilities:{...J,textStreaming:e.streamText===!0,midRunInput:e.keepInputOpen===!0},defaults:{cwd:e.cwd,env:e.env,command:e.command?s(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?[...s(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 W:void 0}fork(){if(!this.sessionId)throw new a(`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})}onValidateRun(e,t){if((e.forkSession??this.runDefaults.forkSession??this.forkOnNextRun)&&!this.sessionId)throw new a(`forkSession requires an existing sessionId on the agent.`)}async onBeforeRun(e){await super.onBeforeRun(e);let t=this.getPermissionHandler(),n=this.getQuestionHandler();(t!==void 0||n!==void 0||this.creationOptions.keepInputOpen===!0)&&(this.activeSession=new H({permissionHandler:t,questionHandler:n}))}async sendRunInput(e,t){let n=this.activeSession;if(n===void 0||n.isClosed)throw r(`Claude Code's input is not open.`);n.sendUserMessage(i(t))}sendControlRequest(e){return this.activeSession?this.activeSession.sendControlRequest(e):Promise.reject(new m(`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){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 I(e,{recursive:!0,force:!0}).catch(()=>{})}}ensureMcpTempFile(e){this.mcpTempDir&&=(M(this.mcpTempDir,{recursive:!0,force:!0}),void 0),this.mcpTempDir=j(A(P(),`cw-mcp-`));let t=A(this.mcpTempDir,`mcp.json`);return N(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=d(e.disallowedTools??this.runDefaults.disallowedTools),c=e.mcpConfig??this.runDefaults.mcpConfig,u=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(t.runId,new l({requestedSessionId:t.requestedSessionId,recordedSessionTotals:this.recordedSessionTotals,mayResumeUntrackedSession:q([...h,...p??[]])})),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(`,`)),c)for(let e of s(c))n.push(`--mcp-config`,e);return u&&n.push(`--mcp-config`,this.ensureMcpTempFile(u)),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(f(e.schema.jsonSchema))),t.requestedSessionId&&(n.push(`--resume`,t.requestedSessionId),m&&n.push(`--fork-session`)),p&&p.length>0&&n.push(...p),n.push(`--input-format`,this.activeSession?`stream-json`:`text`,`--print`),n}buildEnv(e,t){let n=o({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`),u(n),n}mapRawEvent(e,t){this.appendRawLog(e);let n=h.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):this.activeSession?.receiveControlResponse(n.data),{events:[]};if(this.hasProviderEventListeners){let n=g.safeParse(e);n.success&&this.emitProviderEvent(n.data,t,n.data.session_id??t.sessionId)}if(this.activeSession?.observeEvent(e),this.textStream!==void 0){let n=k.safeParse(e);if(n.success)return this.textStream.mapStreamEvent(n.data,t)}if(E.safeParse(e).success)return{events:[]};let r=O(e);if(!r)return T.safeParse(e).success||this.onParseError(JSON.stringify(e).slice(0,200),/* @__PURE__ */ Error(`schema validation failed`)),{events:[]};let i=S(r)??t.sessionId;this.forkOnNextRun&&t.requestedSessionId&&i&&i!==t.requestedSessionId&&(this.forkOnNextRun=!1);let a=y(r,{...t,sessionId:i},{statsAccumulator:this.runStats.get(t.runId),textStream:this.textStream});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 X=e=>new Y(t(e));export{m as ClaudeControlRequestError,X 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-DoVEbwlx.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-BUsykYQW.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 };
@@ -1,4 +1,4 @@
1
- import{c as e,d as t,i as n,n as r,t as i,u as a}from"../../classify-error-DJq_uoy2.mjs";import{t as o}from"../../execution-target-CdlYXh6Z.mjs";import{n as s}from"../../types-B72tDMEZ.mjs";import{t as c}from"../../env-Cb8MIvH7.mjs";import{t as l}from"../../spawner-CYAQQABs.mjs";import{a as u,n as d,r as f,t as p}from"../../util-CCXryPDO.mjs";import{n as m,o as h,r as ee,t as te}from"../../permission-updates-lGl8T2lW.mjs";import{h as g,m as _,t as ne}from"../../parser-D-7JMlQr.mjs";import{join as v,posix as y}from"node:path";import{appendFileSync as b,existsSync as x,mkdtempSync as S,readFileSync as C,writeFileSync as w}from"node:fs";import{tmpdir as re}from"node:os";import{rm as T}from"node:fs/promises";import{randomUUID as ie}from"node:crypto";import{createServer as ae}from"node:http";const E=e=>typeof e==`object`&&!!e&&!Array.isArray(e),oe=async e=>{let t=[];for await(let n of e)t.push(Buffer.isBuffer(n)?n:Buffer.from(n));if(t.length===0)return;let n;try{n=JSON.parse(Buffer.concat(t).toString(`utf8`))}catch{return}if(E(n)&&n.hook_event_name===`PermissionRequest`&&typeof n.tool_name==`string`&&n.tool_name.length!==0&&E(n.tool_input))return{toolName:n.tool_name,input:n.tool_input,toolUseId:typeof n.tool_use_id==`string`&&n.tool_use_id.length>0?n.tool_use_id:ie()}},D=(e,t)=>{e.writeHead(200,{"content-type":`application/json`}),e.end(JSON.stringify(t))},O=e=>{if(e.decision===`allow`){let t=te(e);return{hookSpecificOutput:{hookEventName:`PermissionRequest`,decision:{behavior:`allow`,...e.updatedInput?{updatedInput:e.updatedInput}:{},...t===void 0?{}:{updatedPermissions:t}}}}}return{hookSpecificOutput:{hookEventName:`PermissionRequest`,decision:{behavior:`deny`,message:e.message??`Tool call denied.`}}}},se=()=>`import { Buffer } from "node:buffer";
1
+ import{f as e,i as t,l as n,n as r,p as i,t as a}from"../../classify-error-_WNZMhMY.mjs";import{t as o}from"../../execution-target-CdlYXh6Z.mjs";import{n as s}from"../../types-B72tDMEZ.mjs";import{t as c}from"../../env-Cb8MIvH7.mjs";import{t as l}from"../../spawner-CYAQQABs.mjs";import{a as u,n as d,r as f,t as p}from"../../util-CCXryPDO.mjs";import{c as m,n as h,r as ee,t as te}from"../../permission-updates-CkFvevWQ.mjs";import{t as g,v as _,y as ne}from"../../parser-BY3CZGmc.mjs";import{join as v,posix as y}from"node:path";import{appendFileSync as b,existsSync as x,mkdtempSync as S,readFileSync as C,writeFileSync as w}from"node:fs";import{tmpdir as re}from"node:os";import{rm as T}from"node:fs/promises";import{randomUUID as ie}from"node:crypto";import{createServer as ae}from"node:http";const E=e=>typeof e==`object`&&!!e&&!Array.isArray(e),oe=async e=>{let t=[];for await(let n of e)t.push(Buffer.isBuffer(n)?n:Buffer.from(n));if(t.length===0)return;let n;try{n=JSON.parse(Buffer.concat(t).toString(`utf8`))}catch{return}if(E(n)&&n.hook_event_name===`PermissionRequest`&&typeof n.tool_name==`string`&&n.tool_name.length!==0&&E(n.tool_input))return{toolName:n.tool_name,input:n.tool_input,toolUseId:typeof n.tool_use_id==`string`&&n.tool_use_id.length>0?n.tool_use_id:ie()}},D=(e,t)=>{e.writeHead(200,{"content-type":`application/json`}),e.end(JSON.stringify(t))},O=e=>{if(e.decision===`allow`){let t=te(e);return{hookSpecificOutput:{hookEventName:`PermissionRequest`,decision:{behavior:`allow`,...e.updatedInput?{updatedInput:e.updatedInput}:{},...t===void 0?{}:{updatedPermissions:t}}}}}return{hookSpecificOutput:{hookEventName:`PermissionRequest`,decision:{behavior:`deny`,message:e.message??`Tool call denied.`}}}},se=()=>`import { Buffer } from "node:buffer";
2
2
 
3
3
  const url = process.argv[2];
4
4
  if (!url) {
@@ -29,7 +29,7 @@ try {
29
29
  }
30
30
  `,k=async({handler:e,signal:t})=>{let n=ae(async(n,r)=>{if(n.method!==`POST`){r.writeHead(405).end();return}let i=await oe(n);if(!i)r.writeHead(400).end();else try{let n=await e({toolName:i.toolName,input:i.input,toolUseId:i.toolUseId,signal:t});D(r,O(n))}catch(e){let t=e instanceof Error?e.message:String(e);D(r,O({decision:`deny`,message:t}))}});return await new Promise((e,t)=>{n.once(`error`,t),n.listen(0,`127.0.0.1`,()=>{n.removeListener(`error`,t),e()})}),{url:`http://127.0.0.1:${n.address().port}/permission-hook`,dispose:()=>new Promise(e=>{n.close(()=>e())})}},A={structuredOutput:!0,sessionResume:!0,imageInput:!1,mcp:!0,eventStreaming:!0,sessionFork:!0,permissionRequests:!0},j=/* @__PURE__ */ new Set(/* @__PURE__ */ `SIGABRT.SIGALRM.SIGBREAK.SIGBUS.SIGCHLD.SIGCONT.SIGFPE.SIGHUP.SIGILL.SIGINT.SIGIO.SIGIOT.SIGKILL.SIGPIPE.SIGPOLL.SIGPROF.SIGPWR.SIGQUIT.SIGSEGV.SIGSTKFLT.SIGSTOP.SIGSYS.SIGTERM.SIGTRAP.SIGTSTP.SIGTTIN.SIGTTOU.SIGUNUSED.SIGURG.SIGUSR1.SIGUSR2.SIGVTALRM.SIGWINCH.SIGXCPU.SIGXFSZ`.split(`.`)),M=e=>new Promise(t=>{setTimeout(t,e)}),N=(e,t)=>{Object.assign(e,t)},P=e=>`'${e.replace(/'/g,`'\\''`)}'`,F=(e,t)=>[e,...t].map(P).join(` `),I=(e,t)=>[process.execPath,e,t].map(P).join(` `),L=e=>e.replace(/\\/g,`\\\\`).replace(/,/g,`\\,`),R=e=>{if(e&&j.has(e))return e},z=(e=l)=>({spawn:(t,n,r)=>{let i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Set,o=r.initialInputPath&&r.initialInputBootstrapPath?[r.initialInputBootstrapPath,r.initialInputPath,t,...n]:n,s=r.initialInputPath&&r.initialInputBootstrapPath?`/bin/sh`:t,c=`EXEC:${L(F(s,o))},pty,setsid,ctty`,l=e.spawn(`socat`,[`-`,c],{cwd:r.cwd,env:r.env,stdio:[`pipe`,`pipe`,`pipe`]}),u=e=>{for(let t of a)t(e)},d=e=>{for(let t of i)t(e)},f=async e=>{if(!e)return;let t=new TextDecoder;for await(let n of e)u(t.decode(n,{stream:!0}));let n=t.decode();n&&u(n)};return f(l.stdout).catch(e=>{u(p(e))}),f(l.stderr).catch(e=>{u(p(e))}),l.wait().then(e=>{d({exitCode:e.exitCode??0,signal:e.signal??void 0})}).catch(e=>{u(p(e)),d({exitCode:127})}),{write:e=>{l.stdin?.write?.(e)},kill:e=>{l.kill(R(e))},onData:e=>(a.add(e),{dispose:()=>a.delete(e)}),onExit:e=>(i.add(e),{dispose:()=>i.delete(e)})}}}),B=({sentinelPath:e,permissionHookCommand:t,skipDangerousModePermissionPrompt:n})=>{let r=`cat > ${P(e)}`,i={Stop:[{hooks:[{type:`command`,command:`sh -c ${P(r)}`}]}]};t&&(i.PermissionRequest=[{hooks:[{type:`command`,command:t}]}]);let a={...n&&{skipDangerousModePermissionPrompt:!0},hooks:i};return JSON.stringify(a)},V=e=>{let t=JSON.parse(e);return d(t)?{sessionId:typeof t.session_id==`string`?t.session_id:void 0,transcriptPath:typeof t.transcript_path==`string`?t.transcript_path:void 0,lastAssistantMessage:t.last_assistant_message}:{}},H=e=>{try{return V(e)}catch{return}},U=e=>{if(typeof e==`string`)return e;if(!d(e))return;if(typeof e.text==`string`)return e.text;let t=e.content;if(!Array.isArray(t))return;let n=t.flatMap(e=>!d(e)||e.type!==`text`||typeof e.text!=`string`?[]:[e.text]);return n.length>0?n.join(`
31
31
  `):void 0},W=(e,t)=>{let n=e[t];return typeof n==`string`?n:void 0},G=e=>W(e,`session_id`)??W(e,`sessionId`),K=e=>{let t;try{t=JSON.parse(e)}catch{return}if(Array.isArray(t))return t.some(e=>d(e)&&e.type===`tool_result`)?t:void 0},q=e=>{if(e.type!==`user`||!d(e.message))return;let t=e.message.content;if(typeof t==`string`)return K(t)?void 0:t;if(!Array.isArray(t)||t.some(e=>d(e)&&e.type===`tool_result`))return;let n=t.flatMap(e=>!d(e)||e.type!==`text`||typeof e.text!=`string`?[]:[e.text]);return n.length>0?n.join(`
32
- `):void 0},ce=e=>{if(e.type!==`attachment`||!d(e.attachment))return;let t=e.attachment;return`[${[W(t,`type`)??`attachment`,W(t,`hookEvent`)??W(t,`hook_event`),W(t,`hookName`)??W(t,`hook_name`)].filter(e=>e!==void 0).join(` `)}]`},le=(e,t)=>`${e} Return only valid JSON matching this JSON Schema. Do not wrap the JSON in Markdown. ${JSON.stringify(ee(t))}`,J=e=>{let t=a(e.input);return e.schema.kind===`none`?t:le(t,e.schema.jsonSchema)},Y=e=>e.replace(/[/:\\]/g,`-`),X=e=>Promise.resolve(x(e)),ue=e=>{if(!e)return;let t=e.split(`:`)[0];if(t&&!/^\d+$/.test(t))return t===`root`?`/root`:`/home/${t}`},de=e=>{if(e.type===`assistant`&&d(e.message)&&W(e.message,`stop_reason`)!==`tool_use`)return U(e.message)},Z=e=>e.replace(/\r?\n$/,``),Q=e=>{try{let t=JSON.parse(e);return d(t)?t:void 0}catch{return}},$=(e,t)=>{let n=e.split(/\r?\n/).filter(e=>e.trim().length>0),r=!1,i=!1,a=Z(t);for(let e of n){let t=Q(e);if(!t)continue;let n=q(t);n===void 0?r&&de(t)!==void 0&&(i=!0):Z(n)===a&&(r=!0,i=!1)}return i},fe=(e,t)=>{let n=e.split(/\r?\n/).filter(e=>e.trim().length>0),r=Z(t),i=-1;for(let[e,t]of n.entries()){let n=Q(t);if(!n)continue;let a=q(n);a!==void 0&&Z(a)===r&&(i=e)}if(i<0)return n;let a=n.slice(i),o=a.findIndex((e,t)=>t!==0&&Q(e)?.type===`result`);return o<0?a:a.slice(0,o+1)},pe=e=>{if(!d(e)||`session_id`in e)return e;let t=G(e);if(!t)return e;if(e.type===`user`&&d(e.message)&&typeof e.message.content==`string`){let n=K(e.message.content);if(n)return{...e,session_id:t,message:{...e.message,content:n}}}return{...e,session_id:t}},me=async(e,t,n)=>{let r=e.sessionId??e.requestedSessionId;if(r)for(let e of t.transcriptPathsForSession(r)){let r=await t.readText(e);if(r!==void 0&&$(r,n))return e}};var he=class a extends r{type=`claude-code-cli-pty`;creationOptions;runDefaults;forkOnNextRun;activePty;executionTargetRef;tempDirs=/* @__PURE__ */ new Set;logPath;constructor(e={}){super({type:`claude-code-cli-pty`,capabilities:A,sessionId:e.sessionId,onEvent:e.onEvent}),this.creationOptions={...e,command:e.command?[...u(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,readinessTimeoutMs:e.readinessTimeoutMs,stopHookTimeoutMs:e.stopHookTimeoutMs},this.forkOnNextRun=e.forkOnNextRun??!1,this.executionTargetRef=e.container??e.sandbox,this.logPath=e.logPath}get runRequestDefaults(){return{cwd:this.creationOptions.cwd,model:this.creationOptions.model,systemPrompt:this.creationOptions.systemPrompt}}fork(){if(!this.sessionId)throw new s(`Cannot fork a Claude Code CLI PTY agent before it has a sessionId.`);return new a({...this.creationOptions,sessionId:this.sessionId,forkOnNextRun:!0})}onValidateRun(e,t){if((e.forkSession??this.runDefaults.forkSession??this.forkOnNextRun)&&!this.sessionId)throw new s(`forkSession requires an existing sessionId on the agent.`)}async executeRunCore(e,t){let n=this.setupRunLifecycle(e),r,a;try{if(n.abortedBeforeStart)return this.buildResult(e,/* @__PURE__ */ new Date);this.validatePermissionHandlerSupported(),await this.ensureExecutionTarget();let i={...t,...e.normalizedRequest},o=this.getPermissionHandler();if(o){let t=e.normalizedRequest.signal??new AbortController().signal;a=await k({handler:o,signal:t})}r=await this.createRunFiles(e);let s=a?I(r.permissionHookPath,a.url):void 0;a&&await r.writeText(r.permissionHookPath,se());let c=i.permissionMode??this.runDefaults.permissionMode;await r.writeText(r.settingsPath,B({sentinelPath:r.sentinelPath,permissionHookCommand:s,skipDangerousModePermissionPrompt:c===`bypassPermissions`}));let l=this.creationOptions.pty??z(this.creationOptions.spawner),u=J(i);await r.writeText(r.bootstrapPath,`prompt_path=$1
32
+ `):void 0},ce=e=>{if(e.type!==`attachment`||!d(e.attachment))return;let t=e.attachment;return`[${[W(t,`type`)??`attachment`,W(t,`hookEvent`)??W(t,`hook_event`),W(t,`hookName`)??W(t,`hook_name`)].filter(e=>e!==void 0).join(` `)}]`},le=(e,t)=>`${e} Return only valid JSON matching this JSON Schema. Do not wrap the JSON in Markdown. ${JSON.stringify(ee(t))}`,J=t=>{let n=e(t.input);return t.schema.kind===`none`?n:le(n,t.schema.jsonSchema)},Y=e=>e.replace(/[/:\\]/g,`-`),X=e=>Promise.resolve(x(e)),ue=e=>{if(!e)return;let t=e.split(`:`)[0];if(t&&!/^\d+$/.test(t))return t===`root`?`/root`:`/home/${t}`},de=e=>{if(e.type===`assistant`&&d(e.message)&&W(e.message,`stop_reason`)!==`tool_use`)return U(e.message)},Z=e=>e.replace(/\r?\n$/,``),Q=e=>{try{let t=JSON.parse(e);return d(t)?t:void 0}catch{return}},$=(e,t)=>{let n=e.split(/\r?\n/).filter(e=>e.trim().length>0),r=!1,i=!1,a=Z(t);for(let e of n){let t=Q(e);if(!t)continue;let n=q(t);n===void 0?r&&de(t)!==void 0&&(i=!0):Z(n)===a&&(r=!0,i=!1)}return i},fe=(e,t)=>{let n=e.split(/\r?\n/).filter(e=>e.trim().length>0),r=Z(t),i=-1;for(let[e,t]of n.entries()){let n=Q(t);if(!n)continue;let a=q(n);a!==void 0&&Z(a)===r&&(i=e)}if(i<0)return n;let a=n.slice(i),o=a.findIndex((e,t)=>t!==0&&Q(e)?.type===`result`);return o<0?a:a.slice(0,o+1)},pe=e=>{if(!d(e)||`session_id`in e)return e;let t=G(e);if(!t)return e;if(e.type===`user`&&d(e.message)&&typeof e.message.content==`string`){let n=K(e.message.content);if(n)return{...e,session_id:t,message:{...e.message,content:n}}}return{...e,session_id:t}},me=async(e,t,n)=>{let r=e.sessionId??e.requestedSessionId;if(r)for(let e of t.transcriptPathsForSession(r)){let r=await t.readText(e);if(r!==void 0&&$(r,n))return e}};var he=class e extends r{type=`claude-code-cli-pty`;creationOptions;runDefaults;forkOnNextRun;activePty;executionTargetRef;tempDirs=/* @__PURE__ */ new Set;logPath;constructor(e={}){super({type:`claude-code-cli-pty`,capabilities:A,sessionId:e.sessionId,onEvent:e.onEvent}),this.creationOptions={...e,command:e.command?[...u(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,readinessTimeoutMs:e.readinessTimeoutMs,stopHookTimeoutMs:e.stopHookTimeoutMs},this.forkOnNextRun=e.forkOnNextRun??!1,this.executionTargetRef=e.container??e.sandbox,this.logPath=e.logPath}get runRequestDefaults(){return{cwd:this.creationOptions.cwd,model:this.creationOptions.model,systemPrompt:this.creationOptions.systemPrompt}}fork(){if(!this.sessionId)throw new s(`Cannot fork a Claude Code CLI PTY agent before it has a sessionId.`);return new e({...this.creationOptions,sessionId:this.sessionId,forkOnNextRun:!0})}onValidateRun(e,t){if((e.forkSession??this.runDefaults.forkSession??this.forkOnNextRun)&&!this.sessionId)throw new s(`forkSession requires an existing sessionId on the agent.`)}async executeRunCore(e,t){let n=this.setupRunLifecycle(e),r,i;try{if(n.abortedBeforeStart)return this.buildResult(e,/* @__PURE__ */ new Date);this.validatePermissionHandlerSupported(),await this.ensureExecutionTarget();let a={...t,...e.normalizedRequest},o=this.getPermissionHandler();if(o){let t=e.normalizedRequest.signal??new AbortController().signal;i=await k({handler:o,signal:t})}r=await this.createRunFiles(e);let s=i?I(r.permissionHookPath,i.url):void 0;i&&await r.writeText(r.permissionHookPath,se());let c=a.permissionMode??this.runDefaults.permissionMode;await r.writeText(r.settingsPath,B({sentinelPath:r.sentinelPath,permissionHookCommand:s,skipDangerousModePermissionPrompt:c===`bypassPermissions`}));let l=this.creationOptions.pty??z(this.creationOptions.spawner),u=J(a);await r.writeText(r.bootstrapPath,`prompt_path=$1
33
33
  shift
34
34
  cat "$prompt_path" | exec "$@"
35
- `),await r.writeText(r.promptPath,`${u}\n`);let{command:d,args:f}=await this.buildCommand(i,e,r),p=this.buildEnv();if(e.stopReason)return this.buildResult(e,/* @__PURE__ */ new Date);let m=this.spawnPty({run:e,ptyModule:l,command:d,args:f,env:p,initialInputBootstrapPath:r.bootstrapPath,initialInputPath:r.promptPath});e.sessionId&&this.emitSessionStart(e),await this.waitForReadiness(i,e);let h=await this.waitForStopSentinel(i,e,r,m,u);return h&&await this.applyStopSentinel(e,h,r),e.stopReason||this.activePty?.write(`/exit\r`),N(e,{processResult:await this.waitForExit(m)}),e.stopReason||e.error||e.status||N(e,{status:`completed`}),this.buildResult(e,/* @__PURE__ */ new Date)}catch(t){return this.activePty?.kill(),!e.stopReason&&!e.error&&N(e,{error:i(t)}),this.buildResult(e,/* @__PURE__ */ new Date)}finally{n.cleanup(),this.activePty=void 0,await a?.dispose(),await r?.cleanup()}}onStopRequested(e){this.activePty?.kill()}async onDispose(){for(let e of this.tempDirs)await T(e,{recursive:!0,force:!0}).catch(()=>{});this.tempDirs.clear()}onHandlerError(e){this.appendRawLog(`[handler-error] ${p(e)}`)}validatePermissionHandlerSupported(){if(this.getPermissionHandler()&&this.creationOptions.container)throw new s(`onPermissionRequest is not supported when running claude-code-cli-pty inside a container: the generated PermissionRequest hook calls a host loopback bridge and is unreachable from the container's network namespace.`)}async ensureExecutionTarget(){this.executionTargetRef&&this.executionTargetRef.status!==`running`&&await this.executionTargetRef.start()}async createRunFiles(e){let t=this.creationOptions.container,n=this.creationOptions.container?.workdir??this.creationOptions.sandbox?.workdir,r=e.normalizedRequest.cwd??this.creationOptions.cwd??n??process.cwd();if(t){let e=y.join(`/tmp`,`coding-agents-claude-pty-${crypto.randomUUID()}`),n=y.join(e,`prompt-bootstrap.sh`),i=y.join(e,`permission-hook.mjs`),a=y.join(e,`prompt.txt`),o=y.join(e,`settings.json`),s=y.join(e,`stop-sentinel.json`),c=Y(r),l=`user`in t.config?t.config.user:void 0,u=[this.creationOptions.env?.HOME,t.config.env?.HOME,ue(l),`/root`,`/home/node`,`/home/bun`,`/home/agent`,`/home/user`].filter(e=>typeof e==`string`&&e.length>0);return await t.mkdir(e),{runDir:e,bootstrapPath:n,permissionHookPath:i,promptPath:a,settingsPath:o,sentinelPath:s,exists:t.fileExists,readText:async e=>await t.fileExists(e)?t.readFile(e):void 0,writeText:(e,n)=>t.writeFile(e,n),transcriptPathsForSession:e=>Array.from(new Set(u)).map(t=>y.join(t,`.claude`,`projects`,c,`${e}.jsonl`)),cleanup:async()=>{await t.exec(`rm`,[`-rf`,e]).catch(()=>void 0)}}}let i=this.creationOptions.sandbox?r:re(),a=S(v(i,`.coding-agents-claude-pty-`)),o=v(a,`prompt-bootstrap.sh`),s=v(a,`permission-hook.mjs`),c=v(a,`prompt.txt`),l=v(a,`settings.json`),u=v(a,`stop-sentinel.json`),d=[this.creationOptions.env?.HOME,this.creationOptions.sandbox?.config.setEnv?.HOME,process.env.HOME].filter(e=>typeof e==`string`&&e.length>0),f=Array.from(new Set(d)).map(e=>v(e,`.claude`,`projects`,Y(r)));return this.tempDirs.add(a),{runDir:a,bootstrapPath:o,permissionHookPath:s,promptPath:c,settingsPath:l,sentinelPath:u,exists:X,readText:async e=>x(e)?C(e,`utf8`):void 0,writeText:async(e,t)=>{w(e,t,{encoding:`utf8`,mode:384})},transcriptPathsForSession:e=>f.map(t=>v(t,`${e}.jsonl`)),cleanup:async()=>{this.tempDirs.delete(a),await T(a,{recursive:!0,force:!0}).catch(()=>{})}}}async buildCommand(e,t,n){let r=this.creationOptions.command?.[0]??`claude`,i=[...this.creationOptions.command?.slice(1)??[]],a=e.permissionMode??this.runDefaults.permissionMode,o=e.appendSystemPrompt??this.runDefaults.appendSystemPrompt,s=e.allowedTools??this.runDefaults.allowedTools,c=h(e.disallowedTools??this.runDefaults.disallowedTools),l=e.mcpConfig??this.runDefaults.mcpConfig,d=e.mcpServers??this.runDefaults.mcpServers,f=e.extraArgs??this.runDefaults.extraArgs,p=e.forkSession??this.runDefaults.forkSession??this.forkOnNextRun;if(e.model&&i.push(`--model`,e.model),e.systemPrompt&&i.push(`--system-prompt`,e.systemPrompt),o&&i.push(`--append-system-prompt`,o),a&&i.push(`--permission-mode`,a),s&&s.length>0&&i.push(`--allowed-tools`,s.join(`,`)),i.push(`--disallowed-tools`,c.join(`,`)),l)for(let e of u(l))i.push(`--mcp-config`,e);if(d){let e=this.creationOptions.container?y.join(n.runDir,`mcp.json`):v(n.runDir,`mcp.json`);await n.writeText(e,JSON.stringify({mcpServers:d})),i.push(`--mcp-config`,e)}if(i.push(`--settings`,n.settingsPath),t.requestedSessionId)i.push(`--resume`,t.requestedSessionId),p&&i.push(`--fork-session`);else{let e=crypto.randomUUID();N(t,{sessionId:e}),this.setSessionId(e),i.push(`--session-id`,e)}return f&&f.length>0&&i.push(...f),this.forkOnNextRun=!1,{command:r,args:i}}buildEnv(){let e=c({propagateEnv:this.creationOptions.propagateEnv});return this.creationOptions.ci!==!1&&(e.CI=e.CI??`true`),this.creationOptions.env&&Object.assign(e,this.creationOptions.env),m(e),e}spawnPty({run:e,ptyModule:t,command:n,args:r,env:i,initialInputBootstrapPath:a,initialInputPath:o}){this.appendRawLog(`[spawn] ${n} ${r.join(` `)}`);let s=t.spawn(n,r,{cols:120,rows:40,cwd:e.normalizedRequest.cwd,env:i,initialInputBootstrapPath:a,initialInputPath:o});this.activePty=s;let c=new Promise(e=>{s.onExit(t=>{e({exitCode:t.exitCode,signal:typeof t.signal==`string`?R(t.signal)??null:null})})});return N(e,{process:{stdout:null,stderr:null,stdin:{write:e=>s.write(typeof e==`string`?e:new TextDecoder().decode(e)),end:()=>{}},kill:e=>{s.kill(typeof e==`string`?e:void 0)},wait:()=>c}}),s.onData(e=>{this.appendRawLog(`[pty] ${e}`)}),c}async waitForReadiness(e,t){let n=e.readinessTimeoutMs??this.runDefaults.readinessTimeoutMs??5e3,r=this.activePty;!r||n<=0||await new Promise(e=>{let i=!1,a={},o=()=>{i||(i=!0,a.idle&&clearTimeout(a.idle),a.timeout&&clearTimeout(a.timeout),a.subscription?.dispose(),e())};a.timeout=setTimeout(o,n),a.subscription=r.onData(()=>{a.idle&&clearTimeout(a.idle),a.idle=setTimeout(o,Math.min(250,n)),a.idle.unref?.()}),a.timeout.unref?.(),t.stopReason&&o()})}async waitForStopSentinel(e,t,n,r,i){let a=e.stopHookTimeoutMs??this.runDefaults.stopHookTimeoutMs??12e4,o=Date.now()+a,s;for(r.then(e=>{s=e}).catch(()=>{});;){let e=await this.findRunCompletion(t,n,i);if(e)return e;if(t.stopReason)return;if(s){let e=await this.findRunCompletion(t,n,i);if(e)return e;throw N(t,{processResult:s}),Error(`Claude exited before the Stop hook created a sentinel.`)}if(Date.now()>=o)throw Error(`Claude Stop hook did not create a sentinel within ${a}ms.`);await M(50)}}async findRunCompletion(e,t,n){let r=await t.exists(t.sentinelPath)?await t.readText(t.sentinelPath):void 0,i=r===void 0?void 0:H(r);if(i?.transcriptPath){let e=await t.readText(i.transcriptPath);if(e!==void 0&&$(e,n))return i}let a=await me(e,t,n);if(a)return this.appendRawLog(`[transcript] completed turn from ${a}`),{...i,transcriptPath:a}}async applyStopSentinel(e,t,n){if(t.sessionId&&(N(e,{sessionId:t.sessionId}),this.setSessionId(t.sessionId),this.emitSessionStart(e)),t.transcriptPath){let r=await n.readText(t.transcriptPath);r!==void 0&&this.applyTranscript(e,r,J(e.normalizedRequest))}if(e.assistantTexts.length===0){let n=U(t.lastAssistantMessage);n&&this.emitAssistantText(e,n)}let r=e.output.text??e.assistantTexts.at(-1);if(e.normalizedRequest.schema.kind!==`none`&&r&&e.output.value===void 0)try{let t=e.error?.kind===`parse`&&e.error.message.includes(`structured_output`);this.applyBatch(e,{events:[],state:{output:{value:f(r)}}}),t&&e.output.value!==void 0&&N(e,{error:void 0,status:void 0})}catch(t){N(e,{error:i(t),status:`failed`})}e.assistantTexts.length===0&&!e.output.text&&!e.error&&N(e,{error:{kind:`parse`,message:`Claude Stop hook completed without assistant output.`},status:`failed`})}applyTranscript(e,t,r){let a=fe(t,r);for(let t of a){let r;try{r=JSON.parse(t)}catch(t){N(e,{error:i(t),status:`failed`});return}if(this.applyTranscriptNativeEvent(e,r))continue;let a=ne(pe(r));if(!a)continue;let o=_(a)??e.sessionId,s=g(a,n(e,{sessionId:o}));o&&!s.sessionId&&(s.sessionId=o),this.applyBatch(e,s)}}applyTranscriptNativeEvent(e,t){if(!d(t))return!1;let n=G(t)??e.sessionId,r=q(t);if(r!==void 0)return this.emitTextMessage(e,`user`,r,n),!0;let i=ce(t);return i!==void 0&&(this.emitTextMessage(e,`system`,i,n),!0)}emitTextMessage(n,r,i,a=n.sessionId){a&&!n.sessionId&&(N(n,{sessionId:a}),this.setSessionId(a)),n.sessionId&&this.emitSessionStart(n),this.emit(n,e(n.runId,`message`,{sessionId:n.sessionId,model:null,role:r,content:[t(i)],text:i}))}emitAssistantText(e,t){this.emitTextMessage(e,`assistant`,t),this.applyBatch(e,{events:[],state:{output:{text:t}}})}async waitForExit(e){let t=this.activePty,n,r=new Promise(e=>{n=setTimeout(()=>{t?.kill(),e({exitCode:null,signal:`SIGKILL`})},2e3),n.unref?.()});try{return await Promise.race([e,r])}finally{n&&clearTimeout(n)}}appendRawLog(e){if(this.logPath)try{b(this.logPath,`${e}\n`,`utf8`)}catch{}}};const ge=e=>new he(o(e));export{ge as createClaudeCodeCliPtyAgent};
35
+ `),await r.writeText(r.promptPath,`${u}\n`);let{command:d,args:f}=await this.buildCommand(a,e,r),p=this.buildEnv();if(e.stopReason)return this.buildResult(e,/* @__PURE__ */ new Date);let m=this.spawnPty({run:e,ptyModule:l,command:d,args:f,env:p,initialInputBootstrapPath:r.bootstrapPath,initialInputPath:r.promptPath});e.sessionId&&this.emitSessionStart(e),await this.waitForReadiness(a,e);let h=await this.waitForStopSentinel(a,e,r,m,u);return h&&await this.applyStopSentinel(e,h,r),e.stopReason||this.activePty?.write(`/exit\r`),N(e,{processResult:await this.waitForExit(m)}),e.stopReason||e.error||e.status||N(e,{status:`completed`}),this.buildResult(e,/* @__PURE__ */ new Date)}catch(t){return this.activePty?.kill(),!e.stopReason&&!e.error&&N(e,{error:a(t)}),this.buildResult(e,/* @__PURE__ */ new Date)}finally{n.cleanup(),this.activePty=void 0,await i?.dispose(),await r?.cleanup()}}onStopRequested(e){this.activePty?.kill()}async onDispose(){for(let e of this.tempDirs)await T(e,{recursive:!0,force:!0}).catch(()=>{});this.tempDirs.clear()}onHandlerError(e){this.appendRawLog(`[handler-error] ${p(e)}`)}validatePermissionHandlerSupported(){if(this.getPermissionHandler()&&this.creationOptions.container)throw new s(`onPermissionRequest is not supported when running claude-code-cli-pty inside a container: the generated PermissionRequest hook calls a host loopback bridge and is unreachable from the container's network namespace.`)}async ensureExecutionTarget(){this.executionTargetRef&&this.executionTargetRef.status!==`running`&&await this.executionTargetRef.start()}async createRunFiles(e){let t=this.creationOptions.container,n=this.creationOptions.container?.workdir??this.creationOptions.sandbox?.workdir,r=e.normalizedRequest.cwd??this.creationOptions.cwd??n??process.cwd();if(t){let e=y.join(`/tmp`,`coding-agents-claude-pty-${crypto.randomUUID()}`),n=y.join(e,`prompt-bootstrap.sh`),i=y.join(e,`permission-hook.mjs`),a=y.join(e,`prompt.txt`),o=y.join(e,`settings.json`),s=y.join(e,`stop-sentinel.json`),c=Y(r),l=`user`in t.config?t.config.user:void 0,u=[this.creationOptions.env?.HOME,t.config.env?.HOME,ue(l),`/root`,`/home/node`,`/home/bun`,`/home/agent`,`/home/user`].filter(e=>typeof e==`string`&&e.length>0);return await t.mkdir(e),{runDir:e,bootstrapPath:n,permissionHookPath:i,promptPath:a,settingsPath:o,sentinelPath:s,exists:t.fileExists,readText:async e=>await t.fileExists(e)?t.readFile(e):void 0,writeText:(e,n)=>t.writeFile(e,n),transcriptPathsForSession:e=>Array.from(new Set(u)).map(t=>y.join(t,`.claude`,`projects`,c,`${e}.jsonl`)),cleanup:async()=>{await t.exec(`rm`,[`-rf`,e]).catch(()=>void 0)}}}let i=this.creationOptions.sandbox?r:re(),a=S(v(i,`.coding-agents-claude-pty-`)),o=v(a,`prompt-bootstrap.sh`),s=v(a,`permission-hook.mjs`),c=v(a,`prompt.txt`),l=v(a,`settings.json`),u=v(a,`stop-sentinel.json`),d=[this.creationOptions.env?.HOME,this.creationOptions.sandbox?.config.setEnv?.HOME,process.env.HOME].filter(e=>typeof e==`string`&&e.length>0),f=Array.from(new Set(d)).map(e=>v(e,`.claude`,`projects`,Y(r)));return this.tempDirs.add(a),{runDir:a,bootstrapPath:o,permissionHookPath:s,promptPath:c,settingsPath:l,sentinelPath:u,exists:X,readText:async e=>x(e)?C(e,`utf8`):void 0,writeText:async(e,t)=>{w(e,t,{encoding:`utf8`,mode:384})},transcriptPathsForSession:e=>f.map(t=>v(t,`${e}.jsonl`)),cleanup:async()=>{this.tempDirs.delete(a),await T(a,{recursive:!0,force:!0}).catch(()=>{})}}}async buildCommand(e,t,n){let r=this.creationOptions.command?.[0]??`claude`,i=[...this.creationOptions.command?.slice(1)??[]],a=e.permissionMode??this.runDefaults.permissionMode,o=e.appendSystemPrompt??this.runDefaults.appendSystemPrompt,s=e.allowedTools??this.runDefaults.allowedTools,c=m(e.disallowedTools??this.runDefaults.disallowedTools),l=e.mcpConfig??this.runDefaults.mcpConfig,d=e.mcpServers??this.runDefaults.mcpServers,f=e.extraArgs??this.runDefaults.extraArgs,p=e.forkSession??this.runDefaults.forkSession??this.forkOnNextRun;if(e.model&&i.push(`--model`,e.model),e.systemPrompt&&i.push(`--system-prompt`,e.systemPrompt),o&&i.push(`--append-system-prompt`,o),a&&i.push(`--permission-mode`,a),s&&s.length>0&&i.push(`--allowed-tools`,s.join(`,`)),i.push(`--disallowed-tools`,c.join(`,`)),l)for(let e of u(l))i.push(`--mcp-config`,e);if(d){let e=this.creationOptions.container?y.join(n.runDir,`mcp.json`):v(n.runDir,`mcp.json`);await n.writeText(e,JSON.stringify({mcpServers:d})),i.push(`--mcp-config`,e)}if(i.push(`--settings`,n.settingsPath),t.requestedSessionId)i.push(`--resume`,t.requestedSessionId),p&&i.push(`--fork-session`);else{let e=crypto.randomUUID();N(t,{sessionId:e}),this.setSessionId(e),i.push(`--session-id`,e)}return f&&f.length>0&&i.push(...f),this.forkOnNextRun=!1,{command:r,args:i}}buildEnv(){let e=c({propagateEnv:this.creationOptions.propagateEnv});return this.creationOptions.ci!==!1&&(e.CI=e.CI??`true`),this.creationOptions.env&&Object.assign(e,this.creationOptions.env),h(e),e}spawnPty({run:e,ptyModule:t,command:n,args:r,env:i,initialInputBootstrapPath:a,initialInputPath:o}){this.appendRawLog(`[spawn] ${n} ${r.join(` `)}`);let s=t.spawn(n,r,{cols:120,rows:40,cwd:e.normalizedRequest.cwd,env:i,initialInputBootstrapPath:a,initialInputPath:o});this.activePty=s;let c=new Promise(e=>{s.onExit(t=>{e({exitCode:t.exitCode,signal:typeof t.signal==`string`?R(t.signal)??null:null})})});return N(e,{process:{stdout:null,stderr:null,stdin:{write:e=>s.write(typeof e==`string`?e:new TextDecoder().decode(e)),end:()=>{}},kill:e=>{s.kill(typeof e==`string`?e:void 0)},wait:()=>c}}),s.onData(e=>{this.appendRawLog(`[pty] ${e}`)}),c}async waitForReadiness(e,t){let n=e.readinessTimeoutMs??this.runDefaults.readinessTimeoutMs??5e3,r=this.activePty;!r||n<=0||await new Promise(e=>{let i=!1,a={},o=()=>{i||(i=!0,a.idle&&clearTimeout(a.idle),a.timeout&&clearTimeout(a.timeout),a.subscription?.dispose(),e())};a.timeout=setTimeout(o,n),a.subscription=r.onData(()=>{a.idle&&clearTimeout(a.idle),a.idle=setTimeout(o,Math.min(250,n)),a.idle.unref?.()}),a.timeout.unref?.(),t.stopReason&&o()})}async waitForStopSentinel(e,t,n,r,i){let a=e.stopHookTimeoutMs??this.runDefaults.stopHookTimeoutMs??12e4,o=Date.now()+a,s;for(r.then(e=>{s=e}).catch(()=>{});;){let e=await this.findRunCompletion(t,n,i);if(e)return e;if(t.stopReason)return;if(s){let e=await this.findRunCompletion(t,n,i);if(e)return e;throw N(t,{processResult:s}),Error(`Claude exited before the Stop hook created a sentinel.`)}if(Date.now()>=o)throw Error(`Claude Stop hook did not create a sentinel within ${a}ms.`);await M(50)}}async findRunCompletion(e,t,n){let r=await t.exists(t.sentinelPath)?await t.readText(t.sentinelPath):void 0,i=r===void 0?void 0:H(r);if(i?.transcriptPath){let e=await t.readText(i.transcriptPath);if(e!==void 0&&$(e,n))return i}let a=await me(e,t,n);if(a)return this.appendRawLog(`[transcript] completed turn from ${a}`),{...i,transcriptPath:a}}async applyStopSentinel(e,t,n){if(t.sessionId&&(N(e,{sessionId:t.sessionId}),this.setSessionId(t.sessionId),this.emitSessionStart(e)),t.transcriptPath){let r=await n.readText(t.transcriptPath);r!==void 0&&this.applyTranscript(e,r,J(e.normalizedRequest))}if(e.assistantTexts.length===0){let n=U(t.lastAssistantMessage);n&&this.emitAssistantText(e,n)}let r=e.output.text??e.assistantTexts.at(-1);if(e.normalizedRequest.schema.kind!==`none`&&r&&e.output.value===void 0)try{let t=e.error?.kind===`parse`&&e.error.message.includes(`structured_output`);this.applyBatch(e,{events:[],state:{output:{value:f(r)}}}),t&&e.output.value!==void 0&&N(e,{error:void 0,status:void 0})}catch(t){N(e,{error:a(t),status:`failed`})}e.assistantTexts.length===0&&!e.output.text&&!e.error&&N(e,{error:{kind:`parse`,message:`Claude Stop hook completed without assistant output.`},status:`failed`})}applyTranscript(e,n,r){let i=fe(n,r);for(let n of i){let r;try{r=JSON.parse(n)}catch(t){N(e,{error:a(t),status:`failed`});return}if(this.applyTranscriptNativeEvent(e,r))continue;let i=g(pe(r));if(!i)continue;let o=_(i)??e.sessionId,s=ne(i,t(e,{sessionId:o}));o&&!s.sessionId&&(s.sessionId=o),this.applyBatch(e,s)}}applyTranscriptNativeEvent(e,t){if(!d(t))return!1;let n=G(t)??e.sessionId,r=q(t);if(r!==void 0)return this.emitTextMessage(e,`user`,r,n),!0;let i=ce(t);return i!==void 0&&(this.emitTextMessage(e,`system`,i,n),!0)}emitTextMessage(e,t,r,a=e.sessionId){a&&!e.sessionId&&(N(e,{sessionId:a}),this.setSessionId(a)),e.sessionId&&this.emitSessionStart(e),this.emit(e,n(e.runId,`message`,{sessionId:e.sessionId,model:null,role:t,content:[i(r)],text:r}))}emitAssistantText(e,t){this.emitTextMessage(e,`assistant`,t),this.applyBatch(e,{events:[],state:{output:{text:t}}})}async waitForExit(e){let t=this.activePty,n,r=new Promise(e=>{n=setTimeout(()=>{t?.kill(),e({exitCode:null,signal:`SIGKILL`})},2e3),n.unref?.()});try{return await Promise.race([e,r])}finally{n&&clearTimeout(n)}}appendRawLog(e){if(this.logPath)try{b(this.logPath,`${e}\n`,`utf8`)}catch{}}};const ge=e=>new he(o(e));export{ge as createClaudeCodeCliPtyAgent};
@@ -1,2 +1,2 @@
1
- import { a as ClaudeCodeSdkExecutable, c as ClaudeCodeSdkSettingSource, i as ClaudeCodeSdkEvent, l as ClaudeCodeSdkSettings, n as ClaudeCodeSdkAgent, o as ClaudeCodeSdkPermissionMode, r as ClaudeCodeSdkAgentOptions, s as ClaudeCodeSdkRunOptions, t as createClaudeCodeSdkAgent } from "../../index-CDN7Re-3.mjs";
1
+ import { a as ClaudeCodeSdkExecutable, c as ClaudeCodeSdkSettingSource, i as ClaudeCodeSdkEvent, l as ClaudeCodeSdkSettings, n as ClaudeCodeSdkAgent, o as ClaudeCodeSdkPermissionMode, r as ClaudeCodeSdkAgentOptions, s as ClaudeCodeSdkRunOptions, t as createClaudeCodeSdkAgent } from "../../index-X-W5isMp.mjs";
2
2
  export { type ClaudeCodeSdkAgent, type ClaudeCodeSdkAgentOptions, type ClaudeCodeSdkEvent, type ClaudeCodeSdkExecutable, type ClaudeCodeSdkPermissionMode, type ClaudeCodeSdkRunOptions, type ClaudeCodeSdkSettingSource, type ClaudeCodeSdkSettings, createClaudeCodeSdkAgent };