coding-agents-sdk 0.14.0 → 0.15.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.
- package/README.md +8 -1
- package/dist/Agent-mSH_-Sf8.mjs +4 -0
- package/dist/SdkAgent-Dtsr8Ycr.mjs +1 -0
- package/dist/adapters/claude-code-cli/index.d.mts +1 -1
- package/dist/adapters/claude-code-cli/index.mjs +1 -1
- package/dist/adapters/claude-code-cli-pty/index.d.mts +2 -2
- package/dist/adapters/claude-code-cli-pty/index.mjs +5 -5
- package/dist/adapters/claude-code-sdk/index.d.mts +1 -1
- package/dist/adapters/claude-code-sdk/index.mjs +4 -4
- package/dist/adapters/codex-cli/index.d.mts +1 -1
- package/dist/adapters/codex-cli/index.mjs +2 -2
- package/dist/adapters/codex-sdk/index.d.mts +1 -1
- package/dist/adapters/codex-sdk/index.mjs +1 -1
- package/dist/adapters/cursor-cli/index.d.mts +1 -1
- package/dist/adapters/cursor-cli/index.mjs +1 -1
- package/dist/adapters/cursor-sdk/index.d.mts +1 -1
- package/dist/adapters/cursor-sdk/index.mjs +1 -1
- package/dist/adapters/gemini-cli/index.d.mts +1 -1
- package/dist/adapters/gemini-cli/index.mjs +1 -1
- package/dist/adapters/opencode-cli/index.d.mts +1 -1
- package/dist/adapters/opencode-cli/index.mjs +1 -1
- package/dist/adapters/pi-cli/index.d.mts +1 -1
- package/dist/adapters/pi-cli/index.mjs +1 -1
- package/dist/classify-error-DOqkMCcy.mjs +8 -0
- package/dist/container/index.d.mts +1 -1
- package/dist/container/index.mjs +1 -1
- package/dist/{container-oGViyTTR.mjs → container-B2i85Vkf.mjs} +1 -1
- package/dist/{container-mzyYSG7P.mjs → container-BwDinlQ1.mjs} +1 -1
- package/dist/{container-BYRWV-A_.mjs → container-CbvaYn8K.mjs} +1 -1
- package/dist/container-DfDs2Bmh.mjs +1 -0
- package/dist/{container-D5P0tyx7.mjs → container-Dk4QgU9G.mjs} +1 -1
- package/dist/diff-C60ujrU_.mjs +1 -0
- package/dist/{events-BF6ELG7c.d.mts → events-BxEB6zHt.d.mts} +6 -7
- package/dist/{index-68ih5kFM.d.mts → index-BXgvYZSv.d.mts} +10 -1
- package/dist/{index-CPnH6YAO.d.mts → index-BkIhoEPd.d.mts} +20 -12
- package/dist/{index-GW5zKifI.d.mts → index-C09YdI2A.d.mts} +26 -16
- package/dist/{index-DwlwQ9R0.d.mts → index-CGGPY1qE.d.mts} +2 -1
- package/dist/{index-ByyejuZo.d.mts → index-CT-rhJzK.d.mts} +2 -3
- package/dist/{index-CzvAiGC9.d.mts → index-D3yvIIre.d.mts} +22 -13
- package/dist/{index-CAWun0L4.d.mts → index-DGY0wFGC.d.mts} +41 -31
- package/dist/{index-DCbDnTQ_.d.mts → index-D_qqPXPO.d.mts} +20 -12
- package/dist/{index-CW1kBJ3d.d.mts → index-Dm9HCmWK.d.mts} +3 -2
- package/dist/{index-CGMqyNOd.d.mts → index-WaVqMCYN.d.mts} +2 -5
- package/dist/{index-62Ld65Q8.d.mts → index-fZiuDQFa.d.mts} +29 -16
- package/dist/{index-DzfIudMp.d.mts → index-gtpzhLCF.d.mts} +22 -13
- package/dist/index.d.mts +27 -26
- package/dist/index.mjs +1 -1
- package/dist/oci-BvdPJQRS.mjs +1 -0
- package/dist/parser-15-5gbtk.mjs +2 -0
- package/dist/sandbox/index.d.mts +1 -1
- package/dist/sandbox/index.mjs +1 -1
- package/dist/sandbox-CoV-gBuM.mjs +4 -0
- package/dist/schemas/index.d.mts +1 -1
- package/dist/session-markers-Dt7TWdKY.mjs +1 -0
- package/dist/{types-BQeZnkDv.d.mts → types-CeIQCAFV.d.mts} +23 -7
- package/dist/{util-DcPzh_0u.mjs → util-B4HTdOSc.mjs} +1 -1
- package/package.json +14 -13
- package/dist/Agent-YQZmTatB.mjs +0 -4
- package/dist/SdkAgent-Dv3I0OW2.mjs +0 -1
- package/dist/classify-error-UZrj89Yi.mjs +0 -8
- package/dist/container-CNM4U7vL.mjs +0 -1
- package/dist/diff-ByicTI7l.mjs +0 -1
- package/dist/oci-FTrEF0I6.mjs +0 -1
- package/dist/parser-CfDBEv7A.mjs +0 -2
- package/dist/sandbox-DQWTg5YL.mjs +0 -4
- package/dist/structured-output-BeZPb2QW.mjs +0 -1
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import { k as ProcessSpawner } from "./types-
|
|
2
|
-
|
|
1
|
+
import { k as ProcessSpawner } from "./types-CeIQCAFV.mjs";
|
|
3
2
|
//#region src/container/types.d.ts
|
|
4
3
|
/** Which provider backs a container. Selects which CLI/SDK the adapter speaks. */
|
|
5
4
|
type ContainerType = "docker" | "e2b" | "nerdctl" | "podman";
|
|
@@ -211,8 +210,6 @@ interface E2BSandboxLifecycleOptions {
|
|
|
211
210
|
interface E2BConnectionConfig {
|
|
212
211
|
/** E2B API key. Falls back to `E2B_API_KEY` if omitted. */
|
|
213
212
|
apiKey?: string;
|
|
214
|
-
/** Personal access token; an alternative to `apiKey`. Falls back to `E2B_ACCESS_TOKEN`. */
|
|
215
|
-
accessToken?: string;
|
|
216
213
|
/** Override the E2B API domain. Use for self-hosted or staging endpoints. */
|
|
217
214
|
domain?: string;
|
|
218
215
|
/** HTTP request timeout in milliseconds. */
|
|
@@ -377,7 +374,7 @@ type Container = DockerContainer | E2BContainer | NerdctlContainer | PodmanConta
|
|
|
377
374
|
* The `type` field on `config` selects the provider; supported values are
|
|
378
375
|
* `"docker"`, `"e2b"`, `"nerdctl"`, and `"podman"`. The provider's daemon
|
|
379
376
|
* (Docker, Podman, etc.) must be running locally, except for `"e2b"` which
|
|
380
|
-
* requires `E2B_API_KEY`
|
|
377
|
+
* requires `E2B_API_KEY` and the optional `e2b` peer
|
|
381
378
|
* dependency.
|
|
382
379
|
*
|
|
383
380
|
* Containers are async-disposable. Use `await using` to ensure cleanup:
|
|
@@ -1,9 +1,8 @@
|
|
|
1
|
-
import { S as McpServerConfig } from "./events-
|
|
2
|
-
import { f as EnsureDisjoint, k as ProcessSpawner, l as BaseAgent, p as ExclusiveExecutionTargetOptions, t as AgentEventHandler } from "./types-
|
|
3
|
-
import { t as Container } from "./index-
|
|
4
|
-
import { l as Sandbox } from "./index-
|
|
1
|
+
import { S as McpServerConfig } from "./events-BxEB6zHt.mjs";
|
|
2
|
+
import { f as EnsureDisjoint, k as ProcessSpawner, l as BaseAgent, p as ExclusiveExecutionTargetOptions, t as AgentEventHandler } from "./types-CeIQCAFV.mjs";
|
|
3
|
+
import { t as Container } from "./index-WaVqMCYN.mjs";
|
|
4
|
+
import { l as Sandbox } from "./index-CT-rhJzK.mjs";
|
|
5
5
|
import { z } from "zod/v4";
|
|
6
|
-
|
|
7
6
|
//#region src/adapters/codex-cli/events/schemas.d.ts
|
|
8
7
|
/**
|
|
9
8
|
* Permissive shape for any raw event Codex CLI emits — `{ type: string }`
|
|
@@ -26,6 +25,7 @@ declare const codexTurnCompletedEventSchema: z.ZodObject<{
|
|
|
26
25
|
usage: z.ZodOptional<z.ZodObject<{
|
|
27
26
|
input_tokens: z.ZodOptional<z.ZodNumber>;
|
|
28
27
|
cached_input_tokens: z.ZodOptional<z.ZodNumber>;
|
|
28
|
+
cache_write_input_tokens: z.ZodOptional<z.ZodNumber>;
|
|
29
29
|
output_tokens: z.ZodOptional<z.ZodNumber>;
|
|
30
30
|
reasoning_output_tokens: z.ZodOptional<z.ZodNumber>;
|
|
31
31
|
total_tokens: z.ZodOptional<z.ZodNumber>;
|
|
@@ -40,6 +40,7 @@ declare const codexTurnFailedEventSchema: z.ZodObject<{
|
|
|
40
40
|
usage: z.ZodOptional<z.ZodObject<{
|
|
41
41
|
input_tokens: z.ZodOptional<z.ZodNumber>;
|
|
42
42
|
cached_input_tokens: z.ZodOptional<z.ZodNumber>;
|
|
43
|
+
cache_write_input_tokens: z.ZodOptional<z.ZodNumber>;
|
|
43
44
|
output_tokens: z.ZodOptional<z.ZodNumber>;
|
|
44
45
|
reasoning_output_tokens: z.ZodOptional<z.ZodNumber>;
|
|
45
46
|
total_tokens: z.ZodOptional<z.ZodNumber>;
|
|
@@ -93,13 +94,16 @@ type CodexCliSandboxMode = "danger-full-access" | "read-only" | "workspace-write
|
|
|
93
94
|
/**
|
|
94
95
|
* How Codex CLI handles approval prompts.
|
|
95
96
|
* - `"default"`: leave Codex CLI's own default approval behavior in place (this adapter does not bridge approvals to a permission handler).
|
|
96
|
-
* - `"auto-approve"`: pass `--
|
|
97
|
-
* - `"bypass-sandbox"`: pass `--dangerously-bypass-approvals-and-sandbox`;
|
|
97
|
+
* - `"auto-approve"`: pass `--approve-for-me`; Codex uses automatic review in the `workspace-write` sandbox.
|
|
98
|
+
* - `"bypass-sandbox"`: pass `--dangerously-bypass-approvals-and-sandbox`; disable approvals and Codex's sandbox for externally isolated execution.
|
|
98
99
|
*/
|
|
99
100
|
type CodexCliPermissionMode = "auto-approve" | "bypass-sandbox" | "default";
|
|
100
101
|
/** Per-run options for the `codex-cli` adapter. */
|
|
101
102
|
interface CodexCliRunOptions {
|
|
102
|
-
/**
|
|
103
|
+
/**
|
|
104
|
+
* Filesystem sandbox policy for the default approval strategy.
|
|
105
|
+
* Other permission modes select their own sandbox behavior.
|
|
106
|
+
*/
|
|
103
107
|
sandboxMode?: CodexCliSandboxMode;
|
|
104
108
|
/** Extra directories outside `cwd` writable under `workspace-write`. */
|
|
105
109
|
additionalDirectories?: string[];
|
|
@@ -120,14 +124,23 @@ interface CodexCliRunOptions {
|
|
|
120
124
|
}
|
|
121
125
|
/** Constructor options for `createAgent("codex-cli", ...)`. */
|
|
122
126
|
type CodexCliAgentOptions = CodexCliRunOptions & ExclusiveExecutionTargetOptions<Container, Sandbox> & {
|
|
123
|
-
/** Path or argv to the `codex` binary. */
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
127
|
+
/** Path or argv to the `codex` binary. */
|
|
128
|
+
command?: string[] | string;
|
|
129
|
+
/** Working directory the agent operates against. */
|
|
130
|
+
cwd?: string;
|
|
131
|
+
/** Environment variables for the subprocess. Layered on top of host env when `propagateEnv` is `true` (default). */
|
|
132
|
+
env?: Record<string, string>;
|
|
133
|
+
/** Default `true`: `process.env` is inherited and `env` overlays it. Set `false` to suppress host-env propagation. */
|
|
134
|
+
propagateEnv?: boolean;
|
|
135
|
+
/** Existing Codex thread ID to resume via `codex resume`. */
|
|
136
|
+
sessionId?: string;
|
|
137
|
+
/** Codex model identifier. */
|
|
138
|
+
model?: string;
|
|
139
|
+
/** File path to write the raw CLI log to (useful for debugging). */
|
|
140
|
+
logPath?: string;
|
|
141
|
+
/** Custom process spawner; set by `createContainer`/`createSandbox`, rarely needed manually. */
|
|
142
|
+
spawner?: ProcessSpawner;
|
|
143
|
+
/** Convenience: equivalent to calling `agent.onEvent(handler)` post-construction. */
|
|
131
144
|
onEvent?: AgentEventHandler;
|
|
132
145
|
};
|
|
133
146
|
/** Agent instance returned by `createAgent("codex-cli", ...)`. */
|
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import { f as EnsureDisjoint, k as ProcessSpawner, l as BaseAgent, p as ExclusiveExecutionTargetOptions, t as AgentEventHandler } from "./types-
|
|
2
|
-
import { t as Container } from "./index-
|
|
3
|
-
import { l as Sandbox } from "./index-
|
|
1
|
+
import { f as EnsureDisjoint, k as ProcessSpawner, l as BaseAgent, p as ExclusiveExecutionTargetOptions, t as AgentEventHandler } from "./types-CeIQCAFV.mjs";
|
|
2
|
+
import { t as Container } from "./index-WaVqMCYN.mjs";
|
|
3
|
+
import { l as Sandbox } from "./index-CT-rhJzK.mjs";
|
|
4
4
|
import { z } from "zod/v4";
|
|
5
|
-
|
|
6
5
|
//#region src/adapters/gemini-cli/events/schemas.d.ts
|
|
7
6
|
/**
|
|
8
7
|
* Permissive raw-event shape for Gemini CLI: `{ type: string }` plus
|
|
@@ -38,15 +37,25 @@ interface GeminiCliRunOptions {
|
|
|
38
37
|
}
|
|
39
38
|
/** Constructor options for `createAgent("gemini-cli", ...)`. */
|
|
40
39
|
type GeminiCliAgentOptions = ExclusiveExecutionTargetOptions<Container, Sandbox> & GeminiCliRunOptions & {
|
|
41
|
-
/** Path or argv to the `gemini` binary. */
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
40
|
+
/** Path or argv to the `gemini` binary. */
|
|
41
|
+
command?: string[] | string;
|
|
42
|
+
/** Working directory the agent operates against. */
|
|
43
|
+
cwd?: string;
|
|
44
|
+
/** Environment variables for the subprocess. Layered on top of host env when `propagateEnv` is `true` (default). */
|
|
45
|
+
env?: Record<string, string>;
|
|
46
|
+
/** Default `true`: `process.env` is inherited and `env` overlays it. Set `false` to suppress host-env propagation. */
|
|
47
|
+
propagateEnv?: boolean;
|
|
48
|
+
/** Existing Gemini session ID to resume. */
|
|
49
|
+
sessionId?: string;
|
|
50
|
+
/** Gemini model identifier. */
|
|
51
|
+
model?: string;
|
|
52
|
+
/** Replaces Gemini's default system prompt entirely. */
|
|
53
|
+
systemPrompt?: string;
|
|
54
|
+
/** File path to write the raw CLI log to (useful for debugging). */
|
|
55
|
+
logPath?: string;
|
|
56
|
+
/** Custom process spawner; set by `createContainer`/`createSandbox`, rarely needed manually. */
|
|
57
|
+
spawner?: ProcessSpawner;
|
|
58
|
+
/** Convenience: equivalent to calling `agent.onEvent(handler)` post-construction. */
|
|
50
59
|
onEvent?: AgentEventHandler;
|
|
51
60
|
};
|
|
52
61
|
/** Agent instance returned by `createAgent("gemini-cli", ...)`. */
|
package/dist/index.d.mts
CHANGED
|
@@ -1,17 +1,18 @@
|
|
|
1
|
-
import { C as TextContentPart, S as McpServerConfig, a as SessionStartEvent, b as ImageContentPart, c as ToolResultEvent, i as SessionEndEvent, n as MessageEvent, o as StderrEvent, r as ReasoningEvent, s as ToolCallEvent, t as AgentEvent, u as eventSchema, v as AgentCapabilities, w as agentCapabilitiesSchema, x as JsonSchema, y as ContentPart } from "./events-
|
|
2
|
-
import { C as StopReason, D as PermissionHandler, E as PermissionDecision, O as PermissionRequest, S as RunTiming, T as ZodRunRequest, _ as RunProcessInfo, a as AgentValidationError, b as RunStats, c as AnyRunResult, d as CompletedRunResult, g as RunError, h as JsonSchemaRunRequest, i as AgentType, l as BaseAgent, m as FailedRunResult, n as AgentMetrics, o as AnyCompletedRunResult, r as AgentRunError, s as AnyRunRequest, t as AgentEventHandler, u as CancelledRunResult, v as RunRequest, w as StructuredRunRequest, x as RunStatus, y as RunResult } from "./types-
|
|
3
|
-
import { A as VolumeMount, C as DockerContainer, D as ExecOptions, E as ContainerType, F as WorkdirSnapshot, I as WorkdirSnapshotOptions, M as WorkdirDiff, N as WorkdirDiffStats, O as ExecResult, P as WorkdirFileChange, S as E2BProviderConfig, T as ContainerStatus, _ as E2BConnectConfig, a as ContainerDiffError, b as E2BContainerConfig, c as ContainerExecError, d as MountValidationError, f as PodmanContainer, g as NerdctlProviderConfig, h as NerdctlContainerConfig, i as ContainerCreateError, j as WorkdirChangeKind, k as PortMapping, l as ContainerNotRunningError, m as NerdctlContainer, n as ContainerConfig, o as ContainerDisposedError, p as PodmanContainerConfig, r as createContainer, s as ContainerError, t as Container, u as ContainerStartError, v as E2BConnectionConfig, w as DockerContainerConfig, x as E2BCreateConfig, y as E2BContainer } from "./index-
|
|
4
|
-
import { a as FirejailSandbox, c as NsjailSandboxConfig, d as SandboxStatus, f as SandboxType, i as BubblewrapSandboxConfig, l as Sandbox, n as createSandbox, o as FirejailSandboxConfig, r as BubblewrapSandbox, s as NsjailSandbox, t as SandboxCreateError, u as SandboxConfig } from "./index-
|
|
5
|
-
import { a as ClaudeCodeCliRunOptions, c as ClaudeRateLimitEvent, d as ClaudeUserEvent, i as ClaudeCodeCliPermissionMode, l as ClaudeResultEvent, n as ClaudeCodeCliAgent, o as ClaudeAssistantEvent, r as ClaudeCodeCliAgentOptions, s as ClaudeEvent, u as ClaudeSystemEvent } from "./index-
|
|
6
|
-
import { a as ClaudeCodeCliPtyPermissionMode, i as ClaudeCodeCliPtyModule, n as ClaudeCodeCliPtyAgent, o as ClaudeCodeCliPtyProcess, r as ClaudeCodeCliPtyAgentOptions, s as ClaudeCodeCliPtyRunOptions } from "./index-
|
|
7
|
-
import { a as ClaudeCodeSdkExecutable, c as ClaudeCodeSdkSettingSource, i as ClaudeCodeSdkEvent, l as ClaudeCodeSdkSettings, n as ClaudeCodeSdkAgent, o as ClaudeCodeSdkPermissionMode, r as ClaudeCodeSdkAgentOptions, s as ClaudeCodeSdkRunOptions } from "./index-
|
|
8
|
-
import { a as CodexCliRunOptions, c as CodexEvent, d as CodexItemUpdatedEvent, f as CodexThreadStartedEvent, i as CodexCliPermissionMode, l as CodexItemCompletedEvent, m as CodexTurnFailedEvent, n as CodexCliAgent, o as CodexCliSandboxMode, p as CodexTurnCompletedEvent, r as CodexCliAgentOptions, s as CodexErrorEvent, u as CodexItemStartedEvent } from "./index-
|
|
9
|
-
import { a as CodexSdkItem, i as CodexSdkEvent, n as CodexSdkAgent, o as CodexSdkPermissionMode, r as CodexSdkAgentOptions, s as CodexSdkRunOptions } from "./index-
|
|
10
|
-
import { a as CursorCliRunOptions, i as CursorCliPermissionMode, n as CursorCliAgent, o as CursorCliSandboxMode, r as CursorCliAgentOptions, s as CursorCliEvent } from "./index-
|
|
11
|
-
import { a as CursorSdkMcpHttpAuth, c as CursorSdkSettingSource, i as CursorSdkEvent, n as CursorSdkAgent, o as CursorSdkMcpServerConfig, r as CursorSdkAgentOptions, s as CursorSdkRunOptions } from "./index-
|
|
12
|
-
import { a as GeminiCliRunOptions, i as GeminiCliPermissionMode, n as GeminiCliAgent, o as GeminiEvent, r as GeminiCliAgentOptions } from "./index-
|
|
13
|
-
import { a as OpencodeEvent, i as OpencodeCliRunOptions, n as OpencodeCliAgent, r as OpencodeCliAgentOptions } from "./index-
|
|
14
|
-
import { a as PiCliThinkingLevel, i as PiCliRunOptions, n as PiCliAgent, o as PiEvent, r as PiCliAgentOptions } from "./index-
|
|
1
|
+
import { C as TextContentPart, S as McpServerConfig, a as SessionStartEvent, b as ImageContentPart, c as ToolResultEvent, i as SessionEndEvent, n as MessageEvent, o as StderrEvent, r as ReasoningEvent, s as ToolCallEvent, t as AgentEvent, u as eventSchema, v as AgentCapabilities, w as agentCapabilitiesSchema, x as JsonSchema, y as ContentPart } from "./events-BxEB6zHt.mjs";
|
|
2
|
+
import { C as StopReason, D as PermissionHandler, E as PermissionDecision, O as PermissionRequest, S as RunTiming, T as ZodRunRequest, _ as RunProcessInfo, a as AgentValidationError, b as RunStats, c as AnyRunResult, d as CompletedRunResult, g as RunError, h as JsonSchemaRunRequest, i as AgentType, l as BaseAgent, m as FailedRunResult, n as AgentMetrics, o as AnyCompletedRunResult, r as AgentRunError, s as AnyRunRequest, t as AgentEventHandler, u as CancelledRunResult, v as RunRequest, w as StructuredRunRequest, x as RunStatus, y as RunResult } from "./types-CeIQCAFV.mjs";
|
|
3
|
+
import { A as VolumeMount, C as DockerContainer, D as ExecOptions, E as ContainerType, F as WorkdirSnapshot, I as WorkdirSnapshotOptions, M as WorkdirDiff, N as WorkdirDiffStats, O as ExecResult, P as WorkdirFileChange, S as E2BProviderConfig, T as ContainerStatus, _ as E2BConnectConfig, a as ContainerDiffError, b as E2BContainerConfig, c as ContainerExecError, d as MountValidationError, f as PodmanContainer, g as NerdctlProviderConfig, h as NerdctlContainerConfig, i as ContainerCreateError, j as WorkdirChangeKind, k as PortMapping, l as ContainerNotRunningError, m as NerdctlContainer, n as ContainerConfig, o as ContainerDisposedError, p as PodmanContainerConfig, r as createContainer, s as ContainerError, t as Container, u as ContainerStartError, v as E2BConnectionConfig, w as DockerContainerConfig, x as E2BCreateConfig, y as E2BContainer } from "./index-WaVqMCYN.mjs";
|
|
4
|
+
import { a as FirejailSandbox, c as NsjailSandboxConfig, d as SandboxStatus, f as SandboxType, i as BubblewrapSandboxConfig, l as Sandbox, n as createSandbox, o as FirejailSandboxConfig, r as BubblewrapSandbox, s as NsjailSandbox, t as SandboxCreateError, u as SandboxConfig } from "./index-CT-rhJzK.mjs";
|
|
5
|
+
import { a as ClaudeCodeCliRunOptions, c as ClaudeRateLimitEvent, d as ClaudeUserEvent, i as ClaudeCodeCliPermissionMode, l as ClaudeResultEvent, n as ClaudeCodeCliAgent, o as ClaudeAssistantEvent, r as ClaudeCodeCliAgentOptions, s as ClaudeEvent, u as ClaudeSystemEvent } from "./index-DGY0wFGC.mjs";
|
|
6
|
+
import { a as ClaudeCodeCliPtyPermissionMode, i as ClaudeCodeCliPtyModule, n as ClaudeCodeCliPtyAgent, o as ClaudeCodeCliPtyProcess, r as ClaudeCodeCliPtyAgentOptions, s as ClaudeCodeCliPtyRunOptions } from "./index-C09YdI2A.mjs";
|
|
7
|
+
import { a as ClaudeCodeSdkExecutable, c as ClaudeCodeSdkSettingSource, i as ClaudeCodeSdkEvent, l as ClaudeCodeSdkSettings, n as ClaudeCodeSdkAgent, o as ClaudeCodeSdkPermissionMode, r as ClaudeCodeSdkAgentOptions, s as ClaudeCodeSdkRunOptions } from "./index-Dm9HCmWK.mjs";
|
|
8
|
+
import { a as CodexCliRunOptions, c as CodexEvent, d as CodexItemUpdatedEvent, f as CodexThreadStartedEvent, i as CodexCliPermissionMode, l as CodexItemCompletedEvent, m as CodexTurnFailedEvent, n as CodexCliAgent, o as CodexCliSandboxMode, p as CodexTurnCompletedEvent, r as CodexCliAgentOptions, s as CodexErrorEvent, u as CodexItemStartedEvent } from "./index-fZiuDQFa.mjs";
|
|
9
|
+
import { a as CodexSdkItem, i as CodexSdkEvent, n as CodexSdkAgent, o as CodexSdkPermissionMode, r as CodexSdkAgentOptions, s as CodexSdkRunOptions } from "./index-BXgvYZSv.mjs";
|
|
10
|
+
import { a as CursorCliRunOptions, i as CursorCliPermissionMode, n as CursorCliAgent, o as CursorCliSandboxMode, r as CursorCliAgentOptions, s as CursorCliEvent } from "./index-BkIhoEPd.mjs";
|
|
11
|
+
import { a as CursorSdkMcpHttpAuth, c as CursorSdkSettingSource, i as CursorSdkEvent, n as CursorSdkAgent, o as CursorSdkMcpServerConfig, r as CursorSdkAgentOptions, s as CursorSdkRunOptions } from "./index-CGGPY1qE.mjs";
|
|
12
|
+
import { a as GeminiCliRunOptions, i as GeminiCliPermissionMode, n as GeminiCliAgent, o as GeminiEvent, r as GeminiCliAgentOptions } from "./index-gtpzhLCF.mjs";
|
|
13
|
+
import { a as OpencodeEvent, i as OpencodeCliRunOptions, n as OpencodeCliAgent, r as OpencodeCliAgentOptions } from "./index-D_qqPXPO.mjs";
|
|
14
|
+
import { a as PiCliThinkingLevel, i as PiCliRunOptions, n as PiCliAgent, o as PiEvent, r as PiCliAgentOptions } from "./index-D3yvIIre.mjs";
|
|
15
|
+
import "./schemas/index.mjs";
|
|
15
16
|
//#region src/core/agent/create-agent.d.ts
|
|
16
17
|
interface AgentOptionsByType {
|
|
17
18
|
"claude-code-cli-pty": ClaudeCodeCliPtyAgentOptions;
|
|
@@ -65,16 +66,16 @@ interface AgentInstanceByType {
|
|
|
65
66
|
* @returns A promise that resolves to the typed agent instance.
|
|
66
67
|
* @throws {AgentValidationError} If a required peer dependency is missing or required options are absent.
|
|
67
68
|
*/
|
|
68
|
-
declare function createAgent(type: "claude-code-cli-pty", options?: ClaudeCodeCliPtyAgentOptions): Promise<ClaudeCodeCliPtyAgent>;
|
|
69
|
-
declare function createAgent(type: "claude-code-cli", options?: ClaudeCodeCliAgentOptions): Promise<ClaudeCodeCliAgent>;
|
|
70
|
-
declare function createAgent(type: "claude-code-sdk", options?: ClaudeCodeSdkAgentOptions): Promise<ClaudeCodeSdkAgent>;
|
|
71
|
-
declare function createAgent(type: "codex-cli", options?: CodexCliAgentOptions): Promise<CodexCliAgent>;
|
|
72
|
-
declare function createAgent(type: "codex-sdk", options?: CodexSdkAgentOptions): Promise<CodexSdkAgent>;
|
|
73
|
-
declare function createAgent(type: "cursor-cli", options?: CursorCliAgentOptions): Promise<CursorCliAgent>;
|
|
74
|
-
declare function createAgent(type: "cursor-sdk", options?: CursorSdkAgentOptions): Promise<CursorSdkAgent>;
|
|
75
|
-
declare function createAgent(type: "gemini-cli", options?: GeminiCliAgentOptions): Promise<GeminiCliAgent>;
|
|
76
|
-
declare function createAgent(type: "opencode-cli", options?: OpencodeCliAgentOptions): Promise<OpencodeCliAgent>;
|
|
77
|
-
declare function createAgent(type: "pi-cli", options?: PiCliAgentOptions): Promise<PiCliAgent>;
|
|
78
|
-
declare function createAgent<T extends AgentType>(type: T, options?: AgentOptionsByType[T]): Promise<AgentInstanceByType[T]>;
|
|
69
|
+
export declare function createAgent(type: "claude-code-cli-pty", options?: ClaudeCodeCliPtyAgentOptions): Promise<ClaudeCodeCliPtyAgent>;
|
|
70
|
+
export declare function createAgent(type: "claude-code-cli", options?: ClaudeCodeCliAgentOptions): Promise<ClaudeCodeCliAgent>;
|
|
71
|
+
export declare function createAgent(type: "claude-code-sdk", options?: ClaudeCodeSdkAgentOptions): Promise<ClaudeCodeSdkAgent>;
|
|
72
|
+
export declare function createAgent(type: "codex-cli", options?: CodexCliAgentOptions): Promise<CodexCliAgent>;
|
|
73
|
+
export declare function createAgent(type: "codex-sdk", options?: CodexSdkAgentOptions): Promise<CodexSdkAgent>;
|
|
74
|
+
export declare function createAgent(type: "cursor-cli", options?: CursorCliAgentOptions): Promise<CursorCliAgent>;
|
|
75
|
+
export declare function createAgent(type: "cursor-sdk", options?: CursorSdkAgentOptions): Promise<CursorSdkAgent>;
|
|
76
|
+
export declare function createAgent(type: "gemini-cli", options?: GeminiCliAgentOptions): Promise<GeminiCliAgent>;
|
|
77
|
+
export declare function createAgent(type: "opencode-cli", options?: OpencodeCliAgentOptions): Promise<OpencodeCliAgent>;
|
|
78
|
+
export declare function createAgent(type: "pi-cli", options?: PiCliAgentOptions): Promise<PiCliAgent>;
|
|
79
|
+
export declare function createAgent<T extends AgentType>(type: T, options?: AgentOptionsByType[T]): Promise<AgentInstanceByType[T]>;
|
|
79
80
|
//#endregion
|
|
80
|
-
export { type AgentCapabilities, type AgentEvent, type AgentEventHandler, type AgentMetrics, AgentRunError, type AgentType, AgentValidationError, type AnyCompletedRunResult, type AnyRunRequest, type AnyRunResult, type BaseAgent, type BubblewrapSandbox, type BubblewrapSandboxConfig, type CancelledRunResult, type ClaudeAssistantEvent, type ClaudeCodeCliAgent, type ClaudeCodeCliAgentOptions, type ClaudeCodeCliPermissionMode, type ClaudeCodeCliPtyAgent, type ClaudeCodeCliPtyAgentOptions, type ClaudeCodeCliPtyModule, type ClaudeCodeCliPtyPermissionMode, type ClaudeCodeCliPtyProcess, type ClaudeCodeCliPtyRunOptions, type ClaudeCodeCliRunOptions, type ClaudeCodeSdkAgent, type ClaudeCodeSdkAgentOptions, type ClaudeCodeSdkEvent, type ClaudeCodeSdkExecutable, type ClaudeCodeSdkPermissionMode, type ClaudeCodeSdkRunOptions, type ClaudeCodeSdkSettingSource, type ClaudeCodeSdkSettings, type ClaudeEvent, type ClaudeRateLimitEvent, type ClaudeResultEvent, type ClaudeSystemEvent, type ClaudeUserEvent, type CodexCliAgent, type CodexCliAgentOptions, type CodexCliPermissionMode, type CodexCliRunOptions, type CodexCliSandboxMode, type CodexErrorEvent, type CodexEvent, type CodexItemCompletedEvent, type CodexItemStartedEvent, type CodexItemUpdatedEvent, type CodexSdkAgent, type CodexSdkAgentOptions, type CodexSdkEvent, type CodexSdkItem, type CodexSdkPermissionMode, type CodexSdkRunOptions, type CodexThreadStartedEvent, type CodexTurnCompletedEvent, type CodexTurnFailedEvent, type CompletedRunResult, type Container, type ContainerConfig, ContainerCreateError, ContainerDiffError, ContainerDisposedError, ContainerError, ContainerExecError, ContainerNotRunningError, ContainerStartError, type ContainerStatus, type ContainerType, type ContentPart, type CursorCliAgent, type CursorCliAgentOptions, type CursorCliEvent, type CursorCliPermissionMode, type CursorCliRunOptions, type CursorCliSandboxMode, type CursorSdkAgent, type CursorSdkAgentOptions, type CursorSdkEvent, type CursorSdkMcpHttpAuth, type CursorSdkMcpServerConfig, type CursorSdkRunOptions, type CursorSdkSettingSource, type DockerContainer, type DockerContainerConfig, type E2BConnectConfig, type E2BConnectionConfig, type E2BContainer, type E2BContainerConfig, type E2BCreateConfig, type E2BProviderConfig, type ExecOptions, type ExecResult, type FailedRunResult, type FirejailSandbox, type FirejailSandboxConfig, type GeminiCliAgent, type GeminiCliAgentOptions, type GeminiCliPermissionMode, type GeminiCliRunOptions, type GeminiEvent, type ImageContentPart, type JsonSchema, type JsonSchemaRunRequest, type McpServerConfig, type MessageEvent, MountValidationError, type NerdctlContainer, type NerdctlContainerConfig, type NerdctlProviderConfig, type NsjailSandbox, type NsjailSandboxConfig, type OpencodeCliAgent, type OpencodeCliAgentOptions, type OpencodeCliRunOptions, type OpencodeEvent, type PermissionDecision, type PermissionHandler, type PermissionRequest, type PiCliAgent, type PiCliAgentOptions, type PiCliRunOptions, type PiCliThinkingLevel, type PiEvent, type PodmanContainer, type PodmanContainerConfig, type PortMapping, type ReasoningEvent, type RunError, type RunProcessInfo, type RunRequest, type RunResult, type RunStats, type RunStatus, type RunTiming, type Sandbox, type SandboxConfig, SandboxCreateError, type SandboxStatus, type SandboxType, type SessionEndEvent, type SessionStartEvent, type StderrEvent, type StopReason, type StructuredRunRequest, type TextContentPart, type ToolCallEvent, type ToolResultEvent, type VolumeMount, type WorkdirChangeKind, type WorkdirDiff, type WorkdirDiffStats, type WorkdirFileChange, type WorkdirSnapshot, type WorkdirSnapshotOptions, type ZodRunRequest, agentCapabilitiesSchema,
|
|
81
|
+
export { type AgentCapabilities, type AgentEvent, type AgentEventHandler, type AgentMetrics, AgentRunError, type AgentType, AgentValidationError, type AnyCompletedRunResult, type AnyRunRequest, type AnyRunResult, type BaseAgent, type BubblewrapSandbox, type BubblewrapSandboxConfig, type CancelledRunResult, type ClaudeAssistantEvent, type ClaudeCodeCliAgent, type ClaudeCodeCliAgentOptions, type ClaudeCodeCliPermissionMode, type ClaudeCodeCliPtyAgent, type ClaudeCodeCliPtyAgentOptions, type ClaudeCodeCliPtyModule, type ClaudeCodeCliPtyPermissionMode, type ClaudeCodeCliPtyProcess, type ClaudeCodeCliPtyRunOptions, type ClaudeCodeCliRunOptions, type ClaudeCodeSdkAgent, type ClaudeCodeSdkAgentOptions, type ClaudeCodeSdkEvent, type ClaudeCodeSdkExecutable, type ClaudeCodeSdkPermissionMode, type ClaudeCodeSdkRunOptions, type ClaudeCodeSdkSettingSource, type ClaudeCodeSdkSettings, type ClaudeEvent, type ClaudeRateLimitEvent, type ClaudeResultEvent, type ClaudeSystemEvent, type ClaudeUserEvent, type CodexCliAgent, type CodexCliAgentOptions, type CodexCliPermissionMode, type CodexCliRunOptions, type CodexCliSandboxMode, type CodexErrorEvent, type CodexEvent, type CodexItemCompletedEvent, type CodexItemStartedEvent, type CodexItemUpdatedEvent, type CodexSdkAgent, type CodexSdkAgentOptions, type CodexSdkEvent, type CodexSdkItem, type CodexSdkPermissionMode, type CodexSdkRunOptions, type CodexThreadStartedEvent, type CodexTurnCompletedEvent, type CodexTurnFailedEvent, type CompletedRunResult, type Container, type ContainerConfig, ContainerCreateError, ContainerDiffError, ContainerDisposedError, ContainerError, ContainerExecError, ContainerNotRunningError, ContainerStartError, type ContainerStatus, type ContainerType, type ContentPart, type CursorCliAgent, type CursorCliAgentOptions, type CursorCliEvent, type CursorCliPermissionMode, type CursorCliRunOptions, type CursorCliSandboxMode, type CursorSdkAgent, type CursorSdkAgentOptions, type CursorSdkEvent, type CursorSdkMcpHttpAuth, type CursorSdkMcpServerConfig, type CursorSdkRunOptions, type CursorSdkSettingSource, type DockerContainer, type DockerContainerConfig, type E2BConnectConfig, type E2BConnectionConfig, type E2BContainer, type E2BContainerConfig, type E2BCreateConfig, type E2BProviderConfig, type ExecOptions, type ExecResult, type FailedRunResult, type FirejailSandbox, type FirejailSandboxConfig, type GeminiCliAgent, type GeminiCliAgentOptions, type GeminiCliPermissionMode, type GeminiCliRunOptions, type GeminiEvent, type ImageContentPart, type JsonSchema, type JsonSchemaRunRequest, type McpServerConfig, type MessageEvent, MountValidationError, type NerdctlContainer, type NerdctlContainerConfig, type NerdctlProviderConfig, type NsjailSandbox, type NsjailSandboxConfig, type OpencodeCliAgent, type OpencodeCliAgentOptions, type OpencodeCliRunOptions, type OpencodeEvent, type PermissionDecision, type PermissionHandler, type PermissionRequest, type PiCliAgent, type PiCliAgentOptions, type PiCliRunOptions, type PiCliThinkingLevel, type PiEvent, type PodmanContainer, type PodmanContainerConfig, type PortMapping, type ReasoningEvent, type RunError, type RunProcessInfo, type RunRequest, type RunResult, type RunStats, type RunStatus, type RunTiming, type Sandbox, type SandboxConfig, SandboxCreateError, type SandboxStatus, type SandboxType, type SessionEndEvent, type SessionStartEvent, type StderrEvent, type StopReason, type StructuredRunRequest, type TextContentPart, type ToolCallEvent, type ToolResultEvent, type VolumeMount, type WorkdirChangeKind, type WorkdirDiff, type WorkdirDiffStats, type WorkdirFileChange, type WorkdirSnapshot, type WorkdirSnapshotOptions, type ZodRunRequest, agentCapabilitiesSchema, createContainer, createSandbox, eventSchema };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e,t}from"./types-B72tDMEZ.mjs";import{a as n,c as r,i,l as a,n as o,o as s,r as c,s as l,t as u}from"./container-
|
|
1
|
+
import{n as e,t}from"./types-B72tDMEZ.mjs";import{a as n,c as r,i,l as a,n as o,o as s,r as c,s as l,t as u}from"./container-Dk4QgU9G.mjs";import{n as d,t as f}from"./sandbox-CoV-gBuM.mjs";import{n as p,u as m}from"./schemas-CkdQXAep.mjs";const h=(e,t)=>{if(!(e instanceof Error)||!e.message.includes(t))return!1;let n=typeof e==`object`&&e&&`code`in e?e.code:void 0;return n===`ERR_MODULE_NOT_FOUND`||n===`MODULE_NOT_FOUND`},g=(t,n,r)=>{throw h(r,n)?new e(`Agent type "${t}" requires the optional peer dependency "${n}". Install it to use this adapter.`):r};async function _(t,n){switch(t){case`claude-code-cli-pty`:{let{createClaudeCodeCliPtyAgent:e}=await import(`./adapters/claude-code-cli-pty/index.mjs`);return e(n)}case`claude-code-cli`:{let{createClaudeCodeCliAgent:e}=await import(`./adapters/claude-code-cli/index.mjs`);return e(n)}case`claude-code-sdk`:{let e=n;try{let{createClaudeCodeSdkAgent:t}=await import(`./adapters/claude-code-sdk/index.mjs`);return t(e)}catch(e){return g(`claude-code-sdk`,`@anthropic-ai/claude-agent-sdk`,e)}}case`codex-cli`:{let{createCodexCliAgent:e}=await import(`./adapters/codex-cli/index.mjs`);return e(n)}case`codex-sdk`:{let e=n;try{let{createCodexSdkAgent:t}=await import(`./adapters/codex-sdk/index.mjs`);return t(e)}catch(e){return g(`codex-sdk`,`@openai/codex-sdk`,e)}}case`cursor-cli`:{let{createCursorCliAgent:e}=await import(`./adapters/cursor-cli/index.mjs`);return e(n)}case`cursor-sdk`:{let e=n;try{let{createCursorSdkAgent:t}=await import(`./adapters/cursor-sdk/index.mjs`);return t(e)}catch(e){return g(`cursor-sdk`,`@cursor/sdk`,e)}}case`gemini-cli`:{let{createGeminiCliAgent:e}=await import(`./adapters/gemini-cli/index.mjs`);return e(n)}case`opencode-cli`:{let{createOpencodeCliAgent:e}=await import(`./adapters/opencode-cli/index.mjs`);return e(n)}case`pi-cli`:{let{createPiCliAgent:e}=await import(`./adapters/pi-cli/index.mjs`);return e(n)}default:throw new e(`Unsupported agent type.`)}}export{t as AgentRunError,e as AgentValidationError,o as ContainerCreateError,c as ContainerDiffError,i as ContainerDisposedError,n as ContainerError,s as ContainerExecError,l as ContainerNotRunningError,r as ContainerStartError,a as MountValidationError,f as SandboxCreateError,m as agentCapabilitiesSchema,_ as createAgent,u as createContainer,d as createSandbox,p as eventSchema};
|
|
@@ -0,0 +1 @@
|
|
|
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-Dk4QgU9G.mjs";import{n as c}from"./env-Cb8MIvH7.mjs";import{t as l}from"./spawner-BE2hAC0w.mjs";import{t as u}from"./shell-DvWFuFKb.mjs";import{n as d,r as f,t as p}from"./diff-C60ujrU_.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),l.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=d({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 ${u(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(f(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 ${u(i)} && cat > ${u(r)}`);let c=l.spawn(h.binary,j(h,s),{env:M(h),stdio:[`pipe`,`ignore`,`ignore`]});try{c.stdin?.write?.(o),c.stdin?.end()}catch(t){throw c.kill(),c.wait().catch(()=>{}),new a(`writeFile failed for ${r}: ${e(t)}`)}let d=await c.wait();if(d.exitCode!==0)throw new a(`writeFile failed for ${r} (exit ${d.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};
|
|
@@ -0,0 +1,2 @@
|
|
|
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({type:a.literal(`system`),session_id:a.string(),subtype:h,uuid:a.string(),tools:a.array(a.string()).optional(),mcp_servers:a.array(a.object({name:a.string(),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()}),_=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()})}),v=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()}),y=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()}),b=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()})}),x=a.discriminatedUnion(`type`,[g,_,v,y,b]),S=t(x);export{o as n,m as r,S as t};
|
package/dist/sandbox/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as FirejailSandbox, c as NsjailSandboxConfig, d as SandboxStatus, f as SandboxType, i as BubblewrapSandboxConfig, l as Sandbox, n as createSandbox, o as FirejailSandboxConfig, r as BubblewrapSandbox, s as NsjailSandbox, t as SandboxCreateError, u as SandboxConfig } from "../index-
|
|
1
|
+
import { a as FirejailSandbox, c as NsjailSandboxConfig, d as SandboxStatus, f as SandboxType, i as BubblewrapSandboxConfig, l as Sandbox, n as createSandbox, o as FirejailSandboxConfig, r as BubblewrapSandbox, s as NsjailSandbox, t as SandboxCreateError, u as SandboxConfig } from "../index-CT-rhJzK.mjs";
|
|
2
2
|
export { type BubblewrapSandbox, type BubblewrapSandboxConfig, type FirejailSandbox, type FirejailSandboxConfig, type NsjailSandbox, type NsjailSandboxConfig, type Sandbox, type SandboxConfig, SandboxCreateError, type SandboxStatus, type SandboxType, createSandbox };
|
package/dist/sandbox/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e,t}from"../sandbox-
|
|
1
|
+
import{n as e,t}from"../sandbox-CoV-gBuM.mjs";export{t as SandboxCreateError,e as createSandbox};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{t as e}from"./util-B4HTdOSc.mjs";import{n as t,r as n,t as r}from"./env-Cb8MIvH7.mjs";import{t as i}from"./spawner-BE2hAC0w.mjs";import{t as a}from"./shell-DvWFuFKb.mjs";import{execFile as o}from"node:child_process";import{delimiter as s,isAbsolute as c,join as l,posix as u,resolve as d}from"node:path";import{promisify as f}from"node:util";import{accessSync as p,constants as m,mkdtempSync as h,realpathSync as g,rmSync as _,writeFileSync as v}from"node:fs";import{tmpdir as y}from"node:os";const b=e=>{let t=e.type.charAt(0).toUpperCase()+e.type.slice(1),n=`created`,r=/* @__PURE__ */ new Set,i=()=>{if(n===`disposed`)throw Error(`${t} sandbox has been disposed.`)},a=()=>{if(i(),n!==`running`)throw Error(`${t} sandbox is not running.`)},o=e=>{let t={process:e,waitPromise:e.wait().finally(()=>{r.delete(t)})};return r.add(t),{...e,wait:()=>t.waitPromise}},s=async()=>{let e=Array.from(r,e=>(e.process.kill(`SIGKILL`),e.waitPromise));await Promise.allSettled(e)},c=e.createSpawner(a,o),l={type:e.type,config:e.config,get status(){return n},get workdir(){return e.config.workdir},get spawner(){return c},async start(){i(),n!==`running`&&(await e.onValidate(),n=`running`)},async stop(){i(),n===`running`&&(n=`stopped`,await s())},async dispose(){n!==`disposed`&&(n=`disposed`,await s(),await e.onDispose?.())},[Symbol.asyncDispose](){return l.dispose()}};return e.extend?e.extend(l):l},x=`bwrap`,S=[`/tmp`],C=f(o),w=(e,t)=>e.binds?.some(e=>e.target===t)??!1,T=(e,t)=>{let n=u.relative(e,t);return n===``||!n.startsWith(`..`)&&!u.isAbsolute(n)},E=(e,t)=>e.target.length-t.target.length,ee=e=>{let t=w(e,e.workdir)?[...e.binds??[]]:[{source:e.workdir,target:e.workdir},...e.binds??[]],n=e.tmpfs??S,r=t.filter(e=>!n.some(t=>T(t,e.target))).toSorted(E),i=t.filter(e=>n.some(t=>T(t,e.target))).toSorted(E);return[...r,...i]},te=e=>{let t=[`--ro-bind`,`/`,`/`];for(let n of ee(e))t.push(n.readonly?`--ro-bind`:`--bind`,n.source,n.target);return t},ne=(e,t)=>{let n=[];(e.clearEnv??!0)&&n.push(`--clearenv`);for(let t of e.unsetEnv??[])n.push(`--unsetenv`,t);let r={...e.setEnv,...t.env};for(let[e,t]of Object.entries(r))n.push(`--setenv`,e,t);return n},re=e=>{let t=[`--die-with-parent`,`--new-session`];return(e.unshareAll??!0)&&t.push(`--unshare-all`),e.shareNetwork&&t.push(`--share-net`),e.uid!==void 0&&t.push(`--uid`,String(e.uid)),e.gid!==void 0&&t.push(`--gid`,String(e.gid)),e.hostname&&t.push(`--hostname`,e.hostname),t},ie=e=>{let t=[`--ro-bind`,`/`,`/`];e.proc!==!1&&t.push(`--proc`,e.proc??`/proc`),e.dev!==!1&&t.push(`--dev`,e.dev??`/dev`);for(let n of e.tmpfs??S)t.push(`--tmpfs`,n);t.push(...te(e).slice(3));for(let n of e.remountReadonly??[])t.push(`--remount-ro`,n);return t},ae=(e,t,n,r={})=>[...re(e),...ie(e),...ne(e,r),`--chdir`,r.cwd??e.workdir,...e.args??[],`--`,t,...n],oe=async t=>{try{await C(t,[`--version`],{env:r(),encoding:`utf8`})}catch(t){throw Error(`Bubblewrap start failed: ${e(t)}`)}},D=(e,t,n,i)=>({spawn(a,o,s={}){return t(),n(i.spawn(e.binary??x,ae(e,a,o,s),{env:r(),stdio:s.stdio}))}}),O=async(e,t=i)=>b({type:`bubblewrap`,config:e,onValidate:()=>oe(e.binary??x),createSpawner:(n,r)=>D(e,n,r,t)}),k=e=>new Set((e??[]).flatMap(e=>[e,e.toUpperCase(),e.toLowerCase()])),A=(e,t)=>{let n=k(t);return n.size===0?e:Object.fromEntries(Object.entries(e).filter(([e])=>!n.has(e)))},j=e=>{try{return p(e,m.X_OK),!0}catch{return!1}},M=(e,t)=>c(e)?e:d(t,e),N=(e,t,r)=>{if(c(e)||e.includes(`/`))return e;let i=t[n(t)];if(!i)return e;for(let t of i.split(s)){let n=l(M(t,r),e);if(j(n))return n}return e},P=(e,r)=>{if((r??[]).some(e=>e.toLowerCase()===`path`))return;let i=n(e);if(i in e)return;let a=t(),o=a[n(a)];o&&Object.assign(e,{[i]:o})},F=[`/run/wrappers/bin`,`/usr/local/bin`,`/usr/bin`,`/bin`],I=f(o),L=e=>e.binary??`firejail`,R=()=>{let e=t();return e[n(e)]},z=e=>{if(e.clearEnv===!1)return r({extraPaths:F});let t=r({propagateEnv:!1,extraPaths:F}),i=R();return i&&(t[n(t)]=[...F,i].filter(Boolean).join(s)),t},B=(e,t,n)=>{let r=A({...n,...e.setEnv,...t.env},e.unsetEnv);return P(r,e.unsetEnv),r},V=(e,t,n)=>{let r=[];for(let t of e.unsetEnv??[])r.push(`--rmenv=${t}`);let i={...e.setEnv,...t.env};for(let[e,t]of Object.entries(i))n[e]!==t&&r.push(`--env=${e}=${t}`);return r},H=(e,t,n,r={},i={})=>{let a=[`--noprofile`];e.shareNetwork||a.push(`--net=none`);for(let t of e.whitelist??[])a.push(`--whitelist=${t}`);for(let t of e.blacklist??[])a.push(`--blacklist=${t}`);for(let t of e.readOnly??[])a.push(`--read-only=${t}`);for(let t of e.readWrite??[])a.push(`--read-write=${t}`);return e.privateTmp&&a.push(`--private-tmp`),a.push(...V(e,r,i)),e.args?.length&&a.push(...e.args),a.push(`--`,t,...n),a},U=async t=>{try{await I(t,[`--version`],{env:r({extraPaths:F}),encoding:`utf8`})}catch(t){throw Error(`Firejail start failed: ${e(t)}`)}},W=(e,t,n,r)=>({spawn(i,o,s={}){t();let c=s.cwd??e.workdir,l=z(e),u=`exec ${[N(i,B(e,s,l),c),...o].map(a).join(` `)}`;return n(r.spawn(L(e),H(e,`sh`,[`-c`,u],s,l),{cwd:c,env:l,stdio:s.stdio}))}}),G=async(e,t=i)=>b({type:`firejail`,config:e,onValidate:()=>U(L(e)),createSpawner:(n,r)=>W(e,n,r,t)}),K=`nsjail`,se=[`/tmp`],ce=f(o),q=e=>JSON.stringify(e),J=(e,t)=>e.target.length-t.target.length||Number(!!e.readonly)-Number(!!t.readonly),le=(e,t)=>e.binds?.some(e=>e.target===t)??!1,Y=e=>e.tmpfs??[...se],ue=(e,t)=>Y(e).includes(t),de=e=>{let t=le(e,e.workdir)?[...e.binds??[]]:[{source:e.workdir,target:e.workdir},...e.binds??[]],n=(e.readOnly??[]).map(e=>({source:e,target:e,readonly:!0,type:`bind`}));return[...t.map(e=>({source:e.source,target:e.target,readonly:e.readonly,type:`bind`})),...n].filter(t=>!ue(e,t.target)).toSorted(J)},fe=e=>Y(e).map(t=>({target:t,readonly:e.readOnly?.includes(t),type:`tmpfs`})).toSorted(J),pe=e=>[{source:`/`,target:`/`,readonly:!0,type:`bind`},...fe(e),...de(e)],X=(e,t)=>{let n=A(e.clearEnv===!1?r():r({propagateEnv:!1}),e.unsetEnv);return Object.assign(n,e.setEnv,t.env),P(n,e.unsetEnv),n},Z=(e,t,n)=>[`${e} {`,` inside_id: ${q(String(t))}`,` outside_id: ${q(String(n))}`,` count: 1`,`}`].join(`
|
|
2
|
+
`),me=e=>{if(e!==void 0)try{return g(e)}catch{return e}},Q=e=>{let t=[`mount {`],n=me(e.source);return n!==void 0&&t.push(` src: ${q(n)}`),t.push(` dst: ${q(e.target)}`),e.type===`tmpfs`?t.push(` fstype: ${q(`tmpfs`)}`):t.push(` is_bind: true`),t.push(` rw: ${e.readonly?`false`:`true`}`),t.push(` mandatory: true`),t.push(`}`),t.join(`
|
|
3
|
+
`)},he=(e,t,n)=>{let r=t.cwd??e.workdir,i=n??X(e,t),a=e.hostname??`NSJAIL`,o=typeof process.getuid==`function`?process.getuid():0,s=typeof process.getgid==`function`?process.getgid():0,c=e.uid??o,l=e.gid??s,u=e.clearEnv===!1&&(e.unsetEnv?.length??0)===0,d=[`name: "coding-agents-sdk"`,`mode: ONCE`,`hostname: ${q(a)}`,`cwd: ${q(r)}`,`keep_env: ${u?`true`:`false`}`,`clone_newnet: ${e.shareNetwork?`false`:`true`}`,`clone_newuser: true`,`clone_newns: true`,`clone_newpid: true`,`clone_newipc: true`,`clone_newuts: true`,`mount_proc: true`,`time_limit: ${String(e.timeLimitSec??0)}`,Z(`uidmap`,c,o),Z(`gidmap`,l,s)];e.seccompString&&d.push(`seccomp_string: ${q(e.seccompString)}`);for(let[e,t]of Object.entries(i)){let n=`${e}=${t}`;d.push(`envar: ${q(n)}`)}for(let t of pe(e))d.push(Q(t));return`${d.join(`
|
|
4
|
+
`)}\n`},ge=(e,t,n,r)=>{let i=[`-C`,t];return(e.disableRlimits??!0)&&i.push(`--disable_rlimits`),i.push(...e.args??[],`--`,n,...r),i},_e=async t=>{try{await ce(t,[`--help`],{env:r(),encoding:`utf8`})}catch(t){throw Error(`Nsjail start failed: ${e(t)}`)}},ve=(e,t,n,i,a)=>({spawn(o,s,c={}){n();let u=t(),d=X(e,c),f=c.cwd??e.workdir,p=N(o,d,f),m=l(u.configDir,`spawn-${Date.now()}-${Math.random().toString(16).slice(2)}.cfg`);v(m,he(e,c,d),{encoding:`utf8`,mode:384});try{let t=i(a.spawn(e.binary??K,ge(e,m,p,s),{env:r(),stdio:c.stdio})),n=t.wait().finally(()=>{_(m,{force:!0})});return{...t,wait:()=>n}}catch(e){throw _(m,{force:!0}),e}}}),ye=async(e,t=i)=>{let n,r=()=>{if(!n)throw Error(`Nsjail sandbox has not been started.`);return n};return b({type:`nsjail`,config:e,async onValidate(){await _e(e.binary??K),n??={configDir:h(l(y(),`cw-nsjail-`))}},onDispose(){n&&_(n.configDir,{recursive:!0,force:!0})},createSpawner:(n,i)=>ve(e,r,n,i,t)})};var $=class extends Error{constructor(e){super(e),this.name=`SandboxCreateError`}};async function be(e){switch(e.type){case`bubblewrap`:return O(e);case`firejail`:return G(e);case`nsjail`:return ye(e);default:throw new $(`Unsupported sandbox type.`)}}export{be as n,$ as t};
|
package/dist/schemas/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { C as TextContentPart, D as textContentPartSchema, E as imageContentPartSchema, S as McpServerConfig, T as contentPartSchema, _ as toolResultEventSchema, a as SessionStartEvent, b as ImageContentPart, c as ToolResultEvent, d as messageEventSchema, f as reasoningEventSchema, g as toolCallEventSchema, h as stderrEventSchema, i as SessionEndEvent, l as baseEventSchema, m as sessionStartEventSchema, n as MessageEvent, o as StderrEvent, p as sessionEndEventSchema, r as ReasoningEvent, s as ToolCallEvent, t as AgentEvent, u as eventSchema, v as AgentCapabilities, w as agentCapabilitiesSchema, x as JsonSchema, y as ContentPart } from "../events-
|
|
1
|
+
import { C as TextContentPart, D as textContentPartSchema, E as imageContentPartSchema, S as McpServerConfig, T as contentPartSchema, _ as toolResultEventSchema, a as SessionStartEvent, b as ImageContentPart, c as ToolResultEvent, d as messageEventSchema, f as reasoningEventSchema, g as toolCallEventSchema, h as stderrEventSchema, i as SessionEndEvent, l as baseEventSchema, m as sessionStartEventSchema, n as MessageEvent, o as StderrEvent, p as sessionEndEventSchema, r as ReasoningEvent, s as ToolCallEvent, t as AgentEvent, u as eventSchema, v as AgentCapabilities, w as agentCapabilitiesSchema, x as JsonSchema, y as ContentPart } from "../events-BxEB6zHt.mjs";
|
|
2
2
|
export { type AgentCapabilities, type AgentEvent, type ContentPart, type ImageContentPart, type JsonSchema, type McpServerConfig, type MessageEvent, type ReasoningEvent, type SessionEndEvent, type SessionStartEvent, type StderrEvent, type TextContentPart, type ToolCallEvent, type ToolResultEvent, agentCapabilitiesSchema, baseEventSchema, contentPartSchema, eventSchema, imageContentPartSchema, messageEventSchema, reasoningEventSchema, sessionEndEventSchema, sessionStartEventSchema, stderrEventSchema, textContentPartSchema, toolCallEventSchema, toolResultEventSchema };
|
|
@@ -0,0 +1 @@
|
|
|
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,6 +1,5 @@
|
|
|
1
|
-
import { t as AgentEvent, v as AgentCapabilities, x as JsonSchema, y as ContentPart } from "./events-
|
|
1
|
+
import { t as AgentEvent, v as AgentCapabilities, x as JsonSchema, y as ContentPart } from "./events-BxEB6zHt.mjs";
|
|
2
2
|
import { ZodType } from "zod/v4";
|
|
3
|
-
|
|
4
3
|
//#region src/core/process/types.d.ts
|
|
5
4
|
type StdioOption = "ignore" | "inherit" | "pipe" | number;
|
|
6
5
|
/** POSIX signal name (re-export of `NodeJS.Signals`). */
|
|
@@ -91,10 +90,14 @@ interface PermissionRequest {
|
|
|
91
90
|
* model as the rejection reason.
|
|
92
91
|
*/
|
|
93
92
|
type PermissionDecision = {
|
|
94
|
-
/** Approve the tool call. */
|
|
93
|
+
/** Approve the tool call. */
|
|
94
|
+
decision: "allow";
|
|
95
|
+
/** Optional rewritten tool input; overrides {@link PermissionRequest.input}. */
|
|
95
96
|
updatedInput?: Record<string, unknown>;
|
|
96
97
|
} | {
|
|
97
|
-
/** Reject the tool call. */
|
|
98
|
+
/** Reject the tool call. */
|
|
99
|
+
decision: "deny";
|
|
100
|
+
/** Rejection reason sent back to the model. */
|
|
98
101
|
message?: string;
|
|
99
102
|
};
|
|
100
103
|
/**
|
|
@@ -135,6 +138,17 @@ type StopReason = "abort" | "timeout" | "user";
|
|
|
135
138
|
* optional because providers differ — Claude reports caching tokens, Codex
|
|
136
139
|
* reports reasoning tokens, others may report nothing beyond `turns` and
|
|
137
140
|
* `costUsd`.
|
|
141
|
+
*
|
|
142
|
+
* The token classes are disjoint: a token counted in `inputTokens` is never also counted in
|
|
143
|
+
* `cacheCreationInputTokens` or `cacheReadInputTokens`, so
|
|
144
|
+
* `inputTokens + cacheCreationInputTokens + cacheReadInputTokens + outputTokens` equals
|
|
145
|
+
* `totalTokens` for every adapter that reports them. Providers disagree upstream — Anthropic bills
|
|
146
|
+
* the cache classes separately from `input_tokens` while OpenAI nests them inside it — so adapters
|
|
147
|
+
* normalize to this layout rather than passing provider fields through.
|
|
148
|
+
*
|
|
149
|
+
* `reasoningOutputTokens` is the one exception: it is a breakdown of `outputTokens` rather than a
|
|
150
|
+
* class of its own, so it is already counted in both `outputTokens` and `totalTokens` and must not
|
|
151
|
+
* be added to either.
|
|
138
152
|
*/
|
|
139
153
|
interface RunStats {
|
|
140
154
|
/** Wall-clock duration of the run as reported by the provider, in milliseconds. */
|
|
@@ -145,7 +159,7 @@ interface RunStats {
|
|
|
145
159
|
turns: number;
|
|
146
160
|
/** Provider-reported cost in USD; `0` if the provider does not report cost. */
|
|
147
161
|
costUsd: number;
|
|
148
|
-
/** Input tokens billed
|
|
162
|
+
/** Input tokens billed at the full rate, excluding both cache-read and cache-write tokens. */
|
|
149
163
|
inputTokens?: number;
|
|
150
164
|
/** Tokens written to the provider's prompt cache during this run. */
|
|
151
165
|
cacheCreationInputTokens?: number;
|
|
@@ -153,7 +167,9 @@ interface RunStats {
|
|
|
153
167
|
cacheReadInputTokens?: number;
|
|
154
168
|
/** Output tokens generated by the model. */
|
|
155
169
|
outputTokens?: number;
|
|
156
|
-
/**
|
|
170
|
+
/** Reasoning/thinking tokens spent producing the output; already included in `outputTokens`. */
|
|
171
|
+
reasoningOutputTokens?: number;
|
|
172
|
+
/** Sum of the disjoint token classes above. */
|
|
157
173
|
totalTokens?: number;
|
|
158
174
|
}
|
|
159
175
|
/**
|
|
@@ -351,7 +367,7 @@ interface AgentMetrics {
|
|
|
351
367
|
/** Timestamp of the most recent emitted event (not updated on plain method calls like `reset`/`dispose`). */
|
|
352
368
|
lastActivityAt: Date;
|
|
353
369
|
}
|
|
354
|
-
type EffectiveKeys<T> = keyof { [K in keyof T as Required<T>[K] extends never ? never : K]: unknown };
|
|
370
|
+
type EffectiveKeys<T> = keyof { [K in keyof T as Required<T>[K] extends never ? never : K]: unknown; };
|
|
355
371
|
/**
|
|
356
372
|
* Compile-time assertion that an adapter's `*RunOptions` shape does not
|
|
357
373
|
* collide with the keys of {@link RunRequest}. Resolves to `T` when disjoint,
|
|
@@ -1 +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
|
|
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};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "coding-agents-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.15.0",
|
|
4
4
|
"description": "Run coding agents (Claude Code, Codex, Cursor, Gemini, OpenCode, Pi — CLI and SDK) behind one uniform TypeScript interface, with optional container and sandbox execution.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"coding-agent",
|
|
@@ -106,22 +106,23 @@
|
|
|
106
106
|
"typecheck": "bun run tsc"
|
|
107
107
|
},
|
|
108
108
|
"devDependencies": {
|
|
109
|
-
"@anthropic-ai/claude-agent-sdk": "^0.3.
|
|
110
|
-
"@cursor/sdk": "^1.0.
|
|
111
|
-
"@openai/codex-sdk": "^0.
|
|
112
|
-
"@types/bun": "^1.
|
|
113
|
-
"@types/node": "^
|
|
114
|
-
"e2b": "^2.
|
|
115
|
-
"knip": "^6.
|
|
116
|
-
"picoprint": "^2.
|
|
117
|
-
"tsdown": "^0.
|
|
109
|
+
"@anthropic-ai/claude-agent-sdk": "^0.3.280",
|
|
110
|
+
"@cursor/sdk": "^1.0.32",
|
|
111
|
+
"@openai/codex-sdk": "^0.156.1",
|
|
112
|
+
"@types/bun": "^1.4.2",
|
|
113
|
+
"@types/node": "^26.6.2",
|
|
114
|
+
"e2b": "^2.51.0",
|
|
115
|
+
"knip": "^6.35.1",
|
|
116
|
+
"picoprint": "^2.2.2",
|
|
117
|
+
"tsdown": "^0.23.0",
|
|
118
|
+
"typescript": "^7.0.2"
|
|
118
119
|
},
|
|
119
120
|
"peerDependencies": {
|
|
120
121
|
"@anthropic-ai/claude-agent-sdk": "^0.3.170",
|
|
121
122
|
"@cursor/sdk": "^1.0.12",
|
|
122
|
-
"@openai/codex-sdk": "
|
|
123
|
-
"e2b": "^2.
|
|
124
|
-
"typescript": "^6.0.3"
|
|
123
|
+
"@openai/codex-sdk": ">=0.150.0 <0.157.0",
|
|
124
|
+
"e2b": "^2.28.0",
|
|
125
|
+
"typescript": "^6.0.3 || ^7.0.0"
|
|
125
126
|
},
|
|
126
127
|
"peerDependenciesMeta": {
|
|
127
128
|
"@anthropic-ai/claude-agent-sdk": {
|
package/dist/Agent-YQZmTatB.mjs
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./util-DcPzh_0u.mjs";import{t}from"./env-Cb8MIvH7.mjs";import{t as n}from"./spawner-BE2hAC0w.mjs";import{a as r,i,n as a,s as o,t as s}from"./classify-error-UZrj89Yi.mjs";import{dirname as c}from"node:path";import{createWriteStream as l,mkdirSync as u}from"node:fs";async function*d(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 f=t=>t.status===`rejected`?e(t.reason):void 0,p=(e,t)=>{if(e.stopReason)return;let n=f(t.processResult);if(n)return{kind:`spawn`,message:n};let i=f(t.stdoutResult);if(i)return{kind:`process`,message:i};let a=f(t.stderrResult);if(a)return{kind:`process`,message:a};if(!e.status&&!e.error){let t=e.processResult,n=e.stderrLines.join(`
|
|
3
|
-
`);if(t&&t.exitCode!==null&&t.exitCode!==0)return{kind:`process`,message:n||`Process exited with code ${t.exitCode}.`};if(!r(e)&&e.stderrLines.length>0)return{kind:`process`,message:n}}},m=e=>{let t=s(e);return t.kind===`provider`?{kind:`process`,message:t.message}:t};var h=class extends a{spawner;defaults;executionTargetRef;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,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=p(t,{stdoutResult:s,stderrResult:c,processResult:l});u&&(t.error=u)}catch(e){!t.stopReason&&!t.error&&(t.error=m(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 d(t))this.appendLog(`stdout`,n),this.processLine(e,n)}async watchStderr(e){let t=e.process?.stderr;if(t)for await(let n of d(t))this.appendLog(`stderr`,n),e.stderrLines.push(n),this.emit(e,o(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,i(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(){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{u(c(e),{recursive:!0}),this.logStream=l(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.executionTargetRef&&this.executionTargetRef.status!==`running`&&await this.executionTargetRef.start()}};export{h as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as e,t}from"./classify-error-UZrj89Yi.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,new Date):(e.sessionId&&this.emitSessionStart(e),await this.executeSdkRun(e,n,r),this.buildResult(e,new Date))}catch(n){return!e.stopReason&&!e.error&&(e.error=t(n)),this.buildResult(e,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: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=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:new Date,requestedSessionId:this._sessionId,sessionId:this._sessionId,normalizedRequest:n,events:[],stderrLines:[],assistantTexts:[],toolCalls: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++;break;default:break}}};const T=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{t as e}from"./util-DcPzh_0u.mjs";import{c as t,i as n,n as r,r as i,s as a}from"./container-D5P0tyx7.mjs";import{t as o}from"./shell-DvWFuFKb.mjs";import{n as s}from"./diff-ByicTI7l.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 r(`E2B create failed: ${e(t)}`)}let l=o.name??c.sandboxId,d=`running`,p=k(c,o),m={},h=()=>{if(d===`disposed`)throw new n},g=()=>{if(h(),d!==`running`)throw new a},_=s({owner:m,workdir:o.workdir,materialize:async(e,t)=>{g();let n=x(o),r=await R(c,e,n);if(!r)throw new i(`Target path does not exist: ${e}`);if(r.type!==v.DIR)throw new i(`Target path is not a directory: ${e}`);await f(t,{recursive:!0});for(let r of await c.files.list(e,{user:n}))await H(c,r.path,u(t,r.name),n)}}),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(n){throw new t(`E2B start failed: ${e(n)}`)}},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};
|
package/dist/diff-ByicTI7l.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./util-DcPzh_0u.mjs";import{i as t,r as n,s as r}from"./container-D5P0tyx7.mjs";import{execFile as i}from"node:child_process";import{dirname as a,isAbsolute as o,join as s,posix as c,relative as l,sep as u}from"node:path";import{promisify as d}from"node:util";import{createReadStream as f}from"node:fs";import{tmpdir as p}from"node:os";import{copyFile as m,lstat as h,mkdir as g,mkdtemp as _,readdir as v,readlink as y,rm as b,stat as x,symlink as S}from"node:fs/promises";import{createHash as C}from"node:crypto";import{pipeline as w}from"node:stream/promises";const T=e=>e instanceof Error&&`code`in e&&(`stdout`in e||`stderr`in e),E=d(i),D=e=>e!==`..`&&!e.startsWith(`..${u}`)&&!o(e),O=(e,t)=>{let n=l(e,t);if(D(n))return n.split(u).join(c.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 v(e,{withFileTypes:!0});for(let n of t){let t=s(e,n.name);if(n.name===`.git`){await b(t,{recursive:!0,force:!0});continue}n.isDirectory()&&await j(t)}},M=()=>_(s(p(),`cw-workdir-diff-`)),N=async e=>{e&&await b(e,{recursive:!0,force:!0}).catch(()=>{})},P=(e,t)=>{let n={cwd:e.cwd,createdAt: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=>C(`sha256`).update(e).digest(`hex`),R=e=>Buffer.isBuffer(e)?e:Buffer.from(e,`utf8`),z=async e=>{let t=C(`sha256`);return await w(f(e),t),t.digest(`hex`)},B=async(e,t,r)=>{let i=`${e}:${t}`;if(r.has(i))return r.get(i);let a=s(e,...t.split(c.sep));try{let e=await h(a),t,o;if(e.isSymbolicLink()){let e=Buffer.from(await y(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{return V(R((await E(`git`,[`diff`,`--no-index`,`-z`,`--name-status`,`-M`,`--find-renames=100%`,t,r],{cwd:p(),encoding:`buffer`,maxBuffer:50*1024*1024})).stdout),t,r)}catch(i){if(!T(i))throw new n(`Failed to run git diff: ${e(i)}`);let a=i.code??1,o=Buffer.isBuffer(i.stdout)?i.stdout:Buffer.from(String(i.stdout??``),`utf8`),s=Buffer.isBuffer(i.stderr)?i.stderr:Buffer.from(String(i.stderr??``),`utf8`);if(a===0||a===1)return V(o,t,r);throw new n(`Failed to run git diff: ${s.toString(`utf8`).trim()||o.toString(`utf8`).trim()||`exit code ${a}`}`)}},U=async(e,t,n)=>{let r=new Map;return A(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}})))},W=e=>{let t=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 x(e)).isDirectory())throw new n(`Target path is not a directory: ${e}`);await g(t,{recursive:!0});let r=await v(e,{withFileTypes:!0});await Promise.all(r.filter(e=>e.name!==`.git`).map(async r=>{let i=s(e,r.name),o=s(t,r.name);if(r.isDirectory()){await K(i,o);return}if(r.isSymbolicLink()){await g(a(o),{recursive:!0}),await S(await y(i),o);return}if(r.isFile()){await g(a(o),{recursive:!0}),await m(i,o);return}throw new n(`Unsupported filesystem entry in workdir diff: ${i}`)}))},q=e=>{let t=new Set,n=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 U(await H(a.tempDir,o),a.tempDir,o),n=W(t);return{cwd:a.cwd,changedFiles:n,fileChanges:t,stats:{durationMs:Date.now()-i,filesCompared:n.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=>{await a(F(e.owner,t,n))},disposeSnapshots:async()=>{await Promise.all(Array.from(t).map(a))}}};export{q as n,T as r,K as t};
|
package/dist/oci-FTrEF0I6.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./util-DcPzh_0u.mjs";import{c as t,i as n,l as r,n as i,o as a,r as o,s}from"./container-D5P0tyx7.mjs";import{n as c}from"./env-Cb8MIvH7.mjs";import{t as l}from"./spawner-BE2hAC0w.mjs";import{t as u}from"./shell-DvWFuFKb.mjs";import{n as d,r as f,t as p}from"./diff-ByicTI7l.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:50*1024*1024});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=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),l.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=new Map,U=()=>{if(V===`disposed`)throw new n},W=()=>{if(U(),V!==`running`)throw new s},G=I(B,h),K=d({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 ${u(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(f(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 ${u(i)} && cat > ${u(r)}`);let c=l.spawn(h.binary,j(h,s),{env:M(h),stdio:[`pipe`,`ignore`,`ignore`]});try{c.stdin?.write?.(o),c.stdin?.end()}catch(t){throw c.kill(),c.wait().catch(()=>{}),new a(`writeFile failed for ${r}: ${e(t)}`)}let d=await c.wait();if(d.exitCode!==0)throw new a(`writeFile failed for ${r} (exit ${d.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};
|
package/dist/parser-CfDBEv7A.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{i as e}from"./util-DcPzh_0u.mjs";import{c as t,s as n,u as r}from"./classify-error-UZrj89Yi.mjs";import{t as i}from"./structured-output-BeZPb2QW.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}));break;default:break}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}default: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({type:a.literal(`system`),session_id:a.string(),subtype:h,uuid:a.string(),tools:a.array(a.string()).optional(),mcp_servers:a.array(a.object({name:a.string(),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()}),_=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()})}),v=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()}),y=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()}),b=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()})}),x=t(a.discriminatedUnion(`type`,[g,_,v,y,b]));export{o as n,m as r,x as t};
|