coding-agents-sdk 0.0.1 → 0.2.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 (41) hide show
  1. package/README.md +242 -0
  2. package/dist/Agent-D8WkUilj.mjs +262 -0
  3. package/dist/SdkAgent-B47mJiIE.mjs +38 -0
  4. package/dist/adapters/claude-code-cli/index.d.mts +2 -0
  5. package/dist/adapters/claude-code-cli/index.mjs +490 -0
  6. package/dist/adapters/claude-code-sdk/index.d.mts +2 -0
  7. package/dist/adapters/claude-code-sdk/index.mjs +483 -0
  8. package/dist/adapters/codex-cli/index.d.mts +2 -0
  9. package/dist/adapters/codex-cli/index.mjs +626 -0
  10. package/dist/adapters/codex-sdk/index.d.mts +2 -0
  11. package/dist/adapters/codex-sdk/index.mjs +286 -0
  12. package/dist/adapters/gemini-cli/index.d.mts +2 -0
  13. package/dist/adapters/gemini-cli/index.mjs +292 -0
  14. package/dist/classify-error-pL6jeu4T.mjs +456 -0
  15. package/dist/container/index.d.mts +2 -0
  16. package/dist/container/index.mjs +24 -0
  17. package/dist/container-2UmPZ0CI.mjs +22 -0
  18. package/dist/container-CHxKIonn.mjs +440 -0
  19. package/dist/container-D2Z0ITDJ.mjs +22 -0
  20. package/dist/diff-De8d3MVb.mjs +333 -0
  21. package/dist/errors-BAmHDQu8.mjs +45 -0
  22. package/dist/events-nxuRbYIu.d.mts +239 -0
  23. package/dist/index-B3YqrgIp.d.mts +45 -0
  24. package/dist/index-ByAOGMUM.d.mts +224 -0
  25. package/dist/index-C3ZxLAd0.d.mts +315 -0
  26. package/dist/index-CFpNOmdA.d.mts +145 -0
  27. package/dist/index-dRVpEAr8.d.mts +39 -0
  28. package/dist/index-nzo1sBiK.d.mts +110 -0
  29. package/dist/index.d.mts +16 -0
  30. package/dist/index.mjs +61 -0
  31. package/dist/oci-DMZZQZ47.mjs +438 -0
  32. package/dist/schemas/index.d.mts +2 -0
  33. package/dist/schemas/index.mjs +2 -0
  34. package/dist/schemas-DwD4pwJB.mjs +96 -0
  35. package/dist/spawner-Bw9UBEGX.mjs +54 -0
  36. package/dist/structured-output-BHtr_zpz.mjs +19 -0
  37. package/dist/types-Cb_EXIEe.d.mts +177 -0
  38. package/dist/types-aNMD8h3x.mjs +19 -0
  39. package/dist/util-B4RQZkKr.mjs +77 -0
  40. package/package.json +86 -9
  41. package/index.js +0 -7
