coding-agents-sdk 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +46 -0
  2. package/dist/Agent-BjaeRtLk.mjs +4 -0
  3. package/dist/adapters/claude-code-cli/index.d.mts +2 -2
  4. package/dist/adapters/claude-code-cli/index.mjs +1 -1
  5. package/dist/adapters/claude-code-cli-pty/index.d.mts +2 -2
  6. package/dist/adapters/claude-code-cli-pty/index.mjs +2 -2
  7. package/dist/adapters/claude-code-sdk/index.d.mts +1 -1
  8. package/dist/adapters/codex-cli/index.d.mts +2 -2
  9. package/dist/adapters/codex-cli/index.mjs +2 -2
  10. package/dist/adapters/codex-sdk/index.d.mts +1 -1
  11. package/dist/adapters/cursor-cli/index.d.mts +1 -1
  12. package/dist/adapters/cursor-cli/index.mjs +1 -1
  13. package/dist/adapters/cursor-sdk/index.d.mts +1 -1
  14. package/dist/adapters/gemini-cli/index.d.mts +1 -1
  15. package/dist/adapters/gemini-cli/index.mjs +1 -1
  16. package/dist/adapters/opencode-cli/index.d.mts +1 -1
  17. package/dist/adapters/opencode-cli/index.mjs +1 -1
  18. package/dist/adapters/pi-cli/index.d.mts +1 -1
  19. package/dist/adapters/pi-cli/index.mjs +1 -1
  20. package/dist/container/index.d.mts +1 -1
  21. package/dist/container/index.mjs +1 -1
  22. package/dist/{container-B2i85Vkf.mjs → container-Bdb90GJb.mjs} +1 -1
  23. package/dist/{container-Dk4QgU9G.mjs → container-DMFxf-kn.mjs} +1 -1
  24. package/dist/{container-CbvaYn8K.mjs → container-Dvr-p53c.mjs} +1 -1
  25. package/dist/{container-BwDinlQ1.mjs → container-dCRMBvQw.mjs} +1 -1
  26. package/dist/container-w0rl1QMH.mjs +1 -0
  27. package/dist/core/process/index.d.mts +3 -0
  28. package/dist/core/process/index.mjs +1 -0
  29. package/dist/diff-Dqyk2cdt.mjs +1 -0
  30. package/dist/errors-aYGbvsaq.mjs +1 -0
  31. package/dist/index-65Dv7ed0.d.mts +415 -0
  32. package/dist/{index-gtpzhLCF.d.mts → index-BbZPkmE-.d.mts} +4 -3
  33. package/dist/{index-C09YdI2A.d.mts → index-Bi9Dh34t.d.mts} +4 -4
  34. package/dist/{index-D3yvIIre.d.mts → index-BiUoRRsR.d.mts} +4 -3
  35. package/dist/{index-CT-rhJzK.d.mts → index-CN0WGc9T.d.mts} +3 -2
  36. package/dist/{index-BXgvYZSv.d.mts → index-CQzF8Cli.d.mts} +1 -1
  37. package/dist/{index-CGGPY1qE.d.mts → index-CZbgTv8P.d.mts} +1 -1
  38. package/dist/{index-Dm9HCmWK.d.mts → index-CjjUmMwQ.d.mts} +1 -1
  39. package/dist/{index-DGY0wFGC.d.mts → index-CyIiBK-O.d.mts} +130 -4
  40. package/dist/{index-D_qqPXPO.d.mts → index-DmpVdnKm.d.mts} +4 -3
  41. package/dist/index-DvwVRB7K.d.mts +10 -0
  42. package/dist/{index-WaVqMCYN.d.mts → index-kXfBtyJn.d.mts} +2 -1
  43. package/dist/{index-BkIhoEPd.d.mts → index-m5Pqs8Jz.d.mts} +4 -3
  44. package/dist/index.d.mts +16 -14
  45. package/dist/index.mjs +1 -1
  46. package/dist/oci-DTNwW-WH.mjs +1 -0
  47. package/dist/{parser-15-5gbtk.mjs → parser-C1kvDtRD.mjs} +1 -1
  48. package/dist/sandbox/index.d.mts +1 -1
  49. package/dist/sandbox/index.mjs +1 -1
  50. package/dist/{sandbox-CoV-gBuM.mjs → sandbox-CYA69miM.mjs} +1 -1
  51. package/dist/spawner-CgfyvnR4.mjs +1 -0
  52. package/dist/{types-CeIQCAFV.d.mts → types-Ba2NYJOB.d.mts} +10 -57
  53. package/dist/types-COmjfh8B.d.mts +57 -0
  54. package/package.json +5 -1
  55. package/dist/Agent-mSH_-Sf8.mjs +0 -4
  56. package/dist/container-DfDs2Bmh.mjs +0 -1
  57. package/dist/diff-C60ujrU_.mjs +0 -1
  58. package/dist/index-fZiuDQFa.d.mts +0 -154
  59. package/dist/oci-BvdPJQRS.mjs +0 -1
  60. package/dist/spawner-BE2hAC0w.mjs +0 -1
@@ -0,0 +1,10 @@
1
+ import { a as SpawnOptions, t as AgentProcess } from "./types-COmjfh8B.mjs";
2
+ //#region src/core/process/spawner.d.ts
3
+ declare const spawnProcess: (command: string, args: string[], options?: SpawnOptions) => AgentProcess;
4
+ //#endregion
5
+ //#region src/core/process/errors.d.ts
6
+ declare class ProcessStdinError extends Error {
7
+ constructor(cause: unknown);
8
+ }
9
+ //#endregion
10
+ export { spawnProcess as n, ProcessStdinError as t };
@@ -1,4 +1,5 @@
1
- import { k as ProcessSpawner } from "./types-CeIQCAFV.mjs";
1
+ import { i as ProcessSpawner } from "./types-COmjfh8B.mjs";
2
+ import "./types-Ba2NYJOB.mjs";
2
3
  //#region src/container/types.d.ts
3
4
  /** Which provider backs a container. Selects which CLI/SDK the adapter speaks. */
4
5
  type ContainerType = "docker" | "e2b" | "nerdctl" | "podman";
@@ -1,6 +1,7 @@
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";
1
+ import { i as ProcessSpawner } from "./types-COmjfh8B.mjs";
2
+ import { f as EnsureDisjoint, l as BaseAgent, p as ExclusiveExecutionTargetOptions, t as AgentEventHandler } from "./types-Ba2NYJOB.mjs";
3
+ import { t as Container } from "./index-kXfBtyJn.mjs";
4
+ import { l as Sandbox } from "./index-CN0WGc9T.mjs";
4
5
  import { z } from "zod/v4";
5
6
  //#region src/adapters/cursor-cli/events/schemas.d.ts
