coding-agents-sdk 0.17.0 → 0.20.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 (82) hide show
  1. package/README.md +222 -3
  2. package/dist/Agent-DjrM6eSk.mjs +4 -0
  3. package/dist/SdkAgent-DYmXd2QH.mjs +1 -0
  4. package/dist/adapters/claude-code-cli/index.d.mts +2 -2
  5. package/dist/adapters/claude-code-cli/index.mjs +1 -1
  6. package/dist/adapters/claude-code-cli-pty/index.d.mts +2 -2
  7. package/dist/adapters/claude-code-cli-pty/index.mjs +5 -5
  8. package/dist/adapters/claude-code-sdk/index.d.mts +1 -1
  9. package/dist/adapters/claude-code-sdk/index.mjs +4 -4
  10. package/dist/adapters/codex-cli/index.d.mts +1 -1
  11. package/dist/adapters/codex-cli/index.mjs +4 -2
  12. package/dist/adapters/codex-sdk/index.d.mts +1 -1
  13. package/dist/adapters/codex-sdk/index.mjs +1 -1
  14. package/dist/adapters/cursor-cli/index.d.mts +1 -1
  15. package/dist/adapters/cursor-cli/index.mjs +1 -1
  16. package/dist/adapters/cursor-sdk/index.d.mts +1 -1
  17. package/dist/adapters/cursor-sdk/index.mjs +1 -1
  18. package/dist/adapters/gemini-cli/index.d.mts +1 -1
  19. package/dist/adapters/gemini-cli/index.mjs +1 -1
  20. package/dist/adapters/opencode-cli/index.d.mts +1 -1
  21. package/dist/adapters/opencode-cli/index.mjs +1 -1
  22. package/dist/adapters/pi-cli/index.d.mts +1 -1
  23. package/dist/adapters/pi-cli/index.mjs +1 -1
  24. package/dist/classify-error-DJq_uoy2.mjs +8 -0
  25. package/dist/container/index.d.mts +2 -2
  26. package/dist/container/index.mjs +1 -1
  27. package/dist/container-BlsSoBe1.mjs +1 -0
  28. package/dist/container-C7oWwLGK.mjs +1 -0
  29. package/dist/container-DUoj_mnh.mjs +1 -0
  30. package/dist/container-DXQ92RVu.mjs +1 -0
  31. package/dist/container-MazMFZg8.mjs +1 -0
  32. package/dist/control-requests-DtjV0e4o.mjs +1 -0
  33. package/dist/core/process/index.d.mts +2 -2
  34. package/dist/core/process/index.mjs +1 -1
  35. package/dist/diff-CMWH9a0d.mjs +1 -0
  36. package/dist/{errors-aYGbvsaq.mjs → errors-BauhTL3l.mjs} +1 -1
  37. package/dist/{events-BxEB6zHt.d.mts → events-DoTNE9UF.d.mts} +64 -5
  38. package/dist/{index-DmpVdnKm.d.mts → index--TbBtTi8.d.mts} +4 -10
  39. package/dist/{index-m5Pqs8Jz.d.mts → index-B6HqsIFZ.d.mts} +4 -10
  40. package/dist/{index-CN0WGc9T.d.mts → index-BA-SATzW.d.mts} +3 -7
  41. package/dist/{index-CQzF8Cli.d.mts → index-BOpfjzkT.d.mts} +1 -5
  42. package/dist/{index-Bi9Dh34t.d.mts → index-BUsykYQW.d.mts} +5 -9
  43. package/dist/index-BimeR91j.d.mts +6 -0
  44. package/dist/{index-BbZPkmE-.d.mts → index-Bs2PNdMx.d.mts} +4 -10
  45. package/dist/{index-CjjUmMwQ.d.mts → index-CDN7Re-3.d.mts} +3 -7
  46. package/dist/{index-kXfBtyJn.d.mts → index-DOsWiOqK.d.mts} +88 -25
  47. package/dist/{index-CZbgTv8P.d.mts → index-DP-w59TG.d.mts} +1 -5
  48. package/dist/{index-BiUoRRsR.d.mts → index-DmzP2soo.d.mts} +4 -10
  49. package/dist/{index-CyIiBK-O.d.mts → index-DoVEbwlx.d.mts} +102 -23
  50. package/dist/{index-65Dv7ed0.d.mts → index-_lsNncl5.d.mts} +29 -18
  51. package/dist/index.d.mts +17 -19
  52. package/dist/index.mjs +1 -1
  53. package/dist/oci-t88M5ODN.mjs +2 -0
  54. package/dist/parser-D-7JMlQr.mjs +2 -0
  55. package/dist/permission-updates-lGl8T2lW.mjs +1 -0
  56. package/dist/sandbox/index.d.mts +1 -1
  57. package/dist/sandbox/index.mjs +1 -1
  58. package/dist/{sandbox-CYA69miM.mjs → sandbox-BemAIoIo.mjs} +2 -2
  59. package/dist/schemas/index.d.mts +2 -2
  60. package/dist/schemas/index.mjs +1 -1
  61. package/dist/schemas-CF1pu_vW.mjs +1 -0
  62. package/dist/spawner-CYAQQABs.mjs +1 -0
  63. package/dist/{types-Ba2NYJOB.d.mts → types-1ueeWtwd.d.mts} +76 -10
  64. package/dist/{types-COmjfh8B.d.mts → types-BetgZysV.d.mts} +0 -2
  65. package/dist/util-CCXryPDO.mjs +1 -0
  66. package/package.json +10 -10
  67. package/dist/Agent-BjaeRtLk.mjs +0 -4
  68. package/dist/SdkAgent-Dtsr8Ycr.mjs +0 -1
  69. package/dist/classify-error-DOqkMCcy.mjs +0 -8
  70. package/dist/container-Bdb90GJb.mjs +0 -1
  71. package/dist/container-DMFxf-kn.mjs +0 -1
  72. package/dist/container-Dvr-p53c.mjs +0 -1
  73. package/dist/container-dCRMBvQw.mjs +0 -1
  74. package/dist/container-w0rl1QMH.mjs +0 -1
  75. package/dist/diff-Dqyk2cdt.mjs +0 -1
  76. package/dist/index-DvwVRB7K.d.mts +0 -10
  77. package/dist/oci-DTNwW-WH.mjs +0 -1
  78. package/dist/parser-C1kvDtRD.mjs +0 -2
  79. package/dist/schemas-CkdQXAep.mjs +0 -1
  80. package/dist/session-markers-Dt7TWdKY.mjs +0 -1
  81. package/dist/spawner-CgfyvnR4.mjs +0 -1
  82. package/dist/util-B4HTdOSc.mjs +0 -1
package/README.md CHANGED
@@ -194,14 +194,173 @@ Useful bits:
194
194
  - pass `sessionId` to `await createAgent(type, { sessionId })` to resume one explicitly
195
195
  - `reset()` forgets the stored session
196
196
  - Claude adapters and `pi-cli` support `fork()`
197
- - `opencode-cli` supports `forkSession: true` on a run, not a `fork()` method
197
+ - `opencode-cli` and `codex-cli` with `transport: "app-server"` support `forkSession: true` on a run, not a `fork()` method
198
198
 
199
199
  ## Permission requests
200
200
 