@@ -0,0 +1,39 @@
1
+ import { E as ProcessSpawner, f as EnsureDisjoint, l as BaseAgent, t as AgentEventHandler } from "./types-Cb_EXIEe.mjs";
2
+ import { t as Container } from "./index-ByAOGMUM.mjs";
3
+ import { z } from "zod/v4";
4
+
5
+ //#region src/adapters/gemini-cli/events/schemas.d.ts
6
+ declare const geminiEventSchema: z.ZodObject<{
7
+ type: z.ZodString;
8
+ }, z.core.$loose>;
9
+ type GeminiEvent = z.infer<typeof geminiEventSchema>;
10
+ //#endregion
11
+ //#region src/adapters/gemini-cli/types.d.ts
12
+ type GeminiCliPermissionMode = "default" | "full";
13
+ interface GeminiCliRunOptions {
14
+ allowedTools?: string[];
15
+ disallowedTools?: string[];
16
+ permissionMode?: GeminiCliPermissionMode;
17
+ extraArgs?: string[];
18
+ }
19
+ interface GeminiCliAgentOptions extends GeminiCliRunOptions {
20
+ command?: string[] | string;
21
+ cwd?: string;
22
+ env?: Record<string, string>;
23
+ propagateEnv?: boolean;
24
+ sessionId?: string;
25
+ model?: string;
26
+ systemPrompt?: string;
27
+ logPath?: string;
28
+ container?: Container;
29
+ spawner?: ProcessSpawner;
30
+ onEvent?: AgentEventHandler;
31
+ }
32
+ interface GeminiCliAgent extends BaseAgent<EnsureDisjoint<GeminiCliRunOptions>> {
33
+ readonly type: "gemini-cli";
34
+ }
35
+ //#endregion
36
+ //#region src/adapters/gemini-cli/adapter.d.ts
37
+ declare const createGeminiCliAgent: (options?: GeminiCliAgentOptions) => GeminiCliAgent;
38
+ //#endregion
39
+ export { GeminiCliRunOptions as a, GeminiCliPermissionMode as i, GeminiCliAgent as n, GeminiEvent as o, GeminiCliAgentOptions as r, createGeminiCliAgent as t };
@@ -0,0 +1,110 @@
1
+ import { S as McpServerConfig } from "./events-nxuRbYIu.mjs";
2
+ import { E as ProcessSpawner, f as EnsureDisjoint, l as BaseAgent, t as AgentEventHandler } from "./types-Cb_EXIEe.mjs";
3
+ import { t as Container } from "./index-ByAOGMUM.mjs";
4
+ import { z } from "zod/v4";
5
+
6
+ //#region src/adapters/codex-cli/events/schemas.d.ts
7
+ declare const codexEventSchema: z.ZodObject<{
8
+ type: z.ZodString;
9
+ }, z.core.$loose>;
10
+ type CodexEvent = z.infer<typeof codexEventSchema>;
11
+ declare const codexThreadStartedEventSchema: z.ZodObject<{
12
+ type: z.ZodLiteral<"thread.started">;
13
+ thread_id: z.ZodString;
14
+ }, z.core.$loose>;
15
+ type CodexThreadStartedEvent = z.infer<typeof codexThreadStartedEventSchema>;
16
+ declare const codexTurnCompletedEventSchema: z.ZodObject<{
17
+ type: z.ZodLiteral<"turn.completed">;
18
+ usage: z.ZodOptional<z.ZodObject<{
19
+ input_tokens: z.ZodOptional<z.ZodNumber>;
20
+ cached_input_tokens: z.ZodOptional<z.ZodNumber>;
21
+ output_tokens: z.ZodOptional<z.ZodNumber>;
22
+ reasoning_output_tokens: z.ZodOptional<z.ZodNumber>;
23
+ total_tokens: z.ZodOptional<z.ZodNumber>;
24
+ }, z.core.$loose>>;
25
+ last_agent_message: z.ZodOptional<z.ZodString>;
26
+ duration_ms: z.ZodOptional<z.ZodNumber>;
27
+ num_turns: z.ZodOptional<z.ZodNumber>;
28
+ }, z.core.$loose>;
29
+ type CodexTurnCompletedEvent = z.infer<typeof codexTurnCompletedEventSchema>;
30
+ declare const codexTurnFailedEventSchema: z.ZodObject<{
31
+ type: z.ZodLiteral<"turn.failed">;
32
+ usage: z.ZodOptional<z.ZodObject<{
33
+ input_tokens: z.ZodOptional<z.ZodNumber>;
34
+ cached_input_tokens: z.ZodOptional<z.ZodNumber>;
35
+ output_tokens: z.ZodOptional<z.ZodNumber>;
36
+ reasoning_output_tokens: z.ZodOptional<z.ZodNumber>;
37
+ total_tokens: z.ZodOptional<z.ZodNumber>;
38
+ }, z.core.$loose>>;
39
+ last_agent_message: z.ZodOptional<z.ZodString>;
40
+ duration_ms: z.ZodOptional<z.ZodNumber>;
41
+ num_turns: z.ZodOptional<z.ZodNumber>;
42
+ message: z.ZodOptional<z.ZodString>;
43
+ error: z.ZodOptional<z.ZodUnknown>;
44
+ }, z.core.$loose>;
45
+ type CodexTurnFailedEvent = z.infer<typeof codexTurnFailedEventSchema>;
46
+ declare const codexItemStartedEventSchema: z.ZodObject<{
47
+ type: z.ZodLiteral<"item.started">;
48
+ item: z.ZodObject<{
49
+ id: z.ZodString;
50
+ type: z.ZodString;
51
+ }, z.core.$loose>;
52
+ }, z.core.$loose>;
53
+ type CodexItemStartedEvent = z.infer<typeof codexItemStartedEventSchema>;
54
+ declare const codexItemUpdatedEventSchema: z.ZodObject<{
55
+ type: z.ZodLiteral<"item.updated">;
56
+ item: z.ZodObject<{
57
+ id: z.ZodString;
58
+ type: z.ZodString;
59
+ }, z.core.$loose>;
60
+ }, z.core.$loose>;
61
+ type CodexItemUpdatedEvent = z.infer<typeof codexItemUpdatedEventSchema>;
62
+ declare const codexItemCompletedEventSchema: z.ZodObject<{
63
+ type: z.ZodLiteral<"item.completed">;
64
+ item: z.ZodObject<{
65
+ id: z.ZodString;
66
+ type: z.ZodString;
67
+ }, z.core.$loose>;
68
+ }, z.core.$loose>;
69
+ type CodexItemCompletedEvent = z.infer<typeof codexItemCompletedEventSchema>;
70
+ declare const codexErrorEventSchema: z.ZodObject<{
71
+ type: z.ZodLiteral<"error">;
72
+ message: z.ZodOptional<z.ZodString>;
73
+ error: z.ZodOptional<z.ZodUnknown>;
74
+ }, z.core.$loose>;
75
+ type CodexErrorEvent = z.infer<typeof codexErrorEventSchema>;
76
+ //#endregion
77
+ //#region src/adapters/codex-cli/types.d.ts
78
+ type CodexCliSandboxMode = "danger-full-access" | "read-only" | "workspace-write";
79
+ type CodexCliPermissionMode = "default" | "full-access" | "full-auto";
80
+ interface CodexCliRunOptions {
81
+ sandbox?: CodexCliSandboxMode;
82
+ additionalDirectories?: string[];
83
+ skipGitRepoCheck?: boolean;
84
+ permissionMode?: CodexCliPermissionMode;
85
+ ephemeral?: boolean;
86
+ mcpConfig?: string;
87
+ mcpServers?: Record<string, McpServerConfig>;
88
+ extraArgs?: string[];
89
+ systemPrompt?: never;
90
+ }
91
+ interface CodexCliAgentOptions extends CodexCliRunOptions {
92
+ command?: string[] | string;
93
+ cwd?: string;
94
+ env?: Record<string, string>;
95
+ propagateEnv?: boolean;
96
+ sessionId?: string;
97
+ model?: string;
98
+ logPath?: string;
99
+ container?: Container;
100
+ spawner?: ProcessSpawner;
101
+ onEvent?: AgentEventHandler;
102
+ }
103
+ interface CodexCliAgent extends BaseAgent<EnsureDisjoint<CodexCliRunOptions>> {
104
+ readonly type: "codex-cli";
105
+ }
106
+ //#endregion
107
+ //#region src/adapters/codex-cli/adapter.d.ts
108
+ declare const createCodexCliAgent: (options?: CodexCliAgentOptions) => CodexCliAgent;
109
+ //#endregion
110
+ 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 };
@@ -0,0 +1,16 @@
1
+ import { C as OutputSchema, S as McpServerConfig, T as agentCapabilitiesSchema, 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 TextContentPart, x as JsonSchema, y as ContentPart } from "./events-nxuRbYIu.mjs";
2
+ import { C as StopReason, S as RunTiming, T as ZodRunRequest, _ as RunRequest, a as AgentValidationError, b as RunStats, c as AnyRunResult, d as CompletedRunResult, f as EnsureDisjoint, g as RunProcessInfo, h as RunError, i as AgentType, l as BaseAgent, m as JsonSchemaRunRequest, n as AgentMetrics, o as AnyCompletedRunResult, p as FailedRunResult, r as AgentRunError, s as AnyRunRequest, t as AgentEventHandler, u as CancelledRunResult, v as RunResult, w as StructuredRunRequest, x as RunStatus, y as RunResultBase } from "./types-Cb_EXIEe.mjs";
3
+ import { A as ContainerBase, B as ExecResult, C as E2BProviderConfig, D as DockerContainerBase, E as DockerContainer, F as ContainerLifecycle, G as WorkdirDiffStats, H as VolumeMount, I as ContainerObservability, J as WorkdirSnapshotOptions, K as WorkdirFileChange, L as ContainerStatus, M as ContainerExecution, N as ContainerFileSystem, O as DockerContainerConfig, P as ContainerIdentity, R as ContainerType, S as E2BCreateConfig, T as DockerBuildConfig, U as WorkdirChangeKind, V as PortMapping, W as WorkdirDiff, _ as E2BConnectConfig, a as ContainerDiffError, b as E2BContainerBase, c as ContainerExecError, d as PodmanBuildBase, f as PodmanBuildConfig, g as PodmanProviderConfig, h as PodmanContainerConfig, i as ContainerCreateError, j as ContainerConfigBase, k as DockerProviderConfig, l as ContainerNotRunningError, m as PodmanContainerBase, n as ContainerConfig, o as ContainerDisposedError, p as PodmanContainer, q as WorkdirSnapshot, r as createContainer, s as ContainerError, t as Container, u as ContainerStartError, v as E2BConnectionConfig, w as DockerBuildBase, x as E2BContainerConfig, y as E2BContainer, z as ExecOptions } from "./index-ByAOGMUM.mjs";
4
+ 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-C3ZxLAd0.mjs";
5
+ 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-B3YqrgIp.mjs";
6
+ 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-nzo1sBiK.mjs";
7
+ import { a as CodexSdkItem, i as CodexSdkEvent, n as CodexSdkAgent, o as CodexSdkPermissionMode, r as CodexSdkAgentOptions, s as CodexSdkRunOptions } from "./index-CFpNOmdA.mjs";
8
+ import { a as GeminiCliRunOptions, i as GeminiCliPermissionMode, n as GeminiCliAgent, o as GeminiEvent, r as GeminiCliAgentOptions } from "./index-dRVpEAr8.mjs";
9
+ //#region src/core/agent/create-agent.d.ts
10
+ declare function createAgent(type: "claude-code-cli", options?: ClaudeCodeCliAgentOptions): Promise<ClaudeCodeCliAgent>;
11
+ declare function createAgent(type: "claude-code-sdk", options?: ClaudeCodeSdkAgentOptions): Promise<ClaudeCodeSdkAgent>;
12
+ declare function createAgent(type: "codex-cli", options?: CodexCliAgentOptions): Promise<CodexCliAgent>;
13
+ declare function createAgent(type: "codex-sdk", options?: CodexSdkAgentOptions): Promise<CodexSdkAgent>;
14
+ declare function createAgent(type: "gemini-cli", options?: GeminiCliAgentOptions): Promise<GeminiCliAgent>;
15
+ //#endregion
16
+ export { type AgentCapabilities, type AgentEvent, type AgentEventHandler, type AgentMetrics, AgentRunError, type AgentType, AgentValidationError, type AnyCompletedRunResult, type AnyRunRequest, type AnyRunResult, type BaseAgent, type CancelledRunResult, type ClaudeAssistantEvent, type ClaudeCodeCliAgent, type ClaudeCodeCliAgentOptions, type ClaudeCodeCliPermissionMode, 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 ContainerBase, type ContainerConfig, type ContainerConfigBase, ContainerCreateError, ContainerDiffError, ContainerDisposedError, ContainerError, ContainerExecError, type ContainerExecution, type ContainerFileSystem, type ContainerIdentity, type ContainerLifecycle, ContainerNotRunningError, type ContainerObservability, ContainerStartError, type ContainerStatus, type ContainerType, type ContentPart, type DockerBuildBase, type DockerBuildConfig, type DockerContainer, type DockerContainerBase, type DockerContainerConfig, type DockerProviderConfig, type E2BConnectConfig, type E2BConnectionConfig, type E2BContainer, type E2BContainerBase, type E2BContainerConfig, type E2BCreateConfig, type E2BProviderConfig, type EnsureDisjoint, type ExecOptions, type ExecResult, type FailedRunResult, type GeminiCliAgent, type GeminiCliAgentOptions, type GeminiCliPermissionMode, type GeminiCliRunOptions, type GeminiEvent, type ImageContentPart, type JsonSchema, type JsonSchemaRunRequest, type McpServerConfig, type MessageEvent, type OutputSchema, type PodmanBuildBase, type PodmanBuildConfig, type PodmanContainer, type PodmanContainerBase, type PodmanContainerConfig, type PodmanProviderConfig, type PortMapping, type ReasoningEvent, type RunError, type RunProcessInfo, type RunRequest, type RunResult, type RunResultBase, type RunStats, type RunStatus, type RunTiming, 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, createAgent, createContainer, eventSchema };
package/dist/index.mjs ADDED
@@ -0,0 +1,61 @@
1
+ import { n as AgentValidationError, t as AgentRunError } from "./types-aNMD8h3x.mjs";
2
+ import { a as ContainerExecError, i as ContainerError, n as ContainerDiffError, o as ContainerNotRunningError, r as ContainerDisposedError, s as ContainerStartError, t as ContainerCreateError } from "./errors-BAmHDQu8.mjs";
3
+ import { createContainer } from "./container/index.mjs";
4
+ import { n as eventSchema, u as agentCapabilitiesSchema } from "./schemas-DwD4pwJB.mjs";
5
+ //#region src/core/agent/create-agent.ts
6
+ function resolveContainerOptions(options) {
7
+ if (!options?.container) return options;
8
+ return {
9
+ ...options,
10
+ cwd: options.cwd ?? options.container.workdir
11
+ };
12
+ }
13
+ const isMissingModuleError = (error, packageName) => {
14
+ if (!(error instanceof Error) || !error.message.includes(packageName)) return false;
15
+ const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
16
+ return code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND";
17
+ };
18
+ const wrapMissingPeerDependency = (type, packageName, error) => {
19
+ if (isMissingModuleError(error, packageName)) throw new AgentValidationError(`Agent type "${type}" requires the optional peer dependency "${packageName}". Install it to use this adapter.`);
20
+ throw error;
21
+ };
22
+ async function createAgent(type, options) {
23
+ switch (type) {
24
+ case "claude-code-cli": {
25
+ const typedOptions = resolveContainerOptions(options);
26
+ const { createClaudeCodeCliAgent } = await import("./adapters/claude-code-cli/index.mjs");
27
+ return createClaudeCodeCliAgent(typedOptions);
28
+ }
29
+ case "claude-code-sdk": {
30
+ const typedOptions = options;
31
+ try {
32
+ const { createClaudeCodeSdkAgent } = await import("./adapters/claude-code-sdk/index.mjs");
33
+ return createClaudeCodeSdkAgent(typedOptions);
34
+ } catch (error) {
35
+ return wrapMissingPeerDependency("claude-code-sdk", "@anthropic-ai/claude-agent-sdk", error);
36
+ }
37
+ }
38
+ case "codex-cli": {
39
+ const typedOptions = resolveContainerOptions(options);
40
+ const { createCodexCliAgent } = await import("./adapters/codex-cli/index.mjs");
41
+ return createCodexCliAgent(typedOptions);
42
+ }
43
+ case "codex-sdk": {
44
+ const typedOptions = options;
45
+ try {
46
+ const { createCodexSdkAgent } = await import("./adapters/codex-sdk/index.mjs");
47
+ return createCodexSdkAgent(typedOptions);
48
+ } catch (error) {
49
+ return wrapMissingPeerDependency("codex-sdk", "@openai/codex-sdk", error);
50
+ }
51
+ }
52
+ case "gemini-cli": {
53
+ const typedOptions = resolveContainerOptions(options);
54
+ const { createGeminiCliAgent } = await import("./adapters/gemini-cli/index.mjs");
55
+ return createGeminiCliAgent(typedOptions);
56
+ }
57
+ default: throw new AgentValidationError("Unsupported agent type.");
58
+ }
59
+ }
60
+ //#endregion
61
+ export { AgentRunError, AgentValidationError, ContainerCreateError, ContainerDiffError, ContainerDisposedError, ContainerError, ContainerExecError, ContainerNotRunningError, ContainerStartError, agentCapabilitiesSchema, createAgent, createContainer, eventSchema };
@@ -0,0 +1,438 @@
1
+ import { t as formatError } from "./util-B4RQZkKr.mjs";
2
+ import { a as ContainerExecError, n as ContainerDiffError, o as ContainerNotRunningError, r as ContainerDisposedError, s as ContainerStartError, t as ContainerCreateError } from "./errors-BAmHDQu8.mjs";
3
+ import { t as DEFAULT_SPAWNER } from "./spawner-Bw9UBEGX.mjs";
4
+ import { i as isExecFileError, n as createWorkdirDiffApi, r as shellEscape, t as copyLocalDirectoryContents } from "./diff-De8d3MVb.mjs";
5
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
6
+ import { tmpdir } from "node:os";
7
+ import { isAbsolute, join, posix } from "node:path";
8
+ import { execFile } from "node:child_process";
9
+ import { randomBytes } from "node:crypto";
10
+ import { promisify } from "node:util";
11
+ //#region src/container/oci.ts
12
+ const execFileAsync = promisify(execFile);
13
+ const generateContainerName = () => `cw-${randomBytes(6).toString("hex")}`;
14
+ const runOci = async (binary, args, options) => {
15
+ const result = await execFileAsync(binary, args, {
16
+ encoding: "utf8",
17
+ timeout: options?.timeoutMs,
18
+ signal: options?.signal,
19
+ maxBuffer: 50 * 1024 * 1024
20
+ });
21
+ return {
22
+ stdout: result.stdout,
23
+ stderr: result.stderr
24
+ };
25
+ };
26
+ const buildOciImage = async (binary, build) => {
27
+ const tag = build.tag ?? `cw-build-${randomBytes(4).toString("hex")}`;
28
+ const args = [
29
+ "build",
30
+ "-t",
31
+ tag
32
+ ];
33
+ if (build.args) for (const [key, value] of Object.entries(build.args)) args.push("--build-arg", `${key}=${value}`);
34
+ if ("dockerfile" in build && build.dockerfile) {
35
+ args.push("-f", build.dockerfile);
36
+ args.push(build.context ?? ".");
37
+ }
38
+ let tempDir;
39
+ if ("content" in build && build.content) {
40
+ tempDir = await mkdtemp(join(tmpdir(), "cw-oci-build-"));
41
+ const dockerfilePath = join(tempDir, "Dockerfile");
42
+ await writeFile(dockerfilePath, build.content, {
43
+ encoding: "utf8",
44
+ mode: 384
45
+ });
46
+ args.push("-f", dockerfilePath);
47
+ args.push(build.context ?? tempDir);
48
+ }
49
+ try {
50
+ await runOci(binary, args);
51
+ } catch (error) {
52
+ throw new ContainerCreateError(`Image build failed: ${formatError(error)}`);
53
+ } finally {
54
+ if (tempDir) await rm(tempDir, {
55
+ recursive: true,
56
+ force: true
57
+ }).catch(() => {});
58
+ }
59
+ return tag;
60
+ };
61
+ const resolvePortMappings = async (binary, containerId, ports) => {
62
+ const results = await Promise.all(ports.map(async (port) => {
63
+ try {
64
+ const { container: containerPort, protocol = "tcp" } = port;
65
+ const { stdout } = await runOci(binary, [
66
+ "port",
67
+ containerId,
68
+ `${containerPort}/${protocol}`
69
+ ]);
70
+ const match = /:(\d+)$/m.exec(stdout.trim());
71
+ if (match?.[1]) return [containerPort, Number(match[1])];
72
+ } catch {}
73
+ }));
74
+ const mapped = /* @__PURE__ */ new Map();
75
+ for (const entry of results) if (entry) mapped.set(entry[0], entry[1]);
76
+ return mapped;
77
+ };
78
+ const createOciSpawner = (containerId, binary) => ({ spawn: (command, args, options = {}) => {
79
+ const execArgs = ["exec", "-i"];
80
+ if (options.cwd) execArgs.push("-w", options.cwd);
81
+ if (options.env) for (const [key, value] of Object.entries(options.env)) execArgs.push("-e", `${key}=${value}`);
82
+ execArgs.push(containerId, command, ...args);
83
+ return DEFAULT_SPAWNER.spawn(binary, execArgs, { stdio: options.stdio });
84
+ } });
85
+ const isWithinContainerMount = (mountTarget, cwd) => {
86
+ const relativePath = posix.relative(mountTarget, cwd);
87
+ return relativePath === "" || !relativePath.startsWith("..") && !posix.isAbsolute(relativePath);
88
+ };
89
+ const resolveHostMountPath = (mounts, cwd) => {
90
+ if (!mounts || mounts.length === 0) return;
91
+ const normalizedCwd = posix.normalize(cwd);
92
+ let bestMatch;
93
+ for (const mount of mounts) {
94
+ if (!isAbsolute(mount.source)) continue;
95
+ const normalizedTarget = posix.normalize(mount.target);
96
+ if (!isWithinContainerMount(normalizedTarget, normalizedCwd)) continue;
97
+ if (!bestMatch || normalizedTarget.length > posix.normalize(bestMatch.target).length) bestMatch = mount;
98
+ }
99
+ if (!bestMatch) return;
100
+ const relativePath = posix.relative(posix.normalize(bestMatch.target), normalizedCwd);
101
+ return relativePath === "" ? bestMatch.source : join(bestMatch.source, ...relativePath.split("/"));
102
+ };
103
+ const createOciContainer = async (type, params, config) => {
104
+ const { binary, builtImage, containerName: requestedContainerName, workdir, user, network, platform, env, ports, mounts, extraArgs, image } = params;
105
+ const containerName = requestedContainerName ?? generateContainerName();
106
+ const createArgs = [
107
+ "create",
108
+ "--name",
109
+ containerName
110
+ ];
111
+ if (user) createArgs.push("--user", user);
112
+ if (network) createArgs.push("--network", network);
113
+ if (platform) createArgs.push("--platform", platform);
114
+ if (env) for (const [key, value] of Object.entries(env)) createArgs.push("-e", `${key}=${value}`);
115
+ if (ports) for (const port of ports) {
116
+ const { host, container, protocol = "tcp" } = port;
117
+ createArgs.push("-p", `${host ?? ""}:${container}/${protocol}`);
118
+ }
119
+ if (mounts) for (const mount of mounts) {
120
+ const { readonly: isReadonly, source, target } = mount;
121
+ const mode = isReadonly ? "ro" : "rw";
122
+ createArgs.push("-v", `${source}:${target}:${mode}`);
123
+ }
124
+ if (extraArgs) createArgs.push(...extraArgs);
125
+ createArgs.push(image, "sleep", "infinity");
126
+ let containerId;
127
+ try {
128
+ const { stdout } = await runOci(binary, createArgs);
129
+ containerId = stdout.trim();
130
+ } catch (error) {
131
+ throw new ContainerCreateError(`Container create failed: ${formatError(error)}`);
132
+ }
133
+ let status = "created";
134
+ let portMappings = /* @__PURE__ */ new Map();
135
+ const assertNotDisposed = () => {
136
+ if (status === "disposed") throw new ContainerDisposedError();
137
+ };
138
+ const assertRunning = () => {
139
+ assertNotDisposed();
140
+ if (status !== "running") throw new ContainerNotRunningError();
141
+ };
142
+ const spawner = createOciSpawner(containerId, binary);
143
+ const diffApi = createWorkdirDiffApi({
144
+ owner: {},
145
+ workdir,
146
+ materialize: async (cwd, targetDir) => {
147
+ assertNotDisposed();
148
+ const hostPath = resolveHostMountPath(mounts, cwd);
149
+ if (hostPath) {
150
+ await copyLocalDirectoryContents(hostPath, targetDir);
151
+ return;
152
+ }
153
+ assertRunning();
154
+ try {
155
+ await runOci(binary, [
156
+ "exec",
157
+ containerId,
158
+ "sh",
159
+ "-c",
160
+ `test -d ${shellEscape(cwd)}`
161
+ ]);
162
+ } catch {
163
+ throw new ContainerDiffError(`Target path is not a directory: ${cwd}`);
164
+ }
165
+ try {
166
+ await runOci(binary, [
167
+ "cp",
168
+ `${containerId}:${cwd}/.`,
169
+ targetDir
170
+ ]);
171
+ } catch (error) {
172
+ throw new ContainerDiffError(`Failed to materialize container path ${cwd}: ${formatError(error)}`);
173
+ }
174
+ }
175
+ });
176
+ const instance = {
177
+ get type() {
178
+ return type;
179
+ },
180
+ get id() {
181
+ return containerId;
182
+ },
183
+ get name() {
184
+ return containerName;
185
+ },
186
+ get config() {
187
+ return config;
188
+ },
189
+ get status() {
190
+ return status;
191
+ },
192
+ get workdir() {
193
+ return workdir;
194
+ },
195
+ get spawner() {
196
+ return spawner;
197
+ },
198
+ async start() {
199
+ assertNotDisposed();
200
+ if (status === "running") return;
201
+ try {
202
+ await runOci(binary, ["start", containerId]);
203
+ } catch (error) {
204
+ throw new ContainerStartError(`Container start failed: ${formatError(error)}`);
205
+ }
206
+ try {
207
+ await runOci(binary, [
208
+ "exec",
209
+ containerId,
210
+ "mkdir",
211
+ "-p",
212
+ workdir
213
+ ]);
214
+ } catch (error) {
215
+ try {
216
+ await runOci(binary, [
217
+ "stop",
218
+ "-t",
219
+ "0",
220
+ containerId
221
+ ]);
222
+ status = "stopped";
223
+ } catch {
224
+ try {
225
+ const { stdout } = await runOci(binary, [
226
+ "inspect",
227
+ "--format",
228
+ "{{.State.Status}}",
229
+ containerId
230
+ ]);
231
+ status = stdout.trim() === "running" ? "running" : "stopped";
232
+ } catch {
233
+ status = "disposed";
234
+ }
235
+ }
236
+ throw new ContainerStartError(`Container start failed: ${formatError(error)}`);
237
+ }
238
+ status = "running";
239
+ if (ports?.length) portMappings = await resolvePortMappings(binary, containerId, ports);
240
+ },
241
+ async stop() {
242
+ assertNotDisposed();
243
+ if (status !== "running") return;
244
+ try {
245
+ await runOci(binary, [
246
+ "stop",
247
+ "-t",
248
+ "2",
249
+ containerId
250
+ ]);
251
+ } catch {
252
+ try {
253
+ const { stdout } = await runOci(binary, [
254
+ "inspect",
255
+ "--format",
256
+ "{{.State.Status}}",
257
+ containerId
258
+ ]);
259
+ if (stdout.trim() === "running") return;
260
+ } catch {
261
+ status = "disposed";
262
+ return;
263
+ }
264
+ }
265
+ status = "stopped";
266
+ },
267
+ async dispose() {
268
+ if (status === "disposed") return;
269
+ try {
270
+ await runOci(binary, [
271
+ "stop",
272
+ "-t",
273
+ "0",
274
+ containerId
275
+ ]);
276
+ } catch {}
277
+ try {
278
+ await runOci(binary, [
279
+ "rm",
280
+ "-f",
281
+ containerId
282
+ ]);
283
+ } catch {}
284
+ if (builtImage) await runOci(binary, ["rmi", image]).catch(() => {});
285
+ await diffApi.disposeSnapshots().catch(() => {});
286
+ status = "disposed";
287
+ },
288
+ async exec(command, args, options = {}) {
289
+ assertRunning();
290
+ const execArgs = ["exec"];
291
+ if (options.cwd) execArgs.push("-w", options.cwd);
292
+ if (options.env) for (const [key, value] of Object.entries(options.env)) execArgs.push("-e", `${key}=${value}`);
293
+ execArgs.push(containerId, command, ...args);
294
+ try {
295
+ const { stdout, stderr } = await runOci(binary, execArgs, {
296
+ timeoutMs: options.timeoutMs,
297
+ signal: options.signal
298
+ });
299
+ return {
300
+ exitCode: 0,
301
+ stdout,
302
+ stderr
303
+ };
304
+ } catch (error) {
305
+ if (isExecFileError(error)) return {
306
+ exitCode: typeof error.code === "number" ? error.code : -1,
307
+ stdout: String(error.stdout ?? ""),
308
+ stderr: String(error.stderr ?? "")
309
+ };
310
+ throw error;
311
+ }
312
+ },
313
+ async copyTo(hostPath, containerPath) {
314
+ assertRunning();
315
+ await runOci(binary, [
316
+ "cp",
317
+ hostPath,
318
+ `${containerId}:${containerPath}`
319
+ ]);
320
+ },
321
+ async copyFrom(containerPath, hostPath) {
322
+ assertRunning();
323
+ await runOci(binary, [
324
+ "cp",
325
+ `${containerId}:${containerPath}`,
326
+ hostPath
327
+ ]);
328
+ },
329
+ async writeFile(path, content) {
330
+ assertRunning();
331
+ const resolved = posix.isAbsolute(path) ? path : posix.resolve(workdir, path);
332
+ const dir = posix.dirname(resolved);
333
+ const encoded = typeof content === "string" ? Buffer.from(content, "utf8") : content;
334
+ const execArgs = ["exec", "-i"];
335
+ if (user) execArgs.push("--user", user);
336
+ execArgs.push(containerId, "sh", "-c", `mkdir -p ${shellEscape(dir)} && cat > ${shellEscape(resolved)}`);
337
+ const proc = DEFAULT_SPAWNER.spawn(binary, execArgs, { stdio: [
338
+ "pipe",
339
+ "ignore",
340
+ "ignore"
341
+ ] });
342
+ proc.stdin?.write?.(encoded);
343
+ proc.stdin?.end();
344
+ const result = await proc.wait();
345
+ if (result.exitCode !== 0) throw new ContainerExecError(`writeFile failed for ${resolved} (exit ${result.exitCode})`);
346
+ },
347
+ async readFile(path) {
348
+ assertRunning();
349
+ const resolved = posix.isAbsolute(path) ? path : posix.resolve(workdir, path);
350
+ const { stdout } = await runOci(binary, [
351
+ "exec",
352
+ containerId,
353
+ "cat",
354
+ resolved
355
+ ]);
356
+ return stdout;
357
+ },
358
+ async fileExists(path) {
359
+ assertRunning();
360
+ const resolved = posix.isAbsolute(path) ? path : posix.resolve(workdir, path);
361
+ try {
362
+ await runOci(binary, [
363
+ "exec",
364
+ containerId,
365
+ "test",
366
+ "-e",
367
+ resolved
368
+ ]);
369
+ return true;
370
+ } catch {
371
+ return false;
372
+ }
373
+ },
374
+ async mkdir(path) {
375
+ assertRunning();
376
+ const resolved = posix.isAbsolute(path) ? path : posix.resolve(workdir, path);
377
+ await runOci(binary, [
378
+ "exec",
379
+ containerId,
380
+ "mkdir",
381
+ "-p",
382
+ resolved
383
+ ]);
384
+ },
385
+ async execShell(script, options = {}) {
386
+ return instance.exec("sh", ["-c", script], options);
387
+ },
388
+ async logs(options = {}) {
389
+ assertNotDisposed();
390
+ const args = ["logs"];
391
+ if (options.tail !== void 0) args.push("--tail", String(options.tail));
392
+ args.push(containerId);
393
+ const { stdout } = await runOci(binary, args);
394
+ return stdout;
395
+ },
396
+ async syncStatus() {
397
+ assertNotDisposed();
398
+ try {
399
+ const { stdout } = await runOci(binary, [
400
+ "inspect",
401
+ "--format",
402
+ "{{.State.Status}}",
403
+ containerId
404
+ ]);
405
+ const raw = stdout.trim();
406
+ if (raw === "running") status = "running";
407
+ else if (raw === "created") status = "created";
408
+ else status = "stopped";
409
+ } catch {
410
+ status = "disposed";
411
+ }
412
+ return status;
413
+ },
414
+ async snapshotWorkdir(options = {}) {
415
+ return diffApi.snapshotWorkdir(options);
416
+ },
417
+ async diffWorkdir(snapshot) {
418
+ return diffApi.diffWorkdir(snapshot);
419
+ },
420
+ async releaseWorkdirSnapshot(snapshot) {
421
+ return diffApi.releaseWorkdirSnapshot(snapshot);
422
+ },
423
+ getMappedPort(containerPort) {
424
+ return portMappings.get(containerPort);
425
+ },
426
+ [Symbol.asyncDispose]() {
427
+ return instance.dispose();
428
+ }
429
+ };
430
+ return instance;
431
+ };
432
+ const resolveOciImage = async (binary, provider) => {
433
+ if (provider.image) return provider.image;
434
+ if (provider.build) return buildOciImage(binary, provider.build);
435
+ throw new ContainerCreateError("Either image or build must be provided.");
436
+ };
437
+ //#endregion
438
+ export { resolveOciImage as n, createOciContainer as t };
@@ -0,0 +1,2 @@
1
+ import { C as OutputSchema, D as imageContentPartSchema, E as contentPartSchema, O as textContentPartSchema, S as McpServerConfig, T as agentCapabilitiesSchema, _ as toolResultEventSchema, a as SessionStartEvent, b as ImageContentPart, c as ToolResultEvent, d as messageEventSchema, f as reasoningEventSchema, g as toolCallEventSchema, h as stderrEventSchema, i as SessionEndEvent, l as baseEventSchema, m as sessionStartEventSchema, n as MessageEvent, o as StderrEvent, p as sessionEndEventSchema, r as ReasoningEvent, s as ToolCallEvent, t as AgentEvent, u as eventSchema, v as AgentCapabilities, w as TextContentPart, x as JsonSchema, y as ContentPart } from "../events-nxuRbYIu.mjs";
2
+ export { type AgentCapabilities, type AgentEvent, type ContentPart, type ImageContentPart, type JsonSchema, type McpServerConfig, type MessageEvent, type OutputSchema, type ReasoningEvent, type SessionEndEvent, type SessionStartEvent, type StderrEvent, type TextContentPart, type ToolCallEvent, type ToolResultEvent, agentCapabilitiesSchema, baseEventSchema, contentPartSchema, eventSchema, imageContentPartSchema, messageEventSchema, reasoningEventSchema, sessionEndEventSchema, sessionStartEventSchema, stderrEventSchema, textContentPartSchema, toolCallEventSchema, toolResultEventSchema };
@@ -0,0 +1,2 @@
1
+ import { a as sessionEndEventSchema, c as toolCallEventSchema, d as contentPartSchema, f as imageContentPartSchema, i as reasoningEventSchema, l as toolResultEventSchema, n as eventSchema, o as sessionStartEventSchema, p as textContentPartSchema, r as messageEventSchema, s as stderrEventSchema, t as baseEventSchema, u as agentCapabilitiesSchema } from "../schemas-DwD4pwJB.mjs";
2
+ export { agentCapabilitiesSchema, baseEventSchema, contentPartSchema, eventSchema, imageContentPartSchema, messageEventSchema, reasoningEventSchema, sessionEndEventSchema, sessionStartEventSchema, stderrEventSchema, textContentPartSchema, toolCallEventSchema, toolResultEventSchema };