6
7
  /**
package/dist/index.d.mts CHANGED
@@ -1,17 +1,19 @@
1
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";
2
+ import { a as SpawnOptions, i as ProcessSpawner, n as ProcessResult, r as ProcessSignal, t as AgentProcess } from "./types-COmjfh8B.mjs";
3
+ import { A as PermissionRequest, C as RunStatus, D as ZodRunRequest, E as StructuredRunRequest, O as PermissionDecision, S as RunStats, T as StopReason, _ as ProviderEventHandler, a as AgentValidationError, b as RunRequest, c as AnyRunResult, d as CompletedRunResult, g as ProviderEvent, h as JsonSchemaRunRequest, i as AgentType, k as PermissionHandler, 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 RunError, w as RunTiming, x as RunResult, y as RunProcessInfo } from "./types-Ba2NYJOB.mjs";
4
+ 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-kXfBtyJn.mjs";
5
+ 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-CN0WGc9T.mjs";
6
+ import { a as ClaudeCodeCliRunOptions, c as ClaudeProviderEvent, d as ClaudeSystemEvent, f as ClaudeUserEvent, i as ClaudeCodeCliPermissionMode, l as ClaudeRateLimitEvent, n as ClaudeCodeCliAgent, o as ClaudeAssistantEvent, r as ClaudeCodeCliAgentOptions, s as ClaudeEvent, u as ClaudeResultEvent } from "./index-CyIiBK-O.mjs";
7
+ import { a as ClaudeCodeCliPtyPermissionMode, i as ClaudeCodeCliPtyModule, n as ClaudeCodeCliPtyAgent, o as ClaudeCodeCliPtyProcess, r as ClaudeCodeCliPtyAgentOptions, s as ClaudeCodeCliPtyRunOptions } from "./index-Bi9Dh34t.mjs";
8
+ 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-CjjUmMwQ.mjs";
9
+ import { a as CodexCliRunOptions, c as CodexEvent, d as CodexItemUpdatedEvent, f as CodexProviderEvent, g as CodexTurnFailedEvent, h as CodexTurnCompletedEvent, i as CodexCliPermissionMode, l as CodexItemCompletedEvent, m as CodexThreadStartedEvent, n as CodexCliAgent, o as CodexCliSandboxMode, p as CodexProviderItem, r as CodexCliAgentOptions, s as CodexErrorEvent, u as CodexItemStartedEvent } from "./index-65Dv7ed0.mjs";
10
+ import { a as CodexSdkItem, i as CodexSdkEvent, n as CodexSdkAgent, o as CodexSdkPermissionMode, r as CodexSdkAgentOptions, s as CodexSdkRunOptions } from "./index-CQzF8Cli.mjs";
11
+ import { a as CursorCliRunOptions, i as CursorCliPermissionMode, n as CursorCliAgent, o as CursorCliSandboxMode, r as CursorCliAgentOptions, s as CursorCliEvent } from "./index-m5Pqs8Jz.mjs";
12
+ import { a as CursorSdkMcpHttpAuth, c as CursorSdkSettingSource, i as CursorSdkEvent, n as CursorSdkAgent, o as CursorSdkMcpServerConfig, r as CursorSdkAgentOptions, s as CursorSdkRunOptions } from "./index-CZbgTv8P.mjs";
13
+ import { a as GeminiCliRunOptions, i as GeminiCliPermissionMode, n as GeminiCliAgent, o as GeminiEvent, r as GeminiCliAgentOptions } from "./index-BbZPkmE-.mjs";
14
+ import { a as OpencodeEvent, i as OpencodeCliRunOptions, n as OpencodeCliAgent, r as OpencodeCliAgentOptions } from "./index-DmpVdnKm.mjs";
15
+ import { a as PiCliThinkingLevel, i as PiCliRunOptions, n as PiCliAgent, o as PiEvent, r as PiCliAgentOptions } from "./index-BiUoRRsR.mjs";
16
+ import { n as spawnProcess, t as ProcessStdinError } from "./index-DvwVRB7K.mjs";
15
17
  import "./schemas/index.mjs";
16
18
  //#region src/core/agent/create-agent.d.ts
17
19
  interface AgentOptionsByType {
@@ -78,4 +80,4 @@ export declare function createAgent(type: "opencode-cli", options?: OpencodeCliA
78
80
  export declare function createAgent(type: "pi-cli", options?: PiCliAgentOptions): Promise<PiCliAgent>;
79
81
  export declare function createAgent<T extends AgentType>(type: T, options?: AgentOptionsByType[T]): Promise<AgentInstanceByType[T]>;
80
82
  //#endregion
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 };
83
+ export { type AgentCapabilities, type AgentEvent, type AgentEventHandler, type AgentMetrics, type AgentProcess, 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 ClaudeProviderEvent, 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 CodexProviderEvent, type CodexProviderItem, 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 ProcessResult, type ProcessSignal, type ProcessSpawner, ProcessStdinError, type ProviderEvent, type ProviderEventHandler, 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 SpawnOptions, 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, spawnProcess };
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-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};
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-DMFxf-kn.mjs";import{t as d}from"./errors-aYGbvsaq.mjs";import{n as f}from"./spawner-CgfyvnR4.mjs";import{n as p,t as m}from"./sandbox-CYA69miM.mjs";import"./core/process/index.mjs";import{n as h,u as g}from"./schemas-CkdQXAep.mjs";const _=(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`},v=(t,n,r)=>{throw _(r,n)?new e(`Agent type "${t}" requires the optional peer dependency "${n}". Install it to use this adapter.`):r};async function y(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 v(`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 v(`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 v(`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,d as ProcessStdinError,m as SandboxCreateError,g as agentCapabilitiesSchema,y as createAgent,u as createContainer,p as createSandbox,h as eventSchema,f as spawnProcess};
@@ -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-DMFxf-kn.mjs";import{n as c}from"./env-Cb8MIvH7.mjs";import{n as l}from"./errors-aYGbvsaq.mjs";import{t as u}from"./spawner-CgfyvnR4.mjs";import{t as d}from"./shell-DvWFuFKb.mjs";import{n as f,t as p}from"./diff-Dqyk2cdt.mjs";import{execFile as m}from"node:child_process";import{isAbsolute as h,join as g,posix as _,resolve as v}from"node:path";import{promisify as y}from"node:util";import{existsSync as b}from"node:fs";import{tmpdir as x}from"node:os";import{mkdtemp as S,rm as C,writeFile as w}from"node:fs/promises";import{randomBytes as T}from"node:crypto";const E=(e,t)=>{let n=_.relative(e,t);return n===``||!n.startsWith(`..`)&&!_.isAbsolute(n)},D=(e,t)=>{if(!e||e.length===0)return;let n=_.normalize(t),r;for(let t of e){if(!h(t.source))continue;let e=_.normalize(t.target);E(e,n)&&(!r||e.length>_.normalize(r.target).length)&&(r=t)}if(!r)return;let i=_.relative(_.normalize(r.target),n);return i===``?r.source:_.join(r.source,...i.split(`/`))},O=(e,t)=>{let n=h(e.source)?e.source:v(t.cwd,e.source);if(!b(n))throw new r(`Mount source does not exist: ${n}`);return{...e,source:n}},k=y(m),A=()=>`cw-${T(6).toString(`hex`)}`,j=(e,t)=>e.baseArgs?[...e.baseArgs,...t]:t,M=e=>{if(e.env)return{...c(),...e.env}},N=async(e,t,n)=>{let r=await k(e.binary,j(e,t),{encoding:`utf8`,env:M(e),timeout:n?.timeoutMs,signal:n?.signal,maxBuffer:52428800});return{stdout:r.stdout,stderr:r.stderr}},P=async(t,n)=>{let r=n.tag??`cw-build-${T(4).toString(`hex`)}`,a=[`build`,`-t`,r];if(n.args)for(let[e,t]of Object.entries(n.args))a.push(`--build-arg`,`${e}=${t}`);`dockerfile`in n&&n.dockerfile&&(a.push(`-f`,n.dockerfile),a.push(n.context??`.`));let o;if(`content`in n&&n.content){o=await S(g(x(),`cw-oci-build-`));let e=g(o,`Dockerfile`);await w(e,n.content,{encoding:`utf8`,mode:384}),a.push(`-f`,e),a.push(n.context??o)}try{await N(t,a)}catch(t){throw new i(`Image build failed: ${e(t)}`)}finally{o&&await C(o,{recursive:!0,force:!0}).catch(()=>{})}return r},F=async(e,t,n)=>{let r=await Promise.all(n.map(async n=>{try{let{container:r,protocol:i=`tcp`}=n,{stdout:a}=await N(e,[`port`,t,`${r}/${i}`]),o=/:(\d+)$/m.exec(a.trim());if(o?.[1])return[r,Number(o[1])]}catch{}})),i=/* @__PURE__ */ new Map;for(let e of r)e&&i.set(e[0],e[1]);return i},I=(e,t)=>({spawn:(n,r,i={})=>{let a=[`exec`,`-i`];if(i.cwd&&a.push(`-w`,i.cwd),i.env)for(let[e,t]of Object.entries(i.env))a.push(`-e`,`${e}=${t}`);return a.push(e,n,...r),u.spawn(t.binary,j(t,a),{env:M(t),stdio:i.stdio})}}),L=async(r,c,m)=>{let{commandContext:h,builtImage:g,containerName:v,workdir:y,user:b,network:x,platform:S,env:C,ports:w,mounts:T,mountCwd:E,extraArgs:k,image:P}=c,L=v??A(),R=T?.map(e=>O(e,{cwd:E??process.cwd()})),z=[`create`,`--name`,L];if(b&&z.push(`--user`,b),x&&z.push(`--network`,x),S&&z.push(`--platform`,S),C)for(let[e,t]of Object.entries(C))z.push(`-e`,`${e}=${t}`);if(w)for(let e of w){let{host:t,container:n,protocol:r=`tcp`}=e;z.push(`-p`,`${t??``}:${n}/${r}`)}if(R)for(let e of R){let{readonly:t,source:n,target:r}=e,i=t?`ro`:`rw`;z.push(`-v`,`${n}:${r}:${i}`)}k&&z.push(...k),z.push(P,`sleep`,`infinity`);let B;try{let{stdout:e}=await N(h,z);B=e.trim()}catch(t){throw new i(`Container create failed: ${e(t)}`)}let V=`created`,H=/* @__PURE__ */ new Map,U=()=>{if(V===`disposed`)throw new n},W=()=>{if(U(),V!==`running`)throw new s},G=I(B,h),K=f({owner:{},workdir:y,materialize:async(t,n)=>{U();let r=D(R,t);if(r){await p(r,n);return}W();try{await N(h,[`exec`,B,`sh`,`-c`,`test -d ${d(t)}`])}catch{throw new o(`Target path is not a directory: ${t}`)}try{await N(h,[`cp`,`${B}:${t}/.`,n])}catch(n){throw new o(`Failed to materialize container path ${t}: ${e(n)}`)}}}),q={get type(){return r},get id(){return B},get name(){return L},get config(){return m},get status(){return V},get workdir(){return y},get spawner(){return G},async start(){if(U(),V!==`running`){try{await N(h,[`start`,B])}catch(n){throw new t(`Container start failed: ${e(n)}`)}try{await N(h,[`exec`,B,`mkdir`,`-p`,y])}catch(n){try{await N(h,[`stop`,`-t`,`0`,B]),V=`stopped`}catch{try{let{stdout:e}=await N(h,[`inspect`,`--format`,`{{.State.Status}}`,B]);V=e.trim()===`running`?`running`:`stopped`}catch{V=`disposed`}}throw new t(`Container start failed: ${e(n)}`)}V=`running`,w?.length&&(H=await F(h,B,w))}},async stop(){if(U(),V===`running`){try{await N(h,[`stop`,`-t`,`2`,B])}catch{try{let{stdout:e}=await N(h,[`inspect`,`--format`,`{{.State.Status}}`,B]);if(e.trim()===`running`)return}catch{V=`disposed`;return}}V=`stopped`}},async dispose(){if(V!==`disposed`){try{await N(h,[`stop`,`-t`,`0`,B])}catch{}try{await N(h,[`rm`,`-f`,B])}catch{}g&&await N(h,[`rmi`,P]).catch(()=>{}),await K.disposeSnapshots().catch(()=>{}),V=`disposed`}},async exec(e,t,n={}){W();let r=[`exec`];if(n.cwd&&r.push(`-w`,n.cwd),n.env)for(let[e,t]of Object.entries(n.env))r.push(`-e`,`${e}=${t}`);r.push(B,e,...t);try{let{stdout:e,stderr:t}=await N(h,r,{timeoutMs:n.timeoutMs,signal:n.signal});return{exitCode:0,stdout:e,stderr:t}}catch(e){if(l(e))return{exitCode:typeof e.code==`number`?e.code:-1,stdout:String(e.stdout??``),stderr:String(e.stderr??``)};throw e}},async copyTo(e,t){W(),await N(h,[`cp`,e,`${B}:${t}`])},async copyFrom(e,t){W(),await N(h,[`cp`,`${B}:${e}`,t])},async writeFile(t,n){W();let r=_.isAbsolute(t)?t:_.resolve(y,t),i=_.dirname(r),o=typeof n==`string`?Buffer.from(n,`utf8`):n,s=[`exec`,`-i`];b&&s.push(`--user`,b),s.push(B,`sh`,`-c`,`mkdir -p ${d(i)} && cat > ${d(r)}`);let c=u.spawn(h.binary,j(h,s),{env:M(h),stdio:[`pipe`,`ignore`,`ignore`]}),l;try{c.stdin?.write?.(o),c.stdin?.end(),l=await c.wait()}catch(t){throw c.kill(),c.wait().catch(()=>{}),new a(`writeFile failed for ${r}: ${e(t)}`)}if(l.exitCode!==0)throw new a(`writeFile failed for ${r} (exit ${l.exitCode})`)},async readFile(e){W();let t=_.isAbsolute(e)?e:_.resolve(y,e),{stdout:n}=await N(h,[`exec`,B,`cat`,t]);return n},async fileExists(e){W();let t=_.isAbsolute(e)?e:_.resolve(y,e);try{return await N(h,[`exec`,B,`test`,`-e`,t]),!0}catch{return!1}},async mkdir(e){W();let t=_.isAbsolute(e)?e:_.resolve(y,e);await N(h,[`exec`,B,`mkdir`,`-p`,t])},async execShell(e,t={}){return q.exec(`sh`,[`-c`,e],t)},async logs(e={}){U();let t=[`logs`];e.tail!==void 0&&t.push(`--tail`,String(e.tail)),t.push(B);let{stdout:n}=await N(h,t);return n},async syncStatus(){U();try{let{stdout:e}=await N(h,[`inspect`,`--format`,`{{.State.Status}}`,B]),t=e.trim();V=t===`running`?`running`:t===`created`?`created`:`stopped`}catch{V=`disposed`}return V},async snapshotWorkdir(e={}){return K.snapshotWorkdir(e)},async diffWorkdir(e){return K.diffWorkdir(e)},async releaseWorkdirSnapshot(e){return K.releaseWorkdirSnapshot(e)},getMappedPort(e){return H.get(e)},[Symbol.asyncDispose](){return q.dispose()}};return q},R=async(e,t)=>{if(t.image)return t.image;if(t.build)return P(e,t.build);throw new i(`Either image or build must be provided.`)};export{R as n,L as t};
@@ -1,2 +1,2 @@
1
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};
2
+ `),c=e=>typeof e.result==`string`&&e.result.trim()!==``?e.result:e.subtype,l=(e,t)=>{let i=[`[${e.subtype}]`];if(e.subtype===`init`){if(e.tools&&i.push(`tools: ${e.tools.length}`),e.mcp_servers){let t=e.mcp_servers.filter(e=>e.status===`connected`).length;i.push(`mcp: ${t}/${e.mcp_servers.length} connected`)}}else e.hook_name&&(i.push(e.hook_name),e.exit_code!==void 0&&i.push(`exit: ${e.exit_code}`));let a=i.join(` `);return{events:[n(t.runId,`message`,{sessionId:t.sessionId,model:e.model??null,role:`system`,content:[r(a)],text:a})]}},u=(e,t)=>{let i=[],a=[];for(let o of e.message.content)switch(o.type){case`text`:i.push(n(t.runId,`message`,{sessionId:t.sessionId,model:e.message.model??null,role:`assistant`,content:[r(o.text)],text:o.text}));break;case`thinking`:i.push(n(t.runId,`reasoning`,{sessionId:t.sessionId,model:e.message.model??null,content:[r(o.thinking)],text:o.thinking}));break;case`tool_use`:a.push({toolCallId:o.id,toolName:o.name,input:o.input}),i.push(n(t.runId,`tool-call`,{sessionId:t.sessionId,model:e.message.model??null,toolCallId:o.id,toolName:o.name,input:o.input}))}return{events:i,toolCalls:a}},d=(e,t)=>{let i=[];for(let a of e.message.content)switch(a.type){case`text`:i.push(n(t.runId,`message`,{sessionId:t.sessionId,model:null,role:`user`,content:[r(a.text)],text:a.text}));break;case`tool_result`:{let e=t.toolCalls.get(a.tool_use_id),r=s(a);i.push(n(t.runId,`tool-result`,{sessionId:t.sessionId,toolCallId:a.tool_use_id,toolName:e?.toolName,input:e?.input,output:r,isError:a.is_error,error:a.is_error?r:void 0}));break}}return{events:i}},f=(t,n)=>{let r=t.usage?.input_tokens,a=t.usage?.cache_creation_input_tokens,o=t.usage?.cache_read_input_tokens,s=t.usage?.output_tokens,l=e(r,a,o,s),u={stats:{durationMs:t.duration_ms,apiDurationMs:t.duration_api_ms,turns:t.num_turns,inputTokens:r,cacheCreationInputTokens:a,cacheReadInputTokens:o,outputTokens:s,totalTokens:l,costUsd:t.total_cost_usd}};typeof t.result==`string`&&(u.output={...u.output,text:t.result});let d=!t.is_error&&t.subtype===`success`,f=i(t.structured_output,{schemaRequested:n.schemaRequested,toolCalls:n.toolCalls,allowToolCallFallback:!1},{isSuccess:d},`Structured output was requested but Claude did not return structured_output.`);return f.value!==void 0&&(u.output={...u.output,value:f.value}),f.error&&(u.status=`failed`,u.error=f.error),t.is_error||t.subtype!==`success`?(u.status=`failed`,u.error={kind:`provider`,message:c(t)}):u.error||(u.status=`completed`),{events:[],state:u}},p=(e,t)=>{let i=`rate limited: ${e.rate_limit_info.status}`;return{events:[n(t.runId,`message`,{sessionId:t.sessionId,model:null,role:`system`,content:[r(i)],text:i})]}},m=(e,t)=>{switch(e.type){case`system`:return l(e,t);case`assistant`:return u(e,t);case`user`:return d(e,t);case`result`:return f(e,t);case`rate_limit_event`:return p(e,t);default:return{events:[]}}},h=a.enum([`init`,`hook_response`,`hook_started`,`hook_finished`,`hook_failed`,`hook_skipped`]),g=a.object({name:a.string(),status:a.string()}),_=a.object({type:a.literal(`system`),session_id:a.string(),subtype:h,uuid:a.string(),tools:a.array(a.string()).optional(),mcp_servers:a.array(g.extend({status:a.enum([`connected`,`disconnected`,`error`,`failed`])})).optional(),model:a.string().optional(),cwd:a.string().optional(),hook_name:a.string().optional(),hook_event:a.string().optional(),stdout:a.string().optional(),stderr:a.string().optional(),exit_code:a.number().optional()}),v=a.object({type:a.literal(`assistant`),session_id:a.string(),uuid:a.string(),parent_tool_use_id:a.string().nullable().optional(),message:a.object({id:a.string(),type:a.literal(`message`),role:a.literal(`assistant`),model:a.string(),content:a.array(a.union([a.object({type:a.literal(`text`),text:a.string()}),a.object({type:a.literal(`tool_use`),id:a.string(),name:a.string(),input:a.record(a.string(),a.unknown())}),a.object({type:a.literal(`thinking`),thinking:a.string(),signature:a.string().optional()})])),stop_reason:a.enum([`end_turn`,`max_tokens`,`tool_use`,`stop_sequence`]).nullable(),stop_sequence:a.string().nullable().optional(),context_management:a.unknown().nullable().optional(),usage:a.object({input_tokens:a.number(),output_tokens:a.number(),cache_creation_input_tokens:a.number().optional(),cache_read_input_tokens:a.number().optional(),service_tier:a.enum([`premium`,`standard`]).nullable().optional()}),ttftMs:a.number().optional()})}),y=a.object({type:a.literal(`user`),session_id:a.string(),message:a.object({role:a.literal(`user`),content:a.array(a.union([a.object({type:a.literal(`tool_result`),tool_use_id:a.string(),content:a.union([a.string(),a.array(a.object({type:a.literal(`text`),text:a.string()}))]),is_error:a.boolean().optional()}),a.object({type:a.literal(`text`),text:a.string()})]))}),parent_tool_use_id:a.string().nullable().optional(),uuid:a.string(),isSynthetic:a.boolean().optional()}),b=a.object({type:a.literal(`result`),session_id:a.string(),uuid:a.string(),subtype:a.enum([`success`,`error_max_turns`,`error_during_execution`]),duration_ms:a.number(),duration_api_ms:a.number(),is_error:a.boolean(),num_turns:a.number(),result:a.unknown().optional(),structured_output:a.unknown().optional(),total_cost_usd:a.number(),usage:a.object({input_tokens:a.number(),cache_creation_input_tokens:a.number().optional(),cache_read_input_tokens:a.number().optional(),output_tokens:a.number(),server_tool_use:a.object({web_search_requests:a.number()}).optional()}).optional()}),x=a.object({type:a.literal(`rate_limit_event`),uuid:a.string(),session_id:a.string().optional(),rate_limit_info:a.object({status:a.string(),resetsAt:a.number().optional(),rateLimitType:a.string().optional(),overageStatus:a.string().optional(),overageDisabledReason:a.string().optional(),isUsingOverage:a.boolean().optional()})}),S=a.discriminatedUnion(`type`,[_,v,y,b,x]),C=a.discriminatedUnion(`type`,[_.extend({uuid:a.string().optional(),mcp_servers:a.array(g).optional()}),v.extend({uuid:a.string().optional()}),y.extend({uuid:a.string().optional()}),b.extend({uuid:a.string().optional(),subtype:a.string()}),x]),w=t(S);export{m as i,C as n,o as r,w as t};
@@ -1,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-CT-rhJzK.mjs";
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-CN0WGc9T.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 };
@@ -1 +1 @@
1
- import{n as e,t}from"../sandbox-CoV-gBuM.mjs";export{t as SandboxCreateError,e as createSandbox};
1
+ import{n as e,t}from"../sandbox-CYA69miM.mjs";export{t as SandboxCreateError,e as createSandbox};
@@ -1,4 +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(`
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-CgfyvnR4.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
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
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
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};
@@ -0,0 +1 @@
1
+ import{t as e}from"./errors-aYGbvsaq.mjs";import{spawn as t}from"node:child_process";const n=e=>({async*[Symbol.asyncIterator](){for await(let t of e){if(t instanceof Buffer){yield new Uint8Array(t);continue}if(typeof t==`string`){yield new TextEncoder().encode(t);continue}if(t instanceof Uint8Array){yield t;continue}throw Error(`Unsupported stdout/stderr chunk type: ${typeof t}`)}}}),r=(r,i,a={})=>{let o=t(r,i,{cwd:a.cwd,env:a.env,stdio:a.stdio,detached:!0}),s,c=t=>{s??=new e(t)};o.stdin?.on(`error`,c);let l=new Promise((e,t)=>{let n=(n,i)=>{if(o.removeListener(`error`,r),s){t(s);return}e({exitCode:n,signal:i})},r=e=>{o.removeListener(`close`,n),t(e)};o.once(`error`,r),o.once(`close`,n)}),u=o.stdin;return{stdout:o.stdout?n(o.stdout):null,stderr:o.stderr?n(o.stderr):null,stdin:u?{write:e=>{let t=new Promise((t,n)=>{u.write(e,e=>{if(e){n(e);return}t()})});return t.catch(c),t},end:()=>{let e=new Promise((e,t)=>{u.end(n=>{if(n){t(n);return}e()})});return e.catch(c),e}}:null,kill:e=>{if(o.pid===void 0){o.kill(e);return}try{process.kill(-o.pid,e??`SIGTERM`)}catch{o.kill(e)}},wait:()=>l}},i={spawn:r};export{r as n,i as t};
@@ -1,61 +1,6 @@
1
1
  import { t as AgentEvent, v as AgentCapabilities, x as JsonSchema, y as ContentPart } from "./events-BxEB6zHt.mjs";