201
- The Claude adapters support `onPermissionRequest()`. Register a handler before the run and return `{ decision: "allow" }` or `{ decision: "deny", message }`. An allow decision can include `updatedInput` to replace the tool input. Check `agent.capabilities.permissionRequests` before relying on a handler with another adapter.
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.
202
+
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.
204
+
205
+ `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.
202
206
 
203
207
  `claude-code-cli-pty` uses a run-local hook for permission requests. Its callback bridge is not supported inside a container.
204
208
 
209
+ ### Codex app-server transport
210
+
211
+ For Codex, opt into the native app-server transport when a person or application must decide permission requests:
212
+
213
+ ```ts
214
+ await using agent = await createAgent("codex-cli", {
215
+ transport: "app-server",
216
+ sandboxMode: "workspace-write",
217
+ extraArgs: ["-c", 'approval_policy="on-request"', "-c", 'approvals_reviewer="user"'],
218
+ });
219
+ agent.onPermissionRequest(decideToolPermission);
220
+ await agent.run({ input: "Make the requested change." });
221
+ ```
222
+
223
+ The default `transport: "exec"` does not bridge permission or question requests, accepts no input during a run, and streams no text. The app-server transport keeps the configured command, environment, execution target, MCP configuration, normalized events, and structured-output contract. Its `extraArgs` must be flags that `codex app-server` accepts, such as `-c` and `--profile`, not `codex exec` flags, and `skipGitRepoCheck` has no effect because app-server does not require a Git repository.
224
+
225
+ Permission review and the filesystem sandbox are separate settings: `permissionMode: "auto-approve"` selects automatic review with workspace-write, while `"bypass-sandbox"` disables both approval prompts and the sandbox.
226
+
227
+ A handler receives command, file-change, additional-permission, and tagged native MCP-tool approval requests. Its decisions work like this:
228
+
229
+ - allow and deny answer one outstanding request; they do not save command rules or session-wide approvals
230
+ - Codex does not accept rewritten inputs or permission-mode changes in an allow decision; returning either rejects the request
231
+ - Codex's native command and file approval protocol does not carry a custom denial message back to the model
232
+ - approving an additional-permissions request grants the requested profile for the current turn, not just one command; the request's `description` states that duration so applications can display it alongside the decision
233
+ - a request without a handler is denied
234
+ - a withdrawn request or stopped run aborts its request signal, and a later handler response is discarded
235
+
236
+ `toolUseId` tells outstanding requests apart:
237
+
238
+ - for command, file-change, and additional-permission requests, it is the ID of the Codex item the request belongs to; for a command or file change that is the `toolCallId` of its `tool-call` and `tool-result` events
239
+ - when Codex asks more than once for one item, such as for a sub-command, it is that item ID followed by `:` and Codex's ID for the request, so each outstanding request stays distinct
240
+ - an MCP-tool approval has no item ID and gets a unique ID of its own
241
+
242
+ Native user questions and general MCP elicitation are not permission requests, and the adapter never treats either as permission to use a tool. It hands native user questions to a registered question handler, as described under [Question requests](#question-requests), rejects them when no question handler is registered, and cancels general elicitation.
243
+
244
+ The app-server transport resumes `sessionId` normally. Two run options require it:
245
+
246
+ - `forkSession: true` forks the session before the run; it also requires an existing session ID
247
+ - `collaborationMode: "plan"` starts the turn in native plan mode
248
+
249
+ When a plan-mode turn proposes a plan, that plan is the run's `text` and a `message` event, and any text Codex writes outside the plan arrives as a separate `message` event. A plan-mode turn that proposes no plan returns Codex's last message as its `text`, like any other turn.
250
+
251
+ The app-server transport rejects `ephemeral: true` on a resume before launching Codex. To continue an existing session without saving the new history, set both `ephemeral: true` and `forkSession: true`; the fork gets a new session ID and leaves the saved source session unchanged. Codex does not save an ephemeral session, so its ID is reported on that run's result but does not become `agent.sessionId`. Later runs keep using the saved session, or start a new one when the agent has none.
252
+
253
+ ## Question requests
254
+
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.
256
+
257
+ ```ts
258
+ import { createAgent, type QuestionAnswers } from "coding-agents-sdk";
259
+
260
+ await using agent = await createAgent("claude-code-cli");
261
+
262
+ agent.onQuestionRequest(async ({ questions, signal }) => {
263
+ const answers: QuestionAnswers = {};
264
+
265
+ for (const question of questions) {
266
+ answers[question.id] = await askUser(question, signal);
267
+ }
268
+
269
+ return answers;
270
+ });
271
+
272
+ await agent.run({ input: "Ask me which test runner to set up, then set it up." });
273
+ ```
274
+
275
+ A request carries one or more questions. It works like this:
276
+
277
+ - 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
+ - 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
280
+ - 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
282
+ - `signal` aborts when the run is cancelled or the provider withdraws the request, and a later handler response is discarded
283
+
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.
285
+
286
+ 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
+
288
+ `claude-code-cli` asks over the same stdin channel as permission requests, so a run with a question handler stays open until Claude reports the session idle, as described under [Permission requests](#permission-requests). The two handlers are separate: questions go to the question handler and every other tool request to the permission handler. With a question handler but no permission handler, the adapter answers Claude Code's other permission requests with an error: Claude Code does not run the tool and tells the model that the permission request failed. Register both handlers when the permission mode lets Claude ask before using a tool.
289
+
290
+ ## Input during a run
291
+
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.
293
+
294
+ ```ts
295
+ await using agent = await createAgent("claude-code-cli", { keepInputOpen: true });
296
+
297
+ const unsubscribe = agent.onEvent((event) => {
298
+ if (event.type !== "session-start") return;
299
+
300
+ showInputBox((text) => agent.sendInput(text));
301
+ });
302
+
303
+ const result = await agent.run({ input: "Refactor the parser module." });
304
+ unsubscribe();
305
+ ```
306
+
307
+ `sendInput()` takes the same input as `run()`: a string or content parts. It resolves once the input is handed to the provider, not when the model has read it, and the run's result still arrives from `run()`.
308
+
309
+ It rejects with `AgentValidationError` in these cases:
310
+
311
+ - the agent does not report `capabilities.midRunInput`
312
+ - no run is active
313
+ - 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
315
+
316
+ `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
+
318
+ - while tool calls are running, the model receives it when they have finished, before its next step, and the run continues as one turn
319
+ - while the model is writing the turn's last reply, or just after the turn has ended, Claude answers it in another turn of the same run: the earlier reply arrives as a `message` event, `run()` resolves after the last turn, its `text` is the last turn's reply, and its `stats` cover every turn
320
+
321
+ No event reports the input itself or the moment the model receives it.
322
+
323
+ `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
+
325
+ ## Control requests
326
+
327
+ `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.
328
+
329
+ Connect a handler like this to your application's task-stop action before starting the run. Call it only after a `task_started` [provider event](#provider-events) supplies the task's ID, not immediately after calling `run()`.
330
+
331
+ ```ts
332
+ import { ClaudeControlRequestError, createClaudeCodeCliAgent } from "coding-agents-sdk/adapters/claude-code-cli";
333
+
334
+ await using claude = createClaudeCodeCliAgent({ keepInputOpen: true });
335
+
336
+ const handleStopTask = async (taskId: string) => {
337
+ try {
338
+ await claude.stopTask(taskId);
339
+ } catch (error) {
340
+ if (!(error instanceof ClaudeControlRequestError)) throw error;
341
+
342
+ console.error(error.reason, error.message);
343
+ }
344
+ };
345
+
346
+ claude.onProviderEvent(({ event }) => {
347
+ if (event.type !== "system" || event.subtype !== "task_started") return;
348
+ if (event.task_id === undefined) return;
349
+
350
+ showStopAction(event.task_id, handleStopTask);
351
+ });
352
+
353
+ await claude.run({ input: "Inspect each part with a subagent." });
354
+ ```
355
+
356
+ - `stopTask(taskId)` sends `{ subtype: "stop_task", task_id }`
357
+ - `sendControlRequest(request)` sends any other control request and resolves with the `response` of Claude Code's success answer
358
+ - 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
359
+
360
+ 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
+
362
+ 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
+
205
364
  ## Events
206
365
 
207
366
  Use `onEvent()` to subscribe to the normalized event stream.
@@ -222,9 +381,49 @@ unsubscribe();
222
381
 
223
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`.
224
383
 
384
+ 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
+
386
+ - the `tool-call` input is `{ changes }`, one entry per file with its `path` and its `kind` of change, `"add"`, `"delete"`, or `"update"`; on the app-server transport each entry also has the `diff`, and a moved file has its destination as `movePath`
387
+ - 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
+ - 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
+
390
+ ### Streamed text
391
+
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.
393
+
394
+ ```ts
395
+ await using agent = await createAgent("claude-code-cli", { streamText: true });
396
+
397
+ const partialTextsByMessageId = new Map<string, string>();
398
+
399
+ agent.onEvent((event) => {
400
+ if (event.type === "message-delta") {
401
+ const partialText = (partialTextsByMessageId.get(event.messageId) ?? "") + event.text;
402
+ partialTextsByMessageId.set(event.messageId, partialText);
403
+ renderMessage(event.messageId, partialText);
404
+ }
405
+
406
+ if (event.type === "message") {
407
+ partialTextsByMessageId.delete(event.id);
408
+ renderMessage(event.id, event.text);
409
+ }
410
+ });
411
+
412
+ await agent.run({ input: "Explain the package layout." });
413
+ ```
414
+
415
+ - a `message-delta` event carries the `text` generated since the previous delta and the `messageId` of the message it belongs to; a `reasoning-delta` event does the same with `reasoningId`
416
+ - the `message` or `reasoning` event that follows has that ID as its `id` and carries the whole text; it is authoritative, so replace the text accumulated from deltas with it
417
+ - a text whose generation is cut short, for example by stopping the run, gets no `message` or `reasoning` event
418
+ - deltas are stored in `RunResult.events` like every other normalized event
419
+ - an agent created without `streamText` emits no delta events
420
+ - 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
+
422
+ 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
+
225
424
  ### Provider events
226
425
 
227
- Use `onProviderEvent()` on `claude-code-cli` or `codex-cli` for provider-specific details not included in normalized events.
426
+ Use `onProviderEvent()` on `claude-code-cli` or `codex-cli` for provider-specific details not included in normalized events. On the app-server transport, Codex notifications arrive translated into the same event shapes the Codex CLI emits; JSON-RPC control messages are not provider events.
228
427
 
229
428
  ```ts
230
429
  import { createClaudeCodeCliAgent } from "coding-agents-sdk/adapters/claude-code-cli";
@@ -240,6 +439,8 @@ await claude.run({ input: "Explain the package layout." });
240
439
  unsubscribe();
