coding-agents-sdk 0.10.0 → 0.12.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 (84) hide show
  1. package/README.md +12 -9
  2. package/dist/Agent-4TZ8JK66.mjs +4 -0
  3. package/dist/{SdkAgent-DQfLwPwY.mjs → SdkAgent-p0nJ6dWV.mjs} +1 -1
  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 +3 -0
  7. package/dist/adapters/claude-code-cli-pty/index.mjs +35 -0
  8. package/dist/adapters/claude-code-sdk/index.d.mts +2 -2
  9. package/dist/adapters/claude-code-sdk/index.mjs +4 -4
  10. package/dist/adapters/codex-cli/index.d.mts +2 -2
  11. package/dist/adapters/codex-cli/index.mjs +2 -2
  12. package/dist/adapters/codex-sdk/index.d.mts +2 -2
  13. package/dist/adapters/codex-sdk/index.mjs +1 -1
  14. package/dist/adapters/cursor-cli/index.d.mts +2 -2
  15. package/dist/adapters/cursor-cli/index.mjs +1 -1
  16. package/dist/adapters/cursor-sdk/index.d.mts +2 -2
  17. package/dist/adapters/cursor-sdk/index.mjs +1 -1
  18. package/dist/adapters/gemini-cli/index.d.mts +2 -2
  19. package/dist/adapters/gemini-cli/index.mjs +1 -1
  20. package/dist/adapters/opencode-cli/index.d.mts +2 -2
  21. package/dist/adapters/opencode-cli/index.mjs +1 -1
  22. package/dist/adapters/pi-cli/index.d.mts +2 -2
  23. package/dist/adapters/pi-cli/index.mjs +1 -1
  24. package/dist/{classify-error-BcWmNftw.mjs → classify-error-BPQtzEVV.mjs} +4 -4
  25. package/dist/container/index.d.mts +2 -2
  26. package/dist/container/index.mjs +1 -1
  27. package/dist/{container-D31bbA4L.mjs → container-46QA1d3v.mjs} +1 -1
  28. package/dist/container-DBXaA-Iv.mjs +1 -0
  29. package/dist/container-DRj7xq5x.mjs +1 -0
  30. package/dist/{container-BhXUiAiK.mjs → container-Dg68bfte.mjs} +1 -1
  31. package/dist/{container-TizHce_7.mjs → container-gJ8B-Z5B.mjs} +1 -1
  32. package/dist/diff-BJWXJsjx.mjs +1 -0
  33. package/dist/{events-Dd9r9luo.d.mts → events-B0BpIsW2.d.mts} +143 -4
  34. package/dist/execution-target-CdlYXh6Z.mjs +1 -0
  35. package/dist/index-5bx9TIY_.d.mts +60 -0
  36. package/dist/index-B5NFoNlS.d.mts +195 -0
  37. package/dist/index-B9ze9hTN.d.mts +97 -0
  38. package/dist/{index-DZDlHIep.d.mts → index-BKK-3gye.d.mts} +44 -13
  39. package/dist/{index-J7V9dJTb.d.mts → index-BQ8cUo2i.d.mts} +50 -19
  40. package/dist/index-C9XD71QR.d.mts +429 -0
  41. package/dist/{index-B-rto_J2.d.mts → index-CG2m7pFJ.d.mts} +77 -1
  42. package/dist/index-CG5DS_NB.d.mts +58 -0
  43. package/dist/index-DPP4zoiJ.d.mts +68 -0
  44. package/dist/{index-BNeL0BbU.d.mts → index-DdyD2ji1.d.mts} +68 -2
  45. package/dist/index-DzFF15zC.d.mts +104 -0
  46. package/dist/index-XWqpUSBc.d.mts +69 -0
  47. package/dist/index.d.mts +69 -16
  48. package/dist/index.mjs +1 -1
  49. package/dist/oci-DmEG3Ia3.mjs +1 -0
  50. package/dist/{parser-BBJPNGZ2.mjs → parser-Dz239_vv.mjs} +2 -2
  51. package/dist/sandbox/index.d.mts +2 -2
  52. package/dist/sandbox/index.mjs +1 -1
  53. package/dist/sandbox-C5vzNxZR.mjs +4 -0
  54. package/dist/schemas/index.d.mts +1 -1
  55. package/dist/schemas/index.mjs +1 -1
  56. package/dist/spawner-BB6W3FVi.mjs +1 -0
  57. package/dist/types-CGzSzwfB.d.mts +476 -0
  58. package/dist/util-DcPzh_0u.mjs +1 -0
  59. package/package.json +24 -24
  60. package/dist/Agent-BD2xHVi0.mjs +0 -4
  61. package/dist/adapters/claude-cli-pty/index.d.mts +0 -3
  62. package/dist/adapters/claude-cli-pty/index.mjs +0 -7
  63. package/dist/container-BurV5WG9.mjs +0 -1
  64. package/dist/diff-DWM1ciiV.mjs +0 -1
  65. package/dist/errors-CeKI_bYK.mjs +0 -1
  66. package/dist/execution-target-CGTSqVEP.mjs +0 -1
  67. package/dist/index-B4RAMnx_.d.mts +0 -46
  68. package/dist/index-BdDz7C4J.d.mts +0 -39
  69. package/dist/index-BiWkGgnz.d.mts +0 -46
  70. package/dist/index-BllemWbi.d.mts +0 -42
  71. package/dist/index-C7J_hmQs.d.mts +0 -67
  72. package/dist/index-CaUzD36R.d.mts +0 -42
  73. package/dist/index-D-8EmRnQ.d.mts +0 -85
  74. package/dist/index-lGZ1lQkG.d.mts +0 -246
  75. package/dist/oci-tjdSZfTm.mjs +0 -1
  76. package/dist/sandbox-_As0qZWn.mjs +0 -4
  77. package/dist/spawner-BJesLc8I.mjs +0 -1
  78. package/dist/types-D6kxBNzj.d.mts +0 -195
  79. package/dist/util-CGg8cK92.mjs +0 -1
  80. /package/dist/{env-DIXTVzTs.mjs → env-Cb8MIvH7.mjs} +0 -0
  81. /package/dist/{schemas-mNF2Xlg_.mjs → schemas-CkdQXAep.mjs} +0 -0
  82. /package/dist/{shell-Dewbmt9R.mjs → shell-DvWFuFKb.mjs} +0 -0
  83. /package/dist/{structured-output-nPFh_ZoY.mjs → structured-output-cpLrrrTN.mjs} +0 -0
  84. /package/dist/{types-CwvWHEpy.mjs → types-B72tDMEZ.mjs} +0 -0