2
+ import { r as ProcessSignal } from "./types-COmjfh8B.mjs";
2
3
  import { ZodType } from "zod/v4";
3
- //#region src/core/process/types.d.ts
4
- type StdioOption = "ignore" | "inherit" | "pipe" | number;
5
- /** POSIX signal name (re-export of `NodeJS.Signals`). */
6
- type ProcessSignal = NodeJS.Signals;
7
- /**
8
- * Options accepted by {@link ProcessSpawner.spawn} when launching a
9
- * subprocess. Adapters set sensible defaults; callers typically only need to
10
- * override these inside custom spawners.
11
- */
12
- interface SpawnOptions {
13
- /** Working directory for the subprocess. Defaults to the spawner's default. */
14
- cwd?: string;
15
- /** Environment variables for the subprocess. */
16
- env?: Record<string, string>;
17
- /** Stdio disposition for [stdin, stdout, stderr]. Default is `["pipe", "pipe", "pipe"]`. */
18
- stdio?: [StdioOption, StdioOption, StdioOption];
19
- }
20
- /** Subprocess termination result returned by {@link AgentProcess.wait}. */
21
- interface ProcessResult {
22
- /** Exit code; `null` if the process was killed by signal. */
23
- exitCode: number | null;
24
- /** Signal that terminated the process; `null` if it exited normally. */
25
- signal: ProcessSignal | null;
26
- }
27
- /**
28
- * Handle to a running subprocess returned by {@link ProcessSpawner.spawn}.
29
- * Exposes byte streams for stdio, a kill signal, and a `wait` for terminal
30
- * status. Each stream is `null` when its slot was set to `"ignore"` or
31
- * `"inherit"` in {@link SpawnOptions.stdio}.
32
- */
33
- interface AgentProcess {
34
- /** Stdout byte stream, or `null` if not piped. */
35
- stdout: AsyncIterable<Uint8Array> | null;
36
- /** Stderr byte stream, or `null` if not piped. */
37
- stderr: AsyncIterable<Uint8Array> | null;
38
- /** Stdin writer with optional `write` and required `end`, or `null` if not piped. */
39
- stdin: {
40
- write?: (chunk: Uint8Array | string) => void;
41
- end: () => void;
42
- } | null;
43
- kill: (signal?: ProcessSignal | number) => void;
44
- /** Resolve with the {@link ProcessResult} once the process exits. */
45
- wait: () => Promise<ProcessResult>;
46
- }
47
- /**
48
- * Pluggable process launcher used by CLI adapters and exposed by
49
- * containers and sandboxes via their `spawner` field. Pass a custom
50
- * `ProcessSpawner` to an adapter's `spawner` option to intercept how the
51
- * underlying agent CLI is launched (for instrumentation, sandboxing, or
52
- * remote execution).
53
- */
54
- interface ProcessSpawner {
55
- /** Launch `command` with `args` and return a live {@link AgentProcess} handle. */
56
- spawn: (command: string, args: string[], options?: SpawnOptions) => AgentProcess;
57
- }
58
- //#endregion
59
4
  //#region src/core/agent/permissions.d.ts
