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
@@ -1,7 +1,6 @@
1
- import { t as AgentEvent, v as AgentCapabilities, x as JsonSchema, y as ContentPart } from "./events-BxEB6zHt.mjs";
2
- import { r as ProcessSignal } from "./types-COmjfh8B.mjs";
1
+ import { C as ContentPart, S as AgentCapabilities, T as JsonSchema, t as AgentEvent } from "./events-DoTNE9UF.mjs";
2
+ import { r as ProcessSignal } from "./types-BetgZysV.mjs";
3
3
  import { ZodType } from "zod/v4";
4
- //#region src/core/agent/permissions.d.ts
5
4
  /**
6
5
  * Information about a tool call the adapter is requesting permission for.
7
6
  * Passed to the {@link PermissionHandler} registered via
@@ -15,7 +14,7 @@ interface PermissionRequest {
15
14
  input: Record<string, unknown>;
16
15
  /** Unique ID for this tool-use attempt. Stable across the permission round-trip. */
17
16
  toolUseId: string;
18
- /** Aborts when the run is cancelled. Honor it in long-running handlers. */
17
+ /** Aborts when the run is cancelled or Claude withdraws the request. Honor it in long-running handlers. */
19
18
  signal: AbortSignal;
20
19
  /** Why the adapter is asking (`"command requires approval"`, etc.). */
21
20
  reason?: string;
@@ -26,6 +25,8 @@ interface PermissionRequest {
26
25
  /** Longer description / justification suitable for a UI prompt. */
27
26
  description?: string;
28
27
  }
28
+ /** Permission mode of a Claude Code session. */
29
+ type ClaudePermissionMode = "acceptEdits" | "auto" | "bypassPermissions" | "default" | "dontAsk" | "plan";
29
30
  /**
30
31
  * Decision returned by a {@link PermissionHandler}.
31
32
  *
@@ -39,6 +40,8 @@ type PermissionDecision = {
39
40
  decision: "allow";
40
41
  /** Optional rewritten tool input; overrides {@link PermissionRequest.input}. */
41
42
  updatedInput?: Record<string, unknown>;