241
440
  ```
242
441
 
442
+ Claude `system` events arrive for every `subtype` Claude Code emits, such as `task_progress` and `task_notification`, with all their fields. Fields the adapter doesn't declare are typed `unknown`, so check them before use.
443
+
243
444
  For Codex, import `createCodexCliAgent` from `coding-agents-sdk/adapters/codex-cli`.
244
445
 
245
446
  Provider events are not stored in `RunResult.events`; collect them in your callback if needed. Subscriptions persist across runs and `reset()`. Subscribe separately on forked agents.
@@ -334,6 +535,22 @@ Your image needs the runtime for the adapter you picked available inside the con
334
535
 
335
536
  If you omit `cwd`, the agent uses `container.workdir`. The agent starts a stopped or created execution target before a run. E2B creates or connects to its remote sandbox during `createContainer()`. Dispose the container separately from the agent; `await using` handles that when declared in the order shown above.
336
537
 
538
+ To use a Docker or Podman container that already exists, attach to it by ID or name:
539
+
540
+ ```ts
541
+ import { attachContainer } from "coding-agents-sdk";
542
+
543
+ const container = await attachContainer({
544
+ type: "docker",
545
+ containerId: "my-workspace",
546
+ workdir: "/workspace",
547
+ });
548
+ ```
549
+
550
+ An attached container has the same methods as a created one, except `getMappedPort`, and can be passed as `container` to a CLI adapter. `attachContainer()` does not start a stopped container; call `start()`, or let the agent start it before a run. A missing container rejects with `ContainerNotFoundError`, and any other failure with `ContainerAttachError`.
551
+
552
+ Disposing an attached container neither stops nor removes it. Call `stop()` to stop it, or `remove()` to stop it and remove it from the engine together with its anonymous volumes. `remove()` succeeds when the container is already gone, leaves the container's image and named volumes in place, and rejects with `ContainerRemoveError` when the engine could not remove the container.
553
+
337
554
  Use `snapshotWorkdir()`, `diffWorkdir()`, and `releaseWorkdirSnapshot()` when you need a before/after file diff. Start the container before taking the first snapshot.
338
555
 
339
556
  `propagateEnv` defaults depend on the execution target:
@@ -344,6 +561,8 @@ Use `snapshotWorkdir()`, `diffWorkdir()`, and `releaseWorkdirSnapshot()` when yo
344
561
  - `env` still applies in every case
345
562
  - set `propagateEnv: true` on a container-backed agent only when you intentionally want host env passed through to `docker exec` / `podman exec` / `nerdctl exec`
346
563
 
564
+ The `docker`, `podman`, and `nerdctl` providers never put environment values on the engine's command line, where other users of the host could read them in the process list. The container's `env`, an `exec()` call's `env`, and an agent's environment reach the engine through a file only your user can read, deleted once the engine command ends. That file format holds one variable per line, and the engines read lines of at most 65,536 bytes, `NAME=value` and its newline together (measured with Docker 29.9.2 and Podman 6.1.4; nerdctl's source uses the same line reader). A value is therefore refused, before the engine runs, when it contains a line break, a carriage return, or a NUL character, or when its line would be longer than that, so a value can be up to 65,534 bytes minus the length of its name. A name is refused when it is empty, starts with `#`, or contains whitespace or `=`. With nerdctl, which trims whitespace from each line, a value that ends in whitespace is refused too. A refused value makes `createContainer()` reject with `ContainerCreateError` and `exec()` reject with `ContainerExecError`, and makes the container's `spawner` throw `ContainerExecError`. The error names the variable, and for a value that is too long it gives the value's size and the most it can be.
565
+
347
566
  Notes:
348
567
 
349
568
  - `nerdctl` reuses the same OCI-backed behavior as `docker` and `podman`, but it depends on a working containerd and BuildKit setup on the host; the bundled `nerdctl` examples use `network: "host"` to avoid rootless CNI/firewall differences across hosts