@@ -0,0 +1,476 @@
1
+ import { t as AgentEvent, v as AgentCapabilities, x as JsonSchema, y as ContentPart } from "./events-B0BpIsW2.mjs";
2
+ import { ZodType } from "zod/v4";
3
+
4
+ //#region src/core/process/types.d.ts
5
+ type StdioOption = "ignore" | "inherit" | "pipe" | number;
6
+ /** POSIX signal name (re-export of `NodeJS.Signals`). */
7
+ type ProcessSignal = NodeJS.Signals;
8
+ /**
9
+ * Options accepted by {@link ProcessSpawner.spawn} when launching a
10
+ * subprocess. Adapters set sensible defaults; callers typically only need to
11
+ * override these inside custom spawners.
12
+ */
13
+ interface SpawnOptions {
14
+ /** Working directory for the subprocess. Defaults to the spawner's default. */
15
+ cwd?: string;
16
+ /** Environment variables for the subprocess. */
17
+ env?: Record<string, string>;
18
+ /** Stdio disposition for [stdin, stdout, stderr]. Default is `["pipe", "pipe", "pipe"]`. */
19
+ stdio?: [StdioOption, StdioOption, StdioOption];
20
+ }
21
+ /** Subprocess termination result returned by {@link AgentProcess.wait}. */
22
+ interface ProcessResult {
23
+ /** Exit code; `null` if the process was killed by signal. */
24
+ exitCode: number | null;
25
+ /** Signal that terminated the process; `null` if it exited normally. */
26
+ signal: ProcessSignal | null;
27
+ }
28
+ /**
29
+ * Handle to a running subprocess returned by {@link ProcessSpawner.spawn}.
30
+ * Exposes byte streams for stdio, a kill signal, and a `wait` for terminal
31
+ * status. Each stream is `null` when its slot was set to `"ignore"` or
32
+ * `"inherit"` in {@link SpawnOptions.stdio}.
33
+ */
34
+ interface AgentProcess {
35
+ /** Stdout byte stream, or `null` if not piped. */
36
+ stdout: AsyncIterable<Uint8Array> | null;
37
+ /** Stderr byte stream, or `null` if not piped. */
38
+ stderr: AsyncIterable<Uint8Array> | null;
39
+ /** Stdin writer with optional `write` and required `end`, or `null` if not piped. */
40
+ stdin: {
41
+ write?: (chunk: Uint8Array | string) => void;
42
+ end: () => void;
43
+ } | null;
44
+ /** Send a signal to the process. Defaults to `"SIGTERM"`. Idempotent after exit. */
45
+ kill: (signal?: ProcessSignal | number) => void;
46
+ /** Resolve with the {@link ProcessResult} once the process exits. */
47
+ wait: () => Promise<ProcessResult>;
48
+ }
49
+ /**
50
+ * Pluggable process launcher used by CLI adapters and exposed by
51
+ * containers and sandboxes via their `spawner` field. Pass a custom
52
+ * `ProcessSpawner` to an adapter's `spawner` option to intercept how the
53
+ * underlying agent CLI is launched (for instrumentation, sandboxing, or
54
+ * remote execution).
55
+ */
56
+ interface ProcessSpawner {
57
+ /** Launch `command` with `args` and return a live {@link AgentProcess} handle. */
58
+ spawn: (command: string, args: string[], options?: SpawnOptions) => AgentProcess;
59
+ }
60
+ //#endregion
61
+ //#region src/core/agent/permissions.d.ts
62
+ /**
63
+ * Information about a tool call the adapter is requesting permission for.
64
+ * Passed to the {@link PermissionHandler} registered via
65
+ * `agent.onPermissionRequest(...)`. Only adapters that report
66
+ * `capabilities.permissionRequests === true` will issue these.
67
+ */
68
+ interface PermissionRequest {
69
+ /** Tool the agent wants to invoke (e.g. `"Bash"`, `"Read"`, an MCP tool name). */
70
+ toolName: string;
71
+ /** Tool input the agent intends to send; you can rewrite this via {@link PermissionDecision.updatedInput}. */
72
+ input: Record<string, unknown>;
73
+ /** Unique ID for this tool-use attempt. Stable across the permission round-trip. */
74
+ toolUseId: string;
75
+ /** Aborts when the run is cancelled. Honor it in long-running handlers. */
76
+ signal: AbortSignal;
77
+ /** Why the adapter is asking (`"command requires approval"`, etc.). */
78
+ reason?: string;
79
+ /** Path the request would touch, when the prompt is filesystem-related. */
80
+ blockedPath?: string;
81
+ /** Short title suitable for a UI prompt. */
82
+ title?: string;
83
+ /** Longer description / justification suitable for a UI prompt. */
84
+ description?: string;
85
+ }
86
+ /**
87
+ * Decision returned by a {@link PermissionHandler}.
88
+ *
89
+ * - `{ decision: "allow" }` lets the call proceed; pass `updatedInput` to
90
+ * rewrite the tool arguments before execution.
91
+ * - `{ decision: "deny" }` blocks the call; `message` is fed back to the
92
+ * model as the rejection reason.
93
+ */
94
+ type PermissionDecision = {
95
+ /** Approve the tool call. */decision: "allow"; /** Optional rewritten tool input; overrides {@link PermissionRequest.input}. */
96
+ updatedInput?: Record<string, unknown>;
97
+ } | {
98
+ /** Reject the tool call. */decision: "deny"; /** Rejection reason sent back to the model. */
99
+ message?: string;
100
+ };
101
+ /**
102
+ * Callback signature for `agent.onPermissionRequest(handler)`. Receives a
103
+ * {@link PermissionRequest} and returns a {@link PermissionDecision} (or a
104
+ * promise thereof). The handler is single-instance per agent — registering
105
+ * a new one replaces the previous handler.
106
+ */
107
+ type PermissionHandler = (request: PermissionRequest) => PermissionDecision | Promise<PermissionDecision>;
108
+ //#endregion
109
+ //#region src/core/agent/types.d.ts
110
+ /**
111
+ * Identifier for one of the supported coding-agent adapters.
112
+ *
113
+ * Passed as the first argument of `createAgent` to select which third-party
114
+ * agent backs the instance. CLI variants spawn a subprocess; SDK variants
115
+ * import an in-process SDK package.
116
+ */
117
+ type AgentType = "claude-code-cli-pty" | "claude-code-cli" | "claude-code-sdk" | "codex-cli" | "codex-sdk" | "cursor-cli" | "cursor-sdk" | "gemini-cli" | "opencode-cli" | "pi-cli";
118
+ /**
119
+ * Terminal status of a run.
120
+ * - `"completed"`: the model produced a final response (and structured output if requested).
121
+ * - `"cancelled"`: a stop was requested before the run finished — see `cancelReason`.
122
+ * - `"failed"`: the underlying process or SDK reported an error — see `error`.
123
+ */
124
+ type RunStatus = "cancelled" | "completed" | "failed";
125
+ /**
126
+ * Why a run was stopped.
127
+ * - `"user"`: explicit `agent.stop()` call.
128
+ * - `"timeout"`: `timeoutMs` on the request expired.
129
+ * - `"abort"`: caller-supplied `AbortSignal` fired.
130
+ */
131
+ type StopReason = "abort" | "timeout" | "user";
132
+ /**
133
+ * Numerical summary of a single run.
134
+ *
135
+ * Adapters fill in whatever the underlying provider reports. Fields are
136
+ * optional because providers differ — Claude reports caching tokens, Codex
137
+ * reports reasoning tokens, others may report nothing beyond `turns` and
138
+ * `costUsd`.
139
+ */
140
+ interface RunStats {
141
+ /** Wall-clock duration of the run as reported by the provider, in milliseconds. */
142
+ durationMs?: number;
143
+ /** Active model API duration excluding tool-call latency, in milliseconds. */
144
+ apiDurationMs?: number;
145
+ /** Number of model turns (request/response pairs) consumed by this run. */
146
+ turns: number;
147
+ /** Provider-reported cost in USD; `0` if the provider does not report cost. */
148
+ costUsd: number;
149
+ /** Input tokens billed (excluding cache-hit tokens, when distinguished). */
150
+ inputTokens?: number;
151
+ /** Tokens written to the provider's prompt cache during this run. */
152
+ cacheCreationInputTokens?: number;
153
+ /** Tokens served from the provider's prompt cache during this run. */
154
+ cacheReadInputTokens?: number;
155
+ /** Output tokens generated by the model. */
156
+ outputTokens?: number;
157
+ /** Sum of all token classes for convenience; provider definitions vary. */
158
+ totalTokens?: number;
159
+ }
160
+ /**
161
+ * Structured failure reason attached to non-completed runs.
162
+ *
163
+ * `kind` distinguishes the failure mode:
164
+ * - `"abort"`: a stop was honored mid-run.
165
+ * - `"parse"`: structured output failed schema validation or JSON parsing.
166
+ * - `"process"`: the underlying subprocess exited non-zero or unexpectedly.
167
+ * - `"provider"`: the SDK or upstream service reported an error.
168
+ * - `"spawn"`: the subprocess could not be launched at all.
169
+ */
170
+ interface RunError {
171
+ kind: "abort" | "parse" | "process" | "provider" | "spawn";
172
+ /** Human-readable message suitable for logging. Not stable enough for string matching. */
173
+ message: string;
174
+ }
175
+ /**
176
+ * Request shape passed to `agent.run(...)`.
177
+ *
178
+ * Adapters extend this with their own `*RunOptions` (`permissionMode`,
179
+ * `sandboxMode`, etc.). Use those adapter-specific types if you want
180
+ * compile-time checking of the per-run knobs.
181
+ */
182
+ interface RunRequest {
183
+ /** The user prompt. Pass a string for plain text, or a `ContentPart[]` to include images. */
184
+ input: ContentPart[] | string;
185
+ /** Working directory for the run. Overrides the agent's default `cwd`. */
186
+ cwd?: string;
187
+ /** Per-run model override. Adapter must support per-run model selection. */
188
+ model?: string;
189
+ /** Adapter-supported per-run system prompt. Adapters that don't accept one declare it as `never` on their `*RunOptions`. */
190
+ systemPrompt?: string;
191
+ /** Hard timeout in milliseconds. The run is cancelled with `cancelReason: "timeout"` when exceeded. */
192
+ timeoutMs?: number;
193
+ /** Caller-controlled AbortSignal. Aborting cancels the run with `cancelReason: "abort"`. */
194
+ signal?: AbortSignal;
195
+ }
196
+ /**
197
+ * Run request that asks the model to produce a JSON value conforming to the
198
+ * given JSON Schema. The returned `RunResult.output` is `unknown` — callers
199
+ * are responsible for validating the shape.
200
+ */
201
+ interface JsonSchemaRunRequest extends RunRequest {
202
+ /** A JSON Schema (Draft 7+) describing the expected output structure. */
203
+ schema: JsonSchema;
204
+ }
205
+ /**
206
+ * Run request that asks the model to produce a value matching the given Zod
207
+ * schema. The returned `RunResult.output` is typed as `TOutput` inferred from
208
+ * the Zod schema.
209
+ */
210
+ interface ZodRunRequest<TOutput = unknown> extends RunRequest {
211
+ /** Zod schema used both to instruct the model and to parse/validate the response. */
212
+ schema: ZodType<TOutput>;
213
+ }
214
+ /** Union of structured-output run requests (JSON Schema or Zod). */
215
+ type StructuredRunRequest<TOutput = unknown> = JsonSchemaRunRequest | ZodRunRequest<TOutput>;
216
+ /** Any run request — text-only or structured-output. */
217
+ type AnyRunRequest = RunRequest | StructuredRunRequest;
218
+ /** Wall-clock timing for the run as observed locally by this SDK. */
219
+ interface RunTiming {
220
+ /** Local timestamp when the run was started. */
221
+ startedAt: Date;
222
+ /** Local timestamp when the run reached a terminal state. */
223
+ endedAt: Date;
224
+ /** `endedAt - startedAt`, in milliseconds. */
225
+ durationMs: number;
226
+ }
227
+ /**
228
+ * Subprocess execution metadata, populated for CLI adapters only.
229
+ *
230
+ * Useful when debugging a failed run — `stderr` carries the captured error
231
+ * output even when the model itself produced no message.
232
+ */
233
+ interface RunProcessInfo {
234
+ /** Process exit code; `null` if killed by signal. */
235
+ exitCode: number | null;
236
+ /** Signal that terminated the process; `null` if it exited normally. */
237
+ signal: ProcessSignal | null;
238
+ /** Captured stderr text. May be empty. */
239
+ stderr: string;
240
+ }
241
+ /** Common fields shared by all run results regardless of terminal status. */
242
+ interface RunResultBase {
243
+ /** Adapter that produced the result. */
244
+ type: AgentType;
245
+ /** Stable, unique identifier for the run. */
246
+ runId: string;
247
+ /** Adapter session/thread ID, when one exists. Useful for resuming with `sessionId`. */
248
+ sessionId?: string;
249
+ /** Final assistant text. For structured runs this is the raw model output before parsing. */
250
+ text: string;
251
+ /** Ordered list of every event emitted during the run. */
252
+ events: readonly AgentEvent[];
253
+ /** Provider-reported stats, when available. */
254
+ stats?: RunStats;
255
+ /** Local timing measured by this SDK. */
256
+ timing: RunTiming;
257
+ /** Subprocess details (CLI adapters only). */
258
+ process?: RunProcessInfo;
259
+ }
260
+ /** A run that was stopped before completion. `cancelReason` indicates how. */
261
+ interface CancelledRunResult extends RunResultBase {
262
+ status: "cancelled";
263
+ output?: undefined;
264
+ /** Always populated with `kind: "abort"` and a brief explanation. */
265
+ error: RunError;
266
+ /** What triggered the cancellation. */
267
+ cancelReason: StopReason;
268
+ }
269
+ /** A run that failed due to a process, parse, or provider error. */
270
+ interface FailedRunResult extends RunResultBase {
271
+ status: "failed";
272
+ output?: undefined;
273
+ /** Always populated; `error.kind` distinguishes the failure mode. */
274
+ error: RunError;
275
+ cancelReason?: undefined;
276
+ }
277
+ /**
278
+ * A run that completed successfully.
279
+ *
280
+ * When the request included a `schema`, `TOutput` carries the parsed value
281
+ * type and `output` is the validated structured result. Otherwise `output`
282
+ * is absent.
283
+ */
284
+ type CompletedRunResult<TOutput = never> = RunResultBase & ([TOutput] extends [never] ? {} : {
285
+ output: TOutput;
286
+ }) & {
287
+ status: "completed";
288
+ error?: undefined;
289
+ cancelReason?: undefined;
290
+ };
291
+ /**
292
+ * Discriminated union of all possible run outcomes.
293
+ *
294
+ * Narrow with `result.status` before reading `output`, `error`, or
295
+ * `cancelReason`:
296
+ *
297
+ * ```ts
298
+ * if (result.status === "completed") {
299
+ * console.log(result.text);
300
+ * } else {
301
+ * console.error(result.error.message);
302
+ * }
303
+ * ```
304
+ */
305
+ type RunResult<TOutput = never> = CancelledRunResult | CompletedRunResult<TOutput> | FailedRunResult;
306
+ /** Any run result — structured or unstructured. Use when the call-site doesn't know. */
307
+ type AnyRunResult = RunResult | RunResult<unknown>;
308
+ /** Any completed (success) run result — structured or unstructured. */
309
+ type AnyCompletedRunResult = CompletedRunResult | CompletedRunResult<unknown>;
310
+ /**
311
+ * Thrown by `agent.runOrThrow(...)` when a run does not complete successfully.
312
+ *
313
+ * `result` is the same structured run result you would have received from
314
+ * `agent.run(...)` — useful when you want exception-based flow but still need
315
+ * access to events, timing, and the typed error.
316
+ */
317
+ declare class AgentRunError<TOutput = never> extends Error {
318
+ readonly result: RunResult<TOutput> & {
319
+ status: "cancelled" | "failed";
320
+ };
321
+ constructor(result: RunResult<TOutput> & {
322
+ status: "cancelled" | "failed";
323
+ });
324
+ }
325
+ /**
326
+ * Thrown synchronously by `createAgent(...)` or `agent.run(...)` when the
327
+ * call's arguments are invalid (missing required option, unsupported value,
328
+ * missing peer dependency, etc.) — i.e. before any provider call is made.
329
+ */
330
+ declare class AgentValidationError extends Error {
331
+ constructor(message: string);
332
+ }
333
+ /** Callback registered via `agent.onEvent(...)`; invoked synchronously for every emitted event. */
334
+ type AgentEventHandler = (event: AgentEvent) => void;
335
+ /**
336
+ * Lifetime counters for an agent instance.
337
+ *
338
+ * These accumulate across every run on the same agent. Reset by calling
339
+ * `agent.reset()` — disposing the agent does not preserve them.
340
+ */
341
+ interface AgentMetrics {
342
+ /** Number of `agent.run(...)` calls completed (any terminal status). */
343
+ runCount: number;
344
+ /** Total assistant/user `message` events observed across all runs. */
345
+ messagesReceived: number;
346
+ /** Total tool calls dispatched across all runs. */
347
+ toolCalls: number;
348
+ /** Total runs that ended with `status: "failed"`. */
349
+ errors: number;
350
+ /** Timestamp when the agent was created. */
351
+ startedAt: Date;
352
+ /** Timestamp of the most recent emitted event (not updated on plain method calls like `reset`/`dispose`). */
353
+ lastActivityAt: Date;
354
+ }
355
+ type EffectiveKeys<T> = keyof { [K in keyof T as Required<T>[K] extends never ? never : K]: unknown };
356
+ /**
357
+ * Compile-time assertion that an adapter's `*RunOptions` shape does not
358
+ * collide with the keys of {@link RunRequest}. Resolves to `T` when disjoint,
359
+ * `never` when there is a collision (which surfaces as a TypeScript error
360
+ * when the adapter types are constructed).
361
+ */
362
+ type EnsureDisjoint<T extends object> = EffectiveKeys<T> & keyof RunRequest extends never ? T : never;
363
+ /**
364
+ * "Either container or sandbox, not both" — used by CLI adapter options.
365
+ *
366
+ * Pass a `container` from `createContainer(...)` to run the agent inside a
367
+ * container, or a `sandbox` from `createSandbox(...)` to wrap its subprocess
368
+ * with a sandbox binary. Passing both at the same time is a type error; the
369
+ * runtime also rejects it with {@link AgentValidationError}.
370
+ */
371
+ type ExclusiveExecutionTargetOptions<TContainer, TSandbox> = {
372
+ container?: never;
373
+ sandbox?: TSandbox;
374
+ } | {
375
+ container?: TContainer;
376
+ sandbox?: never;
377
+ };
378
+ /**
379
+ * Uniform interface implemented by every adapter instance returned from
380
+ * `createAgent(...)`. The `TRunOptions` parameter carries the adapter's
381
+ * per-run option type so that `run()` accepts them with full type-checking.
382
+ */
383
+ interface BaseAgent<TRunOptions extends object = {}> {
384
+ /** Adapter identifier — same string passed to `createAgent`. */
385
+ readonly type: AgentType;
386
+ /** Feature capabilities of this adapter (mcp support, image input, structured output, etc.). */
387
+ readonly capabilities: Readonly<AgentCapabilities>;
388
+ /** Current session/thread ID, if a run has started or `sessionId` was supplied. */
389
+ readonly sessionId?: string;
390
+ /** `true` between the start of a `run(...)` call and its terminal event. */
391
+ readonly isRunning: boolean;
392
+ /** Live lifetime metrics for this instance. */
393
+ readonly metrics: Readonly<AgentMetrics>;
394
+ /**
395
+ * Execute a single prompt and return a structured result.
396
+ *
397
+ * Overloaded so `result.output` narrows from the request's schema:
398
+ * - `ZodRunRequest<T>` → `RunResult<T>` with parsed/validated `output`.
399
+ * - `JsonSchemaRunRequest` → `RunResult<unknown>`; caller validates.
400
+ * - plain `RunRequest` → `RunResult` without `output`.
401
+ *
402
+ * Runtime failures from the agent (process exit, parse failure, provider
403
+ * error) are reported via `result.status` and `result.error` — those do
404
+ * **not** throw. Argument-validation problems (empty input, unsupported
405
+ * structured output or image input, invalid `timeoutMs`, calling `run`
406
+ * while a previous run is still in flight) throw {@link AgentValidationError}.
407
+ */
408
+ run<TOutput>(request: TRunOptions & ZodRunRequest<TOutput>): Promise<RunResult<TOutput>>;
409
+ run(request: JsonSchemaRunRequest & TRunOptions): Promise<RunResult<unknown>>;
410
+ run(request: RunRequest & TRunOptions): Promise<RunResult>;
411
+ /**
412
+ * Like {@link run} but throws {@link AgentRunError} when the run does not
413
+ * complete successfully. Convenient for callers that want exception-based
414
+ * flow; the thrown error carries the full `RunResult` on `.result`.
415
+ */
416
+ runOrThrow<TOutput>(request: TRunOptions & ZodRunRequest<TOutput>): Promise<CompletedRunResult<TOutput>>;
417
+ runOrThrow(request: JsonSchemaRunRequest & TRunOptions): Promise<CompletedRunResult<unknown>>;
418
+ runOrThrow(request: RunRequest & TRunOptions): Promise<CompletedRunResult>;
419
+ /**
420
+ * Request cancellation of the currently in-flight run.
421
+ *
422
+ * Resolves with the cancelled `RunResult` (status `"cancelled"`) once the
423
+ * adapter acknowledges the stop. Resolves to `undefined` if no run is in
424
+ * flight. Safe to call multiple times.
425
+ */
426
+ stop: () => Promise<AnyRunResult | undefined>;
427
+ /**
428
+ * Reset adapter-internal state: clear the session, drop tool-call records,
429
+ * reset metrics. The next `run(...)` starts a fresh session/thread.
430
+ *
431
+ * Does not dispose the underlying SDK or subprocess — use {@link dispose}
432
+ * for that.
433
+ */
434
+ reset: () => void;
435
+ /**
436
+ * Wait for the currently in-flight run to reach a terminal state and
437
+ * resolve with its result. Resolves immediately if no run is in flight
438
+ * (with a synthetic completed result).
439
+ */
440
+ wait: () => Promise<AnyRunResult>;
441
+ /**
442
+ * Dispose the underlying SDK handle or subprocess. After dispose, the
443
+ * agent must not be used again. Idempotent.
444
+ */
445
+ dispose: () => Promise<void>;
446
+ /** Implements `await using` syntax — calls {@link dispose}. */
447
+ [Symbol.asyncDispose]: () => Promise<void>;
448
+ /**
449
+ * Register an event listener. Returns an unsubscribe function; calling it
450
+ * removes only this listener. Multiple listeners may be registered and are
451
+ * invoked in registration order, synchronously, for every emitted event.
452
+ *
453
+ * @example
454
+ * ```ts
455
+ * const off = agent.onEvent((event) => {
456
+ * if (event.type === "tool-call") console.log(event.toolName);
457
+ * });
458
+ * // later
459
+ * off();
460
+ * ```
461
+ */
462
+ onEvent: (handler: AgentEventHandler) => () => void;
463
+ /**
464
+ * Register the (single) permission handler. The handler returns the
465
+ * decision directly — no separate `respond` call is needed. Calling again
466
+ * replaces any previous handler. Returns an unsubscribe function.
467
+ *
468
+ * Only effective when `capabilities.permissionRequests === true`. Adapters
469
+ * without permission support may ignore the handler or reject the run when
470
+ * a registered handler implies interactive permission behavior they don't
471
+ * support.
472
+ */
473
+ onPermissionRequest: (handler: PermissionHandler) => () => void;
474
+ }
475
+ //#endregion
476
+ export { ProcessSpawner as A, RunTiming as C, PermissionDecision as D, ZodRunRequest as E, PermissionHandler as O, RunStatus as S, StructuredRunRequest as T, RunProcessInfo as _, AgentValidationError as a, RunResultBase as b, AnyRunResult as c, CompletedRunResult as d, EnsureDisjoint as f, RunError as g, JsonSchemaRunRequest as h, AgentType as i, PermissionRequest 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, RunRequest as v, StopReason as w, RunStats as x, RunResult as y };
@@ -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));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: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.10.0",
3
+ "version": "0.12.0",
4
4
  "type": "module",