43
+ /** Optional permission mode the session switches to from this point on. Supported by the Claude adapters only. */
44
+ permissionMode?: ClaudePermissionMode;
42
45
  } | {
43
46
  /** Reject the tool call. */
44
47
  decision: "deny";
@@ -52,8 +55,35 @@ type PermissionDecision = {
52
55
  * a new one replaces the previous handler.
53
56
  */
54
57
  type PermissionHandler = (request: PermissionRequest) => PermissionDecision | Promise<PermissionDecision>;
55
- //#endregion
56
- //#region src/core/agent/types.d.ts
58
+ interface QuestionOption {
59
+ label: string;
60
+ description: string;
61
+ }
62
+ interface Question {
63
+ /** Identifies the question within its request. {@link QuestionAnswers} is keyed by it. */
64
+ id: string;
65
+ text: string;
66
+ header: string;
67
+ options: QuestionOption[];
68
+ allowsMultiple: boolean;
69
+ }
70
+ /**
71
+ * Questions the agent asks the user through its question tool. Passed to the {@link QuestionHandler} registered via
72
+ * `agent.onQuestionRequest(...)`. Only adapters that report `capabilities.questionRequests === true` issue these.
73
+ */
74
+ interface QuestionRequest {
75
+ /** Unique ID of the tool call that asks. Tells outstanding requests apart. */
76
+ toolUseId: string;
77
+ questions: Question[];
78
+ /** Aborts when the run is cancelled or the provider withdraws the request. Honor it in long-running handlers. */
79
+ signal: AbortSignal;
80
+ }
81
+ /**
82
+ * Answers returned by a {@link QuestionHandler}, keyed by {@link Question.id}. Each answer lists the labels of the
83
+ * selected options, free-form text, or both. A question without an entry stays unanswered.
84
+ */
85
+ type QuestionAnswers = Record<string, string[]>;
86
+ type QuestionHandler = (request: QuestionRequest) => Promise<QuestionAnswers> | QuestionAnswers;
57
87
  /**
58
88
  * Identifier for one of the supported coding-agent adapters.
59
89
  *
@@ -94,6 +124,17 @@ type StopReason = "abort" | "timeout" | "user";
94
124
  * `reasoningOutputTokens` is the one exception: it is a breakdown of `outputTokens` rather than a
95
125
  * class of its own, so it is already counted in both `outputTokens` and `totalTokens` and must not
96
126
  * be added to either.
127
+ *
128
+ * Claude adapters report per-run values on resumed and forked runs by subtracting the session
129
+ * totals recorded on the agent's earlier runs. A run that resumes a session the agent has not run
130
+ * itself, through a `sessionId` option or a resume flag in `extraArgs` or `command`, reports the
131
+ * session's cumulative `costUsd` and `apiDurationMs`, and its token counts cover only the main
132
+ * agent, not subagents.
133
+ *
134
+ * `codex-cli` on the app-server transport reports the token counts of the run's own turn, also on a
135
+ * resumed session: Codex reports the session's earlier totals before the turn starts, and the adapter
136
+ * subtracts them. A forked app-server run, and a resumed run on the default `exec` transport, report
137
+ * the session's cumulative token counts, because Codex reports no earlier totals for them.
97
138
  */
98
139
  interface RunStats {
99
140
  /** Wall-clock duration of the run as reported by the provider, in milliseconds. */
@@ -402,8 +443,12 @@ interface BaseAgent<TRunOptions extends object = {}> {
402
443
  reset: () => void;
403
444
  /**
404
445
  * Wait for the currently in-flight run to reach a terminal state and
405
- * resolve with its result. Resolves immediately if no run is in flight
406
- * (with a synthetic completed result).
446
+ * resolve with its result. When no run is in flight, resolves with the
447
+ * result of the most recent run.
448
+ *
449
+ * Throws {@link AgentValidationError} when the agent has no run to wait
450
+ * for: before its first run, or after `reset()`. The call itself throws;
451
+ * it does not return a rejected promise.
407
452
  */
408
453
  wait: () => Promise<AnyRunResult>;
409
454
  /**
@@ -439,6 +484,27 @@ interface BaseAgent<TRunOptions extends object = {}> {
439
484
  * support.
440
485
  */
441
486
  onPermissionRequest: (handler: PermissionHandler) => () => void;
487
+ /**
488
+ * Register the (single) question handler. The handler returns the answers
489
+ * directly, and the adapter sends them back to the provider. Calling again
490
+ * replaces any previous handler. Returns an unsubscribe function.
491
+ *
492
+ * Only effective when `capabilities.questionRequests === true`. If the
493
+ * handler throws, the question stays unanswered and the run continues:
494
+ * `claude-code-cli` tells the agent so with the error's message, while
495
+ * `codex-cli` gives the model no answer.
496
+ */
497
+ onQuestionRequest: (handler: QuestionHandler) => () => void;
498
+ /**
499
+ * Send user input into the active run, without waiting for it to finish.
500
+ * Resolves once the provider has been handed the input; when and how the
501
+ * model reads it is up to the provider.
502
+ *
503
+ * Rejects with {@link AgentValidationError} when `capabilities.midRunInput`
504
+ * is not `true`, when no run is active or the active run is not accepting
505
+ * input, and when the input is empty or has a part the adapter does not
506
+ * support.
507
+ */
508
+ sendInput: (input: ContentPart[] | string) => Promise<void>;
442
509
  }
443
- //#endregion
444
- export { PermissionRequest as A, RunStatus as C, ZodRunRequest as D, StructuredRunRequest as E, PermissionDecision as O, RunStats as S, StopReason as T, ProviderEventHandler as _, AgentValidationError as a, RunRequest as b, AnyRunResult as c, CompletedRunResult as d, EnsureDisjoint as f, ProviderEvent as g, JsonSchemaRunRequest as h, AgentType as i, PermissionHandler as k, BaseAgent as l, FailedRunResult as m, AgentMetrics as n, AnyCompletedRunResult as o, ExclusiveExecutionTargetOptions as p, AgentRunError as r, AnyRunRequest as s, AgentEventHandler as t, CancelledRunResult as u, RunError as v, RunTiming as w, RunResult as x, RunProcessInfo as y };
510
+ export { QuestionHandler as A, RunStatus as C, ZodRunRequest as D, StructuredRunRequest as E, PermissionHandler as F, PermissionRequest as I, QuestionRequest as M, ClaudePermissionMode as N, Question as O, PermissionDecision as P, RunStats as S, StopReason as T, ProviderEventHandler as _, AgentValidationError as a, RunRequest as b, AnyRunResult as c, CompletedRunResult as d, EnsureDisjoint as f, ProviderEvent as g, JsonSchemaRunRequest as h, AgentType as i, QuestionOption as j, QuestionAnswers as k, BaseAgent as l, FailedRunResult as m, AgentMetrics as n, AnyCompletedRunResult as o, ExclusiveExecutionTargetOptions as p, AgentRunError as r, AnyRunRequest as s, AgentEventHandler as t, CancelledRunResult as u, RunError as v, RunTiming as w, RunResult as x, RunProcessInfo as y };
@@ -1,4 +1,3 @@
1
- //#region src/core/process/types.d.ts
2
1
  type StdioOption = "ignore" | "inherit" | "pipe" | number;
3
2
  /** POSIX signal name (re-export of `NodeJS.Signals`). */
4
3
  type ProcessSignal = NodeJS.Signals;
@@ -53,5 +52,4 @@ interface ProcessSpawner {
53
52
  /** Launch `command` with `args` and return a live {@link AgentProcess} handle. */
54
53
  spawn: (command: string, args: string[], options?: SpawnOptions) => AgentProcess;
55
54
  }
56
- //#endregion
57
55
  export { SpawnOptions as a, ProcessSpawner as i, ProcessResult as n, ProcessSignal as r, AgentProcess as t };
@@ -0,0 +1 @@
1
+ const e=e=>Array.isArray(e)?e:[e],t=e=>e instanceof Error?e.message:String(e),n=e=>typeof e==`object`&&!!e,r=(...e)=>{if(!e.every(e=>e===void 0))return e.reduce((e,t)=>e+(t??0),0)},i=e=>{let t=e.trim();return t.startsWith("```")?t.replace(/^```[\w-]*\s*/i,``).replace(/\s*```$/i,``).trim():t},a=e=>/```[\w-]*\s*([\S\s]*?)\s*```/i.exec(e)?.[1]?.trim(),o=e=>{let t=-1,n=[],r=!1,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(o){if(t===-1)(o===`{`||o===`[`)&&(t=a,n.push(o));else if(r){if(i){i=!1;continue}if(o===`\\`){i=!0;continue}o===`"`&&(r=!1)}else if(o===`"`)r=!0;else if(o===`{`||o===`[`)n.push(o);else if(o===`}`||o===`]`){let r=n.pop();if(r===`{`&&o!==`}`||r===`[`&&o!==`]`)return;if(n.length===0)return e.slice(t,a+1).trim()}}}},s=e=>{let t=e.trim(),n=[i(t),a(t),o(t)],r;for(let e of new Set(n))if(e)try{return JSON.parse(e)}catch(e){r=e}throw r instanceof Error?r:/* @__PURE__ */ SyntaxError(`Failed to parse JSON response text.`)};export{e as a,r as i,n,s as r,t};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "coding-agents-sdk",
3
- "version": "0.17.0",
3
+ "version": "0.20.0",
4
4
  "description": "Run coding agents behind one uniform TypeScript interface, with optional container and sandbox execution.",
5
5
  "keywords": [
6
6
  "coding-agent",
@@ -110,21 +110,21 @@
110
110
  "typecheck": "bun run tsc"
111
111
  },
112
112
  "devDependencies": {
113
- "@anthropic-ai/claude-agent-sdk": "^0.3.288",
114
- "@cursor/sdk": "^1.0.35",
115
- "@openai/codex-sdk": "^0.160.0",
116
- "@types/bun": "^1.4.2",
117
- "@types/node": "^26.6.4",
118
- "e2b": "^2.52.0",
119
- "knip": "^6.39.0",
113
+ "@anthropic-ai/claude-agent-sdk": "^0.3.321",
114
+ "@cursor/sdk": "^1.3.1",
115
+ "@openai/codex-sdk": "^0.167.0",
116
+ "@types/bun": "^1.4.4",
117
+ "@types/node": "^26.6.6",
118
+ "e2b": "^2.62.1",
119
+ "knip": "^6.44.1",
120
120
  "picoprint": "^2.2.2",
121
- "tsdown": "^0.23.0",
121
+ "tsdown": "^0.23.4",
122
122
  "typescript": "^7.0.2"
123
123
  },
124
124
  "peerDependencies": {
125
125
  "@anthropic-ai/claude-agent-sdk": "^0.3.170",
126
126
  "@cursor/sdk": "^1.0.12",
127
- "@openai/codex-sdk": ">=0.150.0 <0.161.0",
127
+ "@openai/codex-sdk": ">=0.150.0 <0.168.0",
128
128
  "e2b": "^2.28.0",
129
129
  "typescript": "^6.0.3 || ^7.0.0"
130
130
  },
@@ -1,4 +0,0 @@
1
- import{t as e}from"./util-B4HTdOSc.mjs";import{t}from"./env-Cb8MIvH7.mjs";import{t as n}from"./errors-aYGbvsaq.mjs";import{t as r}from"./spawner-CgfyvnR4.mjs";import{a as i,i as a,n as o,s,t as c}from"./classify-error-DOqkMCcy.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=t=>t.status===`rejected`?e(t.reason):void 0,m=(t,r)=>{if(t.stopReason)return;if(r.processResult.status===`rejected`){let t=r.processResult.reason;return{kind:t instanceof n?`process`:`spawn`,message:e(t)}}let a=p(r.stdinResult);if(a)return{kind:`process`,message:a};let o=p(r.stdoutResult);if(o)return{kind:`process`,message:o};let s=p(r.stderrResult);if(s)return{kind:`process`,message:s};if(!t.status&&!t.error){let e=t.processResult,n=t.stderrLines.join(`
3
- `);if(e&&e.exitCode!==null&&e.exitCode!==0)return{kind:`process`,message:n||`Process exited with code ${e.exitCode}.`};if(!i(t)&&t.stderrLines.length>0)return{kind:`process`,message:n}}},h=e=>{let t=c(e);return t.kind===`provider`?{kind:`process`,message:t.message}:t};var g=class extends o{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??r,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(t,n){this.appendRawLog(`[parse-error] ${e(n)} ${t.slice(0,200)}`)}buildDefaultEnv(e){let n=t({propagateEnv:e});return n.CI=n.CI??`true`,this.defaults.env&&Object.assign(n,this.defaults.env),n}async executeRunCore(t,n){let r=this.setupRunLifecycle(t);try{if(r.abortedBeforeStart)return this.buildResult(t,/* @__PURE__ */ new Date);try{await this.onBeforeRun(t);let e={...n,...t.normalizedRequest},r=this.buildArgs(e,t),i=this.buildEnv(e,t),a=this.defaults.command?.[0]??`claude`,o=[...this.defaults.command?.slice(1)??[],...r];if(t.stopReason)return this.buildResult(t,/* @__PURE__ */ new Date);t.sessionId&&this.emitSessionStart(t),t.process=this.spawner.spawn(a,o,{cwd:t.normalizedRequest.cwd,env:i,stdio:[`pipe`,`pipe`,`pipe`]});let[s,c,l,u]=await Promise.allSettled([this.watchStdout(t),this.watchStderr(t),t.process.wait(),this.deliverInput(t.process,this.getStdinInput(e))]);l.status===`fulfilled`&&(t.processResult=l.value);let d=m(t,{stdoutResult:s,stderrResult:c,processResult:l,stdinResult:u});d&&(t.error=d)}catch(e){!t.stopReason&&!t.error&&(t.error=h(e))}return this.buildResult(t,/* @__PURE__ */ new Date)}finally{r.cleanup(),this.sigkillTimer&&=(clearTimeout(this.sigkillTimer),void 0);try{await this.onRunFinished(t)}catch(t){this.appendRawLog(`[cleanup-error] ${e(t)}`)}}}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){try{if(t!==void 0){if(!e.stdin?.write)throw Error(`The process spawner must provide a stdin writer for this adapter.`);await e.stdin.write(t)}await e.stdin?.end()}catch(t){throw e.kill(`SIGKILL`),t}}async watchStderr(e){let t=e.process?.stderr;if(t)for await(let n of f(t))this.appendLog(`stderr`,n),e.stderrLines.push(n),this.emit(e,s(e.runId,`stderr`,{sessionId:e.sessionId,text:n}))}processLine(e,t){let n;try{n=JSON.parse(t)}catch(e){this.onParseError(t,e);return}let r;try{r=this.mapRawEvent(n,a(e))}catch(e){this.onParseError(t,e);return}this.applyBatch(e,r)}get runRequestDefaults(){return this.defaults}onHandlerError(t){this.appendRawLog(`[handler-error] ${e(t)}`)}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()}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{g as t};
@@ -1 +0,0 @@
1
- import{n as e,t}from"./classify-error-DOqkMCcy.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?this.buildResult(e,/* @__PURE__ */ new Date):(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,8 +0,0 @@
1
- import{n as e,t}from"./types-B72tDMEZ.mjs";import{z as n}from"zod/v4";const r=()=>crypto.randomUUID(),i=()=>`evt_${crypto.randomUUID()}`,a=e=>({type:`text`,text:e}),o=e=>e.flatMap(e=>e.type===`text`?[e.text]:[]).join(`
2
- `),s=e=>e.flatMap(e=>e.type===`text`?[e.text]:[]).join(`
3
-
4
- `),c=e=>t=>{let n=e.safeParse(t);return n.success?n.data:null},l=(e,t,n,r)=>{let i;for(let t of e.events){if(t.type!==`message`||t.role!==`assistant`||!t.text)continue;let e=`${n.get(r)??``}${t.text}`;n.set(r,e),i=e}return t&&e.state?.output?.text!==void 0?n.set(r,e.state.output.text):i!==void 0&&(e.state={...e.state,output:{...e.state?.output,text:i}}),e},u=(e,t,n)=>({id:n.id??i(),runId:e,timestamp:/* @__PURE__ */ new Date,type:t,...n}),d=e=>e instanceof n.ZodType,f=e=>{if(!(`schema`in e))return{kind:`none`};let{schema:t}=e;return d(t)?{kind:`zod`,jsonSchema:n.toJSONSchema(t),zodSchema:t}:{kind:`json-schema`,jsonSchema:t}},p=(t,n,r,i)=>{let a=typeof i.input==`string`?[{type:`text`,text:i.input}]:i.input;if(a.length===0||a.every(e=>e.type===`text`&&e.text.trim()===``))throw new e(`Run input cannot be empty.`);if(!n.imageInput&&a.some(e=>e.type===`image`))throw new e(`${t} does not support image input.`);let o=f(i);if(!n.structuredOutput&&o.kind!==`none`)throw new e(`${t} does not support structured output.`);if(i.timeoutMs!==void 0&&(!Number.isFinite(i.timeoutMs)||i.timeoutMs<=0))throw new e(`timeoutMs must be a positive finite number.`);return{input:a,schema:o,cwd:i.cwd??r?.cwd,model:i.model??r?.model,systemPrompt:i.systemPrompt??r?.systemPrompt,timeoutMs:i.timeoutMs,signal:i.signal}},m=(e,t)=>({runId:e.runId,requestedSessionId:e.requestedSessionId,sessionId:e.sessionId,schemaRequested:e.normalizedRequest.schema.kind!==`none`,toolCalls:e.toolCalls,...t}),h=(e,t)=>{if(!e.stats)return;let n=Math.max(0,t.getTime()-e.startedAt.getTime());e.stats={...e.stats,durationMs:e.stats.durationMs??n,apiDurationMs:e.stats.apiDurationMs??n}},g=(e,t)=>{let n=e.normalizedRequest.schema;if(n.kind!==`none`){if(n.kind===`zod`){let r=n.zodSchema.safeParse(t);if(!r.success){e.status=`failed`,e.error={kind:`parse`,message:r.error.message};return}e.output.value=r.data;return}e.output.value=t}},_=(e,t)=>{if(e.events.push(t),t.type!==`message`||t.role!==`assistant`)return;let n=t.text??o(t.content);n&&e.assistantTexts.push(n)},v=(e,t,n={})=>{t.sessionId&&(e.sessionId=t.sessionId,n.onSessionId?.(t.sessionId));for(let n of t.toolCalls??[])e.toolCalls.set(n.toolCallId,{toolName:n.toolName,input:n.input});if(!t.state)return;let r=t.state;r.output&&(`text`in r.output&&(e.output.text=r.output.text),`value`in r.output&&g(e,r.output.value)),`stats`in r&&(e.stats=r.stats),`status`in r&&(e.status=r.status),`error`in r&&(e.error=r.error)},y=e=>e.events.some(e=>e.type===`message`||e.type===`reasoning`||e.type===`tool-call`||e.type===`tool-result`),b=e=>{let t=e.normalizedRequest.schema.kind!==`none`&&e.output.value===void 0;return e.stopReason===`user`||e.stopReason===`abort`||e.stopReason===`timeout`?`cancelled`:e.error?e.error.kind===`abort`?`cancelled`:`failed`:e.status?e.status===`completed`&&t?`failed`:e.status:e.processResult&&e.processResult.exitCode!==null&&e.processResult.exitCode!==0||!y(e)&&e.stderrLines.length>0||t?`failed`:`completed`},x=(e,t)=>{let n=e.processResult,r=e.stderrLines.join(`
5
- `);if(e.stopReason===`user`)return{kind:`abort`,message:`Run stopped by user.`};if(e.stopReason===`abort`)return{kind:`abort`,message:`Run aborted.`};if(e.stopReason===`timeout`)return{kind:`abort`,message:`Run timed out after ${e.normalizedRequest.timeoutMs}ms.`};if(e.error)return e.error;if(n&&n.exitCode!==null&&n.exitCode!==0)return{kind:`process`,message:r||`Process exited with code ${n.exitCode}.`};if(t===`failed`&&e.stderrLines.length>0)return{kind:`process`,message:r};if(t===`failed`&&e.normalizedRequest.schema.kind!==`none`&&e.output.value===void 0)return{kind:`parse`,message:`Structured output was requested but no structured output value was produced.`}},S=(e,t,n,r,i)=>{let a=t.stderrLines.join(`
6
- `),o={type:e,runId:t.runId,sessionId:t.sessionId,text:t.output.text??t.assistantTexts.join(`
7
-
8
- `),events:[...t.events],stats:t.stats,timing:{startedAt:t.startedAt,endedAt:n,durationMs:n.getTime()-t.startedAt.getTime()},process:t.processResult?{exitCode:t.processResult.exitCode,signal:t.processResult.signal,stderr:a}:void 0};switch(r){case`completed`:return t.normalizedRequest.schema.kind===`none`?{...o,status:r,error:void 0,cancelReason:void 0}:{...o,status:r,output:t.output.value,error:void 0,cancelReason:void 0};case`failed`:return{...o,status:r,output:void 0,error:i??{kind:`process`,message:`Unknown error.`},cancelReason:void 0};case`cancelled`:return{...o,status:r,output:void 0,error:i??{kind:`abort`,message:`Run cancelled.`},cancelReason:t.stopReason??`user`};default:throw Error(`Unsupported run status.`)}},C=()=>{let e=/* @__PURE__ */ new Date;return{runCount:0,messagesReceived:0,toolCalls:0,errors:0,startedAt:e,lastActivityAt:e}};var w=class{type;capabilities;currentRun;eventHandlers=[];permissionHandler;_sessionId;_metrics;constructor(e){this.type=e.type,this.capabilities=e.capabilities,this._sessionId=e.sessionId,this._metrics=C(),e.onEvent&&this.onEvent(e.onEvent)}onValidateRun(e,t){}async onDispose(){}onHandlerError(e){}get sessionId(){return this._sessionId}get metrics(){return this._metrics}get isRunning(){return this.currentRun?.running??!1}onEvent(e){return this.eventHandlers.push(e),()=>{let t=this.eventHandlers.indexOf(e);t>=0&&this.eventHandlers.splice(t,1)}}onPermissionRequest(e){return this.permissionHandler=e,()=>{this.permissionHandler===e&&(this.permissionHandler=void 0)}}getPermissionHandler(){return this.permissionHandler}async run(t){if(this.currentRun?.running)throw new e(`This agent is already running. Wait for it to finish first.`);let n=p(this.type,this.capabilities,this.runRequestDefaults,t);this.onValidateRun(t,n);let i={runId:r(),startedAt:/* @__PURE__ */ new Date,requestedSessionId:this._sessionId,sessionId:this._sessionId,normalizedRequest:n,events:[],stderrLines:[],assistantTexts:[],toolCalls:/* @__PURE__ */ new Map,output:{}},a={context:i,running:!0,promise:new Promise(()=>{})};this._metrics.runCount++;let o=Promise.resolve().then(()=>this.executeRunCore(i,t)).finally(()=>{a.running=!1});return a.promise=o,this.currentRun=a,o}async runOrThrow(e){let n=await this.run(e);if(n.status!==`completed`)throw new t(n);return n}async stop(){let e=this.currentRun?.context;if(e&&this.currentRun?.running){this.requestStop(e,`user`);try{return await this.currentRun.promise}catch{return}}}reset(){if(this.currentRun?.running)throw new e(`Cannot reset agent state while a run is active. Call stop() and wait() first.`);this.currentRun=void 0,this._sessionId=void 0,this._metrics=C()}wait(){if(!this.currentRun)throw new e(`There is no run to wait for.`);return this.currentRun.promise}async dispose(){if(this.currentRun?.running){this.requestStop(this.currentRun.context,`user`);try{await this.currentRun.promise}catch{}}await this.onDispose()}async[Symbol.asyncDispose](){await this.dispose()}applyBatch(e,t){v(e,t,{onSessionId:e=>{this.setSessionId(e)}}),e.sessionId&&this.emitSessionStart(e);for(let n of t.events)this.emit(e,n)}setupRunLifecycle(e){let t=!1,n=()=>{t||this.requestStop(e,`abort`)},r=e.normalizedRequest.timeoutMs===void 0?void 0:setTimeout(()=>{t||this.requestStop(e,`timeout`)},e.normalizedRequest.timeoutMs);r?.unref?.(),e.normalizedRequest.signal?.addEventListener(`abort`,n,{once:!0});let i=e.normalizedRequest.signal?.aborted===!0;return i&&this.requestStop(e,`abort`),{abortedBeforeStart:i,cleanup:()=>{t=!0,r&&clearTimeout(r),e.normalizedRequest.signal?.removeEventListener(`abort`,n)}}}emitSessionStart(e){e.sessionStarted||(e.sessionStarted=!0,this.emit(e,u(e.runId,`session-start`,{requestedSessionId:e.requestedSessionId,sessionId:e.sessionId,resumed:e.requestedSessionId!==void 0})))}emit(e,t){_(e,t),this.updateMetrics(t);for(let e of this.eventHandlers)try{e(t)}catch(e){this.onHandlerError(e)}}requestStop(e,t){e.stopReason||(e.stopReason=t,this.onStopRequested(e))}buildResult(e,t){h(e,t);let n=b(e),r=x(e,n);return e.sessionStarted&&this.emit(e,u(e.runId,`session-end`,{sessionId:e.sessionId,status:n,error:r?.message})),S(this.type,e,t,n,r)}setSessionId(e){this._sessionId=e}updateMetrics(e){switch(this._metrics.lastActivityAt=e.timestamp,e.type){case`message`:e.role===`assistant`&&this._metrics.messagesReceived++;break;case`tool-call`:this._metrics.toolCalls++;break;case`session-end`:e.status===`failed`&&this._metrics.errors++}}};const T=/* @__PURE__ */ new Set([`ENOENT`,`ERR_MODULE_NOT_FOUND`]),E=e=>`code`in e,D=(e,t)=>{let n=t??(e instanceof Error?e.message:String(e));if(e instanceof Error){if(e.name===`AbortError`)return{kind:`abort`,message:n};if(E(e)&&T.has(String(e.code)))return{kind:`spawn`,message:n};if(e instanceof SyntaxError)return{kind:`parse`,message:n}}return{kind:`provider`,message:n}};export{y as a,c,m as i,s as l,w as n,l as o,v as r,u as s,D as t,a as u};
@@ -1 +0,0 @@
1
- import{n as e,t}from"./oci-DTNwW-WH.mjs";const n=async n=>{let r={binary:n.binary??`docker`},i=await e(r,n);return t(`docker`,{commandContext:r,containerName:n.name,workdir:n.workdir,user:n.user,network:n.network,platform:n.platform,env:n.env,ports:n.ports,mounts:n.mounts,mountCwd:n.mountCwd,extraArgs:n.extraArgs,image:i,builtImage:n.build!==void 0&&!n.build.tag},n)};export{n as createDockerContainer};
@@ -1 +0,0 @@
1
- var e=class extends Error{constructor(e){super(e),this.name=`ContainerError`}},t=class extends e{constructor(e){super(e),this.name=`ContainerCreateError`}},n=class extends e{constructor(e){super(e),this.name=`MountValidationError`}},r=class extends e{constructor(e){super(e),this.name=`ContainerStartError`}},i=class extends e{constructor(e){super(e),this.name=`ContainerExecError`}},a=class extends e{constructor(e=`Container is not running.`){super(e),this.name=`ContainerNotRunningError`}},o=class extends e{constructor(e=`Container has been disposed.`){super(e),this.name=`ContainerDisposedError`}},s=class extends e{constructor(e){super(e),this.name=`ContainerDiffError`}};async function c(e){switch(e.type){case`docker`:{let{createDockerContainer:t}=await import(`./container-Bdb90GJb.mjs`);return t(e)}case`e2b`:try{let{createE2BContainer:t}=await import(`./container-w0rl1QMH.mjs`);return await t(e)}catch(e){throw e instanceof Error&&e.message.includes(`e2b`)&&(e.code===`ERR_MODULE_NOT_FOUND`||e.code===`MODULE_NOT_FOUND`)?new t(`Container type "e2b" requires the optional peer dependency "e2b". Install it to use this provider.`):e}case`nerdctl`:{let{createNerdctlContainer:t}=await import(`./container-dCRMBvQw.mjs`);return t(e)}case`podman`:{let{createPodmanContainer:t}=await import(`./container-Dvr-p53c.mjs`);return t(e)}default:throw new t(`Unsupported container type.`)}}export{e as a,r as c,o as i,n as l,t as n,i as o,s as r,a as s,c as t};
@@ -1 +0,0 @@
1
- import{n as e,t}from"./oci-DTNwW-WH.mjs";const n=async n=>{let r={binary:n.binary??`podman`},i=await e(r,n);return t(`podman`,{commandContext:r,containerName:n.name,workdir:n.workdir,user:n.user,network:n.network,platform:n.platform,env:n.env,ports:n.ports,mounts:n.mounts,mountCwd:n.mountCwd,extraArgs:n.extraArgs,image:i,builtImage:n.build!==void 0&&!n.build.tag},n)};export{n as createPodmanContainer};
@@ -1 +0,0 @@
1
- import{n as e,t}from"./oci-DTNwW-WH.mjs";const n=e=>{let t={};return e.address&&(t.CONTAINERD_ADDRESS=e.address),e.namespace&&(t.CONTAINERD_NAMESPACE=e.namespace),e.buildkitHost&&(t.BUILDKIT_HOST=e.buildkitHost),Object.keys(t).length>0?t:void 0},r=e=>{let t=[];return e.namespace&&t.push(`--namespace`,e.namespace),e.address&&t.push(`--address`,e.address),e.snapshotter&&t.push(`--snapshotter`,e.snapshotter),e.args&&t.push(...e.args),t.length>0?t:void 0},i=e=>({binary:e.binary??`nerdctl`,baseArgs:r(e),env:n(e)}),a=async n=>{let r=i(n),a=await e(r,n);return t(`nerdctl`,{commandContext:r,containerName:n.name,workdir:n.workdir,user:n.user,network:n.network,platform:n.platform,env:n.env,ports:n.ports,mounts:n.mounts,mountCwd:n.mountCwd,extraArgs:n.extraArgs,image:a,builtImage:n.build!==void 0&&!n.build.tag},n)};export{a as createNerdctlContainer};
@@ -1 +0,0 @@
1
- import{t as e}from"./util-B4HTdOSc.mjs";import{c as t,i as n,n as r,r as i,s as a}from"./container-DMFxf-kn.mjs";import{t as o}from"./errors-aYGbvsaq.mjs";import{t as s}from"./shell-DvWFuFKb.mjs";import{n as c}from"./diff-Dqyk2cdt.mjs";import{basename as l,dirname as u,join as d,posix as f}from"node:path";import{mkdir as p,readFile as m,readdir as h,stat as g,writeFile as _}from"node:fs/promises";import{CommandExitError as v,FileType as y,Sandbox as b}from"e2b";const x=(e,t)=>[e,...t].map(s).join(` `),S=e=>e.user,C=(e,t)=>{let n={...e.env,...t};return Object.keys(n).length>0?n:void 0},w=(e,t)=>t??e.workdir,T=new TextEncoder,E=e=>e instanceof Error?e:Error(String(e)),D=e=>typeof e==`string`?e:`SIGKILL`,O=(e,t)=>{let n=e?.stdio?.[t];return n===`ignore`||n===`inherit`||n===`pipe`?n:n===void 0?`pipe`:`ignore`},k=()=>{let e=[],t=[],n=!1,r,i=()=>{for(;t.length>0&&e.length>0;)t.shift().resolve({done:!1,value:e.shift()});if(r){for(;t.length>0;)t.shift().reject(r);return}if(n)for(;t.length>0;)t.shift().resolve({done:!0,value:void 0})};return{iterable:{async*[Symbol.asyncIterator](){for(;;){if(e.length>0){yield e.shift();continue}if(r)throw E(r);if(n)return;let i=await new Promise((e,n)=>{t.push({resolve:e,reject:n})});if(i.done)return;yield i.value}}},push(t){t.length===0||n||r||(e.push(T.encode(t)),i())},end(){n||r||(n=!0,i())},fail(e){n||r||(r=e,i())}}},A=(e,t)=>({spawn:(n,r,i={})=>{let a=O(i,0),s=O(i,1),c=O(i,2),l=s===`pipe`?k():void 0,u=c===`pipe`?k():void 0,d=null,f={background:!0,stdin:a===`pipe`,cwd:w(t,i.cwd),envs:C(t,i.env),user:S(t),requestTimeoutMs:t.requestTimeoutMs,onStdout:e=>{if(s===`inherit`){process.stdout.write(e);return}l?.push(e)},onStderr:e=>{if(c===`inherit`){process.stderr.write(e);return}u?.push(e)}},p=e.commands.run(x(n,r),f),m=Promise.resolve(),h,g=e=>{let t=m.then(async()=>{await e((await p).pid)});return m=t.catch(e=>{h??=new o(e)}),t};return p.catch(e=>{l?.fail(e),u?.fail(e)}),{stdout:l?.iterable??null,stderr:u?.iterable??null,stdin:a===`pipe`?{write:n=>g(r=>e.commands.sendStdin(r,n,{requestTimeoutMs:t.requestTimeoutMs})),end:()=>g(n=>e.commands.closeStdin(n,{requestTimeoutMs:t.requestTimeoutMs}))}:null,kill:e=>{d=D(e),p.then(e=>e.kill()).catch(()=>{})},wait:async()=>{try{let e=await(await p).wait();if(await m,h)throw h;return l?.end(),u?.end(),d?{exitCode:null,signal:d}:{exitCode:e.exitCode,signal:null}}catch(e){if(l?.end(),u?.end(),e instanceof v)return d?{exitCode:null,signal:d}:{exitCode:e.exitCode,signal:null};throw e}}}}}),j=e=>({apiKey:e.apiKey,domain:e.domain,requestTimeoutMs:e.requestTimeoutMs,apiHeaders:e.headers}),M=e=>`sandboxId`in e&&typeof e.sandboxId==`string`,N=e=>{let t=j(e);return M(e)?t:{...t,envs:e.env,timeoutMs:e.timeoutMs,metadata:e.metadata,secure:e.secure,allowInternetAccess:e.allowInternetAccess,network:e.network,lifecycle:e.lifecycle}},P=async(e,t)=>{await e.files.makeDir(t.workdir,{user:S(t)})},F=e=>e instanceof Error&&e.name===`AbortError`,I=e=>Uint8Array.from(e).buffer,L=e=>{let t=e.endsWith(`/`)&&e!==`/`?e.slice(0,-1):e;return f.basename(t)},R=async e=>{try{return await g(e)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}},z=async(e,t,n)=>{if(await e.files.exists(t,{user:n}))return e.files.getInfo(t,{user:n})},B=async(e,t,n,r)=>(await z(e,n,r))?.type===y.DIR?f.join(n,l(t)):n,V=async(e,t)=>(await R(t))?.isDirectory()?d(t,L(e)):t,H=async(e,t,n,r)=>{let i=await g(t);if(i.isDirectory()){await e.files.makeDir(n,{user:r});let i=await h(t);await Promise.all(i.map(i=>H(e,d(t,i),f.join(n,i),r)));return}if(!i.isFile())throw Error(`Unsupported local filesystem entry at ${t}.`);let a=await m(t);await e.files.write(n,I(a),{user:r})},U=async(e,t,n,r)=>{if((await e.files.getInfo(t,{user:r})).type===y.DIR){await p(n,{recursive:!0});let i=await e.files.list(t,{user:r});await Promise.all(i.map(t=>U(e,t.path,d(n,t.name),r)));return}let i=await e.files.read(t,{format:`bytes`,user:r});await p(u(n),{recursive:!0}),await _(n,i)},W=async e=>{if(M(e))return b.connect(e.sandboxId,j(e));let t=N(e);return e.template?b.create(e.template,t):b.create(t)},G=async(e,t)=>e.connect(j(t)),K=async(e,t)=>{let n=t.signal;if(n?.aborted){let e=n.reason;throw e instanceof Error?e:new DOMException(`The operation was aborted.`,`AbortError`)}let r=!1,i=()=>{r=!0,e.kill()};n?.addEventListener(`abort`,i,{once:!0});try{let t=await e.wait();if(r)throw new DOMException(`The operation was aborted.`,`AbortError`);return{exitCode:t.exitCode,stdout:t.stdout,stderr:t.stderr}}catch(e){if(r||F(e))throw new DOMException(`The operation was aborted.`,`AbortError`);if(e instanceof v)return{exitCode:e.exitCode,stdout:e.stdout,stderr:e.stderr};throw e}finally{n?.removeEventListener(`abort`,i)}},q=async o=>{let s;try{s=await W(o),await P(s,o)}catch(t){throw new r(`E2B create failed: ${e(t)}`)}let l=o.name??s.sandboxId,u=`running`,f=A(s,o),m={},h=()=>{if(u===`disposed`)throw new n},g=()=>{if(h(),u!==`running`)throw new a},_=c({owner:m,workdir:o.workdir,materialize:async(e,t)=>{g();let n=S(o),r=await z(s,e,n);if(!r)throw new i(`Target path does not exist: ${e}`);if(r.type!==y.DIR)throw new i(`Target path is not a directory: ${e}`);await p(t,{recursive:!0});for(let r of await s.files.list(e,{user:n}))await U(s,r.path,d(t,r.name),n)}}),v={get type(){return`e2b`},get id(){return s.sandboxId},get name(){return l},get config(){return o},get status(){return u},get workdir(){return o.workdir},get spawner(){return f},async start(){if(h(),u!==`running`)try{s=await G(s,o),await P(s,o),f=A(s,o),u=`running`}catch(n){throw new t(`E2B start failed: ${e(n)}`)}},async stop(){h(),u===`running`&&(await s.pause({requestTimeoutMs:o.requestTimeoutMs}),u=`stopped`)},async dispose(){if(u!==`disposed`){try{await s.kill({requestTimeoutMs:o.requestTimeoutMs})}catch{}await _.disposeSnapshots().catch(()=>{}),u=`disposed`}},async exec(e,t,n={}){g();let r={background:!0,cwd:w(o,n.cwd),envs:C(o,n.env),user:S(o),timeoutMs:n.timeoutMs,requestTimeoutMs:o.requestTimeoutMs},i=await s.commands.run(x(e,t),r);return K(i,n)},async copyTo(e,t){g();let n=await B(s,e,t,S(o));await H(s,e,n,S(o))},async copyFrom(e,t){g();let n=await V(e,t);await U(s,e,n,S(o))},async writeFile(e,t){g(),await s.files.write(e,typeof t==`string`?t:I(t),{user:S(o)})},async readFile(e){return g(),s.files.read(e,{format:`text`,user:S(o)})},async fileExists(e){return g(),s.files.exists(e,{user:S(o)})},async mkdir(e){g(),await s.files.makeDir(e,{user:S(o)})},async execShell(e,t={}){return v.exec(`sh`,[`-c`,e],t)},async logs(){return``},async syncStatus(){return u},async snapshotWorkdir(e={}){return _.snapshotWorkdir(e)},async diffWorkdir(e){return _.diffWorkdir(e)},async releaseWorkdirSnapshot(e){return _.releaseWorkdirSnapshot(e)},getHost(e){return g(),s.getHost(e)},[Symbol.asyncDispose](){return v.dispose()}};return v};export{q as createE2BContainer};
@@ -1 +0,0 @@
1
- import{t as e}from"./util-B4HTdOSc.mjs";import{i as t,r as n,s as r}from"./container-DMFxf-kn.mjs";import{n as i}from"./errors-aYGbvsaq.mjs";import{execFile as a}from"node:child_process";import{dirname as o,isAbsolute as s,join as c,posix as l,relative as u,sep as d}from"node:path";import{promisify as f}from"node:util";import{createReadStream as p}from"node:fs";import{tmpdir as m}from"node:os";import{copyFile as h,lstat as g,mkdir as _,mkdtemp as v,readdir as y,readlink as b,rm as x,stat as S,symlink as C}from"node:fs/promises";import{createHash as w}from"node:crypto";import{pipeline as T}from"node:stream/promises";const E=f(a),D=e=>e!==`..`&&!e.startsWith(`..${d}`)&&!s(e),O=(e,t)=>{let n=u(e,t);if(D(n))return n.split(d).join(l.sep)},k=(e,t,r)=>{let i=O(t,e);if(i!==void 0)return i;let a=O(r,e);if(a!==void 0)return a;throw new n(`Git diff produced a path outside the materialized trees: ${e}`)},A=e=>e.sort((e,t)=>e.path===t.path?(e.previousPath??``).localeCompare(t.previousPath??``):e.path.localeCompare(t.path)),j=async e=>{let t=await y(e,{withFileTypes:!0});for(let n of t){let t=c(e,n.name);if(n.name===`.git`){await x(t,{recursive:!0,force:!0});continue}n.isDirectory()&&await j(t)}},M=()=>v(c(m(),`cw-workdir-diff-`)),N=async e=>{e&&await x(e,{recursive:!0,force:!0}).catch(()=>{})},P=(e,t)=>{let n={cwd:e.cwd,createdAt:/* @__PURE__ */ new Date};return t.set(n,e),n},F=(e,t,r)=>{if(typeof t!=`object`||!t)throw new n(`Invalid workdir snapshot.`);let i=r.get(t);if(!i)throw new n(`Invalid workdir snapshot.`);if(i.owner!==e)throw new n(`Workdir snapshot was created by a different container instance.`);return i},I=(e,t)=>{if(!t.has(e))throw new n(`Workdir snapshot has been released.`)},L=e=>w(`sha256`).update(e).digest(`hex`),R=e=>Buffer.isBuffer(e)?e:Buffer.from(e,`utf8`),z=async e=>{let t=w(`sha256`);return await T(p(e),t),t.digest(`hex`)},B=async(e,t,r)=>{let i=`${e}:${t}`;if(r.has(i))return r.get(i);let a=c(e,...t.split(l.sep));try{let e=await g(a),t,o;if(e.isSymbolicLink()){let e=Buffer.from(await b(a));t=L(e),o=e.byteLength}else if(e.isFile())t=await z(a),o=e.size;else throw new n(`Unsupported filesystem entry in diff metadata: ${a}`);let s={hash:t,size:o};return r.set(i,s),s}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`){r.set(i,void 0);return}throw e}},V=(e,t,r)=>{if(e.byteLength===0)return[];let i=e.toString(`utf8`).split(`\0`);i[i.length-1]===``&&i.pop();let a=[];for(let e=0;e<i.length;){let o=i[e++];if(!o)continue;if(o.startsWith(`R`)){let o=i[e++],s=i[e++];if(!o||!s)throw new n(`Failed to parse git rename entry.`);a.push({kind:`renamed`,previousPath:k(o,t,r),path:k(s,t,r)});continue}let s=i[e++];if(!s)throw new n(`Failed to parse git diff entry.`);switch(o){case`A`:a.push({kind:`added`,path:k(s,t,r)});break;case`D`:a.push({kind:`deleted`,path:k(s,t,r)});break;case`M`:a.push({kind:`modified`,path:k(s,t,r)});break;case`T`:a.push({kind:`modified`,path:k(s,t,r)});break;default:throw new n(`Unsupported git diff change kind: ${o}`)}}return a},H=async(t,r)=>{try{let e=await E(`git`,[`diff`,`--no-index`,`-z`,`--name-status`,`-M`,`--find-renames=100%`,t,r],{cwd:m(),encoding:`buffer`,maxBuffer:52428800});return V(R(e.stdout),t,r)}catch(a){if(!i(a))throw new n(`Failed to run git diff: ${e(a)}`);let o=a.code??1,s=Buffer.isBuffer(a.stdout)?a.stdout:Buffer.from(String(a.stdout??``),`utf8`),c=Buffer.isBuffer(a.stderr)?a.stderr:Buffer.from(String(a.stderr??``),`utf8`);if(o===0||o===1)return V(s,t,r);let l=c.toString(`utf8`).trim()||s.toString(`utf8`).trim()||`exit code ${o}`;throw new n(`Failed to run git diff: ${l}`)}},U=async(e,t,n)=>{let r=/* @__PURE__ */ new Map,i=await Promise.all(e.map(async e=>{let i;i=e.kind===`added`?void 0:e.kind===`renamed`?e.previousPath:e.path;let a=e.kind===`deleted`?void 0:e.path,[o,s]=await Promise.all([i===void 0?void 0:B(t,i,r),a===void 0?void 0:B(n,a,r)]);return{path:e.path,previousPath:e.previousPath,kind:e.kind,beforeHash:o?.hash,afterHash:s?.hash,beforeSize:o?.size,afterSize:s?.size}}));return A(i)},W=e=>{let t=/* @__PURE__ */ new Set;for(let n of e)t.add(n.path),n.kind===`renamed`&&n.previousPath&&t.add(n.previousPath);return[...t].sort((e,t)=>e.localeCompare(t))},G=(i,a)=>{throw a instanceof n||a instanceof t||a instanceof r?a:new n(`${i}: ${e(a)}`)},K=async(e,t)=>{if(!(await S(e)).isDirectory())throw new n(`Target path is not a directory: ${e}`);await _(t,{recursive:!0});let r=await y(e,{withFileTypes:!0});await Promise.all(r.filter(e=>e.name!==`.git`).map(async r=>{let i=c(e,r.name),a=c(t,r.name);if(r.isDirectory()){await K(i,a);return}if(r.isSymbolicLink()){await _(o(a),{recursive:!0}),await C(await b(i),a);return}if(r.isFile()){await _(o(a),{recursive:!0}),await h(i,a);return}throw new n(`Unsupported filesystem entry in workdir diff: ${i}`)}))},q=e=>{let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new WeakMap,r=async(r={})=>{let i=r.cwd??e.workdir,a;try{a=await M(),await e.materialize(i,a),await j(a);let r={owner:e.owner,tempDir:a,cwd:i,inFlightDiffs:0,released:!1};return t.add(r),a=void 0,P(r,n)}catch(e){return await N(a),G(`Failed to materialize workdir snapshot`,e)}},i=async r=>{let i=Date.now(),a=F(e.owner,r,n);I(a,t),a.inFlightDiffs++;let o;try{o=await M(),await e.materialize(a.cwd,o),await j(o);let t=await H(a.tempDir,o),n=await U(t,a.tempDir,o),r=W(n);return{cwd:a.cwd,changedFiles:r,fileChanges:n,stats:{durationMs:Date.now()-i,filesCompared:r.length}}}catch(e){return G(`Failed to diff workdir snapshot`,e)}finally{a.inFlightDiffs--,a.inFlightDiffs===0&&(a.resolveIdle?.(),a.resolveIdle=void 0),await N(o)}},a=e=>{let n=e;return n.releasePromise?n.releasePromise:(n.released=!0,t.delete(n),n.releasePromise=(async()=>{n.inFlightDiffs>0&&await new Promise(e=>{n.resolveIdle=e}),await N(n.tempDir)})(),n.releasePromise)};return{snapshotWorkdir:r,diffWorkdir:i,releaseWorkdirSnapshot:async t=>{let r=F(e.owner,t,n);await a(r)},disposeSnapshots:async()=>{await Promise.all(Array.from(t).map(a))}}};export{q as n,K as t};
@@ -1,10 +0,0 @@
1
- import { a as SpawnOptions, t as AgentProcess } from "./types-COmjfh8B.mjs";
2
- //#region src/core/process/spawner.d.ts
3
- declare const spawnProcess: (command: string, args: string[], options?: SpawnOptions) => AgentProcess;
4
- //#endregion
5
- //#region src/core/process/errors.d.ts
6
- declare class ProcessStdinError extends Error {
7
- constructor(cause: unknown);
8
- }
9
- //#endregion
10
- export { spawnProcess as n, ProcessStdinError as t };
@@ -1 +0,0 @@
1
- import{t as e}from"./util-B4HTdOSc.mjs";import{c as t,i as n,l as r,n as i,o as a,r as o,s}from"./container-DMFxf-kn.mjs";import{n as c}from"./env-Cb8MIvH7.mjs";import{n as l}from"./errors-aYGbvsaq.mjs";import{t as u}from"./spawner-CgfyvnR4.mjs";import{t as d}from"./shell-DvWFuFKb.mjs";import{n as f,t as p}from"./diff-Dqyk2cdt.mjs";import{execFile as m}from"node:child_process";import{isAbsolute as h,join as g,posix as _,resolve as v}from"node:path";import{promisify as y}from"node:util";import{existsSync as b}from"node:fs";import{tmpdir as x}from"node:os";import{mkdtemp as S,rm as C,writeFile as w}from"node:fs/promises";import{randomBytes as T}from"node:crypto";const E=(e,t)=>{let n=_.relative(e,t);return n===``||!n.startsWith(`..`)&&!_.isAbsolute(n)},D=(e,t)=>{if(!e||e.length===0)return;let n=_.normalize(t),r;for(let t of e){if(!h(t.source))continue;let e=_.normalize(t.target);E(e,n)&&(!r||e.length>_.normalize(r.target).length)&&(r=t)}if(!r)return;let i=_.relative(_.normalize(r.target),n);return i===``?r.source:_.join(r.source,...i.split(`/`))},O=(e,t)=>{let n=h(e.source)?e.source:v(t.cwd,e.source);if(!b(n))throw new r(`Mount source does not exist: ${n}`);return{...e,source:n}},k=y(m),A=()=>`cw-${T(6).toString(`hex`)}`,j=(e,t)=>e.baseArgs?[...e.baseArgs,...t]:t,M=e=>{if(e.env)return{...c(),...e.env}},N=async(e,t,n)=>{let r=await k(e.binary,j(e,t),{encoding:`utf8`,env:M(e),timeout:n?.timeoutMs,signal:n?.signal,maxBuffer:52428800});return{stdout:r.stdout,stderr:r.stderr}},P=async(t,n)=>{let r=n.tag??`cw-build-${T(4).toString(`hex`)}`,a=[`build`,`-t`,r];if(n.args)for(let[e,t]of Object.entries(n.args))a.push(`--build-arg`,`${e}=${t}`);`dockerfile`in n&&n.dockerfile&&(a.push(`-f`,n.dockerfile),a.push(n.context??`.`));let o;if(`content`in n&&n.content){o=await S(g(x(),`cw-oci-build-`));let e=g(o,`Dockerfile`);await w(e,n.content,{encoding:`utf8`,mode:384}),a.push(`-f`,e),a.push(n.context??o)}try{await N(t,a)}catch(t){throw new i(`Image build failed: ${e(t)}`)}finally{o&&await C(o,{recursive:!0,force:!0}).catch(()=>{})}return r},F=async(e,t,n)=>{let r=await Promise.all(n.map(async n=>{try{let{container:r,protocol:i=`tcp`}=n,{stdout:a}=await N(e,[`port`,t,`${r}/${i}`]),o=/:(\d+)$/m.exec(a.trim());if(o?.[1])return[r,Number(o[1])]}catch{}})),i=/* @__PURE__ */ new Map;for(let e of r)e&&i.set(e[0],e[1]);return i},I=(e,t)=>({spawn:(n,r,i={})=>{let a=[`exec`,`-i`];if(i.cwd&&a.push(`-w`,i.cwd),i.env)for(let[e,t]of Object.entries(i.env))a.push(`-e`,`${e}=${t}`);return a.push(e,n,...r),u.spawn(t.binary,j(t,a),{env:M(t),stdio:i.stdio})}}),L=async(r,c,m)=>{let{commandContext:h,builtImage:g,containerName:v,workdir:y,user:b,network:x,platform:S,env:C,ports:w,mounts:T,mountCwd:E,extraArgs:k,image:P}=c,L=v??A(),R=T?.map(e=>O(e,{cwd:E??process.cwd()})),z=[`create`,`--name`,L];if(b&&z.push(`--user`,b),x&&z.push(`--network`,x),S&&z.push(`--platform`,S),C)for(let[e,t]of Object.entries(C))z.push(`-e`,`${e}=${t}`);if(w)for(let e of w){let{host:t,container:n,protocol:r=`tcp`}=e;z.push(`-p`,`${t??``}:${n}/${r}`)}if(R)for(let e of R){let{readonly:t,source:n,target:r}=e,i=t?`ro`:`rw`;z.push(`-v`,`${n}:${r}:${i}`)}k&&z.push(...k),z.push(P,`sleep`,`infinity`);let B;try{let{stdout:e}=await N(h,z);B=e.trim()}catch(t){throw new i(`Container create failed: ${e(t)}`)}let V=`created`,H=/* @__PURE__ */ new Map,U=()=>{if(V===`disposed`)throw new n},W=()=>{if(U(),V!==`running`)throw new s},G=I(B,h),K=f({owner:{},workdir:y,materialize:async(t,n)=>{U();let r=D(R,t);if(r){await p(r,n);return}W();try{await N(h,[`exec`,B,`sh`,`-c`,`test -d ${d(t)}`])}catch{throw new o(`Target path is not a directory: ${t}`)}try{await N(h,[`cp`,`${B}:${t}/.`,n])}catch(n){throw new o(`Failed to materialize container path ${t}: ${e(n)}`)}}}),q={get type(){return r},get id(){return B},get name(){return L},get config(){return m},get status(){return V},get workdir(){return y},get spawner(){return G},async start(){if(U(),V!==`running`){try{await N(h,[`start`,B])}catch(n){throw new t(`Container start failed: ${e(n)}`)}try{await N(h,[`exec`,B,`mkdir`,`-p`,y])}catch(n){try{await N(h,[`stop`,`-t`,`0`,B]),V=`stopped`}catch{try{let{stdout:e}=await N(h,[`inspect`,`--format`,`{{.State.Status}}`,B]);V=e.trim()===`running`?`running`:`stopped`}catch{V=`disposed`}}throw new t(`Container start failed: ${e(n)}`)}V=`running`,w?.length&&(H=await F(h,B,w))}},async stop(){if(U(),V===`running`){try{await N(h,[`stop`,`-t`,`2`,B])}catch{try{let{stdout:e}=await N(h,[`inspect`,`--format`,`{{.State.Status}}`,B]);if(e.trim()===`running`)return}catch{V=`disposed`;return}}V=`stopped`}},async dispose(){if(V!==`disposed`){try{await N(h,[`stop`,`-t`,`0`,B])}catch{}try{await N(h,[`rm`,`-f`,B])}catch{}g&&await N(h,[`rmi`,P]).catch(()=>{}),await K.disposeSnapshots().catch(()=>{}),V=`disposed`}},async exec(e,t,n={}){W();let r=[`exec`];if(n.cwd&&r.push(`-w`,n.cwd),n.env)for(let[e,t]of Object.entries(n.env))r.push(`-e`,`${e}=${t}`);r.push(B,e,...t);try{let{stdout:e,stderr:t}=await N(h,r,{timeoutMs:n.timeoutMs,signal:n.signal});return{exitCode:0,stdout:e,stderr:t}}catch(e){if(l(e))return{exitCode:typeof e.code==`number`?e.code:-1,stdout:String(e.stdout??``),stderr:String(e.stderr??``)};throw e}},async copyTo(e,t){W(),await N(h,[`cp`,e,`${B}:${t}`])},async copyFrom(e,t){W(),await N(h,[`cp`,`${B}:${e}`,t])},async writeFile(t,n){W();let r=_.isAbsolute(t)?t:_.resolve(y,t),i=_.dirname(r),o=typeof n==`string`?Buffer.from(n,`utf8`):n,s=[`exec`,`-i`];b&&s.push(`--user`,b),s.push(B,`sh`,`-c`,`mkdir -p ${d(i)} && cat > ${d(r)}`);let c=u.spawn(h.binary,j(h,s),{env:M(h),stdio:[`pipe`,`ignore`,`ignore`]}),l;try{c.stdin?.write?.(o),c.stdin?.end(),l=await c.wait()}catch(t){throw c.kill(),c.wait().catch(()=>{}),new a(`writeFile failed for ${r}: ${e(t)}`)}if(l.exitCode!==0)throw new a(`writeFile failed for ${r} (exit ${l.exitCode})`)},async readFile(e){W();let t=_.isAbsolute(e)?e:_.resolve(y,e),{stdout:n}=await N(h,[`exec`,B,`cat`,t]);return n},async fileExists(e){W();let t=_.isAbsolute(e)?e:_.resolve(y,e);try{return await N(h,[`exec`,B,`test`,`-e`,t]),!0}catch{return!1}},async mkdir(e){W();let t=_.isAbsolute(e)?e:_.resolve(y,e);await N(h,[`exec`,B,`mkdir`,`-p`,t])},async execShell(e,t={}){return q.exec(`sh`,[`-c`,e],t)},async logs(e={}){U();let t=[`logs`];e.tail!==void 0&&t.push(`--tail`,String(e.tail)),t.push(B);let{stdout:n}=await N(h,t);return n},async syncStatus(){U();try{let{stdout:e}=await N(h,[`inspect`,`--format`,`{{.State.Status}}`,B]),t=e.trim();V=t===`running`?`running`:t===`created`?`created`:`stopped`}catch{V=`disposed`}return V},async snapshotWorkdir(e={}){return K.snapshotWorkdir(e)},async diffWorkdir(e){return K.diffWorkdir(e)},async releaseWorkdirSnapshot(e){return K.releaseWorkdirSnapshot(e)},getMappedPort(e){return H.get(e)},[Symbol.asyncDispose](){return q.dispose()}};return q},R=async(e,t)=>{if(t.image)return t.image;if(t.build)return P(e,t.build);throw new i(`Either image or build must be provided.`)};export{R as n,L as t};
@@ -1,2 +0,0 @@
1
- import{i as e}from"./util-B4HTdOSc.mjs";import{c as t,s as n,u as r}from"./classify-error-DOqkMCcy.mjs";import{r as i}from"./session-markers-Dt7TWdKY.mjs";import{z as a}from"zod/v4";const o=e=>`session_id`in e?e.session_id:void 0,s=e=>typeof e.content==`string`?e.content:e.content.map(e=>e.text).join(`
2
- `),c=e=>typeof e.result==`string`&&e.result.trim()!==``?e.result:e.subtype,l=(e,t)=>{let i=[`[${e.subtype}]`];if(e.subtype===`init`){if(e.tools&&i.push(`tools: ${e.tools.length}`),e.mcp_servers){let t=e.mcp_servers.filter(e=>e.status===`connected`).length;i.push(`mcp: ${t}/${e.mcp_servers.length} connected`)}}else e.hook_name&&(i.push(e.hook_name),e.exit_code!==void 0&&i.push(`exit: ${e.exit_code}`));let a=i.join(` `);return{events:[n(t.runId,`message`,{sessionId:t.sessionId,model:e.model??null,role:`system`,content:[r(a)],text:a})]}},u=(e,t)=>{let i=[],a=[];for(let o of e.message.content)switch(o.type){case`text`:i.push(n(t.runId,`message`,{sessionId:t.sessionId,model:e.message.model??null,role:`assistant`,content:[r(o.text)],text:o.text}));break;case`thinking`:i.push(n(t.runId,`reasoning`,{sessionId:t.sessionId,model:e.message.model??null,content:[r(o.thinking)],text:o.thinking}));break;case`tool_use`:a.push({toolCallId:o.id,toolName:o.name,input:o.input}),i.push(n(t.runId,`tool-call`,{sessionId:t.sessionId,model:e.message.model??null,toolCallId:o.id,toolName:o.name,input:o.input}))}return{events:i,toolCalls:a}},d=(e,t)=>{let i=[];for(let a of e.message.content)switch(a.type){case`text`:i.push(n(t.runId,`message`,{sessionId:t.sessionId,model:null,role:`user`,content:[r(a.text)],text:a.text}));break;case`tool_result`:{let e=t.toolCalls.get(a.tool_use_id),r=s(a);i.push(n(t.runId,`tool-result`,{sessionId:t.sessionId,toolCallId:a.tool_use_id,toolName:e?.toolName,input:e?.input,output:r,isError:a.is_error,error:a.is_error?r:void 0}));break}}return{events:i}},f=(t,n)=>{let r=t.usage?.input_tokens,a=t.usage?.cache_creation_input_tokens,o=t.usage?.cache_read_input_tokens,s=t.usage?.output_tokens,l=e(r,a,o,s),u={stats:{durationMs:t.duration_ms,apiDurationMs:t.duration_api_ms,turns:t.num_turns,inputTokens:r,cacheCreationInputTokens:a,cacheReadInputTokens:o,outputTokens:s,totalTokens:l,costUsd:t.total_cost_usd}};typeof t.result==`string`&&(u.output={...u.output,text:t.result});let d=!t.is_error&&t.subtype===`success`,f=i(t.structured_output,{schemaRequested:n.schemaRequested,toolCalls:n.toolCalls,allowToolCallFallback:!1},{isSuccess:d},`Structured output was requested but Claude did not return structured_output.`);return f.value!==void 0&&(u.output={...u.output,value:f.value}),f.error&&(u.status=`failed`,u.error=f.error),t.is_error||t.subtype!==`success`?(u.status=`failed`,u.error={kind:`provider`,message:c(t)}):u.error||(u.status=`completed`),{events:[],state:u}},p=(e,t)=>{let i=`rate limited: ${e.rate_limit_info.status}`;return{events:[n(t.runId,`message`,{sessionId:t.sessionId,model:null,role:`system`,content:[r(i)],text:i})]}},m=(e,t)=>{switch(e.type){case`system`:return l(e,t);case`assistant`:return u(e,t);case`user`:return d(e,t);case`result`:return f(e,t);case`rate_limit_event`:return p(e,t);default:return{events:[]}}},h=a.enum([`init`,`hook_response`,`hook_started`,`hook_finished`,`hook_failed`,`hook_skipped`]),g=a.object({name:a.string(),status:a.string()}),_=a.object({type:a.literal(`system`),session_id:a.string(),subtype:h,uuid:a.string(),tools:a.array(a.string()).optional(),mcp_servers:a.array(g.extend({status:a.enum([`connected`,`disconnected`,`error`,`failed`])})).optional(),model:a.string().optional(),cwd:a.string().optional(),hook_name:a.string().optional(),hook_event:a.string().optional(),stdout:a.string().optional(),stderr:a.string().optional(),exit_code:a.number().optional()}),v=a.object({type:a.literal(`assistant`),session_id:a.string(),uuid:a.string(),parent_tool_use_id:a.string().nullable().optional(),message:a.object({id:a.string(),type:a.literal(`message`),role:a.literal(`assistant`),model:a.string(),content:a.array(a.union([a.object({type:a.literal(`text`),text:a.string()}),a.object({type:a.literal(`tool_use`),id:a.string(),name:a.string(),input:a.record(a.string(),a.unknown())}),a.object({type:a.literal(`thinking`),thinking:a.string(),signature:a.string().optional()})])),stop_reason:a.enum([`end_turn`,`max_tokens`,`tool_use`,`stop_sequence`]).nullable(),stop_sequence:a.string().nullable().optional(),context_management:a.unknown().nullable().optional(),usage:a.object({input_tokens:a.number(),output_tokens:a.number(),cache_creation_input_tokens:a.number().optional(),cache_read_input_tokens:a.number().optional(),service_tier:a.enum([`premium`,`standard`]).nullable().optional()}),ttftMs:a.number().optional()})}),y=a.object({type:a.literal(`user`),session_id:a.string(),message:a.object({role:a.literal(`user`),content:a.array(a.union([a.object({type:a.literal(`tool_result`),tool_use_id:a.string(),content:a.union([a.string(),a.array(a.object({type:a.literal(`text`),text:a.string()}))]),is_error:a.boolean().optional()}),a.object({type:a.literal(`text`),text:a.string()})]))}),parent_tool_use_id:a.string().nullable().optional(),uuid:a.string(),isSynthetic:a.boolean().optional()}),b=a.object({type:a.literal(`result`),session_id:a.string(),uuid:a.string(),subtype:a.enum([`success`,`error_max_turns`,`error_during_execution`]),duration_ms:a.number(),duration_api_ms:a.number(),is_error:a.boolean(),num_turns:a.number(),result:a.unknown().optional(),structured_output:a.unknown().optional(),total_cost_usd:a.number(),usage:a.object({input_tokens:a.number(),cache_creation_input_tokens:a.number().optional(),cache_read_input_tokens:a.number().optional(),output_tokens:a.number(),server_tool_use:a.object({web_search_requests:a.number()}).optional()}).optional()}),x=a.object({type:a.literal(`rate_limit_event`),uuid:a.string(),session_id:a.string().optional(),rate_limit_info:a.object({status:a.string(),resetsAt:a.number().optional(),rateLimitType:a.string().optional(),overageStatus:a.string().optional(),overageDisabledReason:a.string().optional(),isUsingOverage:a.boolean().optional()})}),S=a.discriminatedUnion(`type`,[_,v,y,b,x]),C=a.discriminatedUnion(`type`,[_.extend({uuid:a.string().optional(),mcp_servers:a.array(g).optional()}),v.extend({uuid:a.string().optional()}),y.extend({uuid:a.string().optional()}),b.extend({uuid:a.string().optional(),subtype:a.string()}),x]),w=t(S);export{m as i,C as n,o as r,w as t};
@@ -1 +0,0 @@
1
- import{z as e}from"zod/v4";const t=e.object({type:e.literal(`text`),text:e.string()}),n=e.object({type:e.literal(`image`),path:e.string(),mediaType:e.string().optional()}),r=e.discriminatedUnion(`type`,[t,n]),i=e.object({structuredOutput:e.boolean(),sessionResume:e.boolean(),imageInput:e.boolean(),mcp:e.boolean(),eventStreaming:e.boolean(),sessionFork:e.boolean().optional(),permissionRequests:e.boolean().optional()}),a=e.object({id:e.string(),runId:e.string(),timestamp:e.date()}),o=a.extend({type:e.literal(`session-start`),requestedSessionId:e.string().optional(),sessionId:e.string().optional(),resumed:e.boolean()}),s=a.extend({type:e.literal(`message`),sessionId:e.string().optional(),model:e.string().nullable(),role:e.enum([`system`,`user`,`assistant`]),content:e.array(r),text:e.string().optional()}),c=a.extend({type:e.literal(`reasoning`),sessionId:e.string().optional(),model:e.string().nullable(),content:e.array(r),text:e.string().optional()}),l=a.extend({type:e.literal(`tool-call`),sessionId:e.string().optional(),model:e.string().nullable(),toolCallId:e.string(),toolName:e.string(),input:e.unknown().optional()}),u=a.extend({type:e.literal(`tool-result`),sessionId:e.string().optional(),toolCallId:e.string(),toolName:e.string().optional(),input:e.unknown().optional(),output:e.unknown(),isError:e.boolean().optional(),error:e.string().optional()}),d=a.extend({type:e.literal(`stderr`),sessionId:e.string().optional(),text:e.string()}),f=a.extend({type:e.literal(`session-end`),sessionId:e.string().optional(),status:e.enum([`completed`,`failed`,`cancelled`]),error:e.string().optional()}),p=e.discriminatedUnion(`type`,[o,s,c,l,u,d,f]);export{f as a,l as c,r as d,n as f,c as i,u as l,p as n,o,t as p,s as r,d as s,a as t,i as u};
@@ -1 +0,0 @@
1
- const e=`SendUserMessage`,t=t=>t?.includes(e)?[...t]:[...t??[],e],n=e=>{let t;for(let[,n]of e)n.toolName===`StructuredOutput`&&n.input!==void 0&&(t=n.input);return t},r=(e,t,r,i)=>{if(e!=null)return{value:e};if(!t.schemaRequested)return{};if(t.allowToolCallFallback??!0){let e=n(t.toolCalls);if(e!==void 0)return{value:e}}return r.isSuccess?{error:{kind:`parse`,message:i}}:{}},i=e=>{let t={...e};return delete t.$schema,t},a=[`CLAUDECODE`,`CLAUDE_CODE_CHILD_SESSION`],o=e=>{for(let t of a)delete e[t]};export{t as i,i as n,r,o as t};
@@ -1 +0,0 @@
1
- import{t as e}from"./errors-aYGbvsaq.mjs";import{spawn as t}from"node:child_process";const n=e=>({async*[Symbol.asyncIterator](){for await(let t of e){if(t instanceof Buffer){yield new Uint8Array(t);continue}if(typeof t==`string`){yield new TextEncoder().encode(t);continue}if(t instanceof Uint8Array){yield t;continue}throw Error(`Unsupported stdout/stderr chunk type: ${typeof t}`)}}}),r=(r,i,a={})=>{let o=t(r,i,{cwd:a.cwd,env:a.env,stdio:a.stdio,detached:!0}),s,c=t=>{s??=new e(t)};o.stdin?.on(`error`,c);let l=new Promise((e,t)=>{let n=(n,i)=>{if(o.removeListener(`error`,r),s){t(s);return}e({exitCode:n,signal:i})},r=e=>{o.removeListener(`close`,n),t(e)};o.once(`error`,r),o.once(`close`,n)}),u=o.stdin;return{stdout:o.stdout?n(o.stdout):null,stderr:o.stderr?n(o.stderr):null,stdin:u?{write:e=>{let t=new Promise((t,n)=>{u.write(e,e=>{if(e){n(e);return}t()})});return t.catch(c),t},end:()=>{let e=new Promise((e,t)=>{u.end(n=>{if(n){t(n);return}e()})});return e.catch(c),e}}:null,kill:e=>{if(o.pid===void 0){o.kill(e);return}try{process.kill(-o.pid,e??`SIGTERM`)}catch{o.kill(e)}},wait:()=>l}},i={spawn:r};export{r as n,i as t};
@@ -1 +0,0 @@
1
- const e=e=>Array.isArray(e)?e:[e],t=e=>e instanceof Error?e.message:String(e),n=e=>typeof e==`object`&&!!e,r=(...e)=>{if(!e.every(e=>e===void 0))return e.reduce((e,t)=>e+(t??0),0)},i=e=>{let t=e.trim();return t.startsWith("```")?t.replace(/^```[\w-]*\s*/i,``).replace(/\s*```$/i,``).trim():t},a=e=>/```[\w-]*\s*([\S\s]*?)\s*```/i.exec(e)?.[1]?.trim(),o=e=>{let t=-1,n=[],r=!1,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(o){if(t===-1){(o===`{`||o===`[`)&&(t=a,n.push(o));continue}if(r){if(i){i=!1;continue}if(o===`\\`){i=!0;continue}o===`"`&&(r=!1);continue}if(o===`"`){r=!0;continue}if(o===`{`||o===`[`){n.push(o);continue}if(o===`}`||o===`]`){let r=n.pop();if(r===`{`&&o!==`}`||r===`[`&&o!==`]`)return;if(n.length===0)return e.slice(t,a+1).trim()}}}},s=e=>{let t=e.trim(),n=[i(t),a(t),o(t)],r;for(let e of new Set(n))if(e)try{return JSON.parse(e)}catch(e){r=e}throw r instanceof Error?r:/* @__PURE__ */ SyntaxError(`Failed to parse JSON response text.`)};export{e as a,r as i,n,s as r,t};