60
5
  /**
61
6
  * Information about a tool call the adapter is requesting permission for.
@@ -347,6 +292,14 @@ declare class AgentValidationError extends Error {
347
292
  }
348
293
  /** Callback registered via `agent.onEvent(...)`; invoked synchronously for every emitted event. */
349
294
  type AgentEventHandler = (event: AgentEvent) => void;
295
+ interface ProviderEvent<TEvent> {
296
+ agentType: AgentType;
297
+ runId: string;
298
+ sessionId?: string;
299
+ timestamp: Date;
300
+ event: TEvent;
301
+ }
302
+ type ProviderEventHandler<TEvent> = (event: ProviderEvent<TEvent>) => void;
350
303
  /**
351
304
  * Lifetime counters for an agent instance.
352
305
  *
@@ -488,4 +441,4 @@ interface BaseAgent<TRunOptions extends object = {}> {
488
441
  onPermissionRequest: (handler: PermissionHandler) => () => void;
489
442
  }
490
443
  //#endregion
491
- export { StopReason as C, PermissionHandler as D, PermissionDecision as E, PermissionRequest as O, RunTiming as S, ZodRunRequest as T, RunProcessInfo as _, AgentValidationError as a, RunStats as b, AnyRunResult as c, CompletedRunResult as d, EnsureDisjoint as f, RunError as g, JsonSchemaRunRequest as h, AgentType as i, ProcessSpawner as k, BaseAgent as l, FailedRunResult as m, AgentMetrics as n, AnyCompletedRunResult as o, ExclusiveExecutionTargetOptions as p, AgentRunError as r, AnyRunRequest as s, AgentEventHandler as t, CancelledRunResult as u, RunRequest as v, StructuredRunRequest as w, RunStatus as x, RunResult as y };
444
+ export { PermissionRequest as A, RunStatus as C, ZodRunRequest as D, StructuredRunRequest as E, PermissionDecision as O, RunStats as S, StopReason as T, ProviderEventHandler as _, AgentValidationError as a, RunRequest as b, AnyRunResult as c, CompletedRunResult as d, EnsureDisjoint as f, ProviderEvent as g, JsonSchemaRunRequest as h, AgentType as i, PermissionHandler as k, BaseAgent as l, FailedRunResult as m, AgentMetrics as n, AnyCompletedRunResult as o, ExclusiveExecutionTargetOptions as p, AgentRunError as r, AnyRunRequest as s, AgentEventHandler as t, CancelledRunResult as u, RunError as v, RunTiming as w, RunResult as x, RunProcessInfo as y };
@@ -0,0 +1,57 @@
1
+ //#region src/core/process/types.d.ts
2
+ type StdioOption = "ignore" | "inherit" | "pipe" | number;
3
+ /** POSIX signal name (re-export of `NodeJS.Signals`). */
4
+ type ProcessSignal = NodeJS.Signals;
5
+ /**
6
+ * Options accepted by {@link ProcessSpawner.spawn} when launching a
7
+ * subprocess. Adapters set sensible defaults; callers typically only need to
8
+ * override these inside custom spawners.
9
+ */
10
+ interface SpawnOptions {
11
+ /** Working directory for the subprocess. Defaults to the spawner's default. */
12
+ cwd?: string;
13
+ /** Environment variables for the subprocess. */
14
+ env?: Record<string, string>;
15
+ /** Stdio disposition for [stdin, stdout, stderr]. Default is `["pipe", "pipe", "pipe"]`. */
16
+ stdio?: [StdioOption, StdioOption, StdioOption];
17
+ }
18
+ /** Subprocess termination result returned by {@link AgentProcess.wait}. */
19
+ interface ProcessResult {
20
+ /** Exit code; `null` if the process was killed by signal. */
21
+ exitCode: number | null;
22
+ /** Signal that terminated the process; `null` if it exited normally. */
23
+ signal: ProcessSignal | null;
24
+ }
25
+ /**
26
+ * Handle to a running subprocess returned by {@link ProcessSpawner.spawn}.
27
+ * Exposes byte streams for stdio, a kill signal, and a `wait` for terminal
28
+ * status. Each stream is `null` when its slot was set to `"ignore"` or
29
+ * `"inherit"` in {@link SpawnOptions.stdio}.
30
+ */
31
+ interface AgentProcess {
32
+ /** Stdout byte stream, or `null` if not piped. */
33
+ stdout: AsyncIterable<Uint8Array> | null;
34
+ /** Stderr byte stream, or `null` if not piped. */
35
+ stderr: AsyncIterable<Uint8Array> | null;
36
+ /** Stdin writer with optional `write` and required `end`, or `null` if not piped. */
37
+ stdin: {
38
+ write?: (chunk: Uint8Array | string) => void | Promise<void>;
39
+ end: () => void | Promise<void>;
40
+ } | null;
41
+ kill: (signal?: ProcessSignal | number) => void;
42
+ /** Resolve with the {@link ProcessResult} once the process exits. */
43
+ wait: () => Promise<ProcessResult>;
44
+ }
45
+ /**
46
+ * Pluggable process launcher used by CLI adapters and exposed by
47
+ * containers and sandboxes via their `spawner` field. Pass a custom
48
+ * `ProcessSpawner` to an adapter's `spawner` option to intercept how the
49
+ * underlying agent CLI is launched (for instrumentation, sandboxing, or
50
+ * remote execution).
51
+ */
52
+ interface ProcessSpawner {
53
+ /** Launch `command` with `args` and return a live {@link AgentProcess} handle. */
54
+ spawn: (command: string, args: string[], options?: SpawnOptions) => AgentProcess;
55
+ }
56
+ //#endregion
57
+ export { SpawnOptions as a, ProcessSpawner as i, ProcessResult as n, ProcessSignal as r, AgentProcess as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "coding-agents-sdk",
3
- "version": "0.15.0",
3
+ "version": "0.16.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",
@@ -25,6 +25,10 @@
25
25
  "types": "./dist/index.d.mts",
26
26
  "default": "./dist/index.mjs"
27
27
  },