5
5
  "types": "./dist/index.d.mts",
6
6
  "exports": {
@@ -20,9 +20,9 @@
20
20
  "types": "./dist/sandbox/index.d.mts",
21
21
  "default": "./dist/sandbox/index.mjs"
22
22
  },
23
- "./adapters/claude-cli-pty": {
24
- "types": "./dist/adapters/claude-cli-pty/index.d.mts",
25
- "default": "./dist/adapters/claude-cli-pty/index.mjs"
23
+ "./adapters/claude-code-cli-pty": {
24
+ "types": "./dist/adapters/claude-code-cli-pty/index.d.mts",
25
+ "default": "./dist/adapters/claude-code-cli-pty/index.mjs"
26
26
  },
27
27
  "./adapters/claude-code-cli": {
28
28
  "types": "./dist/adapters/claude-code-cli/index.d.mts",
@@ -74,35 +74,35 @@
74
74
  "test:agent": "bun test ./tests",
75
75
  "test:package": "bun run test:package:runtime",
76
76
  "test:package:runtime": "bun test ./tests/package-exports.smoke.ts",
77
- "test:agent:claude-cli-pty": "CODE_WORKFLOW_TEST_AGENTS=claude-cli-pty bun run test:agent",
78
- "test:agent:claude-code-cli": "CODE_WORKFLOW_TEST_AGENTS=claude-code-cli bun run test:agent",
79
- "test:agent:claude-code-sdk": "CODE_WORKFLOW_TEST_AGENTS=claude-code-sdk bun run test:agent",
80
- "test:agent:codex-cli": "CODE_WORKFLOW_TEST_AGENTS=codex-cli bun run test:agent",
81
- "test:agent:codex-sdk": "CODE_WORKFLOW_TEST_AGENTS=codex-sdk bun run test:agent",
82
- "test:agent:cursor-cli": "CODE_WORKFLOW_TEST_AGENTS=cursor-cli bun run test:agent",
83
- "test:agent:cursor-sdk": "CODE_WORKFLOW_TEST_AGENTS=cursor-sdk bun run test:agent",
84
- "test:agent:gemini-cli": "CODE_WORKFLOW_TEST_AGENTS=gemini-cli bun run test:agent",
85
- "test:agent:opencode-cli": "CODE_WORKFLOW_TEST_AGENTS=opencode-cli bun run test:agent",
86
- "test:agent:pi-cli": "CODE_WORKFLOW_TEST_AGENTS=pi-cli bun run test:agent",
77
+ "test:agent:claude-code-cli-pty": "ADAPTERS=claude-code-cli-pty bun run test:agent",
78
+ "test:agent:claude-code-cli": "ADAPTERS=claude-code-cli bun run test:agent",
79
+ "test:agent:claude-code-sdk": "ADAPTERS=claude-code-sdk bun run test:agent",
80
+ "test:agent:codex-cli": "ADAPTERS=codex-cli bun run test:agent",
81
+ "test:agent:codex-sdk": "ADAPTERS=codex-sdk bun run test:agent",
82
+ "test:agent:cursor-cli": "ADAPTERS=cursor-cli bun run test:agent",
83
+ "test:agent:cursor-sdk": "ADAPTERS=cursor-sdk bun run test:agent",
84
+ "test:agent:gemini-cli": "ADAPTERS=gemini-cli bun run test:agent",
85
+ "test:agent:opencode-cli": "ADAPTERS=opencode-cli bun run test:agent",
86
+ "test:agent:pi-cli": "ADAPTERS=pi-cli bun run test:agent",
87
87
  "knip": "knip",
88
88
  "tsc": "tsc --noEmit --pretty",
89
89
  "typecheck": "bun run tsc"
90
90
  },
91
91
  "devDependencies": {
92
- "@anthropic-ai/claude-agent-sdk": "^0.2.128",
93
- "@cursor/sdk": "^1.0.12",
94
- "@openai/codex-sdk": "^0.128.0",
95
- "@types/bun": "^1.3.13",
96
- "@types/node": "^25.6.0",
97
- "e2b": "^2.19.4",
98
- "knip": "^6.11.0",
92
+ "@anthropic-ai/claude-agent-sdk": "^0.3.170",
93
+ "@cursor/sdk": "^1.0.18",
94
+ "@openai/codex-sdk": "^0.139.0",
95
+ "@types/bun": "^1.3.14",
96
+ "@types/node": "^25.9.2",
97
+ "e2b": "^2.28.2",
98
+ "knip": "^6.16.1",
99
99
  "picoprint": "^2.0.0",
100
- "tsdown": "^0.21.10"
100
+ "tsdown": "^0.22.2"
101
101
  },
102
102
  "peerDependencies": {
103
- "@anthropic-ai/claude-agent-sdk": "^0.2.128",
103
+ "@anthropic-ai/claude-agent-sdk": "^0.3.170",
104
104
  "@cursor/sdk": "^1.0.12",
105
- "@openai/codex-sdk": "^0.128.0",
105
+ "@openai/codex-sdk": "^0.139.0",
106
106
  "e2b": "^2.19.4",
107
107
  "typescript": "^6.0.3"
108
108
  },
@@ -1,4 +0,0 @@
1
- import{t as e}from"./util-CGg8cK92.mjs";import{t}from"./env-DIXTVzTs.mjs";import{t as n}from"./spawner-BJesLc8I.mjs";import{a as r,i,n as a,t as o}from"./classify-error-BcWmNftw.mjs";import{dirname as s}from"node:path";import{createWriteStream as c,mkdirSync as l}from"node:fs";async function*u(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 d=t=>t.status===`rejected`?e(t.reason):void 0,f=(e,t)=>{if(e.stopReason)return;let n=d(t.processResult);if(n)return{kind:`spawn`,message:n};let r=d(t.stdoutResult);if(r)return{kind:`process`,message:r};let a=d(t.stderrResult);if(a)return{kind:`process`,message:a};if(!e.status&&!e.error){let t=e.processResult,n=e.stderrLines.join(`
3
- `);if(t&&t.exitCode!==null&&t.exitCode!==0)return{kind:`process`,message:n||`Process exited with code ${t.exitCode}.`};if(!i(e)&&e.stderrLines.length>0)return{kind:`process`,message:n}}},p=e=>{let t=o(e);return t.kind===`provider`?{kind:`process`,message:t.message}:t};var m=class extends a{spawner;defaults;executionTargetRef;autoStartExecutionTarget;autoStopExecutionTarget;executionTargetStopPromise;logStream;sigkillTimer;constructor(e){super({type:e.type,capabilities:e.capabilities,sessionId:e.defaults?.sessionId,onEvent:e.onEvent}),this.spawner=e.spawner??n,this.defaults=e.defaults??{},this.executionTargetRef=e.executionTarget,this.autoStartExecutionTarget=e.autoStartExecutionTarget??!0,this.autoStopExecutionTarget=e.autoStopExecutionTarget??!1,e.logPath&&this.initLogStream(e.logPath)}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,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,new Date);t.sessionId&&this.emitSessionStart(t),t.process=this.spawner.spawn(a,o,{cwd:t.normalizedRequest.cwd,env:i,stdio:[`pipe`,`pipe`,`pipe`]}),t.process.stdin?.end();let[s,c,l]=await Promise.allSettled([this.watchStdout(t),this.watchStderr(t),t.process.wait()]);l.status===`fulfilled`&&(t.processResult=l.value);let u=f(t,{stdoutResult:s,stderrResult:c,processResult:l});u&&(t.error=u)}catch(e){!t.stopReason&&!t.error&&(t.error=p(e))}return this.buildResult(t,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 u(t))this.appendLog(`stdout`,n),this.processLine(e,n)}async watchStderr(e){let t=e.process?.stderr;if(t)for await(let n of u(t))this.appendLog(`stderr`,n),e.stderrLines.push(n),this.emit(e,r(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,{runId:e.runId,requestedSessionId:e.requestedSessionId,sessionId:e.sessionId,schemaRequested:e.normalizedRequest.schema.kind!==`none`,toolCalls:e.toolCalls})}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(){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(t){this.autoStopExecutionTarget&&this.executionTargetRef&&this.executionTargetRef.status===`running`&&(this.executionTargetStopPromise=this.executionTargetRef.stop().catch(t=>{this.appendRawLog(`[auto-stop-error] ${e(t)}`)}),await this.executionTargetStopPromise)}appendRawLog(e){if(!this.logStream)return;let t=typeof e==`string`?e:JSON.stringify(e);this.logStream.write(`${t}\n`)}initLogStream(e){try{l(s(e),{recursive:!0}),this.logStream=c(e,{flags:`a`}),this.logStream.write(`\n--- ${new Date().toISOString()} ---\n`)}catch{this.logStream=void 0}}appendLog(e,t){if(!this.logStream||!t)return;let n=e===`stderr`?`STDERR`:`STDOUT`,r=new Date().toISOString();for(let e of t.split(`
4
- `))e&&this.logStream.write(`[${r}] ${n} ${e}\n`)}async ensureExecutionTarget(){this.executionTargetStopPromise&&=(await this.executionTargetStopPromise,void 0),this.autoStartExecutionTarget&&this.executionTargetRef&&this.executionTargetRef.status!==`running`&&await this.executionTargetRef.start()}};export{m as t};
@@ -1,3 +0,0 @@
1
- import { c as ClaudeRateLimitEvent, d as ClaudeUserEvent, l as ClaudeResultEvent, o as ClaudeAssistantEvent, s as ClaudeEvent, u as ClaudeSystemEvent } from "../../index-J7V9dJTb.mjs";
2
- import { a as ClaudeCliPtyPermissionMode, i as ClaudeCliPtyModule, n as ClaudeCliPtyAgent, o as ClaudeCliPtyProcess, r as ClaudeCliPtyAgentOptions, s as ClaudeCliPtyRunOptions, t as createClaudeCliPtyAgent } from "../../index-C7J_hmQs.mjs";
3
- export { ClaudeAssistantEvent, ClaudeCliPtyAgent, ClaudeCliPtyAgentOptions, ClaudeCliPtyModule, ClaudeCliPtyPermissionMode, ClaudeCliPtyProcess, ClaudeCliPtyRunOptions, ClaudeEvent, ClaudeRateLimitEvent, ClaudeResultEvent, ClaudeSystemEvent, ClaudeUserEvent, createClaudeCliPtyAgent };
@@ -1,7 +0,0 @@
1
- import{n as e}from"../../types-CwvWHEpy.mjs";import{a as t,n,r,t as i}from"../../util-CGg8cK92.mjs";import{t as a}from"../../env-DIXTVzTs.mjs";import{t as o}from"../../spawner-BJesLc8I.mjs";import{a as s,c,n as l,s as u,t as d}from"../../classify-error-BcWmNftw.mjs";import{t as f}from"../../execution-target-CGTSqVEP.mjs";import{n as p,r as m,t as h}from"../../parser-BBJPNGZ2.mjs";import{join as g,posix as _}from"node:path";import{appendFileSync as v,existsSync as y,mkdtempSync as b,readFileSync as x,writeFileSync as S}from"node:fs";import{tmpdir as C}from"node:os";import{rm as w}from"node:fs/promises";const T={structuredOutput:!0,sessionResume:!0,imageInput:!1,mcp:!0,eventStreaming:!0,sessionFork:!0,permissionRequests:!0},E=new Set(`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(`.`)),D=e=>new Promise(t=>setTimeout(t,e)),O=e=>{let{$schema:t,...n}={...e};return n},k=e=>`'${e.replace(/'/g,`'\\''`)}'`,A=(e,t)=>[e,...t].map(k).join(` `),j=e=>e.replace(/\\/g,`\\\\`).replace(/,/g,`\\,`),M=e=>e.replace(/\u001b\[(\d*)C/g,(e,t)=>` `.repeat(Number(t||`1`))).replace(/\u001b][^\u0007]*(?:\u0007|\u001b\\)/g,``).replace(/\u001b\[[0-?]*[ -/]*[@-~]/g,``).replace(/\u001b[78=>]/g,``).replace(/\r/g,`
2
- `),N=e=>{let t=M(e),n=t.lastIndexOf(`Do you want to proceed?`);if(n===-1)return;let r=t.slice(0,n),i=r.lastIndexOf(`Bash command`);if(i===-1)return;let a=r.slice(i+12).split(/\n/).map(e=>e.trim().replace(/^\$\s*/,``)).find(e=>e.length>0);if(a)return{key:`Bash:${a}`,toolName:`Bash`,input:{command:a}}},P=e=>{if(!(!e||!E.has(e)))return e},F=(e=o)=>({spawn:(t,n,r)=>{let a=new Set,o=new Set,s=r.initialInputPath&&r.initialInputBootstrapPath?[r.initialInputBootstrapPath,r.initialInputPath,t,...n]:n,c=`EXEC:${j(A(r.initialInputPath&&r.initialInputBootstrapPath?`/bin/sh`:t,s))},pty,setsid,ctty`,l=e.spawn(`socat`,[`-`,c],{cwd:r.cwd,env:r.env,stdio:[`pipe`,`pipe`,`pipe`]}),u=e=>{for(let t of o)t(e)},d=e=>{for(let t of a)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(i(e))}),f(l.stderr).catch(e=>{u(i(e))}),l.wait().then(e=>{d({exitCode:e.exitCode??0,signal:e.signal??void 0})}).catch(e=>{u(i(e)),d({exitCode:127})}),{write:e=>{l.stdin?.write?.(e)},kill:e=>{l.kill(P(e))},onData:e=>(o.add(e),{dispose:()=>o.delete(e)}),onExit:e=>(a.add(e),{dispose:()=>a.delete(e)})}}}),I=e=>{let t={hooks:{Stop:[{hooks:[{type:`command`,command:`sh -c ${k(`cat > ${k(e)}`)}`}]}]}};return JSON.stringify(t)},L=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}:{}},R=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(`
3
- `):void 0},z=(e,t)=>{let n=e[t];return typeof n==`string`?n:void 0},B=e=>z(e,`session_id`)??z(e,`sessionId`),V=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},H=e=>{if(e.type!==`user`||!n(e.message))return;let t=e.message.content;if(typeof t==`string`)return V(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(`
4
- `):void 0},U=e=>{if(e.type!==`attachment`||!n(e.attachment))return;let t=e.attachment;return`[${[z(t,`type`)??`attachment`,z(t,`hookEvent`)??z(t,`hook_event`),z(t,`hookName`)??z(t,`hook_name`)].filter(e=>e!==void 0).join(` `)}]`},W=(e,t)=>`${e} Return only valid JSON matching this JSON Schema. Do not wrap the JSON in Markdown. ${JSON.stringify(O(t))}`,G=e=>e.replace(/[/:\\]/g,`-`),K=e=>{if(!(e.type!==`assistant`||!n(e.message))&&z(e.message,`stop_reason`)!==`tool_use`)return R(e.message)},q=(e,t)=>{let r=e.split(/\r?\n/).filter(e=>e.trim().length>0),i=!1,a=!1,o=t.replace(/\r?\n$/,``);for(let e of r){let t;try{t=JSON.parse(e)}catch{continue}if(!n(t))continue;let r=H(t);if(r!==void 0){i=r.replace(/\r?\n$/,``)===o,a=!1;continue}i&&K(t)!==void 0&&(a=!0)}return a},J=e=>{if(!n(e)||`session_id`in e)return e;let t=B(e);if(!t)return e;if(e.type===`user`&&n(e.message)&&typeof e.message.content==`string`){let n=V(e.message.content);if(n)return{...e,session_id:t,message:{...e.message,content:n}}}return{...e,session_id:t}};var Y=class o extends l{type=`claude-cli-pty`;creationOptions;runDefaults;forkOnNextRun;activePty;executionTargetRef;tempDirs=new Set;logPath;permissionPromptBuffer=``;permissionPromptInFlight=!1;lastPermissionPrompt;permissionPromptCount=0;constructor(e={}){super({type:`claude-cli-pty`,capabilities:T,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 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;try{if(n.abortedBeforeStart)return this.buildResult(e,new Date);await this.ensureExecutionTarget(),this.resetPermissionPromptState();let i={...t,...e.normalizedRequest};r=await this.createRunFiles(e);let a=this.creationOptions.pty??F(this.creationOptions.spawner),o=this.buildPrompt(i);await r.writeText(r.bootstrapPath,`prompt_path=$1
5
- shift
6
- cat "$prompt_path" | exec "$@"
7
- `),await r.writeText(r.promptPath,`${o}\n`);let{command:s,args:c}=await this.buildCommand(i,e,r),l=this.buildEnv(),u=this.spawnPty(e,a,s,c,l,r.bootstrapPath,r.promptPath);e.sessionId&&this.emitSessionStart(e),await this.waitForReadiness(i,e);let d=await this.waitForStopSentinel(i,e,r,u,o);return d&&await this.applyStopSentinel(e,d,r),e.stopReason||this.activePty?.write(`/exit\r`),e.processResult=await this.waitForExit(u),!e.stopReason&&!e.error&&!e.status&&(e.status=`completed`),this.buildResult(e,new Date)}catch(t){return this.activePty?.kill(),!e.stopReason&&!e.error&&(e.error=d(t)),this.buildResult(e,new Date)}finally{n.cleanup(),this.activePty=void 0,await r?.cleanup()}}onStopRequested(e){this.activePty?.kill()}async onDispose(){for(let e of this.tempDirs)await w(e,{recursive:!0,force:!0}).catch(()=>{});this.tempDirs.clear()}onHandlerError(e){this.appendRawLog(`[handler-error] ${i(e)}`)}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=_.join(`/tmp`,`coding-agents-claude-pty-${crypto.randomUUID()}`),n=_.join(e,`prompt-bootstrap.sh`),i=_.join(e,`prompt.txt`),a=_.join(e,`settings.json`),o=_.join(e,`stop-sentinel.json`),s=G(r),c=[this.creationOptions.env?.HOME,`/root`,`/home/node`,`/home/bun`].filter(e=>typeof e==`string`&&e.length>0);return await t.mkdir(e),await t.writeFile(a,I(o)),{runDir:e,bootstrapPath:n,promptPath:i,settingsPath:a,sentinelPath:o,exists:e=>t.fileExists(e),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(c)).map(t=>_.join(t,`.claude`,`projects`,s,`${e}.jsonl`)),cleanup:async()=>{await t.exec(`rm`,[`-rf`,e]).catch(()=>void 0)}}}let i=b(g(this.creationOptions.sandbox?r:C(),`.coding-agents-claude-pty-`)),a=g(i,`prompt-bootstrap.sh`),o=g(i,`prompt.txt`),s=g(i,`settings.json`),c=g(i,`stop-sentinel.json`),l=[this.creationOptions.env?.HOME,this.creationOptions.sandbox?.config.setEnv?.HOME,process.env.HOME].filter(e=>typeof e==`string`&&e.length>0),u=Array.from(new Set(l)).map(e=>g(e,`.claude`,`projects`,G(r)));return this.tempDirs.add(i),S(s,I(c),{encoding:`utf8`,mode:384}),{runDir:i,bootstrapPath:a,promptPath:o,settingsPath:s,sentinelPath:c,exists:async e=>y(e),readText:async e=>y(e)?x(e,`utf8`):void 0,writeText:async(e,t)=>{S(e,t,{encoding:`utf8`,mode:384})},transcriptPathsForSession:e=>u.map(t=>g(t,`${e}.jsonl`)),cleanup:async()=>{this.tempDirs.delete(i),await w(i,{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=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(`,`)),l&&l.length>0&&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?_.join(r.runDir,`mcp.json`):g(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.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}}buildPrompt(e){let t=u(e.input);return e.schema.kind===`none`?t:W(t,e.schema.jsonSchema)}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),delete e.CLAUDECODE,e}spawnPty(e,t,n,r,i,a,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`?P(t.signal)??null:null})})});return 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(t=>{this.appendRawLog(`[pty] ${t}`),this.handlePermissionPromptData(e,t)}),c}resetPermissionPromptState(){this.permissionPromptBuffer=``,this.permissionPromptInFlight=!1,this.lastPermissionPrompt=void 0,this.permissionPromptCount=0}handlePermissionPromptData(e,t){if(!this.getPermissionHandler()||!this.activePty)return;this.permissionPromptBuffer=`${this.permissionPromptBuffer}${t}`.slice(-12e3);let n=N(this.permissionPromptBuffer);if(!n||this.permissionPromptInFlight)return;let r=Date.now();this.lastPermissionPrompt?.key===n.key&&r-this.lastPermissionPrompt.at<2e3||(this.permissionPromptInFlight=!0,this.lastPermissionPrompt={key:n.key,at:r},this.permissionPromptCount+=1,this.respondToPermissionPrompt(e,n).finally(()=>{this.permissionPromptBuffer=``,this.permissionPromptInFlight=!1}))}async respondToPermissionPrompt(e,t){let n=this.getPermissionHandler();if(!(!n||!this.activePty))try{let r=await n({toolName:t.toolName,input:t.input,toolUseId:`pty-permission-${this.permissionPromptCount}`,signal:e.normalizedRequest.signal??new AbortController().signal}),i=r.decision===`allow`&&r.updatedInput===void 0;this.activePty.write(i?`\r`:`3\r`)}catch(e){this.onHandlerError(e),this.activePty.write(`3\r`)}}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,s=()=>{i||(i=!0,a&&clearTimeout(a),o&&clearTimeout(o),c.dispose(),e())},c=r.onData(()=>{a&&clearTimeout(a),a=setTimeout(s,Math.min(250,n)),a.unref?.()});o=setTimeout(s,n),o.unref?.(),t.stopReason&&s()})}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});;){let e=await n.exists(n.sentinelPath)?await n.readText(n.sentinelPath):void 0,r=e===void 0?void 0:L(e);if(r?.transcriptPath){let e=await n.readText(r.transcriptPath);if(e!==void 0&&q(e,i))return r}let c=await this.findCompletedTranscriptPath(t,n,i);if(c)return this.appendRawLog(`[transcript] completed turn from ${c}`),{...r,transcriptPath:c};if(t.stopReason)return;if(s)throw 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 D(50)}}async findCompletedTranscriptPath(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&&q(r,n))return e}}async applyStopSentinel(e,t,n){if(t.sessionId&&(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)}if(e.assistantTexts.length===0){let n=R(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&&(e.error=void 0,e.status=void 0)}catch(t){e.error=d(t),e.status=`failed`}e.assistantTexts.length===0&&!e.output.text&&!e.error&&(e.error={kind:`parse`,message:`Claude Stop hook completed without assistant output.`},e.status=`failed`)}applyTranscript(e,t){let n=t.split(/\r?\n/).filter(e=>e.trim().length>0);for(let t of n){let n;try{n=JSON.parse(t)}catch(t){e.error=d(t),e.status=`failed`;return}if(this.applyTranscriptNativeEvent(e,n))continue;let r=h(J(n));if(!r)continue;let i=p(r)??e.sessionId,a=m(r,{runId:e.runId,requestedSessionId:e.requestedSessionId,sessionId:i,schemaRequested:e.normalizedRequest.schema.kind!==`none`,toolCalls:e.toolCalls});i&&!a.sessionId&&(a.sessionId=i),this.applyBatch(e,a)}}applyTranscriptNativeEvent(e,t){if(!n(t))return!1;let r=B(t)??e.sessionId,i=H(t);if(i!==void 0)return this.emitTextMessage(e,`user`,i,r),!0;let a=U(t);return a===void 0?!1:(this.emitTextMessage(e,`system`,a,r),!0)}emitTextMessage(e,t,n,r=e.sessionId){r&&!e.sessionId&&(e.sessionId=r,this.setSessionId(r)),e.sessionId&&this.emitSessionStart(e),this.emit(e,s(e.runId,`message`,{sessionId:e.sessionId,model:null,role:t,content:[c(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{v(this.logPath,`${e}\n`,`utf8`)}catch{}}};const X=e=>new Y(f(e).options??e);export{X as createClaudeCliPtyAgent};
@@ -1 +0,0 @@
1
- import{t as e}from"./util-CGg8cK92.mjs";import{n as t,o as n,r,s as i,t as a}from"./errors-CeKI_bYK.mjs";import{t as o}from"./shell-Dewbmt9R.mjs";import{n as s}from"./diff-DWM1ciiV.mjs";import{basename as c,dirname as l,join as u,posix as d}from"node:path";import{mkdir as f,readFile as p,readdir as m,stat as h,writeFile as g}from"node:fs/promises";import{CommandExitError as _,FileType as v,Sandbox as y}from"e2b";const b=(e,t)=>[e,...t].map(o).join(` `),x=e=>e.user,S=(e,t)=>{let n={...e.env,...t};return Object.keys(n).length>0?n:void 0},C=(e,t)=>t??e.workdir,w=new TextEncoder,T=e=>e instanceof Error?e:Error(String(e)),E=e=>typeof e==`string`?e:`SIGKILL`,D=(e,t)=>{let n=e?.stdio?.[t];return n===`ignore`||n===`inherit`||n===`pipe`?n:n===void 0?`pipe`:`ignore`},O=()=>{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 T(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(w.encode(t)),i())},end(){n||r||(n=!0,i())},fail(e){n||r||(r=e,i())}}},k=(e,t)=>({spawn:(n,r,i={})=>{let a=D(i,0),o=D(i,1),s=D(i,2),c=o===`pipe`?O():void 0,l=s===`pipe`?O():void 0,u=null,d={background:!0,stdin:a===`pipe`,cwd:C(t,i.cwd),envs:S(t,i.env),user:x(t),requestTimeoutMs:t.requestTimeoutMs,onStdout:e=>{if(o===`inherit`){process.stdout.write(e);return}c?.push(e)},onStderr:e=>{if(s===`inherit`){process.stderr.write(e);return}l?.push(e)}},f=e.commands.run(b(n,r),d);return f.catch(e=>{c?.fail(e),l?.fail(e)}),{stdout:c?.iterable??null,stderr:l?.iterable??null,stdin:a===`pipe`?{write:n=>{f.then(r=>{e.commands.sendStdin(r.pid,n,{requestTimeoutMs:t.requestTimeoutMs})}).catch(()=>{})},end:()=>{f.then(n=>{e.commands.closeStdin(n.pid,{requestTimeoutMs:t.requestTimeoutMs})}).catch(()=>{})}}:null,kill:e=>{u=E(e),f.then(e=>e.kill()).catch(()=>{})},wait:async()=>{try{let e=await(await f).wait();return c?.end(),l?.end(),u?{exitCode:null,signal:u}:{exitCode:e.exitCode,signal:null}}catch(e){if(c?.end(),l?.end(),e instanceof _)return u?{exitCode:null,signal:u}:{exitCode:e.exitCode,signal:null};throw e}}}}}),A=e=>({apiKey:e.apiKey,accessToken:e.accessToken,domain:e.domain,requestTimeoutMs:e.requestTimeoutMs,headers:e.headers}),j=e=>`sandboxId`in e&&typeof e.sandboxId==`string`,M=e=>{let t=A(e);return j(e)?t:{...t,envs:e.env,timeoutMs:e.timeoutMs,metadata:e.metadata,secure:e.secure,allowInternetAccess:e.allowInternetAccess,network:e.network,lifecycle:e.lifecycle}},N=async(e,t)=>{await e.files.makeDir(t.workdir,{user:x(t)})},P=e=>e instanceof Error&&e.name===`AbortError`,F=e=>Uint8Array.from(e).buffer,I=e=>{let t=e.endsWith(`/`)&&e!==`/`?e.slice(0,-1):e;return d.basename(t)},L=async e=>{try{return await h(e)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}},R=async(e,t,n)=>{if(await e.files.exists(t,{user:n}))return e.files.getInfo(t,{user:n})},z=async(e,t,n,r)=>(await R(e,n,r))?.type===v.DIR?d.join(n,c(t)):n,B=async(e,t)=>(await L(t))?.isDirectory()?u(t,I(e)):t,V=async(e,t,n,r)=>{let i=await h(t);if(i.isDirectory()){await e.files.makeDir(n,{user:r});let i=await m(t);await Promise.all(i.map(i=>V(e,u(t,i),d.join(n,i),r)));return}if(!i.isFile())throw Error(`Unsupported local filesystem entry at ${t}.`);let a=await p(t);await e.files.write(n,F(a),{user:r})},H=async(e,t,n,r)=>{if((await e.files.getInfo(t,{user:r})).type===v.DIR){await f(n,{recursive:!0});let i=await e.files.list(t,{user:r});await Promise.all(i.map(t=>H(e,t.path,u(n,t.name),r)));return}let i=await e.files.read(t,{format:`bytes`,user:r});await f(l(n),{recursive:!0}),await g(n,i)},U=async e=>{if(j(e))return y.connect(e.sandboxId,A(e));let t=M(e);return e.template?y.create(e.template,t):y.create(t)},W=async(e,t)=>e.connect(A(t)),G=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||P(e))throw new DOMException(`The operation was aborted.`,`AbortError`);if(e instanceof _)return{exitCode:e.exitCode,stdout:e.stdout,stderr:e.stderr};throw e}finally{n?.removeEventListener(`abort`,i)}},K=async o=>{let c;try{c=await U(o),await N(c,o)}catch(t){throw new a(`E2B create failed: ${e(t)}`)}let l=o.name??c.sandboxId,d=`running`,p=k(c,o),m={},h=()=>{if(d===`disposed`)throw new r},g=()=>{if(h(),d!==`running`)throw new n},_=s({owner:m,workdir:o.workdir,materialize:async(e,n)=>{g();let r=x(o),i=await R(c,e,r);if(!i)throw new t(`Target path does not exist: ${e}`);if(i.type!==v.DIR)throw new t(`Target path is not a directory: ${e}`);await f(n,{recursive:!0});for(let t of await c.files.list(e,{user:r}))await H(c,t.path,u(n,t.name),r)}}),y={get type(){return`e2b`},get id(){return c.sandboxId},get name(){return l},get config(){return o},get status(){return d},get workdir(){return o.workdir},get spawner(){return p},async start(){if(h(),d!==`running`)try{c=await W(c,o),await N(c,o),p=k(c,o),d=`running`}catch(t){throw new i(`E2B start failed: ${e(t)}`)}},async stop(){h(),d===`running`&&(await c.pause({requestTimeoutMs:o.requestTimeoutMs}),d=`stopped`)},async dispose(){if(d!==`disposed`){try{await c.kill({requestTimeoutMs:o.requestTimeoutMs})}catch{}await _.disposeSnapshots().catch(()=>{}),d=`disposed`}},async exec(e,t,n={}){g();let r={background:!0,cwd:C(o,n.cwd),envs:S(o,n.env),user:x(o),timeoutMs:n.timeoutMs,requestTimeoutMs:o.requestTimeoutMs};return G(await c.commands.run(b(e,t),r),n)},async copyTo(e,t){g();let n=await z(c,e,t,x(o));await V(c,e,n,x(o))},async copyFrom(e,t){g();let n=await B(e,t);await H(c,e,n,x(o))},async writeFile(e,t){g(),await c.files.write(e,typeof t==`string`?t:F(t),{user:x(o)})},async readFile(e){return g(),c.files.read(e,{format:`text`,user:x(o)})},async fileExists(e){return g(),c.files.exists(e,{user:x(o)})},async mkdir(e){g(),await c.files.makeDir(e,{user:x(o)})},async execShell(e,t={}){return y.exec(`sh`,[`-c`,e],t)},async logs(){return``},async syncStatus(){return d},async snapshotWorkdir(e={}){return _.snapshotWorkdir(e)},async diffWorkdir(e){return _.diffWorkdir(e)},async releaseWorkdirSnapshot(e){return _.releaseWorkdirSnapshot(e)},getHost(e){return g(),c.getHost(e)},[Symbol.asyncDispose](){return y.dispose()}};return y};export{K as createE2BContainer};