@@ -0,0 +1,4 @@
1
+ import{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(`
4
+ `))e&&this.logStream.write(`[${r}] ${n} ${e}\n`)}async ensureExecutionTarget(){this.executionTargetRef&&this.executionTargetRef.status!==`running`&&await this.executionTargetRef.start()}};export{v as t};
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./classify-error-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,2 +1,2 @@
1
- import { a as ClaudeCodeCliRunOptions, c as ClaudeProviderEvent, d as ClaudeSystemEvent, f as ClaudeUserEvent, i as ClaudeCodeCliPermissionMode, l as ClaudeRateLimitEvent, n as ClaudeCodeCliAgent, o as ClaudeAssistantEvent, r as ClaudeCodeCliAgentOptions, s as ClaudeEvent, t as createClaudeCodeCliAgent, u as ClaudeResultEvent } from "../../index-CyIiBK-O.mjs";
2
- export { type ClaudeAssistantEvent, type ClaudeCodeCliAgent, type ClaudeCodeCliAgentOptions, type ClaudeCodeCliPermissionMode, type ClaudeCodeCliRunOptions, type ClaudeEvent, type ClaudeProviderEvent, type ClaudeRateLimitEvent, type ClaudeResultEvent, type ClaudeSystemEvent, type ClaudeUserEvent, createClaudeCodeCliAgent };
1
+ import { 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 +1 @@
1
- import{n as e}from"../../types-B72tDMEZ.mjs";import{a as t}from"../../util-B4HTdOSc.mjs";import{t as n}from"../../env-Cb8MIvH7.mjs";import{l as r}from"../../classify-error-DOqkMCcy.mjs";import{t as i}from"../../execution-target-CdlYXh6Z.mjs";import{i as a,n as o,t as s}from"../../session-markers-Dt7TWdKY.mjs";import{i as c,n as l,r as u,t as d}from"../../parser-C1kvDtRD.mjs";import{t as f}from"../../Agent-BjaeRtLk.mjs";import{join as p}from"node:path";import{mkdtempSync as m,rmSync as h,writeFileSync as g}from"node:fs";import{tmpdir as _}from"node:os";import{rm as v}from"node:fs/promises";import{createServer as y}from"node:http";const b=`coding_agents_permission_bridge`,x=`permission_prompt`,S=e=>typeof e==`object`&&!!e&&!Array.isArray(e),C=e=>typeof e==`number`||typeof e==`string`||e===null,w=e=>{if(S(e)&&typeof e.method==`string`&&e.method.length!==0)return{id:C(e.id)?e.id:null,method:e.method,params:e.params}},T=async e=>{let t=[];for await(let n of e)t.push(Buffer.isBuffer(n)?n:Buffer.from(n));if(t.length!==0)try{return w(JSON.parse(Buffer.concat(t).toString(`utf8`)))}catch{return}},E=(e,t)=>{e.writeHead(200,{"content-type":`application/json`}),e.end(JSON.stringify(t))},D=(e,t,n,r)=>{E(e,{jsonrpc:`2.0`,id:t,error:{code:n,message:r}})},O=(e,t)=>e.decision===`allow`?{behavior:`allow`,updatedInput:e.updatedInput??t}:{behavior:`deny`,message:e.message??`Tool call denied.`},k=async({handler:e,signal:t})=>{let n=y(async(n,r)=>{if(n.method!==`POST`){r.writeHead(405).end();return}let i=await T(n);if(!i){r.writeHead(400).end();return}let a=i.id;if(i.method===`initialize`){E(r,{jsonrpc:`2.0`,id:a,result:{protocolVersion:`2025-03-26`,capabilities:{tools:{}},serverInfo:{name:b,version:`1.0.0`}}});return}if(i.method.startsWith(`notifications/`)){r.writeHead(202).end();return}if(i.method===`tools/list`){E(r,{jsonrpc:`2.0`,id:a,result:{tools:[{name:x,description:`Forward Claude Code permission prompts to the host agent's handler.`,inputSchema:{type:`object`,properties:{tool_name:{type:`string`},input:{type:`object`},tool_use_id:{type:`string`}},required:[`tool_name`,`input`,`tool_use_id`]}}]}});return}if(i.method===`tools/call`){if(!S(i.params)){D(r,a,-32600,`tools/call params must be an object.`);return}let n=i.params;if(n.name!==x){D(r,a,-32602,`Unknown tool: ${String(n.name)}`);return}if(!S(n.arguments)){D(r,a,-32600,`permission_prompt arguments must be an object.`);return}let o=n.arguments;if(typeof o.tool_name!=`string`||o.tool_name.length===0){D(r,a,-32600,`permission_prompt.tool_name must be a non-empty string.`);return}if(!S(o.input)){D(r,a,-32600,`permission_prompt.input must be an object.`);return}if(typeof o.tool_use_id!=`string`||o.tool_use_id.length===0){D(r,a,-32600,`permission_prompt.tool_use_id must be a non-empty string.`);return}try{let n=await e({toolName:o.tool_name,input:o.input,toolUseId:o.tool_use_id,signal:t}),i=O(n,o.input);E(r,{jsonrpc:`2.0`,id:a,result:{content:[{type:`text`,text:JSON.stringify(i)}]}})}catch(e){let t=e instanceof Error?e.message:String(e);E(r,{jsonrpc:`2.0`,id:a,result:{content:[{type:`text`,text:JSON.stringify({behavior:`deny`,message:t})}],isError:!0}})}return}D(r,a,-32601,`Method not found: ${i.method}`)});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}/mcp`,serverName:b,toolName:`mcp__${b}__${x}`,dispose:()=>new Promise(e=>{n.close(()=>e())})}},A={structuredOutput:!0,sessionResume:!0,imageInput:!1,mcp:!0,eventStreaming:!0,sessionFork:!0,permissionRequests:!0};var j=class i extends f{type=`claude-code-cli`;creationOptions;runDefaults;forkOnNextRun;mcpTempDir;activeBridge;constructor(e={}){super({type:`claude-code-cli`,capabilities:A,defaults:{cwd:e.cwd,env:e.env,command:e.command?t(e.command):void 0,sessionId:e.sessionId,model:e.model,systemPrompt:e.systemPrompt},spawner:e.spawner,executionTarget:e.container??e.sandbox,logPath:e.logPath,onEvent:e.onEvent,onProviderEvent:e.onProviderEvent}),this.creationOptions={...e,command:e.command?[...t(e.command)]:void 0,env:e.env?{...e.env}:void 0,allowedTools:e.allowedTools?[...e.allowedTools]:void 0,disallowedTools:e.disallowedTools?[...e.disallowedTools]:void 0,mcpConfig:Array.isArray(e.mcpConfig)?[...e.mcpConfig]:e.mcpConfig,mcpServers:e.mcpServers?{...e.mcpServers}:void 0,extraArgs:e.extraArgs?[...e.extraArgs]:void 0},this.runDefaults={allowedTools:e.allowedTools?[...e.allowedTools]:void 0,disallowedTools:e.disallowedTools?[...e.disallowedTools]:void 0,appendSystemPrompt:e.appendSystemPrompt,permissionMode:e.permissionMode,mcpConfig:Array.isArray(e.mcpConfig)?[...e.mcpConfig]:e.mcpConfig,mcpServers:e.mcpServers?{...e.mcpServers}:void 0,forkSession:e.forkSession,extraArgs:e.extraArgs?[...e.extraArgs]:void 0},this.forkOnNextRun=e.forkOnNextRun??!1}fork(){if(!this.sessionId)throw new e(`Cannot fork a Claude Code CLI agent before it has a sessionId.`);return new i({...this.creationOptions,sessionId:this.sessionId,forkSession:void 0,forkOnNextRun:!0,onProviderEvent:void 0})}onValidateRun(t,n){if((t.forkSession??this.runDefaults.forkSession??this.forkOnNextRun)&&!this.sessionId)throw new e(`forkSession requires an existing sessionId on the agent.`)}async onBeforeRun(t){await super.onBeforeRun(t);let n=this.getPermissionHandler();if(!n)return;if(this.creationOptions.container)throw new e(`onPermissionRequest is not supported when running claude-code-cli inside a container: the in-process MCP bridge listens on host loopback and is unreachable from the container's network namespace.`);let r=t.normalizedRequest.signal??new AbortController().signal;this.activeBridge=await k({handler:n,signal:r})}async onRunFinished(e){await super.onRunFinished(e),await this.cleanupMcpTempDir(),await this.disposeBridge()}async onDispose(){await super.onDispose(),await this.cleanupMcpTempDir(),await this.disposeBridge()}async disposeBridge(){if(!this.activeBridge)return;let e=this.activeBridge;this.activeBridge=void 0,await e.dispose().catch(()=>{})}async cleanupMcpTempDir(){if(this.mcpTempDir){let e=this.mcpTempDir;this.mcpTempDir=void 0,await v(e,{recursive:!0,force:!0}).catch(()=>{})}}ensureMcpTempFile(e){this.mcpTempDir&&=(h(this.mcpTempDir,{recursive:!0,force:!0}),void 0),this.mcpTempDir=m(p(_(),`cw-mcp-`));let t=p(this.mcpTempDir,`mcp.json`);return g(t,JSON.stringify({mcpServers:e}),{encoding:`utf8`,mode:384}),t}buildArgs(e,n){let r=[`--verbose`,`--output-format`,`stream-json`],i=e.permissionMode??this.runDefaults.permissionMode,s=e.appendSystemPrompt??this.runDefaults.appendSystemPrompt,c=e.allowedTools??this.runDefaults.allowedTools,l=a(e.disallowedTools??this.runDefaults.disallowedTools),u=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&&r.push(`--model`,e.model),e.systemPrompt&&r.push(`--system-prompt`,e.systemPrompt),s&&r.push(`--append-system-prompt`,s),i&&r.push(`--permission-mode`,i),c&&c.length>0&&r.push(`--allowed-tools`,c.join(`,`)),r.push(`--disallowed-tools`,l.join(`,`)),u)for(let e of t(u))r.push(`--mcp-config`,e);let m=this.activeBridge,h=m?{...d,[m.serverName]:{type:`http`,url:m.url}}:d;return h&&r.push(`--mcp-config`,this.ensureMcpTempFile(h)),m&&r.push(`--permission-prompt-tool`,m.toolName),e.schema.kind!==`none`&&r.push(`--json-schema`,JSON.stringify(o(e.schema.jsonSchema))),n.requestedSessionId&&(r.push(`--resume`,n.requestedSessionId),p&&r.push(`--fork-session`)),f&&f.length>0&&r.push(...f),r.push(`--input-format`,`text`,`--print`),r}buildEnv(e,t){let r=n({propagateEnv:this.creationOptions.propagateEnv});return this.creationOptions.ci!==!1&&(r.CI=r.CI??`true`),this.defaults.env&&Object.assign(r,this.defaults.env),s(r),r}mapRawEvent(e,t){if(this.appendRawLog(e),this.hasProviderEventListeners){let n=l.safeParse(e);n.success&&this.emitProviderEvent(n.data,t,n.data.session_id??t.sessionId)}let n=d(e);if(!n)return this.onParseError(JSON.stringify(e).slice(0,200),/* @__PURE__ */ Error(`schema validation failed`)),{events:[]};let r=u(n)??t.sessionId;this.forkOnNextRun&&t.requestedSessionId&&r&&r!==t.requestedSessionId&&(this.forkOnNextRun=!1);let i=c(n,{...t,sessionId:r});return r&&i.sessionId===void 0&&(i.sessionId=r),i}getStdinInput(e){return r(e.input)}};const M=e=>new j(i(e));export{M as createClaudeCodeCliAgent};
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,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-CyIiBK-O.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-Bi9Dh34t.mjs";
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";
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{n as e}from"../../types-B72tDMEZ.mjs";import{a as t,n,r,t as i}from"../../util-B4HTdOSc.mjs";import{t as a}from"../../env-Cb8MIvH7.mjs";import{t as o}from"../../spawner-CgfyvnR4.mjs";import{i as s,l as c,n as l,s as u,t as d,u as f}from"../../classify-error-DOqkMCcy.mjs";import{t as p}from"../../execution-target-CdlYXh6Z.mjs";import{i as m,n as h,t as ee}from"../../session-markers-Dt7TWdKY.mjs";import{i as te,r as g,t as _}from"../../parser-C1kvDtRD.mjs";import{join as v,posix as y}from"node:path";import{appendFileSync as ne,existsSync as b,mkdtempSync as x,readFileSync as S,writeFileSync as C}from"node:fs";import{tmpdir as w}from"node:os";import{rm as T}from"node:fs/promises";import{randomUUID as re}from"node:crypto";import{createServer as E}from"node:http";const D=e=>typeof e==`object`&&!!e&&!Array.isArray(e),ie=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(D(n)&&n.hook_event_name===`PermissionRequest`&&typeof n.tool_name==`string`&&n.tool_name.length!==0&&D(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:re()}},O=(e,t)=>{e.writeHead(200,{"content-type":`application/json`}),e.end(JSON.stringify(t))},k=e=>e.decision===`allow`?{hookSpecificOutput:{hookEventName:`PermissionRequest`,decision:{behavior:`allow`,...e.updatedInput?{updatedInput:e.updatedInput}:{}}}}:{hookSpecificOutput:{hookEventName:`PermissionRequest`,decision:{behavior:`deny`,message:e.message??`Tool call denied.`}}},ae=()=>`import { Buffer } from "node:buffer";
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";
2
2
 
3
3
  const url = process.argv[2];
4
4
  if (!url) {
@@ -27,9 +27,9 @@ try {
27
27
  console.error(error instanceof Error ? error.message : String(error));
28
28
  process.exit(2);
29
29
  }
30
- `,oe=async({handler:e,signal:t})=>{let n=E(async(n,r)=>{if(n.method!==`POST`){r.writeHead(405).end();return}let i=await ie(n);if(!i){r.writeHead(400).end();return}try{let n=await e({toolName:i.toolName,input:i.input,toolUseId:i.toolUseId,signal:t});O(r,k(n))}catch(e){let t=e instanceof Error?e.message:String(e);O(r,k({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=o)=>({spawn:(t,n,r)=>{let a=/* @__PURE__ */ new Set,o=/* @__PURE__ */ new Set,s=r.initialInputPath&&r.initialInputBootstrapPath?[r.initialInputBootstrapPath,r.initialInputPath,t,...n]:n,c=r.initialInputPath&&r.initialInputBootstrapPath?`/bin/sh`:t,l=`EXEC:${L(F(c,s))},pty,setsid,ctty`,u=e.spawn(`socat`,[`-`,l],{cwd:r.cwd,env:r.env,stdio:[`pipe`,`pipe`,`pipe`]}),d=e=>{for(let t of o)t(e)},f=e=>{for(let t of a)t(e)},p=async e=>{if(!e)return;let t=new TextDecoder;for await(let n of e)d(t.decode(n,{stream:!0}));let n=t.decode();n&&d(n)};return p(u.stdout).catch(e=>{d(i(e))}),p(u.stderr).catch(e=>{d(i(e))}),u.wait().then(e=>{f({exitCode:e.exitCode??0,signal:e.signal??void 0})}).catch(e=>{d(i(e)),f({exitCode:127})}),{write:e=>{u.stdin?.write?.(e)},kill:e=>{u.kill(R(e))},onData:e=>(o.add(e),{dispose:()=>o.delete(e)}),onExit:e=>(a.add(e),{dispose:()=>a.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 n(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(!n(e))return;if(typeof e.text==`string`)return e.text;let t=e.content;if(!Array.isArray(t))return;let r=t.flatMap(e=>!n(e)||e.type!==`text`||typeof e.text!=`string`?[]:[e.text]);return r.length>0?r.join(`
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=>n(e)&&e.type===`tool_result`)?t:void 0},q=e=>{if(e.type!==`user`||!n(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=>n(e)&&e.type===`tool_result`))return;let r=t.flatMap(e=>!n(e)||e.type!==`text`||typeof e.text!=`string`?[]:[e.text]);return r.length>0?r.join(`
32
- `):void 0},se=e=>{if(e.type!==`attachment`||!n(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(` `)}]`},ce=(e,t)=>`${e} Return only valid JSON matching this JSON Schema. Do not wrap the JSON in Markdown. ${JSON.stringify(h(t))}`,J=e=>{let t=c(e.input);return e.schema.kind===`none`?t:ce(t,e.schema.jsonSchema)},Y=e=>e.replace(/[/:\\]/g,`-`),le=e=>Promise.resolve(b(e)),X=e=>{if(!e)return;let t=e.split(`:`)[0];if(t&&!/^\d+$/.test(t))return t===`root`?`/root`:`/home/${t}`},ue=e=>{if(e.type===`assistant`&&n(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 n(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);if(n!==void 0){Z(n)===a&&(r=!0,i=!1);continue}r&&ue(t)!==void 0&&(i=!0)}return i},de=(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)},fe=e=>{if(!n(e)||`session_id`in e)return e;let t=G(e);if(!t)return e;if(e.type===`user`&&n(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}},pe=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 me=class o extends l{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?[...t(e.command)]:void 0,env:e.env?{...e.env}:void 0,allowedTools:e.allowedTools?[...e.allowedTools]:void 0,disallowedTools:e.disallowedTools?[...e.disallowedTools]:void 0,mcpConfig:Array.isArray(e.mcpConfig)?[...e.mcpConfig]:e.mcpConfig,mcpServers:e.mcpServers?{...e.mcpServers}:void 0,extraArgs:e.extraArgs?[...e.extraArgs]:void 0},this.runDefaults={allowedTools:e.allowedTools?[...e.allowedTools]:void 0,disallowedTools:e.disallowedTools?[...e.disallowedTools]:void 0,appendSystemPrompt:e.appendSystemPrompt,permissionMode:e.permissionMode,mcpConfig:Array.isArray(e.mcpConfig)?[...e.mcpConfig]:e.mcpConfig,mcpServers:e.mcpServers?{...e.mcpServers}:void 0,forkSession:e.forkSession,extraArgs:e.extraArgs?[...e.extraArgs]:void 0,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 e(`Cannot fork a Claude Code CLI PTY agent before it has a sessionId.`);return new o({...this.creationOptions,sessionId:this.sessionId,forkOnNextRun:!0})}onValidateRun(t,n){if((t.forkSession??this.runDefaults.forkSession??this.forkOnNextRun)&&!this.sessionId)throw new e(`forkSession requires an existing sessionId on the agent.`)}async 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 oe({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,ae());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
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
+ `):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
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(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:d(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] ${i(e)}`)}validatePermissionHandlerSupported(){if(this.getPermissionHandler()&&this.creationOptions.container)throw new e(`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,X(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:w(),a=x(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:le,readText:async e=>b(e)?S(e,`utf8`):void 0,writeText:async(e,t)=>{C(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,n,r){let i=this.creationOptions.command?.[0]??`claude`,a=[...this.creationOptions.command?.slice(1)??[]],o=e.permissionMode??this.runDefaults.permissionMode,s=e.appendSystemPrompt??this.runDefaults.appendSystemPrompt,c=e.allowedTools??this.runDefaults.allowedTools,l=m(e.disallowedTools??this.runDefaults.disallowedTools),u=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&&a.push(`--model`,e.model),e.systemPrompt&&a.push(`--system-prompt`,e.systemPrompt),s&&a.push(`--append-system-prompt`,s),o&&a.push(`--permission-mode`,o),c&&c.length>0&&a.push(`--allowed-tools`,c.join(`,`)),a.push(`--disallowed-tools`,l.join(`,`)),u)for(let e of t(u))a.push(`--mcp-config`,e);if(d){let e=this.creationOptions.container?y.join(r.runDir,`mcp.json`):v(r.runDir,`mcp.json`);await r.writeText(e,JSON.stringify({mcpServers:d})),a.push(`--mcp-config`,e)}if(a.push(`--settings`,r.settingsPath),n.requestedSessionId)a.push(`--resume`,n.requestedSessionId),p&&a.push(`--fork-session`);else{let e=crypto.randomUUID();N(n,{sessionId:e}),this.setSessionId(e),a.push(`--session-id`,e)}return f&&f.length>0&&a.push(...f),this.forkOnNextRun=!1,{command:i,args:a}}buildEnv(){let e=a({propagateEnv:this.creationOptions.propagateEnv});return this.creationOptions.ci!==!1&&(e.CI=e.CI??`true`),this.creationOptions.env&&Object.assign(e,this.creationOptions.env),ee(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 pe(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 i=e.output.text??e.assistantTexts.at(-1);if(e.normalizedRequest.schema.kind!==`none`&&i&&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:r(i)}}}),t&&e.output.value!==void 0&&N(e,{error:void 0,status:void 0})}catch(t){N(e,{error:d(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,n){let r=de(t,n);for(let t of r){let n;try{n=JSON.parse(t)}catch(t){N(e,{error:d(t),status:`failed`});return}if(this.applyTranscriptNativeEvent(e,n))continue;let r=_(fe(n));if(!r)continue;let i=g(r)??e.sessionId,a=te(r,s(e,{sessionId:i}));i&&!a.sessionId&&(a.sessionId=i),this.applyBatch(e,a)}}applyTranscriptNativeEvent(e,t){if(!n(t))return!1;let r=G(t)??e.sessionId,i=q(t);if(i!==void 0)return this.emitTextMessage(e,`user`,i,r),!0;let a=se(t);return a!==void 0&&(this.emitTextMessage(e,`system`,a,r),!0)}emitTextMessage(e,t,n,r=e.sessionId){r&&!e.sessionId&&(N(e,{sessionId:r}),this.setSessionId(r)),e.sessionId&&this.emitSessionStart(e),this.emit(e,u(e.runId,`message`,{sessionId:e.sessionId,model:null,role:t,content:[f(n)],text:n}))}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{ne(this.logPath,`${e}\n`,`utf8`)}catch{}}};const he=e=>new me(p(e));export{he as createClaudeCodeCliPtyAgent};
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};
@@ -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-CjjUmMwQ.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-CDN7Re-3.mjs";
2
2
  export { type ClaudeCodeSdkAgent, type ClaudeCodeSdkAgentOptions, type ClaudeCodeSdkEvent, type ClaudeCodeSdkExecutable, type ClaudeCodeSdkPermissionMode, type ClaudeCodeSdkRunOptions, type ClaudeCodeSdkSettingSource, type ClaudeCodeSdkSettings, createClaudeCodeSdkAgent };
@@ -1,4 +1,4 @@
1
- import{n as e}from"../../types-B72tDMEZ.mjs";import{i as t,n,r}from"../../util-B4HTdOSc.mjs";import{t as i}from"../../env-Cb8MIvH7.mjs";import{i as a,l as o,s,u as c}from"../../classify-error-DOqkMCcy.mjs";import{i as l,n as u,r as d,t as f}from"../../session-markers-Dt7TWdKY.mjs";import{t as p}from"../../SdkAgent-Dtsr8Ycr.mjs";import{query as m}from"@anthropic-ai/claude-agent-sdk";const h=(e,t)=>{if(n(e)&&typeof e[t]==`string`)return e[t]},g=(e,t)=>{if(n(e)&&typeof e[t]==`number`)return e[t]},_=e=>n(e)&&e.type===`text`&&typeof e.text==`string`,v=e=>n(e)&&e.type===`thinking`&&typeof e.thinking==`string`,y=e=>n(e)&&e.type===`tool_use`&&typeof e.id==`string`&&typeof e.name==`string`,b=e=>n(e)&&e.type===`tool_result`&&typeof e.tool_use_id==`string`,x=e=>{let t=n(e.message)?e.message.content:void 0;return Array.isArray(t)?t:[]},S=(e,t)=>h(e.message,`model`)??t.model??null,C=e=>{let t=n(e.message)?e.message.content:void 0;return typeof t==`string`?[t]:Array.isArray(t)?t:[]},w=e=>{if(typeof e==`string`||!Array.isArray(e))return e;let t=e.flatMap(e=>_(e)?[e.text]:[]);return t.length===e.length?t.join(`
2
- `):e},T=e=>{if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return}},E=e=>{let n=g(e.usage,`input_tokens`),r=g(e.usage,`cache_creation_input_tokens`),i=g(e.usage,`cache_read_input_tokens`),a=g(e.usage,`output_tokens`),o=t(n,r,i,a);return{durationMs:e.duration_ms,apiDurationMs:e.duration_api_ms,turns:e.num_turns,costUsd:e.total_cost_usd,inputTokens:n,cacheCreationInputTokens:r,cacheReadInputTokens:i,outputTokens:a,totalTokens:o}},D=e=>{if(`errors`in e&&Array.isArray(e.errors)){let t=e.errors.filter(e=>typeof e==`string`&&e.trim()!==``);if(t.length>0)return t.join(`
3
- `)}return e.subtype===`error_max_structured_output_retries`?`Structured output retries were exhausted.`:e.subtype},O=e=>`session_id`in e?e.session_id:void 0,k=(e,t,n)=>s(e,`message`,{sessionId:t,model:null,role:`system`,content:[c(n)],text:n}),A=(e,t,n)=>{let r=[],i=[],a=S(e,n);for(let n of x(e)){if(_(n)){r.push(s(t.runId,`message`,{sessionId:t.sessionId,model:a,role:`assistant`,content:[c(n.text)],text:n.text}));continue}if(v(n)){r.push(s(t.runId,`reasoning`,{sessionId:t.sessionId,model:a,content:[c(n.thinking)],text:n.thinking}));continue}y(n)&&(i.push({toolCallId:n.id,toolName:n.name,input:n.input}),r.push(s(t.runId,`tool-call`,{sessionId:t.sessionId,model:a,toolCallId:n.id,toolName:n.name,input:n.input})))}return{events:r,toolCalls:i}},j=(e,t)=>{let n=[];for(let r of C(e)){if(typeof r==`string`){n.push(s(t.runId,`message`,{sessionId:t.sessionId,model:null,role:`user`,content:[c(r)],text:r}));continue}if(_(r)){n.push(s(t.runId,`message`,{sessionId:t.sessionId,model:null,role:`user`,content:[c(r.text)],text:r.text}));continue}if(b(r)){let e=t.toolCalls.get(r.tool_use_id),i=w(r.content);n.push(s(t.runId,`tool-result`,{sessionId:t.sessionId,toolCallId:r.tool_use_id,toolName:e?.toolName,input:e?.input,output:i,isError:r.is_error,error:r.is_error?T(i):void 0}))}}return{events:n}},M=(e,t,n)=>t.toolCalls.has(e.tool_use_id)?{events:[]}:{events:[s(t.runId,`tool-call`,{sessionId:t.sessionId,model:n.model??null,toolCallId:e.tool_use_id,toolName:e.tool_name,input:void 0})],toolCalls:[{toolCallId:e.tool_use_id,toolName:e.tool_name}]},N=e=>{switch(e.subtype){case`init`:return;case`status`:return`status: ${e.status??`idle`}`;case`local_command_output`:return e.content;case`hook_started`:return`[hook_started] ${e.hook_name}`;case`hook_progress`:return`[hook_progress] ${e.hook_name}`;case`hook_response`:return`[hook_response] ${e.hook_name}: ${e.outcome}`;case`task_started`:return`[task_started] ${e.description}`;case`task_progress`:return`[task_progress] ${e.summary??e.description}`;case`task_notification`:return`[task_${e.status}] ${e.summary}`;case`compact_boundary`:return`[compact_boundary] ${e.compact_metadata.trigger}`;case`files_persisted`:return`[files_persisted] ${e.files.length} file${e.files.length===1?``:`s`}`;default:return}},P=(e,t)=>{let n=N(e);return n?{events:[k(t.runId,t.sessionId,n)]}:{events:[]}},F=(e,t)=>{switch(e.type){case`auth_status`:{let n=`authenticated`;return e.error?n=`auth error: ${e.error}`:e.isAuthenticating&&(n=`authenticating`),{events:[k(t.runId,t.sessionId,n)]}}case`prompt_suggestion`:return{events:[k(t.runId,t.sessionId,`prompt suggestion: ${e.suggestion}`)]};case`rate_limit_event`:return{events:[k(t.runId,t.sessionId,`rate limited: ${e.rate_limit_info.status}`)]};case`tool_use_summary`:return{events:[k(t.runId,t.sessionId,e.summary)]};default:return{events:[]}}},I=(e,t)=>{let n={stats:E(e)},i=`result`in e?e.result:void 0,a=e.subtype===`success`&&!e.is_error;typeof i==`string`&&(n.output={...n.output,text:i});let o=d(`structured_output`in e?e.structured_output:void 0,t,{isSuccess:a},`Structured output was requested but Claude Agent SDK did not return structured_output.`);if(o.value===void 0&&a&&t.schemaRequested&&typeof i==`string`)try{o.value=r(i),o.error=void 0}catch{}return o.value!==void 0&&(n.output={...n.output,value:o.value}),o.error&&(n.status=`failed`,n.error=o.error),a?n.error||(n.status=`completed`):(n.status=`failed`,n.error={kind:`provider`,message:D(e)}),{events:[],state:n}},L=(e,t,n={})=>{let r;switch(e.type){case`assistant`:r=A(e,t,n);break;case`result`:r=I(e,t);break;case`system`:r=P(e,t);break;case`tool_progress`:r=M(e,t,n);break;case`user`:r=j(e,t);break;case`auth_status`:case`prompt_suggestion`:case`rate_limit_event`:case`tool_use_summary`:r=F(e,t);break;default:r={events:[]}}let i=O(e);return i&&r.sessionId===void 0&&(r.sessionId=i),r},R={structuredOutput:!0,sessionResume:!0,imageInput:!1,mcp:!0,eventStreaming:!0,sessionFork:!0,permissionRequests:!0},z=e=>async(t,n,r)=>{let i=await e({toolName:t,input:n,toolUseId:r.toolUseID,signal:r.signal,reason:r.decisionReason,blockedPath:r.blockedPath,title:r.title,description:r.description});return i.decision===`allow`?{behavior:`allow`,updatedInput:i.updatedInput??n}:{behavior:`deny`,message:i.message??`Tool call denied.`}},B=(e,t)=>e?t?`${e}\n\n${t}`:e:t?{type:`preset`,preset:`claude_code`,append:t}:void 0,V=({prompt:e,options:t})=>m({prompt:e,options:t}),H=t=>{if(t===void 0||typeof t==`string`)return t;if(Array.isArray(t))throw new e(`settings must be an object or a path string.`);return t},U=(t,n)=>{if(n.command){if(n.url)throw new e(`mcpServers.${t} cannot set both command and url.`);if(n.headers)throw new e(`mcpServers.${t}.headers is only supported with url transports.`);if(n.cwd)throw new e(`mcpServers.${t}.cwd is not supported by claude-code-sdk.`);return{type:`stdio`,command:n.command,args:n.args,env:n.env}}if(n.url){if(n.args)throw new e(`mcpServers.${t}.args is only supported with command transports.`);if(n.env)throw new e(`mcpServers.${t}.env is only supported with command transports.`);if(n.cwd)throw new e(`mcpServers.${t}.cwd is not supported by claude-code-sdk.`);return{type:`http`,url:n.url,headers:n.headers}}throw new e(`mcpServers.${t} must set either command or url.`)},W=e=>{if(e)return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,U(e,t)]))};var G=class t extends p{type=`claude-code-sdk`;defaults;creationOptions;runDefaults;createQueryFn;command;forkOnNextRun;currentQuery;constructor(e={}){super({type:`claude-code-sdk`,capabilities:R,sessionId:e.sessionId,onEvent:e.onEvent}),this.command=e.command,this.defaults={cwd:e.cwd,model:e.model,systemPrompt:e.systemPrompt},this.creationOptions={...e,command:e.command,env:e.env?{...e.env}:void 0,executableArgs:e.executableArgs?[...e.executableArgs]:void 0,mcpServers:e.mcpServers?{...e.mcpServers}:void 0,settingSources:e.settingSources?[...e.settingSources]:void 0},this.runDefaults={allowedTools:e.allowedTools?[...e.allowedTools]:void 0,disallowedTools:e.disallowedTools?[...e.disallowedTools]:void 0,appendSystemPrompt:e.appendSystemPrompt,permissionMode:e.permissionMode,mcpServers:e.mcpServers?{...e.mcpServers}:void 0,forkSession:e.forkSession,maxTurns:e.maxTurns},this.createQueryFn=e.createQuery??V,this.forkOnNextRun=e.forkOnNextRun??!1}fork(){if(!this.sessionId)throw new e(`Cannot fork a Claude Code SDK agent before it has a sessionId.`);return new t({...this.creationOptions,sessionId:this.sessionId,forkSession:void 0,forkOnNextRun:!0})}get runRequestDefaults(){return this.defaults}onValidateRun(t,n){if((t.forkSession??this.runDefaults.forkSession??this.forkOnNextRun)&&!this.sessionId)throw new e(`forkSession requires an existing sessionId on the agent.`);if(t.maxTurns!==void 0&&(!Number.isInteger(t.maxTurns)||t.maxTurns<=0))throw new e(`maxTurns must be a positive integer.`)}onStopRequested(e){this.currentQuery?.interrupt?.().catch(()=>{}),super.onStopRequested(e)}async onDispose(){this.cleanupSdkResources()}cleanupSdkResources(){this.currentQuery?.close?.(),this.currentQuery=void 0}async executeSdkRun(e,t,n){let r=this.createQueryFn({prompt:o(e.normalizedRequest.input),options:this.buildQueryOptions(t,e,n)});this.currentQuery=r;for await(let t of r){let n=O(t)??e.sessionId;n&&e.sessionId!==n&&(e.sessionId=n,this.setSessionId(n),this.forkOnNextRun&&e.requestedSessionId&&n!==e.requestedSessionId&&(this.forkOnNextRun=!1));let r=L(t,a(e),{model:e.normalizedRequest.model});this.applyBatch(e,r)}}buildQueryOptions(e,t,n){let r=e.permissionMode??this.runDefaults.permissionMode??`default`,a=e.forkSession??this.runDefaults.forkSession??this.forkOnNextRun,o=e.appendSystemPrompt??this.runDefaults.appendSystemPrompt,c=i({propagateEnv:this.creationOptions.propagateEnv});this.creationOptions.env&&Object.assign(c,this.creationOptions.env),f(c);let d=this.getPermissionHandler();return{abortController:n,canUseTool:d?z(d):void 0,cwd:t.normalizedRequest.cwd,model:t.normalizedRequest.model,systemPrompt:B(t.normalizedRequest.systemPrompt,o),allowedTools:e.allowedTools??this.runDefaults.allowedTools,disallowedTools:l(e.disallowedTools??this.runDefaults.disallowedTools),mcpServers:W(e.mcpServers??this.runDefaults.mcpServers),maxTurns:e.maxTurns??this.runDefaults.maxTurns,outputFormat:t.normalizedRequest.schema.kind===`none`?void 0:{type:`json_schema`,schema:u(t.normalizedRequest.schema.jsonSchema)},permissionMode:r,allowDangerouslySkipPermissions:r===`bypassPermissions`||void 0,resume:t.requestedSessionId,forkSession:t.requestedSessionId?a:void 0,env:c,executable:this.creationOptions.executable,executableArgs:this.creationOptions.executableArgs,pathToClaudeCodeExecutable:this.command,settings:H(this.creationOptions.settings),settingSources:this.creationOptions.settingSources,stderr:e=>{for(let n of e.split(`
4
- `))n&&(t.stderrLines.push(n),this.emit(t,s(t.runId,`stderr`,{sessionId:t.sessionId,text:n})))}}}};const K=e=>new G(e);export{K as createClaudeCodeSdkAgent};
1
+ import{c as e,d as t,i as n,u as r}from"../../classify-error-DJq_uoy2.mjs";import{t as i}from"../../SdkAgent-DYmXd2QH.mjs";import{n as a}from"../../types-B72tDMEZ.mjs";import{t as o}from"../../env-Cb8MIvH7.mjs";import{a as s,i as c,n as l,o as u,r as d,t as f}from"../../permission-updates-lGl8T2lW.mjs";import{n as p,r as m}from"../../util-CCXryPDO.mjs";import{query as h}from"@anthropic-ai/claude-agent-sdk";const g=(e,t)=>{if(p(e)&&typeof e[t]==`string`)return e[t]},_=e=>p(e)&&e.type===`text`&&typeof e.text==`string`,v=e=>p(e)&&e.type===`thinking`&&typeof e.thinking==`string`,y=e=>p(e)&&e.type===`tool_use`&&typeof e.id==`string`&&typeof e.name==`string`,b=e=>p(e)&&e.type===`tool_result`&&typeof e.tool_use_id==`string`,x=e=>{let t=p(e.message)?e.message.content:void 0;return Array.isArray(t)?t:[]},S=(e,t)=>g(e.message,`model`)??t.model??null,C=e=>{let t=p(e.message)?e.message.content:void 0;return typeof t==`string`?[t]:Array.isArray(t)?t:[]},w=e=>{if(typeof e==`string`||!Array.isArray(e))return e;let t=e.flatMap(e=>_(e)?[e.text]:[]);return t.length===e.length?t.join(`
2
+ `):e},T=e=>{if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return}},E=e=>{if(`errors`in e&&Array.isArray(e.errors)){let t=e.errors.filter(e=>typeof e==`string`&&e.trim()!==``);if(t.length>0)return t.join(`
3
+ `)}return e.subtype===`error_max_structured_output_retries`?`Structured output retries were exhausted.`:e.subtype},D=e=>`session_id`in e?e.session_id:void 0,O=(n,r,i)=>e(n,`message`,{sessionId:r,model:null,role:`system`,content:[t(i)],text:i}),k=(n,r,i)=>{let a=[],o=[],s=S(n,i);for(let i of x(n))_(i)?a.push(e(r.runId,`message`,{sessionId:r.sessionId,model:s,role:`assistant`,content:[t(i.text)],text:i.text})):v(i)?a.push(e(r.runId,`reasoning`,{sessionId:r.sessionId,model:s,content:[t(i.thinking)],text:i.thinking})):y(i)&&(o.push({toolCallId:i.id,toolName:i.name,input:i.input}),a.push(e(r.runId,`tool-call`,{sessionId:r.sessionId,model:s,toolCallId:i.id,toolName:i.name,input:i.input})));return{events:a,toolCalls:o}},A=(n,r)=>{let i=[];for(let a of C(n))if(typeof a==`string`)i.push(e(r.runId,`message`,{sessionId:r.sessionId,model:null,role:`user`,content:[t(a)],text:a}));else if(_(a))i.push(e(r.runId,`message`,{sessionId:r.sessionId,model:null,role:`user`,content:[t(a.text)],text:a.text}));else if(b(a)){let t=r.toolCalls.get(a.tool_use_id),n=w(a.content);i.push(e(r.runId,`tool-result`,{sessionId:r.sessionId,toolCallId:a.tool_use_id,toolName:t?.toolName,input:t?.input,output:n,isError:a.is_error,error:a.is_error?T(n):void 0}))}return{events:i}},j=(t,n,r)=>n.toolCalls.has(t.tool_use_id)?{events:[]}:{events:[e(n.runId,`tool-call`,{sessionId:n.sessionId,model:r.model??null,toolCallId:t.tool_use_id,toolName:t.tool_name,input:void 0})],toolCalls:[{toolCallId:t.tool_use_id,toolName:t.tool_name}]},M=e=>{switch(e.subtype){case`init`:return;case`status`:return`status: ${e.status??`idle`}`;case`local_command_output`:return e.content;case`hook_started`:return`[hook_started] ${e.hook_name}`;case`hook_progress`:return`[hook_progress] ${e.hook_name}`;case`hook_response`:return`[hook_response] ${e.hook_name}: ${e.outcome}`;case`task_started`:return`[task_started] ${e.description}`;case`task_progress`:return`[task_progress] ${e.summary??e.description}`;case`task_notification`:return`[task_${e.status}] ${e.summary}`;case`compact_boundary`:return`[compact_boundary] ${e.compact_metadata.trigger}`;case`files_persisted`:return`[files_persisted] ${e.files.length} file${e.files.length===1?``:`s`}`;default:return}},N=(e,t)=>{let n=M(e);return n?{events:[O(t.runId,t.sessionId,n)]}:{events:[]}},P=(e,t)=>{switch(e.type){case`auth_status`:{let n=`authenticated`;return e.error?n=`auth error: ${e.error}`:e.isAuthenticating&&(n=`authenticating`),{events:[O(t.runId,t.sessionId,n)]}}case`prompt_suggestion`:return{events:[O(t.runId,t.sessionId,`prompt suggestion: ${e.suggestion}`)]};case`rate_limit_event`:return{events:[O(t.runId,t.sessionId,`rate limited: ${e.rate_limit_info.status}`)]};case`tool_use_summary`:return{events:[O(t.runId,t.sessionId,e.summary)]};default:return{events:[]}}},F=(e,t,n)=>{let r={stats:(n??new c(t)).addResult(e)},i=`result`in e?e.result:void 0,a=e.subtype===`success`&&!e.is_error;typeof i==`string`&&(r.output={...r.output,text:i});let o=s(`structured_output`in e?e.structured_output:void 0,t,{isSuccess:a},`Structured output was requested but Claude Agent SDK did not return structured_output.`);if(o.value===void 0&&a&&t.schemaRequested&&typeof i==`string`)try{o.value=m(i),o.error=void 0}catch{}return o.value!==void 0&&(r.output={...r.output,value:o.value}),o.error&&(r.status=`failed`,r.error=o.error),a?r.error||=(r.status=`completed`,void 0):(r.status=`failed`,r.error={kind:`provider`,message:E(e)}),{events:[],state:r}},I=(e,t,n={})=>{let r;switch(e.type){case`assistant`:r=k(e,t,n);break;case`result`:r=F(e,t,n.statsAccumulator);break;case`system`:r=N(e,t);break;case`tool_progress`:r=j(e,t,n);break;case`user`:r=A(e,t);break;case`auth_status`:case`prompt_suggestion`:case`rate_limit_event`:case`tool_use_summary`:r=P(e,t);break;default:r={events:[]}}let i=D(e);return i&&r.sessionId===void 0&&(r.sessionId=i),r},L={structuredOutput:!0,sessionResume:!0,imageInput:!1,mcp:!0,eventStreaming:!0,sessionFork:!0,permissionRequests:!0},R=e=>async(t,n,r)=>{let i=await e({toolName:t,input:n,toolUseId:r.toolUseID,signal:r.signal,reason:r.decisionReason,blockedPath:r.blockedPath,title:r.title,description:r.description});if(i.decision===`allow`){let e=f(i);return{behavior:`allow`,updatedInput:i.updatedInput??n,...e===void 0?{}:{updatedPermissions:e}}}return{behavior:`deny`,message:i.message??`Tool call denied.`}},z=(e,t)=>e?t?`${e}\n\n${t}`:e:t?{type:`preset`,preset:`claude_code`,append:t}:void 0,B=({prompt:e,options:t})=>h({prompt:e,options:t}),V=e=>{if(e===void 0||typeof e==`string`)return e;if(Array.isArray(e))throw new a(`settings must be an object or a path string.`);return e},H=(e,t)=>{if(t.command){if(t.url)throw new a(`mcpServers.${e} cannot set both command and url.`);if(t.headers)throw new a(`mcpServers.${e}.headers is only supported with url transports.`);if(t.cwd)throw new a(`mcpServers.${e}.cwd is not supported by claude-code-sdk.`);return{type:`stdio`,command:t.command,args:t.args,env:t.env}}if(t.url){if(t.args)throw new a(`mcpServers.${e}.args is only supported with command transports.`);if(t.env)throw new a(`mcpServers.${e}.env is only supported with command transports.`);if(t.cwd)throw new a(`mcpServers.${e}.cwd is not supported by claude-code-sdk.`);return{type:`http`,url:t.url,headers:t.headers}}throw new a(`mcpServers.${e} must set either command or url.`)},U=e=>{if(e)return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,H(e,t)]))};var W=class t extends i{type=`claude-code-sdk`;defaults;creationOptions;runDefaults;createQueryFn;command;forkOnNextRun;recordedSessionTotals;currentQuery;constructor(e={}){super({type:`claude-code-sdk`,capabilities:L,sessionId:e.sessionId,onEvent:e.onEvent}),this.command=e.command,this.defaults={cwd:e.cwd,model:e.model,systemPrompt:e.systemPrompt},this.creationOptions={...e,command:e.command,env:e.env?{...e.env}:void 0,executableArgs:e.executableArgs?[...e.executableArgs]:void 0,mcpServers:e.mcpServers?{...e.mcpServers}:void 0,settingSources:e.settingSources?[...e.settingSources]:void 0},this.runDefaults={allowedTools:e.allowedTools?[...e.allowedTools]:void 0,disallowedTools:e.disallowedTools?[...e.disallowedTools]:void 0,appendSystemPrompt:e.appendSystemPrompt,permissionMode:e.permissionMode,mcpServers:e.mcpServers?{...e.mcpServers}:void 0,forkSession:e.forkSession,maxTurns:e.maxTurns},this.createQueryFn=e.createQuery??B,this.forkOnNextRun=e.forkOnNextRun??!1,this.recordedSessionTotals=e.recordedSessionTotals}fork(){if(!this.sessionId)throw new a(`Cannot fork a Claude Code SDK agent before it has a sessionId.`);return new t({...this.creationOptions,sessionId:this.sessionId,forkSession:void 0,forkOnNextRun:!0,recordedSessionTotals:this.recordedSessionTotals})}get runRequestDefaults(){return this.defaults}onValidateRun(e,t){if((e.forkSession??this.runDefaults.forkSession??this.forkOnNextRun)&&!this.sessionId)throw new a(`forkSession requires an existing sessionId on the agent.`);if(e.maxTurns!==void 0&&(!Number.isInteger(e.maxTurns)||e.maxTurns<=0))throw new a(`maxTurns must be a positive integer.`)}onStopRequested(e){this.currentQuery?.interrupt?.().catch(()=>{}),super.onStopRequested(e)}async onDispose(){this.cleanupSdkResources()}cleanupSdkResources(){this.currentQuery?.close?.(),this.currentQuery=void 0}async executeSdkRun(e,t,i){let a=this.createQueryFn({prompt:r(e.normalizedRequest.input),options:this.buildQueryOptions(t,e,i)});this.currentQuery=a;let o=new c({requestedSessionId:e.requestedSessionId,recordedSessionTotals:this.recordedSessionTotals});try{for await(let t of a){let r=D(t)??e.sessionId;r&&e.sessionId!==r&&(e.sessionId=r,this.setSessionId(r),this.forkOnNextRun&&e.requestedSessionId&&r!==e.requestedSessionId&&(this.forkOnNextRun=!1));let i=I(t,n(e),{model:e.normalizedRequest.model,statsAccumulator:o});this.applyBatch(e,i)}}finally{this.recordedSessionTotals=o.sessionTotals??this.recordedSessionTotals}}buildQueryOptions(t,n,r){let i=t.permissionMode??this.runDefaults.permissionMode??`default`,a=t.forkSession??this.runDefaults.forkSession??this.forkOnNextRun,s=t.appendSystemPrompt??this.runDefaults.appendSystemPrompt,c=o({propagateEnv:this.creationOptions.propagateEnv});this.creationOptions.env&&Object.assign(c,this.creationOptions.env),l(c);let f=this.getPermissionHandler();return{abortController:r,canUseTool:f?R(f):void 0,cwd:n.normalizedRequest.cwd,model:n.normalizedRequest.model,systemPrompt:z(n.normalizedRequest.systemPrompt,s),allowedTools:t.allowedTools??this.runDefaults.allowedTools,disallowedTools:u(t.disallowedTools??this.runDefaults.disallowedTools),mcpServers:U(t.mcpServers??this.runDefaults.mcpServers),maxTurns:t.maxTurns??this.runDefaults.maxTurns,outputFormat:n.normalizedRequest.schema.kind===`none`?void 0:{type:`json_schema`,schema:d(n.normalizedRequest.schema.jsonSchema)},permissionMode:i,allowDangerouslySkipPermissions:i===`bypassPermissions`||void 0,resume:n.requestedSessionId,forkSession:n.requestedSessionId?a:void 0,env:c,executable:this.creationOptions.executable,executableArgs:this.creationOptions.executableArgs,pathToClaudeCodeExecutable:this.command,settings:V(this.creationOptions.settings),settingSources:this.creationOptions.settingSources,stderr:t=>{for(let r of t.split(`
4
+ `))r&&(n.stderrLines.push(r),this.emit(n,e(n.runId,`stderr`,{sessionId:n.sessionId,text:r})))}}}};const G=e=>new W(e);export{G as createClaudeCodeSdkAgent};
@@ -1,2 +1,2 @@
1
- import { a as CodexCliRunOptions, c as CodexEvent, d as CodexItemUpdatedEvent, f as CodexProviderEvent, g as CodexTurnFailedEvent, h as CodexTurnCompletedEvent, i as CodexCliPermissionMode, l as CodexItemCompletedEvent, m as CodexThreadStartedEvent, n as CodexCliAgent, o as CodexCliSandboxMode, p as CodexProviderItem, r as CodexCliAgentOptions, s as CodexErrorEvent, t as createCodexCliAgent, u as CodexItemStartedEvent } from "../../index-65Dv7ed0.mjs";
1
+ import { a as CodexCliRunOptions, c as CodexEvent, d as CodexItemUpdatedEvent, f as CodexProviderEvent, g as CodexTurnFailedEvent, h as CodexTurnCompletedEvent, i as CodexCliPermissionMode, l as CodexItemCompletedEvent, m as CodexThreadStartedEvent, n as CodexCliAgent, o as CodexCliSandboxMode, p as CodexProviderItem, r as CodexCliAgentOptions, s as CodexErrorEvent, t as createCodexCliAgent, u as CodexItemStartedEvent } from "../../index-_lsNncl5.mjs";
2
2
  export { type CodexCliAgent, type CodexCliAgentOptions, type CodexCliPermissionMode, type CodexCliRunOptions, type CodexCliSandboxMode, type CodexErrorEvent, type CodexEvent, type CodexItemCompletedEvent, type CodexItemStartedEvent, type CodexItemUpdatedEvent, type CodexProviderEvent, type CodexProviderItem, type CodexThreadStartedEvent, type CodexTurnCompletedEvent, type CodexTurnFailedEvent, createCodexCliAgent };