28
+ "./process": {
29
+ "types": "./dist/core/process/index.d.mts",
30
+ "default": "./dist/core/process/index.mjs"
31
+ },
28
32
  "./schemas": {
29
33
  "types": "./dist/schemas/index.d.mts",
30
34
  "default": "./dist/schemas/index.mjs"
@@ -1,4 +0,0 @@
1
- import{t as e}from"./util-B4HTdOSc.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-DOqkMCcy.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,/* @__PURE__ */ new Date);try{await this.onBeforeRun(t);let e={...n,...t.normalizedRequest},r=this.buildArgs(e,t),i=this.buildEnv(e,t),a=this.defaults.command?.[0]??`claude`,o=[...this.defaults.command?.slice(1)??[],...r];if(t.stopReason)return this.buildResult(t,/* @__PURE__ */ new Date);t.sessionId&&this.emitSessionStart(t),t.process=this.spawner.spawn(a,o,{cwd:t.normalizedRequest.cwd,env:i,stdio:[`pipe`,`pipe`,`pipe`]}),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,/* @__PURE__ */ new Date)}finally{r.cleanup(),this.sigkillTimer&&=(clearTimeout(this.sigkillTimer),void 0);try{await this.onRunFinished(t)}catch(t){this.appendRawLog(`[cleanup-error] ${e(t)}`)}}}async watchStdout(e){let t=e.process?.stdout;if(t)for await(let n of 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--- ${(/* @__PURE__ */ new Date()).toISOString()} ---\n`)}catch{this.logStream=void 0}}appendLog(e,t){if(!this.logStream||!t)return;let n=e===`stderr`?`STDERR`:`STDOUT`,r=(/* @__PURE__ */ new Date()).toISOString();for(let e of t.split(`
4
- `))e&&this.logStream.write(`[${r}] ${n} ${e}\n`)}async ensureExecutionTarget(){this.executionTargetRef&&this.executionTargetRef.status!==`running`&&await this.executionTargetRef.start()}};export{h as t};
@@ -1 +0,0 @@
1
- import{t as e}from"./util-B4HTdOSc.mjs";import{c as t,i as n,n as r,r as i,s as a}from"./container-Dk4QgU9G.mjs";import{t as o}from"./shell-DvWFuFKb.mjs";import{n as s}from"./diff-C60ujrU_.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,domain:e.domain,requestTimeoutMs:e.requestTimeoutMs,apiHeaders: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},i=await c.commands.run(b(e,t),r);return G(i,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};
@@ -1 +0,0 @@
1
- import{t as e}from"./util-B4HTdOSc.mjs";import{i as t,r as n,s as r}from"./container-Dk4QgU9G.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:/* @__PURE__ */ new Date};return t.set(n,e),n},F=(e,t,r)=>{if(typeof t!=`object`||!t)throw new n(`Invalid workdir snapshot.`);let i=r.get(t);if(!i)throw new n(`Invalid workdir snapshot.`);if(i.owner!==e)throw new n(`Workdir snapshot was created by a different container instance.`);return i},I=(e,t)=>{if(!t.has(e))throw new n(`Workdir snapshot has been released.`)},L=e=>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{let e=await E(`git`,[`diff`,`--no-index`,`-z`,`--name-status`,`-M`,`--find-renames=100%`,t,r],{cwd:p(),encoding:`buffer`,maxBuffer:52428800});return V(R(e.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);let c=s.toString(`utf8`).trim()||o.toString(`utf8`).trim()||`exit code ${a}`;throw new n(`Failed to run git diff: ${c}`)}},U=async(e,t,n)=>{let r=/* @__PURE__ */ new Map,i=await Promise.all(e.map(async e=>{let i;i=e.kind===`added`?void 0:e.kind===`renamed`?e.previousPath:e.path;let a=e.kind===`deleted`?void 0:e.path,[o,s]=await Promise.all([i===void 0?void 0:B(t,i,r),a===void 0?void 0:B(n,a,r)]);return{path:e.path,previousPath:e.previousPath,kind:e.kind,beforeHash:o?.hash,afterHash:s?.hash,beforeSize:o?.size,afterSize:s?.size}}));return A(i)},W=e=>{let t=/* @__PURE__ */ new Set;for(let n of e)t.add(n.path),n.kind===`renamed`&&n.previousPath&&t.add(n.previousPath);return[...t].sort((e,t)=>e.localeCompare(t))},G=(i,a)=>{throw a instanceof n||a instanceof t||a instanceof r?a:new n(`${i}: ${e(a)}`)},K=async(e,t)=>{if(!(await 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=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new WeakMap,r=async(r={})=>{let i=r.cwd??e.workdir,a;try{a=await M(),await e.materialize(i,a),await j(a);let r={owner:e.owner,tempDir:a,cwd:i,inFlightDiffs:0,released:!1};return t.add(r),a=void 0,P(r,n)}catch(e){return await N(a),G(`Failed to materialize workdir snapshot`,e)}},i=async r=>{let i=Date.now(),a=F(e.owner,r,n);I(a,t),a.inFlightDiffs++;let o;try{o=await M(),await e.materialize(a.cwd,o),await j(o);let t=await H(a.tempDir,o),n=await U(t,a.tempDir,o),r=W(n);return{cwd:a.cwd,changedFiles:r,fileChanges:n,stats:{durationMs:Date.now()-i,filesCompared:r.length}}}catch(e){return G(`Failed to diff workdir snapshot`,e)}finally{a.inFlightDiffs--,a.inFlightDiffs===0&&(a.resolveIdle?.(),a.resolveIdle=void 0),await N(o)}},a=e=>{let n=e;return n.releasePromise?n.releasePromise:(n.released=!0,t.delete(n),n.releasePromise=(async()=>{n.inFlightDiffs>0&&await new Promise(e=>{n.resolveIdle=e}),await N(n.tempDir)})(),n.releasePromise)};return{snapshotWorkdir:r,diffWorkdir:i,releaseWorkdirSnapshot:async t=>{let r=F(e.owner,t,n);await a(r)},disposeSnapshots:async()=>{await Promise.all(Array.from(t).map(a))}}};export{q as n,T as r,K as t};
@@ -1,154 +0,0 @@
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
- import { z } from "zod/v4";
6
- //#region src/adapters/codex-cli/events/schemas.d.ts
7
- /**
8
- * Permissive shape for any raw event Codex CLI emits — `{ type: string }`
9
- * plus arbitrary additional fields. Narrow on `event.type` against the
10
- * specific exported event types (`CodexThreadStartedEvent`,
11
- * `CodexTurnCompletedEvent`, `CodexItemStartedEvent`, etc.) when you need
12
- * field-level access.
13
- */
14
- declare const codexEventSchema: z.ZodObject<{
15
- type: z.ZodString;
16
- }, z.core.$loose>;
17
- type CodexEvent = z.infer<typeof codexEventSchema>;
18
- declare const codexThreadStartedEventSchema: z.ZodObject<{
19
- type: z.ZodLiteral<"thread.started">;
20
- thread_id: z.ZodString;
21
- }, z.core.$loose>;
22
- type CodexThreadStartedEvent = z.infer<typeof codexThreadStartedEventSchema>;
23
- declare const codexTurnCompletedEventSchema: z.ZodObject<{
24
- type: z.ZodLiteral<"turn.completed">;
25
- usage: z.ZodOptional<z.ZodObject<{
26
- input_tokens: z.ZodOptional<z.ZodNumber>;
27
- cached_input_tokens: z.ZodOptional<z.ZodNumber>;
28
- cache_write_input_tokens: z.ZodOptional<z.ZodNumber>;
29
- output_tokens: z.ZodOptional<z.ZodNumber>;
30
- reasoning_output_tokens: z.ZodOptional<z.ZodNumber>;
31
- total_tokens: z.ZodOptional<z.ZodNumber>;
32
- }, z.core.$loose>>;
33
- last_agent_message: z.ZodOptional<z.ZodString>;
34
- duration_ms: z.ZodOptional<z.ZodNumber>;
35
- num_turns: z.ZodOptional<z.ZodNumber>;
36
- }, z.core.$loose>;
37
- type CodexTurnCompletedEvent = z.infer<typeof codexTurnCompletedEventSchema>;
38
- declare const codexTurnFailedEventSchema: z.ZodObject<{
39
- type: z.ZodLiteral<"turn.failed">;
40
- usage: z.ZodOptional<z.ZodObject<{
41
- input_tokens: z.ZodOptional<z.ZodNumber>;
42
- cached_input_tokens: z.ZodOptional<z.ZodNumber>;
43
- cache_write_input_tokens: z.ZodOptional<z.ZodNumber>;
44
- output_tokens: z.ZodOptional<z.ZodNumber>;
45
- reasoning_output_tokens: z.ZodOptional<z.ZodNumber>;
46
- total_tokens: z.ZodOptional<z.ZodNumber>;
47
- }, z.core.$loose>>;
48
- last_agent_message: z.ZodOptional<z.ZodString>;
49
- duration_ms: z.ZodOptional<z.ZodNumber>;
50
- num_turns: z.ZodOptional<z.ZodNumber>;
51
- message: z.ZodOptional<z.ZodString>;
52
- error: z.ZodOptional<z.ZodUnknown>;
53
- }, z.core.$loose>;
54
- type CodexTurnFailedEvent = z.infer<typeof codexTurnFailedEventSchema>;
55
- declare const codexItemStartedEventSchema: z.ZodObject<{
56
- type: z.ZodLiteral<"item.started">;
57
- item: z.ZodObject<{
58
- id: z.ZodString;
59
- type: z.ZodString;
60
- }, z.core.$loose>;
61
- }, z.core.$loose>;
62
- type CodexItemStartedEvent = z.infer<typeof codexItemStartedEventSchema>;
63
- declare const codexItemUpdatedEventSchema: z.ZodObject<{
64
- type: z.ZodLiteral<"item.updated">;
65
- item: z.ZodObject<{
66
- id: z.ZodString;
67
- type: z.ZodString;
68
- }, z.core.$loose>;
69
- }, z.core.$loose>;
70
- type CodexItemUpdatedEvent = z.infer<typeof codexItemUpdatedEventSchema>;
71
- declare const codexItemCompletedEventSchema: z.ZodObject<{
72
- type: z.ZodLiteral<"item.completed">;
73
- item: z.ZodObject<{
74
- id: z.ZodString;
75
- type: z.ZodString;
76
- }, z.core.$loose>;
77
- }, z.core.$loose>;
78
- type CodexItemCompletedEvent = z.infer<typeof codexItemCompletedEventSchema>;
79
- declare const codexErrorEventSchema: z.ZodObject<{
80
- type: z.ZodLiteral<"error">;
81
- message: z.ZodOptional<z.ZodString>;
82
- error: z.ZodOptional<z.ZodUnknown>;
83
- }, z.core.$loose>;
84
- type CodexErrorEvent = z.infer<typeof codexErrorEventSchema>;
85
- //#endregion
86
- //#region src/adapters/codex-cli/types.d.ts
87
- /**
88
- * Filesystem sandbox policy for Codex CLI.
89
- * - `"read-only"`: tools cannot write.
90
- * - `"workspace-write"`: writes allowed inside `cwd` only.
91
- * - `"danger-full-access"`: no filesystem restrictions.
92
- */
93
- type CodexCliSandboxMode = "danger-full-access" | "read-only" | "workspace-write";
94
- /**
95
- * How Codex CLI handles approval prompts.
96
- * - `"default"`: leave Codex CLI's own default approval behavior in place (this adapter does not bridge approvals to a permission handler).
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.
99
- */
100
- type CodexCliPermissionMode = "auto-approve" | "bypass-sandbox" | "default";
101
- /** Per-run options for the `codex-cli` adapter. */
102
- interface CodexCliRunOptions {
103
- /**
104
- * Filesystem sandbox policy for the default approval strategy.
105
- * Other permission modes select their own sandbox behavior.
106
- */
107
- sandboxMode?: CodexCliSandboxMode;
108
- /** Extra directories outside `cwd` writable under `workspace-write`. */
109
- additionalDirectories?: string[];
110
- /** Suppress Codex's "not a git repo" confirmation prompt (`--skip-git-repo-check`). */
111
- skipGitRepoCheck?: boolean;
112
- /** Approval prompt strategy. */
113
- permissionMode?: CodexCliPermissionMode;
114
- /** When `true`, Codex does not persist this run's history. */
115
- ephemeral?: boolean;
116
- /** Path to an MCP config file passed via `--mcp-config`. */
117
- mcpConfig?: string;
118
- /** Inline MCP server config map. */
119
- mcpServers?: Record<string, McpServerConfig>;
120
- /** Extra CLI flags appended verbatim. */
121
- extraArgs?: string[];
122
- /** Not supported — Codex manages its own system prompt. */
123
- systemPrompt?: never;
124
- }
125
- /** Constructor options for `createAgent("codex-cli", ...)`. */
126
- type CodexCliAgentOptions = CodexCliRunOptions & ExclusiveExecutionTargetOptions<Container, Sandbox> & {
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. */
144
- onEvent?: AgentEventHandler;
145
- };
146
- /** Agent instance returned by `createAgent("codex-cli", ...)`. */
147
- interface CodexCliAgent extends BaseAgent<EnsureDisjoint<CodexCliRunOptions>> {
148
- readonly type: "codex-cli";
149
- }
150
- //#endregion
151
- //#region src/adapters/codex-cli/adapter.d.ts
152
- declare const createCodexCliAgent: (options?: CodexCliAgentOptions) => CodexCliAgent;
153
- //#endregion
154
- export { CodexCliRunOptions as a, CodexEvent as c, CodexItemUpdatedEvent as d, CodexThreadStartedEvent as f, CodexCliPermissionMode as i, CodexItemCompletedEvent as l, CodexTurnFailedEvent as m, CodexCliAgent as n, CodexCliSandboxMode as o, CodexTurnCompletedEvent as p, CodexCliAgentOptions as r, CodexErrorEvent as s, createCodexCliAgent as t, CodexItemStartedEvent as u };