agent-neckbeard 1.1.17 → 1.1.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,15 +1,589 @@
1
+ import {
2
+ DETACHED_PROCESS_CONTROL_TIMEOUT_MS,
3
+ DETACHED_PROCESS_LOG_MAX_BYTES,
4
+ DetachedProcessController,
5
+ boundDetachedProcessLog,
6
+ buildLegacyDetachedStopCommand,
7
+ buildReadLegacyDetachedLogsCommand,
8
+ createDaytonaDetachedProcessController,
9
+ daytonaTimeoutSeconds,
10
+ discoverDaytonaSandboxDirectories,
11
+ executeDaytonaCommand,
12
+ executeRawDaytonaCommand,
13
+ makeDaytonaDirectory,
14
+ normalizeProviderSandboxDetachedCommandOptions,
15
+ parseDetachedProcessLogs,
16
+ shellQuote,
17
+ uploadDaytonaFile
18
+ } from "./chunk-3EB4CT5S.js";
1
19
  import {
2
20
  RUNTIME_PROTOCOL_VERSION
3
- } from "./chunk-AM2J5KBI.js";
21
+ } from "./chunk-DHFC3O44.js";
22
+ import "./chunk-33IXN6MM.js";
4
23
 
5
24
  // src/index.ts
6
25
  import { fileURLToPath } from "url";
7
- import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "fs";
8
- import { basename, dirname, join, relative, resolve } from "path";
26
+ import {
27
+ existsSync,
28
+ lstatSync,
29
+ readdirSync,
30
+ readFileSync,
31
+ statSync,
32
+ writeFileSync
33
+ } from "fs";
34
+ import {
35
+ basename,
36
+ dirname,
37
+ isAbsolute,
38
+ join,
39
+ posix,
40
+ relative,
41
+ resolve,
42
+ sep,
43
+ win32
44
+ } from "path";
9
45
  import { builtinModules, createRequire } from "module";
10
46
 
11
47
  // src/runtime/server-source.generated.ts
12
- var RUNTIME_SERVER_SOURCE = '// src/runtime/server.ts\nimport { createServer } from "node:http";\nimport { readFileSync } from "node:fs";\nimport { fileURLToPath } from "node:url";\nimport { dirname, join } from "node:path";\nimport { once } from "node:events";\n\n// src/runtime/protocol.ts\nvar RUNTIME_PROTOCOL_VERSION = 1;\n\n// src/runtime/server.ts\nvar CONFIG_PATH = join(dirname(fileURLToPath(import.meta.url)), "server-config.json");\nvar CONFIG = JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));\nvar MAX_REQUEST_BODY_BYTES = 4 * 1024 * 1024;\nvar DEFAULT_SSE_HEARTBEAT_INTERVAL_MS = 15e3;\nvar RequestBodyTooLargeError = class extends Error {\n constructor(limitBytes) {\n super(`request body exceeds ${limitBytes} bytes`);\n this.name = "RequestBodyTooLargeError";\n }\n};\nfunction createLogger() {\n return {\n debug: (message, ...args) => console.log("[DEBUG]", message, ...args),\n info: (message, ...args) => console.log("[INFO]", message, ...args),\n warn: (message, ...args) => console.warn("[WARN]", message, ...args),\n error: (message, ...args) => console.error("[ERROR]", message, ...args)\n };\n}\nfunction serializeError(error) {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n stack: error.stack\n };\n }\n return { message: String(error) };\n}\nfunction sendJson(res, status, body) {\n res.writeHead(status, { "content-type": "application/json" });\n res.end(JSON.stringify(body));\n}\nfunction getSseHeartbeatIntervalMs() {\n const raw = process.env.NECKBEARD_RUNTIME_SSE_HEARTBEAT_MS;\n if (!raw) return DEFAULT_SSE_HEARTBEAT_INTERVAL_MS;\n const parsed = Number(raw);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_SSE_HEARTBEAT_INTERVAL_MS;\n}\nfunction sendSseComment(res, comment) {\n if (res.writableEnded || res.destroyed) return;\n res.write(`: ${comment}\n\n`);\n}\nasync function sendSseFrame(res, event) {\n const canContinue = res.write(`data: ${JSON.stringify(event)}\n\n`);\n if (!canContinue) {\n await once(res, "drain");\n }\n}\nasync function readRequestBody(req, maxBytes = MAX_REQUEST_BODY_BYTES) {\n const chunks = [];\n let totalBytes = 0;\n for await (const chunk of req) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n totalBytes += buffer.byteLength;\n if (totalBytes > maxBytes) {\n throw new RequestBodyTooLargeError(maxBytes);\n }\n chunks.push(buffer);\n }\n return Buffer.concat(chunks).toString("utf-8");\n}\nfunction createTimeoutError(maxDurationMs) {\n const error = new Error(`Agent invocation exceeded maxDuration (${maxDurationMs}ms)`);\n error.name = "TimeoutError";\n return error;\n}\nasync function rejectOnAbort(promise, signal, maxDurationMs) {\n if (signal.aborted) {\n throw createTimeoutError(maxDurationMs);\n }\n let cleanup = () => void 0;\n const abortPromise = new Promise((_, reject) => {\n const onAbort = () => reject(createTimeoutError(maxDurationMs));\n cleanup = () => signal.removeEventListener("abort", onAbort);\n signal.addEventListener("abort", onAbort, { once: true });\n });\n try {\n return await Promise.race([promise, abortPromise]);\n } finally {\n cleanup();\n }\n}\nasync function loadAgent() {\n const mod = await import(new URL("./agent.mjs", import.meta.url).href);\n const agent = (mod.default && (mod.default._run || mod.default._server) ? mod.default : null) || Object.values(mod).find(\n (value) => value && typeof value === "object" && ("_run" in value || "_server" in value)\n );\n if (!agent || typeof agent !== "object") {\n throw new Error(\n `No agent found in agent.mjs. Exports: ${Object.keys(mod).join(", ")}`\n );\n }\n return agent;\n}\nasync function main() {\n const agent = await loadAgent();\n const server = createServer(async (req, res) => {\n try {\n const url = new URL(req.url ?? "/", "http://localhost");\n if (url.pathname === "/health" && req.method === "GET") {\n return sendJson(res, 200, {\n ok: true,\n protocolVersion: RUNTIME_PROTOCOL_VERSION\n });\n }\n if (url.pathname === "/shutdown" && req.method === "POST") {\n sendJson(res, 200, { ok: true });\n setTimeout(() => shutdown(), 10).unref();\n return;\n }\n if (url.pathname === "/invoke" && req.method === "POST") {\n let rawBody;\n try {\n rawBody = await readRequestBody(req);\n } catch (error) {\n if (error instanceof RequestBodyTooLargeError) {\n return sendJson(res, 413, { error: error.message });\n }\n throw error;\n }\n let requestBody;\n try {\n requestBody = JSON.parse(rawBody);\n } catch {\n return sendJson(res, 400, { error: "invalid JSON body" });\n }\n if (!requestBody || typeof requestBody !== "object" || typeof requestBody.invocationId !== "string") {\n return sendJson(res, 400, { error: "invalid invoke request" });\n }\n let validatedInput;\n try {\n validatedInput = agent.inputSchema.parse(requestBody.input);\n } catch (error) {\n return sendJson(res, 400, {\n error: `input validation failed: ${serializeError(error).message}`\n });\n }\n res.writeHead(200, {\n "content-type": "text/event-stream",\n "cache-control": "no-cache, no-transform",\n connection: "keep-alive",\n "x-accel-buffering": "no"\n });\n const controller = new AbortController();\n req.on("aborted", () => controller.abort());\n res.on("close", () => {\n if (!res.writableEnded) {\n controller.abort();\n }\n });\n const startedAt = Date.now();\n let sequence = 0;\n const timeout = setTimeout(() => controller.abort(), CONFIG.maxDurationMs);\n const invocationId = requestBody.invocationId;\n const heartbeat = setInterval(() => {\n try {\n sendSseComment(res, `heartbeat ${Date.now()}`);\n } catch {\n controller.abort();\n }\n }, getSseHeartbeatIntervalMs());\n heartbeat.unref();\n const emitHarnessEvent = async (event) => {\n if (!res.writableEnded) {\n await sendSseFrame(res, {\n protocolVersion: RUNTIME_PROTOCOL_VERSION,\n sequence: sequence++,\n timestamp: (/* @__PURE__ */ new Date()).toISOString(),\n elapsedMs: Date.now() - startedAt,\n ...event\n });\n }\n };\n const ctx = {\n executionId: invocationId,\n signal: controller.signal,\n env: process.env,\n sandbox: CONFIG.sandboxContext,\n logger: createLogger()\n };\n try {\n await emitHarnessEvent({ kind: "started", invocationId });\n if (agent._server) {\n await rejectOnAbort(\n agent._server.handler({\n input: validatedInput,\n ctx,\n signal: controller.signal,\n emit: async (data) => {\n const validatedFrame = agent._server?.frameSchema ? agent._server.frameSchema.parse(data) : data;\n await emitHarnessEvent({ kind: "frame", invocationId, data: validatedFrame });\n }\n }),\n controller.signal,\n CONFIG.maxDurationMs\n );\n } else if (agent._run) {\n const output = await rejectOnAbort(\n agent._run(validatedInput, ctx),\n controller.signal,\n CONFIG.maxDurationMs\n );\n const validatedOutput = agent.outputSchema ? agent.outputSchema.parse(output) : output;\n await emitHarnessEvent({ kind: "output", invocationId, output: validatedOutput });\n } else {\n throw new Error("Agent has neither a run handler nor a server handler.");\n }\n await emitHarnessEvent({ kind: "done", invocationId });\n } catch (error) {\n await emitHarnessEvent({ kind: "error", invocationId, error: serializeError(error) });\n } finally {\n clearInterval(heartbeat);\n clearTimeout(timeout);\n if (!res.writableEnded) {\n res.end();\n }\n }\n return;\n }\n return sendJson(res, 404, { error: "not found" });\n } catch (error) {\n console.error("[neckbeard-server] unexpected error", error);\n if (!res.headersSent) {\n sendJson(res, 500, { error: "internal error" });\n } else if (!res.writableEnded) {\n res.end();\n }\n }\n });\n function shutdown() {\n console.log("[neckbeard-server] shutting down");\n server.close(() => process.exit(0));\n setTimeout(() => process.exit(0), 5e3).unref();\n }\n server.listen(CONFIG.port, "0.0.0.0", () => {\n console.log(`[neckbeard-server] listening on port ${CONFIG.port}`);\n });\n process.on("SIGTERM", shutdown);\n process.on("SIGINT", shutdown);\n}\nmain().catch((error) => {\n console.error("[neckbeard-server] failed to start", error);\n process.exit(1);\n});\n';
48
+ var RUNTIME_SERVER_SOURCE = '// src/runtime/server.ts\nimport { createServer } from "node:http";\nimport { readFileSync } from "node:fs";\nimport { fileURLToPath } from "node:url";\nimport { dirname, join } from "node:path";\nimport { once } from "node:events";\n\n// src/serialized-error.ts\nfunction serializeError(error) {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n ...error.stack === void 0 ? {} : { stack: error.stack }\n };\n }\n return { message: String(error) };\n}\n\n// src/runtime/protocol.ts\nvar RUNTIME_PROTOCOL_VERSION = 1;\n\n// src/timeout.ts\nfunction settleOperation(operation, options = {}) {\n const { abort, timeout } = options;\n if (abort?.signal.aborted) throw abort.createError();\n if (!abort && !timeout) {\n try {\n return Promise.resolve(operation());\n } catch (error) {\n return Promise.reject(error);\n }\n }\n return new Promise((resolve, reject) => {\n let settled = false;\n let timer;\n const cleanup = () => {\n if (timer !== void 0) {\n clearTimeout(timer);\n timer = void 0;\n }\n abort?.signal.removeEventListener("abort", onAbort);\n };\n const settle = (callback) => {\n if (settled) return;\n settled = true;\n cleanup();\n callback();\n };\n const onAbort = () => settle(() => reject(abort.createError()));\n abort?.signal.addEventListener("abort", onAbort, { once: true });\n if (timeout) {\n timer = setTimeout(\n () => settle(() => reject(timeout.createError())),\n timeout.timeoutMs\n );\n }\n let task;\n try {\n task = operation();\n } catch (error) {\n settle(() => reject(error));\n return;\n }\n void Promise.resolve(task).then(\n (value) => settle(() => resolve(value)),\n (error) => settle(() => reject(error))\n );\n });\n}\n\n// src/runtime/server.ts\nvar CONFIG_PATH = join(dirname(fileURLToPath(import.meta.url)), "server-config.json");\nvar CONFIG = JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));\nvar MAX_REQUEST_BODY_BYTES = 4 * 1024 * 1024;\nvar DEFAULT_SSE_HEARTBEAT_INTERVAL_MS = 15e3;\nvar RequestBodyTooLargeError = class extends Error {\n constructor(limitBytes) {\n super(`request body exceeds ${limitBytes} bytes`);\n this.name = "RequestBodyTooLargeError";\n }\n};\nfunction createLogger() {\n return {\n debug: (message, ...args) => console.log("[DEBUG]", message, ...args),\n info: (message, ...args) => console.log("[INFO]", message, ...args),\n warn: (message, ...args) => console.warn("[WARN]", message, ...args),\n error: (message, ...args) => console.error("[ERROR]", message, ...args)\n };\n}\nfunction sendJson(res, status, body) {\n res.writeHead(status, { "content-type": "application/json" });\n res.end(JSON.stringify(body));\n}\nfunction getSseHeartbeatIntervalMs() {\n const raw = process.env.NECKBEARD_RUNTIME_SSE_HEARTBEAT_MS;\n if (!raw) return DEFAULT_SSE_HEARTBEAT_INTERVAL_MS;\n const parsed = Number(raw);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_SSE_HEARTBEAT_INTERVAL_MS;\n}\nfunction sendSseComment(res, comment) {\n if (res.writableEnded || res.destroyed) return;\n res.write(`: ${comment}\n\n`);\n}\nasync function sendSseFrame(res, event) {\n const canContinue = res.write(`data: ${JSON.stringify(event)}\n\n`);\n if (!canContinue) {\n await once(res, "drain");\n }\n}\nasync function readRequestBody(req, maxBytes = MAX_REQUEST_BODY_BYTES) {\n const chunks = [];\n let totalBytes = 0;\n for await (const chunk of req) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n totalBytes += buffer.byteLength;\n if (totalBytes > maxBytes) {\n throw new RequestBodyTooLargeError(maxBytes);\n }\n chunks.push(buffer);\n }\n return Buffer.concat(chunks).toString("utf-8");\n}\nfunction createTimeoutError(maxDurationMs) {\n const error = new Error(`Agent invocation exceeded maxDuration (${maxDurationMs}ms)`);\n error.name = "TimeoutError";\n return error;\n}\nasync function rejectOnAbort(operation, signal, maxDurationMs) {\n return settleOperation(operation, {\n abort: {\n signal,\n createError: () => createTimeoutError(maxDurationMs)\n }\n });\n}\nasync function loadAgent() {\n const mod = await import(new URL("./agent.mjs", import.meta.url).href);\n const agent = (mod.default && (mod.default._run || mod.default._server) ? mod.default : null) || Object.values(mod).find(\n (value) => value && typeof value === "object" && ("_run" in value || "_server" in value)\n );\n if (!agent || typeof agent !== "object") {\n throw new Error(\n `No agent found in agent.mjs. Exports: ${Object.keys(mod).join(", ")}`\n );\n }\n return agent;\n}\nasync function main() {\n const agent = await loadAgent();\n const server = createServer(async (req, res) => {\n try {\n const url = new URL(req.url ?? "/", "http://localhost");\n if (url.pathname === "/health" && req.method === "GET") {\n return sendJson(res, 200, {\n ok: true,\n protocolVersion: RUNTIME_PROTOCOL_VERSION\n });\n }\n if (url.pathname === "/shutdown" && req.method === "POST") {\n sendJson(res, 200, { ok: true });\n setTimeout(() => shutdown(), 10).unref();\n return;\n }\n if (url.pathname === "/invoke" && req.method === "POST") {\n let rawBody;\n try {\n rawBody = await readRequestBody(req);\n } catch (error) {\n if (error instanceof RequestBodyTooLargeError) {\n return sendJson(res, 413, { error: error.message });\n }\n throw error;\n }\n let requestBody;\n try {\n requestBody = JSON.parse(rawBody);\n } catch {\n return sendJson(res, 400, { error: "invalid JSON body" });\n }\n if (!requestBody || typeof requestBody !== "object" || typeof requestBody.invocationId !== "string") {\n return sendJson(res, 400, { error: "invalid invoke request" });\n }\n let validatedInput;\n try {\n validatedInput = agent.inputSchema.parse(requestBody.input);\n } catch (error) {\n return sendJson(res, 400, {\n error: `input validation failed: ${serializeError(error).message}`\n });\n }\n res.writeHead(200, {\n "content-type": "text/event-stream",\n "cache-control": "no-cache, no-transform",\n connection: "keep-alive",\n "x-accel-buffering": "no"\n });\n const controller = new AbortController();\n req.on("aborted", () => controller.abort());\n res.on("close", () => {\n if (!res.writableEnded) {\n controller.abort();\n }\n });\n const startedAt = Date.now();\n let sequence = 0;\n const timeout = setTimeout(() => controller.abort(), CONFIG.maxDurationMs);\n const invocationId = requestBody.invocationId;\n const heartbeat = setInterval(() => {\n try {\n sendSseComment(res, `heartbeat ${Date.now()}`);\n } catch {\n controller.abort();\n }\n }, getSseHeartbeatIntervalMs());\n heartbeat.unref();\n const emitHarnessEvent = async (event) => {\n if (!res.writableEnded) {\n await sendSseFrame(res, {\n protocolVersion: RUNTIME_PROTOCOL_VERSION,\n sequence: sequence++,\n timestamp: (/* @__PURE__ */ new Date()).toISOString(),\n elapsedMs: Date.now() - startedAt,\n ...event\n });\n }\n };\n const ctx = {\n executionId: invocationId,\n signal: controller.signal,\n env: process.env,\n sandbox: CONFIG.sandboxContext,\n logger: createLogger()\n };\n try {\n await emitHarnessEvent({ kind: "started", invocationId });\n if (agent._server) {\n await rejectOnAbort(\n () => agent._server.handler({\n input: validatedInput,\n ctx,\n signal: controller.signal,\n emit: async (data) => {\n const validatedFrame = agent._server?.frameSchema ? agent._server.frameSchema.parse(data) : data;\n await emitHarnessEvent({ kind: "frame", invocationId, data: validatedFrame });\n }\n }),\n controller.signal,\n CONFIG.maxDurationMs\n );\n } else if (agent._run) {\n const output = await rejectOnAbort(\n () => agent._run(validatedInput, ctx),\n controller.signal,\n CONFIG.maxDurationMs\n );\n const validatedOutput = agent.outputSchema ? agent.outputSchema.parse(output) : output;\n await emitHarnessEvent({ kind: "output", invocationId, output: validatedOutput });\n } else {\n throw new Error("Agent has neither a run handler nor a server handler.");\n }\n await emitHarnessEvent({ kind: "done", invocationId });\n } catch (error) {\n await emitHarnessEvent({ kind: "error", invocationId, error: serializeError(error) });\n } finally {\n clearInterval(heartbeat);\n clearTimeout(timeout);\n if (!res.writableEnded) {\n res.end();\n }\n }\n return;\n }\n return sendJson(res, 404, { error: "not found" });\n } catch (error) {\n console.error("[neckbeard-server] unexpected error", error);\n if (!res.headersSent) {\n sendJson(res, 500, { error: "internal error" });\n } else if (!res.writableEnded) {\n res.end();\n }\n }\n });\n function shutdown() {\n console.log("[neckbeard-server] shutting down");\n server.close(() => process.exit(0));\n setTimeout(() => process.exit(0), 5e3).unref();\n }\n server.listen(CONFIG.port, "0.0.0.0", () => {\n console.log(`[neckbeard-server] listening on port ${CONFIG.port}`);\n });\n process.on("SIGTERM", shutdown);\n process.on("SIGINT", shutdown);\n}\nmain().catch((error) => {\n console.error("[neckbeard-server] failed to start", error);\n process.exit(1);\n});\n';
49
+
50
+ // src/attached-session.ts
51
+ function linkAbortSignals(signals) {
52
+ const controller = new AbortController();
53
+ const listeners = /* @__PURE__ */ new Map();
54
+ const abortFrom = (signal) => {
55
+ if (!controller.signal.aborted) controller.abort(signal.reason);
56
+ };
57
+ for (const signal of signals) {
58
+ if (signal.aborted) {
59
+ abortFrom(signal);
60
+ break;
61
+ }
62
+ const listener = () => abortFrom(signal);
63
+ listeners.set(signal, listener);
64
+ signal.addEventListener("abort", listener, { once: true });
65
+ }
66
+ return {
67
+ signal: controller.signal,
68
+ dispose: () => {
69
+ for (const [signal, listener] of listeners) {
70
+ signal.removeEventListener("abort", listener);
71
+ }
72
+ listeners.clear();
73
+ }
74
+ };
75
+ }
76
+ var AttachedAgentSessionImpl = class {
77
+ durability = "attached";
78
+ sandboxId;
79
+ lifetime = new AbortController();
80
+ runPrompt;
81
+ configurationError;
82
+ activeTurn = null;
83
+ externalSignal = null;
84
+ externalAbortListener = null;
85
+ isClosed = false;
86
+ closePromise = null;
87
+ constructor(options) {
88
+ this.sandboxId = options.sandboxId;
89
+ this.runPrompt = options.runPrompt;
90
+ this.configurationError = options.configurationError;
91
+ const { externalSignal } = options;
92
+ if (externalSignal?.aborted) {
93
+ this.isClosed = true;
94
+ this.lifetime.abort(externalSignal.reason);
95
+ } else if (externalSignal) {
96
+ this.externalSignal = externalSignal;
97
+ this.externalAbortListener = () => {
98
+ void this.closeWithReason(externalSignal.reason);
99
+ };
100
+ externalSignal.addEventListener("abort", this.externalAbortListener, { once: true });
101
+ }
102
+ }
103
+ get closed() {
104
+ return this.isClosed;
105
+ }
106
+ prompt(input) {
107
+ return this.runTurn(input);
108
+ }
109
+ async stop(reason = "attached_session_stopped") {
110
+ await this.stopActiveTurn(reason);
111
+ }
112
+ close() {
113
+ return this.closeWithReason("attached_session_closed");
114
+ }
115
+ async *runTurn(input) {
116
+ if (this.isClosed || this.lifetime.signal.aborted) {
117
+ throw this.configurationError("Attached session is closed.");
118
+ }
119
+ if (this.activeTurn) {
120
+ throw this.configurationError("Attached session already has an active turn.");
121
+ }
122
+ const controller = new AbortController();
123
+ const linked = linkAbortSignals([this.lifetime.signal, controller.signal]);
124
+ const iterator = this.runPrompt(input, linked.signal);
125
+ const turn = {
126
+ controller,
127
+ iterator,
128
+ dispose: linked.dispose
129
+ };
130
+ this.activeTurn = turn;
131
+ try {
132
+ while (true) {
133
+ const next = await iterator.next();
134
+ if (next.done) return;
135
+ yield next.value;
136
+ }
137
+ } finally {
138
+ controller.abort("attached_turn_closed");
139
+ await iterator.return(void 0).catch(() => void 0);
140
+ turn.dispose();
141
+ if (this.activeTurn === turn) this.activeTurn = null;
142
+ }
143
+ }
144
+ async stopActiveTurn(reason) {
145
+ const turn = this.activeTurn;
146
+ if (!turn) return;
147
+ turn.controller.abort(reason);
148
+ await turn.iterator.return(void 0).catch(() => void 0);
149
+ turn.dispose();
150
+ if (this.activeTurn === turn) this.activeTurn = null;
151
+ }
152
+ closeWithReason(reason) {
153
+ if (this.closePromise) return this.closePromise;
154
+ this.closePromise = Promise.resolve().then(() => this.finishClose(reason));
155
+ this.isClosed = true;
156
+ this.lifetime.abort(reason);
157
+ return this.closePromise;
158
+ }
159
+ async finishClose(reason) {
160
+ await this.stopActiveTurn(reason);
161
+ if (this.externalSignal && this.externalAbortListener) {
162
+ this.externalSignal.removeEventListener("abort", this.externalAbortListener);
163
+ }
164
+ this.externalSignal = null;
165
+ this.externalAbortListener = null;
166
+ }
167
+ };
168
+ function createAttachedAgentSession(options) {
169
+ return new AttachedAgentSessionImpl(options);
170
+ }
171
+
172
+ // src/providers/types.ts
173
+ function createProviderSandboxPaths(provider, homeDir, workDir) {
174
+ const agentDir = `${homeDir}/agent`;
175
+ const ioDir = `${homeDir}/io`;
176
+ return {
177
+ provider,
178
+ homeDir,
179
+ workDir,
180
+ agentDir,
181
+ ioDir,
182
+ inputJson: `${ioDir}/input.json`,
183
+ outputJson: `${ioDir}/output.json`,
184
+ agentModule: `${agentDir}/agent.mjs`,
185
+ serverModule: `${agentDir}/server.mjs`,
186
+ serverConfig: `${agentDir}/server-config.json`,
187
+ claudeDir: `${agentDir}/.claude`,
188
+ packageJson: `${agentDir}/package.json`
189
+ };
190
+ }
191
+
192
+ // src/providers/daytona.ts
193
+ var SANDBOX_COMMAND_TIMEOUT_MS = 3e5;
194
+ var QUICK_COMMAND_TIMEOUT_MS = 3e4;
195
+ var LEGACY_DAYTONA_PROCESS_PATTERN = /^daytona-process:(\d+):(\d+):([a-z0-9-]+)$/iu;
196
+ function parseLegacyDaytonaProcessHandle(sessionId) {
197
+ const match = LEGACY_DAYTONA_PROCESS_PATTERN.exec(sessionId);
198
+ if (!match) return null;
199
+ const [, pid, startTicks, nonce] = match;
200
+ return pid && startTicks && nonce ? { pid, startTicks, nonce } : null;
201
+ }
202
+ var DaytonaSandboxHandle = class _DaytonaSandboxHandle {
203
+ constructor(sandbox, paths, failure) {
204
+ this.sandbox = sandbox;
205
+ this.paths = paths;
206
+ this.failure = failure;
207
+ this.detachedProcesses = createDaytonaDetachedProcessController(this.sandbox, {
208
+ homeDir: this.paths.homeDir,
209
+ readLegacyLogs: (command) => this.readLegacySessionLogs(command),
210
+ stopLegacy: (command) => this.stopLegacySession(command),
211
+ failure
212
+ });
213
+ }
214
+ provider = "daytona";
215
+ detachedProcesses;
216
+ static async create(sandbox, failure) {
217
+ const { homeDir, workDir } = await discoverDaytonaSandboxDirectories(
218
+ sandbox,
219
+ { failure }
220
+ );
221
+ return new _DaytonaSandboxHandle(
222
+ sandbox,
223
+ createProviderSandboxPaths("daytona", homeDir, workDir),
224
+ failure
225
+ );
226
+ }
227
+ get id() {
228
+ return this.sandbox.id;
229
+ }
230
+ async makeDir(path) {
231
+ const result = await makeDaytonaDirectory(this.sandbox, path, {
232
+ timeoutMs: QUICK_COMMAND_TIMEOUT_MS
233
+ });
234
+ if (result.exitCode !== 0) {
235
+ throw this.failure(result.result || `Failed to create directory ${path}`);
236
+ }
237
+ }
238
+ writeFile(path, content) {
239
+ return uploadDaytonaFile(this.sandbox, path, content, {
240
+ timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
241
+ });
242
+ }
243
+ async readFile(path) {
244
+ const content = await this.sandbox.fs.downloadFile(
245
+ path,
246
+ daytonaTimeoutSeconds(SANDBOX_COMMAND_TIMEOUT_MS)
247
+ );
248
+ return content.toString("utf8");
249
+ }
250
+ async readFileBytes(path) {
251
+ const content = await this.sandbox.fs.downloadFile(
252
+ path,
253
+ daytonaTimeoutSeconds(SANDBOX_COMMAND_TIMEOUT_MS)
254
+ );
255
+ return new Uint8Array(content);
256
+ }
257
+ async runCommand(cmd, options) {
258
+ const result = await executeDaytonaCommand(this.sandbox, cmd, {
259
+ timeoutMs: options.timeoutMs,
260
+ ...options.cwd === void 0 ? {} : { cwd: options.cwd },
261
+ ...options.envs === void 0 ? {} : { envs: options.envs }
262
+ });
263
+ if (result.stdout) options.onStdout?.(result.stdout);
264
+ return result;
265
+ }
266
+ async startDetachedCommand(command, options = {}) {
267
+ return this.detachedProcesses.start(command, options);
268
+ }
269
+ async readSessionLogs(command) {
270
+ return this.detachedProcesses.readLogs(command);
271
+ }
272
+ async readLegacySessionLogs(command) {
273
+ const { sessionId, commandId } = command;
274
+ const legacy = parseLegacyDaytonaProcessHandle(sessionId);
275
+ if (legacy) {
276
+ try {
277
+ const result = await executeDaytonaCommand(
278
+ this.sandbox,
279
+ buildReadLegacyDetachedLogsCommand(legacy.nonce),
280
+ { timeoutMs: QUICK_COMMAND_TIMEOUT_MS }
281
+ );
282
+ return result.exitCode === 0 ? parseDetachedProcessLogs(result.stdout) ?? { stdout: "", stderr: "" } : { stdout: "", stderr: "" };
283
+ } catch {
284
+ return { stdout: "", stderr: "" };
285
+ }
286
+ }
287
+ if (commandId === void 0) return { stdout: "", stderr: "" };
288
+ try {
289
+ const logs = await this.sandbox.process.getSessionCommandLogs(sessionId, commandId);
290
+ return {
291
+ stdout: boundDetachedProcessLog(logs.stdout ?? logs.output ?? ""),
292
+ stderr: boundDetachedProcessLog(logs.stderr ?? "")
293
+ };
294
+ } catch {
295
+ return { stdout: "", stderr: "" };
296
+ }
297
+ }
298
+ async stopSession(command) {
299
+ await this.detachedProcesses.stop(command);
300
+ }
301
+ async disposeSessionArtifacts(command) {
302
+ await this.detachedProcesses.dispose(command);
303
+ }
304
+ async stopLegacySession(command) {
305
+ const { sessionId } = command;
306
+ const detached = parseLegacyDaytonaProcessHandle(sessionId);
307
+ if (!detached) {
308
+ await this.sandbox.process.deleteSession(sessionId);
309
+ return;
310
+ }
311
+ const result = await executeRawDaytonaCommand(
312
+ this.sandbox,
313
+ buildLegacyDetachedStopCommand(detached.pid, detached.startTicks, "Daytona"),
314
+ { timeoutMs: QUICK_COMMAND_TIMEOUT_MS }
315
+ );
316
+ if (result.exitCode !== 0) {
317
+ throw this.failure(
318
+ result.result || `Failed to stop detached Daytona process ${detached.pid}.`
319
+ );
320
+ }
321
+ }
322
+ async getServerEndpoint(port) {
323
+ const preview = await this.sandbox.getPreviewLink(port);
324
+ return { url: preview.url, trafficToken: preview.token };
325
+ }
326
+ destroy() {
327
+ return this.sandbox.delete(daytonaTimeoutSeconds(SANDBOX_COMMAND_TIMEOUT_MS));
328
+ }
329
+ };
330
+
331
+ // src/timeout.ts
332
+ function settleOperation(operation, options = {}) {
333
+ const { abort, timeout } = options;
334
+ if (abort?.signal.aborted) throw abort.createError();
335
+ if (!abort && !timeout) {
336
+ try {
337
+ return Promise.resolve(operation());
338
+ } catch (error) {
339
+ return Promise.reject(error);
340
+ }
341
+ }
342
+ return new Promise((resolve2, reject) => {
343
+ let settled = false;
344
+ let timer;
345
+ const cleanup = () => {
346
+ if (timer !== void 0) {
347
+ clearTimeout(timer);
348
+ timer = void 0;
349
+ }
350
+ abort?.signal.removeEventListener("abort", onAbort);
351
+ };
352
+ const settle = (callback) => {
353
+ if (settled) return;
354
+ settled = true;
355
+ cleanup();
356
+ callback();
357
+ };
358
+ const onAbort = () => settle(() => reject(abort.createError()));
359
+ abort?.signal.addEventListener("abort", onAbort, { once: true });
360
+ if (timeout) {
361
+ timer = setTimeout(
362
+ () => settle(() => reject(timeout.createError())),
363
+ timeout.timeoutMs
364
+ );
365
+ }
366
+ let task;
367
+ try {
368
+ task = operation();
369
+ } catch (error) {
370
+ settle(() => reject(error));
371
+ return;
372
+ }
373
+ void Promise.resolve(task).then(
374
+ (value) => settle(() => resolve2(value)),
375
+ (error) => settle(() => reject(error))
376
+ );
377
+ });
378
+ }
379
+ function withTimeout(task, timeoutMs, message) {
380
+ return settleOperation(() => task, {
381
+ timeout: {
382
+ timeoutMs,
383
+ createError: () => new Error(message)
384
+ }
385
+ });
386
+ }
387
+
388
+ // src/providers/e2b.ts
389
+ var E2B_SANDBOX_HOME = "/home/user";
390
+ var LEGACY_E2B_PROCESS_HANDLE_PATTERN = /^e2b:([1-9][0-9]*)$/u;
391
+ var LEGACY_E2B_EXIT_POLL_INTERVAL_MS = 100;
392
+ function parseLegacyE2bProcessHandle(value) {
393
+ const match = LEGACY_E2B_PROCESS_HANDLE_PATTERN.exec(value);
394
+ if (!match) return null;
395
+ const pid = Number(match[1]);
396
+ return Number.isSafeInteger(pid) && pid > 0 ? pid : null;
397
+ }
398
+ function remainingTimeoutMs(deadline) {
399
+ return Math.max(1, Math.ceil(deadline - performance.now()));
400
+ }
401
+ function delay(timeoutMs) {
402
+ return new Promise((resolve2) => setTimeout(resolve2, timeoutMs));
403
+ }
404
+ async function withinDeadline(operation, deadline) {
405
+ return withTimeout(
406
+ operation,
407
+ remainingTimeoutMs(deadline),
408
+ "E2B process control request timed out."
409
+ );
410
+ }
411
+ function numberProperty(value, property) {
412
+ if (typeof value !== "object" || value === null) return void 0;
413
+ const propertyValue = Reflect.get(value, property);
414
+ return typeof propertyValue === "number" ? propertyValue : void 0;
415
+ }
416
+ function stringProperty(value, property) {
417
+ if (typeof value !== "object" || value === null) return void 0;
418
+ const propertyValue = Reflect.get(value, property);
419
+ return typeof propertyValue === "string" ? propertyValue : void 0;
420
+ }
421
+ function messageFrom(error) {
422
+ return error instanceof Error ? error.message : String(error);
423
+ }
424
+ function writeContent(content) {
425
+ if (typeof content === "string") return content;
426
+ if (content instanceof ArrayBuffer) return content;
427
+ return Uint8Array.from(content).buffer;
428
+ }
429
+ async function runE2bCommand(sandbox, cmd, options) {
430
+ let stdout = "";
431
+ let stderr = "";
432
+ const command = options.cwd ? `cd ${shellQuote(options.cwd)} && ${cmd}` : cmd;
433
+ try {
434
+ const result = await sandbox.commands.run(command, {
435
+ timeoutMs: options.timeoutMs,
436
+ envs: options.envs,
437
+ background: false,
438
+ onStdout: (data) => {
439
+ stdout += data;
440
+ options.onStdout?.(data);
441
+ },
442
+ onStderr: (data) => {
443
+ stderr += data;
444
+ options.onStderr?.(data);
445
+ }
446
+ });
447
+ return {
448
+ exitCode: result.exitCode,
449
+ stdout: stdout || result.stdout,
450
+ stderr: stderr || result.stderr
451
+ };
452
+ } catch (error) {
453
+ return {
454
+ exitCode: numberProperty(error, "exitCode") ?? 1,
455
+ stdout: stdout || stringProperty(error, "stdout") || "",
456
+ stderr: stderr || stringProperty(error, "stderr") || messageFrom(error)
457
+ };
458
+ }
459
+ }
460
+ var E2bSandboxHandle = class {
461
+ constructor(sandbox, failure) {
462
+ this.sandbox = sandbox;
463
+ this.failure = failure;
464
+ this.detachedProcesses = new DetachedProcessController({
465
+ provider: "e2b",
466
+ genericPayloadEnvironmentDefaults: { HOME: this.paths.homeDir },
467
+ execute: async (command, options) => ({
468
+ state: "completed",
469
+ result: await runE2bCommand(this.sandbox, command, {
470
+ cwd: options?.cwd,
471
+ envs: options?.envs,
472
+ timeoutMs: DETACHED_PROCESS_CONTROL_TIMEOUT_MS
473
+ })
474
+ }),
475
+ readLegacyLogs: (command) => this.readLegacySessionLogs(command),
476
+ stopLegacy: (command) => this.stopLegacySession(command),
477
+ failure
478
+ });
479
+ }
480
+ provider = "e2b";
481
+ detachedProcesses;
482
+ paths = createProviderSandboxPaths(
483
+ "e2b",
484
+ E2B_SANDBOX_HOME,
485
+ E2B_SANDBOX_HOME
486
+ );
487
+ get id() {
488
+ return this.sandbox.sandboxId;
489
+ }
490
+ async makeDir(path) {
491
+ await this.sandbox.files.makeDir(path);
492
+ }
493
+ writeFile(path, content) {
494
+ return this.sandbox.files.write(path, writeContent(content)).then(() => void 0);
495
+ }
496
+ readFile(path) {
497
+ return this.sandbox.files.read(path, { format: "text" });
498
+ }
499
+ readFileBytes(path) {
500
+ return this.sandbox.files.read(path, { format: "bytes" });
501
+ }
502
+ runCommand(cmd, options) {
503
+ return runE2bCommand(this.sandbox, cmd, options);
504
+ }
505
+ setTimeout(timeoutMs) {
506
+ return this.sandbox.setTimeout(timeoutMs);
507
+ }
508
+ async startDetachedCommand(command, options = {}) {
509
+ return this.detachedProcesses.start(command, options);
510
+ }
511
+ async readSessionLogs(command) {
512
+ return this.detachedProcesses.readLogs(command);
513
+ }
514
+ async readLegacySessionLogs(command) {
515
+ const { commandId } = command;
516
+ if (commandId === void 0) return { stdout: "", stderr: "" };
517
+ try {
518
+ const handle = await this.sandbox.commands.connect(Number(commandId));
519
+ return {
520
+ stdout: boundDetachedProcessLog(handle.stdout ?? ""),
521
+ stderr: boundDetachedProcessLog(handle.stderr ?? "")
522
+ };
523
+ } catch {
524
+ return { stdout: "", stderr: "" };
525
+ }
526
+ }
527
+ async stopSession(command) {
528
+ await this.detachedProcesses.stop(command);
529
+ }
530
+ async disposeSessionArtifacts(command) {
531
+ await this.detachedProcesses.dispose(command);
532
+ }
533
+ async stopLegacySession(command) {
534
+ const { sessionId } = command;
535
+ const legacyPid = parseLegacyE2bProcessHandle(sessionId);
536
+ if (legacyPid === null) {
537
+ throw this.failure("Detached process handle is invalid for E2B.");
538
+ }
539
+ const deadline = performance.now() + DETACHED_PROCESS_CONTROL_TIMEOUT_MS;
540
+ let signalled;
541
+ try {
542
+ signalled = await withinDeadline(
543
+ this.sandbox.commands.kill(legacyPid, {
544
+ requestTimeoutMs: remainingTimeoutMs(deadline)
545
+ }),
546
+ deadline
547
+ );
548
+ } catch (error) {
549
+ throw this.failure(
550
+ `Failed to stop legacy detached E2B process ${legacyPid}: ${messageFrom(error)}`
551
+ );
552
+ }
553
+ if (!signalled) return;
554
+ while (performance.now() < deadline) {
555
+ let processes;
556
+ try {
557
+ processes = await withinDeadline(
558
+ this.sandbox.commands.list({
559
+ requestTimeoutMs: remainingTimeoutMs(deadline)
560
+ }),
561
+ deadline
562
+ );
563
+ } catch (error) {
564
+ throw this.failure(
565
+ `Failed to confirm legacy detached E2B process ${legacyPid} exit: ${messageFrom(error)}`
566
+ );
567
+ }
568
+ if (!processes.some((process2) => process2.pid === legacyPid)) return;
569
+ const remaining = deadline - performance.now();
570
+ if (remaining <= 0) break;
571
+ await delay(Math.min(LEGACY_E2B_EXIT_POLL_INTERVAL_MS, remaining));
572
+ }
573
+ throw this.failure(
574
+ `Failed to stop legacy detached E2B process ${legacyPid}: provider still reports it as running.`
575
+ );
576
+ }
577
+ async getServerEndpoint(port) {
578
+ return {
579
+ url: `https://${this.sandbox.getHost(port)}`,
580
+ trafficToken: this.sandbox.trafficAccessToken
581
+ };
582
+ }
583
+ async destroy() {
584
+ await this.sandbox.kill();
585
+ }
586
+ };
13
587
 
14
588
  // src/index.ts
15
589
  function readPackageJson(path) {
@@ -19,8 +593,8 @@ var getEsbuild = () => import("esbuild");
19
593
  var getE2b = () => import("e2b");
20
594
  var getDaytona = () => import("@daytona/sdk");
21
595
  var DEFAULT_MAX_DURATION = 300;
22
- var SANDBOX_COMMAND_TIMEOUT_MS = 3e5;
23
- var QUICK_COMMAND_TIMEOUT_MS = 3e4;
596
+ var SANDBOX_COMMAND_TIMEOUT_MS2 = 3e5;
597
+ var QUICK_COMMAND_TIMEOUT_MS2 = 3e4;
24
598
  var DAYTONA_CREATE_TIMEOUT_SEC = 120;
25
599
  var NODE_TARGET = "node20";
26
600
  var DEFAULT_EXTERNALS = ["@anthropic-ai/claude-agent-sdk"];
@@ -32,9 +606,9 @@ var DEFAULT_SERVER_PORT = 3e3;
32
606
  var SERVER_HEALTH_TIMEOUT_MS = 12e4;
33
607
  var SERVER_RECONNECT_HEALTH_TIMEOUT_MS = 3e3;
34
608
  var SERVER_HEALTH_POLL_INTERVAL_MS = 1e3;
609
+ var SERVER_FAILURE_DIAGNOSTIC_TIMEOUT_MS = 1e3;
35
610
  var NATIVE_EXT_RE = /\.(node|wasm|gyp|c|cc|cpp|cxx|h|hpp|hxx)$/i;
36
611
  var TRACEABLE_SOURCE_EXT_RE = /\.(cjs|cts|js|jsx|mjs|mts|ts|tsx)$/i;
37
- var E2B_SANDBOX_HOME = "/home/user";
38
612
  var NeckbeardError = class extends Error {
39
613
  constructor(message) {
40
614
  super(message);
@@ -496,8 +1070,20 @@ function mergeTracingIncludes(existing, routeGlobs, sourceFiles) {
496
1070
  return includes;
497
1071
  }
498
1072
  var DEFAULT_DEPENDENCIES = {};
499
- function isServerAgentConfig(config) {
500
- return "server" in config && config.server !== void 0;
1073
+ function isSessionAgentConfig(config) {
1074
+ return "session" in config && config.session !== void 0 || "server" in config && config.server !== void 0;
1075
+ }
1076
+ function getSessionHandler(config) {
1077
+ const session = "session" in config ? config.session : void 0;
1078
+ const server = "server" in config ? config.server : void 0;
1079
+ if (session && server) {
1080
+ throw new ConfigurationError("Agent config must use session or deprecated server, not both.");
1081
+ }
1082
+ const handler = session ?? server;
1083
+ if (!handler || typeof handler !== "object") {
1084
+ throw new ConfigurationError("session must be an object.");
1085
+ }
1086
+ return handler;
501
1087
  }
502
1088
  function isSchemaLike(value) {
503
1089
  return Boolean(
@@ -510,6 +1096,67 @@ function requireSchemaLike(name, value) {
510
1096
  }
511
1097
  return value;
512
1098
  }
1099
+ function isAbortSignal(value) {
1100
+ if (!value || typeof value !== "object") return false;
1101
+ try {
1102
+ const abortedGetter = Object.getOwnPropertyDescriptor(
1103
+ AbortSignal.prototype,
1104
+ "aborted"
1105
+ )?.get;
1106
+ if (!abortedGetter || typeof abortedGetter.call(value) !== "boolean") return false;
1107
+ const candidate = value;
1108
+ return typeof candidate.aborted === "boolean" && typeof candidate.addEventListener === "function" && typeof candidate.removeEventListener === "function";
1109
+ } catch {
1110
+ return false;
1111
+ }
1112
+ }
1113
+ function normalizeLocalDirectoryDestination(destination, name) {
1114
+ if (destination.trim() === "") {
1115
+ throw new ConfigurationError(`${name}.destination must be a non-empty relative path.`);
1116
+ }
1117
+ if (destination.includes("\0")) {
1118
+ throw new ConfigurationError(`${name}.destination must not contain null bytes.`);
1119
+ }
1120
+ const sandboxPath = destination.replace(/\\/g, "/");
1121
+ if (isAbsolute(destination) || posix.isAbsolute(sandboxPath) || win32.isAbsolute(destination)) {
1122
+ throw new ConfigurationError(
1123
+ `${name}.destination must be relative to the sandbox agent directory.`
1124
+ );
1125
+ }
1126
+ if (sandboxPath.split("/").includes("..")) {
1127
+ throw new ConfigurationError(
1128
+ `${name}.destination must not traverse outside the sandbox agent directory.`
1129
+ );
1130
+ }
1131
+ const normalized = posix.normalize(sandboxPath);
1132
+ if (normalized === ".") {
1133
+ throw new ConfigurationError(`${name}.destination must not be ".".`);
1134
+ }
1135
+ return normalized;
1136
+ }
1137
+ function validateLocalDirectoriesConfig(value) {
1138
+ if (value === void 0) return;
1139
+ if (!Array.isArray(value)) {
1140
+ throw new ConfigurationError("localDirectories must be an array when provided.");
1141
+ }
1142
+ for (const [index, entry] of value.entries()) {
1143
+ const name = `localDirectories[${index}]`;
1144
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
1145
+ throw new ConfigurationError(`${name} must be an object.`);
1146
+ }
1147
+ const candidate = entry;
1148
+ if (typeof candidate.source !== "string" || candidate.source.trim() === "") {
1149
+ throw new ConfigurationError(`${name}.source must be a non-empty string.`);
1150
+ }
1151
+ if (candidate.source.includes("\0")) {
1152
+ throw new ConfigurationError(`${name}.source must not contain null bytes.`);
1153
+ }
1154
+ if (typeof candidate.destination !== "string") {
1155
+ throw new ConfigurationError(`${name}.destination must be a string.`);
1156
+ }
1157
+ normalizeLocalDirectoryDestination(candidate.destination, name);
1158
+ }
1159
+ }
513
1160
  function validateAgentConfig(config) {
514
1161
  if (!config || typeof config !== "object") {
515
1162
  throw new ConfigurationError("Agent config must be an object.");
@@ -530,21 +1177,20 @@ function validateAgentConfig(config) {
530
1177
  if (config.sourceFile !== void 0 && (typeof config.sourceFile !== "string" || config.sourceFile.trim() === "")) {
531
1178
  throw new ConfigurationError("sourceFile must be a non-empty string when provided.");
532
1179
  }
533
- if (isServerAgentConfig(config)) {
1180
+ validateLocalDirectoriesConfig(config.localDirectories);
1181
+ if (isSessionAgentConfig(config)) {
534
1182
  if ("run" in config && typeof config.run === "function") {
535
- throw new ConfigurationError("Agent config must use either run or server.handler, not both.");
1183
+ throw new ConfigurationError("Agent config must use either run or session.handler, not both.");
536
1184
  }
537
- if (!config.server || typeof config.server !== "object") {
538
- throw new ConfigurationError("server must be an object.");
539
- }
540
- if (config.server.port !== void 0) {
541
- if (!Number.isInteger(config.server.port) || config.server.port < 1 || config.server.port > 65535) {
542
- throw new ConfigurationError("server.port must be an integer between 1 and 65535.");
1185
+ const session = getSessionHandler(config);
1186
+ if (session.port !== void 0) {
1187
+ if (!Number.isInteger(session.port) || session.port < 1 || session.port > 65535) {
1188
+ throw new ConfigurationError("session.port must be an integer between 1 and 65535.");
543
1189
  }
544
1190
  }
545
- requireSchemaLike("server.frameSchema", config.server.frameSchema);
546
- if (typeof config.server.handler !== "function") {
547
- throw new ConfigurationError("server.handler must be a function.");
1191
+ requireSchemaLike("session.frameSchema", session.frameSchema);
1192
+ if (typeof session.handler !== "function") {
1193
+ throw new ConfigurationError("session.handler must be a function.");
548
1194
  }
549
1195
  return;
550
1196
  }
@@ -569,24 +1215,86 @@ function trafficTokenHeaders(descriptor) {
569
1215
  }
570
1216
  return {};
571
1217
  }
572
- async function waitForServerHealthy(healthUrl, descriptor, timeoutMs = SERVER_HEALTH_TIMEOUT_MS) {
1218
+ function abortSignalError(signal) {
1219
+ if (signal.reason instanceof Error) return signal.reason;
1220
+ const error = new Error(
1221
+ signal.reason === void 0 ? "Operation aborted." : String(signal.reason)
1222
+ );
1223
+ error.name = "AbortError";
1224
+ return error;
1225
+ }
1226
+ function throwIfAborted(signal) {
1227
+ if (signal?.aborted) throw abortSignalError(signal);
1228
+ }
1229
+ function awaitWithAbort(operation, signal) {
1230
+ return settleOperation(operation, {
1231
+ ...signal ? {
1232
+ abort: {
1233
+ signal,
1234
+ createError: () => abortSignalError(signal)
1235
+ }
1236
+ } : {}
1237
+ });
1238
+ }
1239
+ function awaitDiagnosticRead(operation, signal) {
1240
+ return settleOperation(operation, {
1241
+ ...signal ? {
1242
+ abort: {
1243
+ signal,
1244
+ createError: () => abortSignalError(signal)
1245
+ }
1246
+ } : {},
1247
+ timeout: {
1248
+ timeoutMs: SERVER_FAILURE_DIAGNOSTIC_TIMEOUT_MS,
1249
+ createError: () => new Error("Server diagnostic read timed out.")
1250
+ }
1251
+ });
1252
+ }
1253
+ function delayWithAbort(delayMs, signal) {
1254
+ if (!signal) {
1255
+ return new Promise((resolve2) => setTimeout(resolve2, delayMs));
1256
+ }
1257
+ throwIfAborted(signal);
1258
+ return new Promise((resolve2, reject) => {
1259
+ const onAbort = () => {
1260
+ clearTimeout(timer);
1261
+ reject(abortSignalError(signal));
1262
+ };
1263
+ const timer = setTimeout(() => {
1264
+ signal.removeEventListener("abort", onAbort);
1265
+ resolve2();
1266
+ }, delayMs);
1267
+ signal.addEventListener("abort", onAbort, { once: true });
1268
+ });
1269
+ }
1270
+ async function waitForServerHealthy(healthUrl, descriptor, timeoutMs = SERVER_HEALTH_TIMEOUT_MS, signal) {
573
1271
  const deadline = Date.now() + timeoutMs;
574
1272
  let lastError;
575
1273
  const urlWithToken = appendTrafficTokenToUrl(healthUrl, descriptor);
576
1274
  while (Date.now() < deadline) {
1275
+ throwIfAborted(signal);
577
1276
  try {
578
- const response = await fetch(urlWithToken, {
579
- headers: trafficTokenHeaders(descriptor)
580
- });
1277
+ const response = await awaitWithAbort(
1278
+ () => fetch(urlWithToken, {
1279
+ headers: trafficTokenHeaders(descriptor),
1280
+ ...signal === void 0 ? {} : { signal }
1281
+ }),
1282
+ signal
1283
+ );
581
1284
  if (response.ok) {
582
- await response.text().catch(() => void 0);
1285
+ try {
1286
+ await awaitWithAbort(() => response.text(), signal);
1287
+ } catch {
1288
+ throwIfAborted(signal);
1289
+ }
583
1290
  return;
584
1291
  }
585
1292
  lastError = new Error(`health check returned ${response.status}`);
586
1293
  } catch (error) {
1294
+ throwIfAborted(signal);
587
1295
  lastError = error;
588
1296
  }
589
- await new Promise((resolve2) => setTimeout(resolve2, SERVER_HEALTH_POLL_INTERVAL_MS));
1297
+ await delayWithAbort(SERVER_HEALTH_POLL_INTERVAL_MS, signal);
590
1298
  }
591
1299
  const message = lastError instanceof Error ? lastError.message : String(lastError);
592
1300
  throw new DeploymentError(
@@ -602,9 +1310,6 @@ function requireEnv(name) {
602
1310
  }
603
1311
  return value;
604
1312
  }
605
- function shellEscape(str) {
606
- return `'${str.replace(/'/g, "'\\''")}'`;
607
- }
608
1313
  var require2 = createRequire(join(process.cwd(), "__agent_neckbeard__.cjs"));
609
1314
  var packageRequire = createPackageRequire();
610
1315
  function createPackageRequire() {
@@ -730,254 +1435,92 @@ function listAllowsTarget(list, target) {
730
1435
  function isPackageCompatible(info) {
731
1436
  const osList = normalizeList(info.packageJson.os);
732
1437
  const cpuList = normalizeList(info.packageJson.cpu);
733
- return listAllowsTarget(osList, SANDBOX_PLATFORM) && listAllowsTarget(cpuList, SANDBOX_ARCH);
734
- }
735
- function filterDefinedEnvs(envs) {
736
- const filtered = {};
737
- for (const [key, value] of Object.entries(envs)) {
738
- if (value !== void 0) {
739
- filtered[key] = value;
740
- }
741
- }
742
- return filtered;
743
- }
744
- function arrayBufferToBuffer(value) {
745
- return Buffer.from(value);
746
- }
747
- function toDaytonaUploadContent(content) {
748
- if (typeof content === "string") return Buffer.from(content);
749
- if (Buffer.isBuffer(content)) return content;
750
- if (content instanceof Uint8Array) return Buffer.from(content);
751
- return arrayBufferToBuffer(content);
752
- }
753
- function toE2bWriteContent(content) {
754
- if (typeof content === "string") return content;
755
- if (content instanceof ArrayBuffer) return content;
756
- return Uint8Array.from(content).buffer;
757
- }
758
- function createSandboxPaths(provider, homeDir, workDir) {
759
- const agentDir = `${homeDir}/agent`;
760
- const ioDir = `${homeDir}/io`;
761
- return {
762
- provider,
763
- homeDir,
764
- workDir,
765
- agentDir,
766
- ioDir,
767
- inputJson: `${ioDir}/input.json`,
768
- outputJson: `${ioDir}/output.json`,
769
- agentModule: `${agentDir}/agent.mjs`,
770
- serverModule: `${agentDir}/server.mjs`,
771
- serverConfig: `${agentDir}/server-config.json`,
772
- claudeDir: `${agentDir}/.claude`,
773
- packageJson: `${agentDir}/package.json`
774
- };
775
- }
776
- function timeoutMsToSeconds(timeoutMs) {
777
- return Math.max(1, Math.ceil(timeoutMs / 1e3));
778
- }
779
- function asError(error) {
780
- return error instanceof Error ? error : new Error(String(error));
781
- }
782
- function errorMessage(error) {
783
- return error instanceof Error ? error.message : String(error);
784
- }
785
- async function resolveDaytonaPaths(sandbox) {
786
- const workDir = await sandbox.getWorkDir() ?? await sandbox.getUserHomeDir();
787
- const homeDir = await sandbox.getUserHomeDir() ?? workDir;
788
- if (!homeDir || !workDir) {
789
- throw new DeploymentError("Daytona sandbox did not report a home or working directory.");
790
- }
791
- return createSandboxPaths("daytona", homeDir, workDir);
792
- }
793
- function numberProperty(value, property) {
794
- if (typeof value !== "object" || value === null) return void 0;
795
- const propertyValue = Reflect.get(value, property);
796
- return typeof propertyValue === "number" ? propertyValue : void 0;
797
- }
798
- function stringProperty(value, property) {
799
- if (typeof value !== "object" || value === null) return void 0;
800
- const propertyValue = Reflect.get(value, property);
801
- return typeof propertyValue === "string" ? propertyValue : void 0;
802
- }
803
- async function runE2bCommand(sandbox, cmd, options) {
804
- let stdout = "";
805
- let stderr = "";
806
- try {
807
- const result = await sandbox.commands.run(cmd, {
808
- timeoutMs: options.timeoutMs,
809
- envs: options.envs,
810
- background: false,
811
- onStdout: (data) => {
812
- stdout += data;
813
- options.onStdout?.(data);
814
- },
815
- onStderr: (data) => {
816
- stderr += data;
817
- options.onStderr?.(data);
818
- }
819
- });
820
- return {
821
- exitCode: result.exitCode,
822
- stdout: stdout || result.stdout,
823
- stderr: stderr || result.stderr
824
- };
825
- } catch (error) {
826
- const exitCode = numberProperty(error, "exitCode") ?? 1;
827
- return {
828
- exitCode,
829
- stdout: stdout || stringProperty(error, "stdout") || "",
830
- stderr: stderr || stringProperty(error, "stderr") || errorMessage(error)
831
- };
832
- }
1438
+ return listAllowsTarget(osList, SANDBOX_PLATFORM) && listAllowsTarget(cpuList, SANDBOX_ARCH);
833
1439
  }
834
- var E2bSandboxHandle = class {
835
- constructor(sandbox) {
836
- this.sandbox = sandbox;
837
- }
838
- provider = "e2b";
839
- paths = createSandboxPaths("e2b", E2B_SANDBOX_HOME, E2B_SANDBOX_HOME);
840
- get id() {
841
- return this.sandbox.sandboxId;
842
- }
843
- async makeDir(path) {
844
- await this.sandbox.files.makeDir(path);
845
- }
846
- writeFile(path, content) {
847
- return this.sandbox.files.write(path, toE2bWriteContent(content)).then(() => void 0);
848
- }
849
- readFile(path) {
850
- return this.sandbox.files.read(path, { format: "text" });
851
- }
852
- readFileBytes(path) {
853
- return this.sandbox.files.read(path, { format: "bytes" });
854
- }
855
- runCommand(cmd, options) {
856
- const command = options.cwd ? `cd ${shellEscape(options.cwd)} && ${cmd}` : cmd;
857
- return runE2bCommand(this.sandbox, command, options);
858
- }
859
- setTimeout(timeoutMs) {
860
- return this.sandbox.setTimeout(timeoutMs);
861
- }
862
- async startDetachedCommand(cmd, options) {
863
- const command = options.cwd ? `cd ${shellEscape(options.cwd)} && ${cmd}` : cmd;
864
- const handle = await this.sandbox.commands.run(command, {
865
- timeoutMs: 0,
866
- envs: options.envs,
867
- background: true
868
- });
869
- return { sessionId: `e2b:${handle.pid}`, commandId: String(handle.pid) };
870
- }
871
- async readSessionLogs(_sessionId, commandId) {
872
- try {
873
- const handle = await this.sandbox.commands.connect(Number(commandId));
874
- return { stdout: handle.stdout ?? "", stderr: handle.stderr ?? "" };
875
- } catch {
876
- return { stdout: "", stderr: "" };
877
- }
1440
+ var INVALID_DETACHED_COMMAND_HANDLE_MESSAGE = "Detached process handle must contain a non-empty sessionId string and an optional commandId string.";
1441
+ function normalizeDetachedCommandHandle(value) {
1442
+ if (!value || typeof value !== "object") {
1443
+ throw new ConfigurationError(INVALID_DETACHED_COMMAND_HANDLE_MESSAGE);
878
1444
  }
879
- async stopSession(sessionId) {
880
- const pid = Number(sessionId.replace(/^e2b:/, ""));
881
- if (Number.isFinite(pid)) {
882
- await this.sandbox.commands.kill(pid);
1445
+ let sessionId;
1446
+ let commandId;
1447
+ try {
1448
+ if (Array.isArray(value)) {
1449
+ throw new Error("invalid detached command handle");
883
1450
  }
1451
+ sessionId = Reflect.get(value, "sessionId");
1452
+ commandId = Reflect.get(value, "commandId");
1453
+ } catch {
1454
+ throw new ConfigurationError(INVALID_DETACHED_COMMAND_HANDLE_MESSAGE);
884
1455
  }
885
- async getServerEndpoint(port) {
886
- return {
887
- url: `https://${this.sandbox.getHost(port)}`,
888
- trafficToken: this.sandbox.trafficAccessToken
889
- };
890
- }
891
- async destroy() {
892
- await this.sandbox.kill();
893
- }
894
- };
895
- var DaytonaSandboxHandle = class _DaytonaSandboxHandle {
896
- constructor(sandbox, paths) {
897
- this.sandbox = sandbox;
898
- this.paths = paths;
899
- }
900
- provider = "daytona";
901
- static async create(sandbox) {
902
- return new _DaytonaSandboxHandle(sandbox, await resolveDaytonaPaths(sandbox));
903
- }
904
- get id() {
905
- return this.sandbox.id;
1456
+ if (typeof sessionId !== "string" || sessionId.length === 0 || commandId !== void 0 && typeof commandId !== "string") {
1457
+ throw new ConfigurationError(INVALID_DETACHED_COMMAND_HANDLE_MESSAGE);
906
1458
  }
907
- async makeDir(path) {
908
- const result = await this.sandbox.process.executeCommand(
909
- `mkdir -p ${shellEscape(path)}`,
910
- void 0,
911
- void 0,
912
- timeoutMsToSeconds(QUICK_COMMAND_TIMEOUT_MS)
913
- );
914
- if (result.exitCode !== 0) {
915
- throw new DeploymentError(result.result || `Failed to create directory ${path}`);
1459
+ return commandId === void 0 ? { sessionId } : { sessionId, commandId };
1460
+ }
1461
+ function filterDefinedEnvs(envs) {
1462
+ const filtered = {};
1463
+ for (const [key, value] of Object.entries(envs)) {
1464
+ if (value !== void 0) {
1465
+ filtered[key] = value;
916
1466
  }
917
1467
  }
918
- writeFile(path, content) {
919
- return this.sandbox.fs.uploadFile(
920
- toDaytonaUploadContent(content),
921
- path,
922
- timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS)
923
- );
1468
+ return filtered;
1469
+ }
1470
+ function asError(error) {
1471
+ return error instanceof Error ? error : new Error(String(error));
1472
+ }
1473
+ function errorMessage(error) {
1474
+ return error instanceof Error ? error.message : String(error);
1475
+ }
1476
+ var MINIMUM_BULK_DIAGNOSTIC_REDACTION_LENGTH = 8;
1477
+ var CREDENTIAL_ENV_NAME_PATTERN = /(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)/iu;
1478
+ function isConfiguredDiagnosticSecret(name, value) {
1479
+ return CREDENTIAL_ENV_NAME_PATTERN.test(name) || value.length >= MINIMUM_BULK_DIAGNOSTIC_REDACTION_LENGTH;
1480
+ }
1481
+ function redactServerFailureDiagnosticStream(value, secrets) {
1482
+ const mayStartAtTailBoundary = Buffer.byteLength(value, "utf8") >= DETACHED_PROCESS_LOG_MAX_BYTES - 3;
1483
+ let redacted = boundDetachedProcessLog(value);
1484
+ for (const secret of secrets) {
1485
+ const replacement = secret.length < "[REDACTED]".length ? "*" : "[REDACTED]";
1486
+ redacted = redacted.split(secret).join(replacement);
924
1487
  }
925
- async readFile(path) {
926
- const content = await this.sandbox.fs.downloadFile(path, timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS));
927
- return content.toString("utf-8");
1488
+ let maximumSecretLength = 0;
1489
+ for (const secret of secrets) {
1490
+ maximumSecretLength = Math.max(maximumSecretLength, secret.length);
928
1491
  }
929
- async readFileBytes(path) {
930
- const content = await this.sandbox.fs.downloadFile(path, timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS));
931
- return new Uint8Array(content);
1492
+ if (mayStartAtTailBoundary && maximumSecretLength > 0 && redacted.length > 0) {
1493
+ redacted = redacted.slice(maximumSecretLength);
932
1494
  }
933
- async runCommand(cmd, options) {
934
- const result = await this.sandbox.process.executeCommand(
935
- cmd,
936
- options.cwd,
937
- options.envs,
938
- timeoutMsToSeconds(options.timeoutMs)
1495
+ return boundDetachedProcessLog(redacted);
1496
+ }
1497
+ async function readServerFailureDiagnostics(sandbox, command, environment, signal) {
1498
+ if (!sandbox.readSessionLogs) return "";
1499
+ try {
1500
+ const captured = await awaitDiagnosticRead(
1501
+ () => sandbox.readSessionLogs(command),
1502
+ signal
939
1503
  );
940
- const stdout = result.artifacts?.stdout ?? result.result ?? "";
941
- if (stdout) options.onStdout?.(stdout);
942
- return {
943
- exitCode: result.exitCode,
944
- stdout,
945
- stderr: ""
946
- };
947
- }
948
- async startDetachedCommand(cmd, options) {
949
- const sessionId = `neckbeard-server-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
950
- await this.sandbox.process.createSession(sessionId);
951
- const envPrefix = options.envs ? Object.entries(options.envs).map(([key, value]) => `${key}=${shellEscape(value)}`).join(" ") + " " : "";
952
- const cwdPrefix = options.cwd ? `cd ${shellEscape(options.cwd)} && ` : "";
953
- const result = await this.sandbox.process.executeSessionCommand(sessionId, {
954
- command: `${cwdPrefix}${envPrefix}${cmd}`,
955
- runAsync: true
956
- });
957
- return { sessionId, commandId: result.cmdId };
958
- }
959
- async readSessionLogs(sessionId, commandId) {
960
- try {
961
- const logs = await this.sandbox.process.getSessionCommandLogs(sessionId, commandId);
962
- return {
963
- stdout: logs.stdout ?? logs.output ?? "",
964
- stderr: logs.stderr ?? ""
965
- };
966
- } catch {
967
- return { stdout: "", stderr: "" };
968
- }
969
- }
970
- stopSession(sessionId) {
971
- return this.sandbox.process.deleteSession(sessionId);
972
- }
973
- async getServerEndpoint(port) {
974
- const preview = await this.sandbox.getPreviewLink(port);
975
- return { url: preview.url, trafficToken: preview.token };
976
- }
977
- destroy() {
978
- return this.sandbox.delete(timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS));
1504
+ const secrets = Object.entries(environment).filter(
1505
+ (entry) => Boolean(entry[1]) && isConfiguredDiagnosticSecret(entry[0], entry[1])
1506
+ ).map(([, value]) => value);
1507
+ secrets.sort((left, right) => right.length - left.length);
1508
+ const stdout = redactServerFailureDiagnosticStream(captured.stdout, secrets);
1509
+ const stderr = redactServerFailureDiagnosticStream(captured.stderr, secrets);
1510
+ const parts = [];
1511
+ if (stdout.trim()) parts.push(`stdout:
1512
+ ${stdout}`);
1513
+ if (stderr.trim()) parts.push(`stderr:
1514
+ ${stderr}`);
1515
+ if (parts.length === 0) return "";
1516
+ return boundDetachedProcessLog(`
1517
+ --- server logs ---
1518
+ ${parts.join("\n\n")}`);
1519
+ } catch {
1520
+ throwIfAborted(signal);
1521
+ return "";
979
1522
  }
980
- };
1523
+ }
981
1524
  function providerApiKey(provider, explicitApiKey) {
982
1525
  if (explicitApiKey) return explicitApiKey;
983
1526
  return requireEnv(provider === "e2b" ? "E2B_API_KEY" : "DAYTONA_API_KEY");
@@ -994,11 +1537,20 @@ async function createProviderSandboxHandle(options) {
994
1537
  ...options.networkAllowList === void 0 ? {} : { networkAllowList: options.networkAllowList },
995
1538
  ...options.domainAllowList === void 0 ? {} : { domainAllowList: options.domainAllowList },
996
1539
  envVars: filterDefinedEnvs(options.envs ?? {}),
1540
+ autoStopInterval: options.autoStopInterval,
997
1541
  autoDeleteInterval: options.autoDeleteInterval ?? -1
998
1542
  },
999
1543
  { timeout: options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC }
1000
1544
  );
1001
- return DaytonaSandboxHandle.create(sandbox2);
1545
+ try {
1546
+ return await DaytonaSandboxHandle.create(
1547
+ sandbox2,
1548
+ (message) => new DeploymentError(message)
1549
+ );
1550
+ } catch (error) {
1551
+ await sandbox2.delete(options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC).catch(() => void 0);
1552
+ throw error;
1553
+ }
1002
1554
  }
1003
1555
  const apiKey = providerApiKey("e2b", options.apiKey);
1004
1556
  const { Sandbox } = await getE2b();
@@ -1010,7 +1562,7 @@ async function createProviderSandboxHandle(options) {
1010
1562
  network: options.allowPublicTraffic === void 0 ? void 0 : { allowPublicTraffic: options.allowPublicTraffic }
1011
1563
  };
1012
1564
  const sandbox = options.template ? await Sandbox.create(options.template, sandboxOptions) : await Sandbox.create(sandboxOptions);
1013
- return new E2bSandboxHandle(sandbox);
1565
+ return new E2bSandboxHandle(sandbox, (message) => new DeploymentError(message));
1014
1566
  }
1015
1567
  async function connectProviderSandboxHandle(options) {
1016
1568
  if (options.provider === "daytona") {
@@ -1025,7 +1577,7 @@ async function connectProviderSandboxHandle(options) {
1025
1577
  await sandbox2.start(options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC);
1026
1578
  }
1027
1579
  }
1028
- return DaytonaSandboxHandle.create(sandbox2);
1580
+ return DaytonaSandboxHandle.create(sandbox2, (message) => new DeploymentError(message));
1029
1581
  }
1030
1582
  const apiKey = providerApiKey("e2b", options.apiKey);
1031
1583
  const { Sandbox } = await getE2b();
@@ -1034,7 +1586,7 @@ async function connectProviderSandboxHandle(options) {
1034
1586
  timeoutMs: options.timeoutMs,
1035
1587
  requestTimeoutMs: options.requestTimeoutMs
1036
1588
  });
1037
- return new E2bSandboxHandle(sandbox);
1589
+ return new E2bSandboxHandle(sandbox, (message) => new DeploymentError(message));
1038
1590
  }
1039
1591
  var SandboxClient = class _SandboxClient {
1040
1592
  constructor(handle) {
@@ -1078,6 +1630,61 @@ var SandboxClient = class _SandboxClient {
1078
1630
  async runCommand(command, options) {
1079
1631
  return this.handle.runCommand(command, options);
1080
1632
  }
1633
+ async startDetachedCommand(command, options = {}) {
1634
+ if (!this.handle.startDetachedCommand) {
1635
+ throw new ConfigurationError(
1636
+ `Sandbox provider "${this.provider}" does not support startDetachedCommand().`
1637
+ );
1638
+ }
1639
+ if (typeof command !== "string") {
1640
+ throw new ConfigurationError("Detached command must be a string.");
1641
+ }
1642
+ const normalized = normalizeProviderSandboxDetachedCommandOptions(
1643
+ options,
1644
+ (message) => new ConfigurationError(message),
1645
+ { requireObject: true }
1646
+ );
1647
+ return this.handle.startDetachedCommand(command, normalized.options);
1648
+ }
1649
+ async readSessionLogs(commandOrSessionId, legacyCommandId) {
1650
+ if (!this.handle.readSessionLogs) {
1651
+ throw new ConfigurationError(
1652
+ `Sandbox provider "${this.provider}" does not support readSessionLogs().`
1653
+ );
1654
+ }
1655
+ if (typeof commandOrSessionId === "string" && legacyCommandId === void 0) {
1656
+ throw new ConfigurationError(
1657
+ "Legacy detached session log reads require a command ID."
1658
+ );
1659
+ }
1660
+ const command = typeof commandOrSessionId === "string" ? { sessionId: commandOrSessionId, commandId: legacyCommandId } : normalizeDetachedCommandHandle(commandOrSessionId);
1661
+ return this.handle.readSessionLogs(command);
1662
+ }
1663
+ async stopSession(commandOrSessionId) {
1664
+ if (!this.handle.stopSession) {
1665
+ throw new ConfigurationError(
1666
+ `Sandbox provider "${this.provider}" does not support stopSession().`
1667
+ );
1668
+ }
1669
+ const command = typeof commandOrSessionId === "string" ? { sessionId: commandOrSessionId } : normalizeDetachedCommandHandle(commandOrSessionId);
1670
+ await this.handle.stopSession(command);
1671
+ }
1672
+ /**
1673
+ * Irreversibly removes private lifecycle state and captured diagnostics for
1674
+ * one managed detached command. Call `stopSession()` first, then perform any
1675
+ * final `readSessionLogs()` before disposal. Disposal is idempotent after a
1676
+ * confirmed stop but is not itself evidence that the process stopped.
1677
+ */
1678
+ async disposeSessionArtifacts(command) {
1679
+ if (!this.handle.disposeSessionArtifacts) {
1680
+ throw new ConfigurationError(
1681
+ `Sandbox provider "${this.provider}" does not support disposeSessionArtifacts().`
1682
+ );
1683
+ }
1684
+ await this.handle.disposeSessionArtifacts(
1685
+ normalizeDetachedCommandHandle(command)
1686
+ );
1687
+ }
1081
1688
  async setTimeout(timeoutMs) {
1082
1689
  if (!this.handle.setTimeout) {
1083
1690
  throw new ConfigurationError(`Sandbox provider "${this.provider}" does not support setTimeout().`);
@@ -1105,17 +1712,26 @@ function normalizeStackFramePath(rawPath, cwd = process.cwd()) {
1105
1712
  }
1106
1713
  function getCallerFile() {
1107
1714
  const stack = new Error().stack?.split("\n") ?? [];
1108
- for (const line of stack.slice(2)) {
1715
+ let moduleFile;
1716
+ let bundledFallback;
1717
+ for (const line of stack.slice(1)) {
1109
1718
  const match = line.match(/\((.+?):\d+:\d+\)/) || line.match(/at (.+?):\d+:\d+/);
1110
1719
  if (!match) continue;
1111
1720
  const file = normalizeStackFramePath(match[1]);
1112
1721
  if (!file) continue;
1722
+ if (!moduleFile) {
1723
+ moduleFile = file;
1724
+ continue;
1725
+ }
1113
1726
  if (file.includes("node:")) continue;
1114
1727
  if (file.includes("node_modules/agent-neckbeard")) continue;
1115
- if (file.includes("agent-neckbeard/dist")) continue;
1116
- if (file.endsWith("/src/index.ts")) continue;
1728
+ if (file === moduleFile) {
1729
+ bundledFallback ??= file;
1730
+ continue;
1731
+ }
1117
1732
  return file;
1118
1733
  }
1734
+ if (bundledFallback) return bundledFallback;
1119
1735
  throw new Error("Could not determine source file");
1120
1736
  }
1121
1737
  function isFrameworkBuildOutputPath(file) {
@@ -1148,50 +1764,156 @@ function resolveSourceFile(sourceFile) {
1148
1764
  }
1149
1765
  return resolved;
1150
1766
  }
1151
- function readDirectoryRecursively(dirPath) {
1767
+ function localPathStats(localPath, upload, isSourceRoot = false) {
1768
+ let stats;
1769
+ try {
1770
+ stats = lstatSync(localPath);
1771
+ } catch (error) {
1772
+ const code = error.code;
1773
+ const detail = isSourceRoot && code === "ENOENT" ? "source does not exist" : "could not read local path";
1774
+ throw new ConfigurationError(
1775
+ `${upload.name} ${detail}: ${localPath} (${errorMessage(error)})`
1776
+ );
1777
+ }
1778
+ if (!stats.isSymbolicLink()) return stats;
1779
+ if (upload.rejectSymlinks) {
1780
+ throw new ConfigurationError(
1781
+ `${upload.name} source tree contains a symbolic link: ${localPath}`
1782
+ );
1783
+ }
1784
+ try {
1785
+ return statSync(localPath);
1786
+ } catch (error) {
1787
+ throw new ConfigurationError(
1788
+ `${upload.name} could not follow legacy symbolic link: ${localPath} (${errorMessage(error)})`
1789
+ );
1790
+ }
1791
+ }
1792
+ function readConfiguredLocalDirectory(upload) {
1793
+ const rootPath = resolve(process.cwd(), upload.source);
1794
+ const rootStats = localPathStats(rootPath, upload, true);
1795
+ if (!rootStats.isDirectory()) {
1796
+ throw new ConfigurationError(`${upload.name}.source must be a directory: ${rootPath}`);
1797
+ }
1798
+ const destination = normalizeLocalDirectoryDestination(upload.destination, upload.name);
1152
1799
  const files = [];
1153
- function walkDir(currentPath) {
1154
- const entries = readdirSync(currentPath);
1800
+ function walk(currentPath) {
1801
+ let entries;
1802
+ try {
1803
+ entries = readdirSync(currentPath).sort((left, right) => left.localeCompare(right));
1804
+ } catch (error) {
1805
+ throw new ConfigurationError(
1806
+ `${upload.name} could not read local directory: ${currentPath} (${errorMessage(error)})`
1807
+ );
1808
+ }
1155
1809
  for (const entry of entries) {
1156
- const fullPath = join(currentPath, entry);
1157
- const stat = statSync(fullPath);
1158
- if (stat.isDirectory()) {
1159
- walkDir(fullPath);
1160
- } else if (stat.isFile()) {
1161
- const relPath = relative(dirPath, fullPath);
1162
- const isBinary = /\.(png|jpg|jpeg|gif|ico|pdf|zip|tar|gz|bin|exe|dll|so|dylib|wasm)$/i.test(entry);
1163
- if (isBinary) {
1164
- const buffer = readFileSync(fullPath);
1165
- const arrayBuffer = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
1166
- files.push({ relativePath: relPath, content: arrayBuffer });
1167
- } else {
1168
- files.push({ relativePath: relPath, content: readFileSync(fullPath, "utf-8") });
1169
- }
1810
+ const localPath = join(currentPath, entry);
1811
+ const stats = localPathStats(localPath, upload);
1812
+ if (stats.isDirectory()) {
1813
+ walk(localPath);
1814
+ continue;
1815
+ }
1816
+ if (!stats.isFile()) {
1817
+ throw new ConfigurationError(
1818
+ `${upload.name} source tree contains an unsupported filesystem entry: ${localPath}`
1819
+ );
1820
+ }
1821
+ const relativePath = relative(rootPath, localPath).split(sep).join("/");
1822
+ const targetPath = posix.join(destination, relativePath);
1823
+ let content;
1824
+ try {
1825
+ content = readFileSync(localPath);
1826
+ } catch (error) {
1827
+ throw new ConfigurationError(
1828
+ `${upload.name} could not read local file: ${localPath} (${errorMessage(error)})`
1829
+ );
1170
1830
  }
1831
+ files.push({ localPath, targetPath, content });
1171
1832
  }
1172
1833
  }
1173
- walkDir(dirPath);
1174
- return files;
1834
+ walk(rootPath);
1835
+ return { rootPath, files };
1836
+ }
1837
+ function prepareLocalDirectoryUploads(localDirectories, claudeDir) {
1838
+ const uploads = localDirectories.map((entry, index) => ({
1839
+ ...entry,
1840
+ name: `localDirectories[${index}]`,
1841
+ rejectSymlinks: true,
1842
+ preserveRootDirectory: false
1843
+ }));
1844
+ if (claudeDir) {
1845
+ uploads.push({
1846
+ source: claudeDir,
1847
+ destination: ".claude",
1848
+ name: "claudeDir",
1849
+ rejectSymlinks: false,
1850
+ preserveRootDirectory: true
1851
+ });
1852
+ }
1853
+ const filesByTarget = /* @__PURE__ */ new Map();
1854
+ const requiredDirectories = /* @__PURE__ */ new Set();
1855
+ for (const upload of uploads) {
1856
+ const prepared = readConfiguredLocalDirectory(upload);
1857
+ const destination = normalizeLocalDirectoryDestination(upload.destination, upload.name);
1858
+ if (upload.preserveRootDirectory) {
1859
+ requiredDirectories.add(destination);
1860
+ }
1861
+ for (const file of prepared.files) {
1862
+ const existing = filesByTarget.get(file.targetPath);
1863
+ if (existing) {
1864
+ throw new ConfigurationError(
1865
+ `Duplicate sandbox target "${file.targetPath}" from local files "${existing.localPath}" and "${file.localPath}".`
1866
+ );
1867
+ }
1868
+ filesByTarget.set(file.targetPath, file);
1869
+ }
1870
+ }
1871
+ for (const file of filesByTarget.values()) {
1872
+ let parent = posix.dirname(file.targetPath);
1873
+ while (parent !== ".") {
1874
+ const parentFile = filesByTarget.get(parent);
1875
+ if (parentFile) {
1876
+ throw new ConfigurationError(
1877
+ `Sandbox target collision: local file "${parentFile.localPath}" maps to "${parent}", which must be a directory for "${file.localPath}".`
1878
+ );
1879
+ }
1880
+ requiredDirectories.add(parent);
1881
+ parent = posix.dirname(parent);
1882
+ }
1883
+ }
1884
+ const directories = [...requiredDirectories].sort((left, right) => {
1885
+ const depthDifference = left.split("/").length - right.split("/").length;
1886
+ return depthDifference || left.localeCompare(right);
1887
+ });
1888
+ const files = [...filesByTarget.values()].sort(
1889
+ (left, right) => left.targetPath.localeCompare(right.targetPath)
1890
+ );
1891
+ return { directories, files };
1175
1892
  }
1176
1893
  var Agent = class {
1177
1894
  sandbox;
1178
1895
  provider;
1179
1896
  template;
1180
1897
  inputSchema;
1181
- /** Only populated for run-output agents; undefined for streaming agents. */
1898
+ /** Only populated for structured-task agents; undefined for session agents. */
1182
1899
  outputSchema;
1183
- /** Only populated for streaming agents; undefined for run-output agents. */
1900
+ /** Only populated for attached-session agents; undefined for run-output agents. */
1184
1901
  frameSchema;
1902
+ /** User-facing execution shape. */
1903
+ kind;
1904
+ /** @deprecated Use `kind`; retained for compatibility with `run | stream` checks. */
1185
1905
  mode;
1186
1906
  maxDuration;
1187
1907
  dependencies;
1188
1908
  files;
1909
+ localDirectories;
1910
+ /** @deprecated Use `localDirectories` with destination `.claude` instead. */
1189
1911
  claudeDir;
1190
1912
  envs;
1191
1913
  build;
1192
1914
  /** @internal Used by the in-sandbox server for run-output agents. */
1193
1915
  _run;
1194
- /** @internal Used by the in-sandbox server for streaming agents. */
1916
+ /** @internal Used by the in-sandbox server for attached-session agents. */
1195
1917
  _server;
1196
1918
  /** @internal Runtime state populated by deploy(). */
1197
1919
  _serverRuntime;
@@ -1207,14 +1929,18 @@ var Agent = class {
1207
1929
  this._sourceFile = resolveSourceFile(config.sourceFile);
1208
1930
  this.dependencies = config.dependencies ?? DEFAULT_DEPENDENCIES;
1209
1931
  this.files = config.files ?? [];
1932
+ this.localDirectories = (config.localDirectories ?? []).map((entry) => ({ ...entry }));
1210
1933
  this.claudeDir = config.claudeDir;
1211
1934
  this.envs = config.envs ?? {};
1212
1935
  this.build = config.build ?? {};
1213
- if (isServerAgentConfig(config)) {
1936
+ if (isSessionAgentConfig(config)) {
1937
+ const session = getSessionHandler(config);
1938
+ this.kind = "session";
1214
1939
  this.mode = "stream";
1215
- this._server = config.server;
1216
- this.frameSchema = config.server.frameSchema;
1940
+ this._server = session;
1941
+ this.frameSchema = session.frameSchema;
1217
1942
  } else {
1943
+ this.kind = "task";
1218
1944
  this.mode = "run";
1219
1945
  this._run = config.run;
1220
1946
  this.outputSchema = config.outputSchema;
@@ -1299,47 +2025,68 @@ var Agent = class {
1299
2025
  envs: this.sandboxEnv
1300
2026
  });
1301
2027
  }
1302
- async resolveRuntimeConnection(sandboxId) {
2028
+ async resolveRuntimeConnection(sandboxId, options = {}) {
2029
+ const { signal } = options;
2030
+ throwIfAborted(signal);
1303
2031
  const targetId = sandboxId ?? this._serverRuntime?.connection.sandboxId ?? this._sandboxId;
1304
2032
  if (!targetId) {
1305
2033
  throw new ConfigurationError("Agent not deployed. Call agent.deploy() first or pass sandboxId.");
1306
2034
  }
1307
- if (!sandboxId && this._serverRuntime?.connection.sandboxId === targetId) {
2035
+ if ((!sandboxId || options.reuseMatchingCachedConnection) && this._serverRuntime?.connection.sandboxId === targetId) {
1308
2036
  return this._serverRuntime.connection;
1309
2037
  }
1310
- const sandbox = await this.connectSandboxHandle(targetId);
1311
- const serverConfig = await this.readRuntimeServerConfig(sandbox);
2038
+ const sandbox = await awaitWithAbort(() => this.connectSandboxHandle(targetId), signal);
2039
+ if (sandbox.id !== targetId) {
2040
+ throw new DeploymentError("Sandbox provider returned an unexpected runtime identity.");
2041
+ }
2042
+ const serverConfig = await awaitWithAbort(
2043
+ () => this.readRuntimeServerConfig(sandbox),
2044
+ signal
2045
+ );
1312
2046
  const port = serverConfig?.port ?? this._server?.port ?? DEFAULT_SERVER_PORT;
1313
- const connection = await this.createRuntimeConnection(sandbox, port);
2047
+ const connection = await awaitWithAbort(
2048
+ () => this.createRuntimeConnection(sandbox, port),
2049
+ signal
2050
+ );
1314
2051
  const healthUrl = this.healthUrlFor(connection);
1315
2052
  try {
1316
- await waitForServerHealthy(healthUrl, connection, SERVER_RECONNECT_HEALTH_TIMEOUT_MS);
1317
- this._serverRuntime = { connection };
2053
+ await waitForServerHealthy(
2054
+ healthUrl,
2055
+ connection,
2056
+ SERVER_RECONNECT_HEALTH_TIMEOUT_MS,
2057
+ signal
2058
+ );
2059
+ throwIfAborted(signal);
2060
+ const cachedRuntime = this._serverRuntime;
2061
+ this._serverRuntime = cachedRuntime?.connection.sandboxId === targetId ? { ...cachedRuntime, connection } : { connection };
1318
2062
  this._sandboxId = targetId;
1319
2063
  return connection;
1320
2064
  } catch {
1321
- const { sessionId, commandId } = await this.startRuntimeServer(sandbox);
2065
+ throwIfAborted(signal);
2066
+ const detachedCommand = await awaitWithAbort(
2067
+ () => this.startRuntimeServer(sandbox),
2068
+ signal
2069
+ );
1322
2070
  try {
1323
- await waitForServerHealthy(healthUrl, connection);
2071
+ await waitForServerHealthy(
2072
+ healthUrl,
2073
+ connection,
2074
+ SERVER_HEALTH_TIMEOUT_MS,
2075
+ signal
2076
+ );
1324
2077
  } catch (error) {
2078
+ throwIfAborted(signal);
1325
2079
  const baseMessage = error instanceof Error ? error.message : String(error);
1326
- let logs = "";
1327
- if (commandId && sandbox.readSessionLogs) {
1328
- const captured = await sandbox.readSessionLogs(sessionId, commandId);
1329
- const parts = [];
1330
- if (captured.stdout.trim()) parts.push(`stdout:
1331
- ${captured.stdout}`);
1332
- if (captured.stderr.trim()) parts.push(`stderr:
1333
- ${captured.stderr}`);
1334
- if (parts.length > 0) {
1335
- logs = `
1336
- --- server logs ---
1337
- ${parts.join("\n\n")}`;
1338
- }
1339
- }
2080
+ const logs = await readServerFailureDiagnostics(
2081
+ sandbox,
2082
+ detachedCommand,
2083
+ this.envs,
2084
+ signal
2085
+ );
1340
2086
  throw new DeploymentError(`${baseMessage}${logs}`);
1341
2087
  }
1342
- this._serverRuntime = { sessionId, commandId, connection };
2088
+ throwIfAborted(signal);
2089
+ this._serverRuntime = { detachedCommand, connection };
1343
2090
  this._sandboxId = targetId;
1344
2091
  return connection;
1345
2092
  }
@@ -1364,8 +2111,8 @@ ${parts.join("\n\n")}`;
1364
2111
  if (!targetId) return;
1365
2112
  try {
1366
2113
  const sandbox = await this.connectSandboxHandle(targetId);
1367
- if (this._serverRuntime && this._serverRuntime.connection.sandboxId === targetId && this._serverRuntime.sessionId && sandbox.stopSession) {
1368
- await sandbox.stopSession(this._serverRuntime.sessionId).catch(() => void 0);
2114
+ if (this._serverRuntime && this._serverRuntime.connection.sandboxId === targetId && this._serverRuntime.detachedCommand && sandbox.stopSession) {
2115
+ await sandbox.stopSession(this._serverRuntime.detachedCommand).catch(() => void 0);
1369
2116
  }
1370
2117
  await sandbox.destroy();
1371
2118
  } catch {
@@ -1409,6 +2156,10 @@ ${parts.join("\n\n")}`;
1409
2156
  }
1410
2157
  async _deploy(options) {
1411
2158
  if (!options?.fresh && this._serverRuntime) return this._serverRuntime.connection.sandboxId;
2159
+ const localDirectoryUploads = prepareLocalDirectoryUploads(
2160
+ this.localDirectories,
2161
+ this.claudeDir
2162
+ );
1412
2163
  const esbuild = await getEsbuild();
1413
2164
  const externalPatterns = Array.from(
1414
2165
  /* @__PURE__ */ new Set([...DEFAULT_EXTERNALS, ...this.build.external ?? []])
@@ -1451,9 +2202,15 @@ var require = __neckbeard_createRequire(import.meta.url);
1451
2202
  this.outputSchema = config.outputSchema;
1452
2203
  this.maxDuration = config.maxDuration ?? 300;
1453
2204
  this._run = config.run;
1454
- if (config.server) {
1455
- this._server = config.server;
1456
- this.frameSchema = config.server.frameSchema;
2205
+ const session = config.session ?? config.server;
2206
+ if (session) {
2207
+ this.kind = 'session';
2208
+ this.mode = 'stream';
2209
+ this._server = session;
2210
+ this.frameSchema = session.frameSchema;
2211
+ } else {
2212
+ this.kind = 'task';
2213
+ this.mode = 'run';
1457
2214
  }
1458
2215
  }
1459
2216
  }
@@ -1485,149 +2242,145 @@ var require = __neckbeard_createRequire(import.meta.url);
1485
2242
  }]
1486
2243
  });
1487
2244
  const sandbox = await this.createSandboxHandle();
1488
- const { paths } = sandbox;
1489
- await sandbox.runCommand(`mkdir -p ${shellEscape(paths.agentDir)}`, {
1490
- timeoutMs: QUICK_COMMAND_TIMEOUT_MS
1491
- });
1492
- const { apt, commands } = this.dependencies;
1493
- if (apt && apt.length > 0) {
1494
- const aptCmd = `sudo apt-get update && sudo apt-get install -y ${apt.join(" ")}`;
1495
- const aptResult = await sandbox.runCommand(aptCmd, {
1496
- timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
2245
+ let deploymentCompleted = false;
2246
+ let detachedCommand;
2247
+ try {
2248
+ const { paths } = sandbox;
2249
+ await sandbox.runCommand(`mkdir -p ${shellQuote(paths.agentDir)}`, {
2250
+ timeoutMs: QUICK_COMMAND_TIMEOUT_MS2
1497
2251
  });
1498
- if (aptResult.exitCode !== 0) {
1499
- const details = [
1500
- `Failed to install apt packages: ${apt.join(", ")}`,
1501
- aptResult.stderr ? `stderr: ${aptResult.stderr}` : "",
1502
- aptResult.stdout ? `stdout: ${aptResult.stdout}` : ""
1503
- ].filter(Boolean).join("\n");
1504
- throw new DeploymentError(details);
1505
- }
1506
- }
1507
- if (commands && commands.length > 0) {
1508
- for (const cmd of commands) {
1509
- const cmdResult = await sandbox.runCommand(cmd, {
1510
- timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
2252
+ const { apt, commands } = this.dependencies;
2253
+ if (apt && apt.length > 0) {
2254
+ const aptCmd = `sudo apt-get update && sudo apt-get install -y ${apt.join(" ")}`;
2255
+ const aptResult = await sandbox.runCommand(aptCmd, {
2256
+ timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS2
1511
2257
  });
1512
- if (cmdResult.exitCode !== 0) {
2258
+ if (aptResult.exitCode !== 0) {
1513
2259
  const details = [
1514
- `Failed to run command: ${cmd}`,
1515
- cmdResult.stderr ? `stderr: ${cmdResult.stderr}` : "",
1516
- cmdResult.stdout ? `stdout: ${cmdResult.stdout}` : ""
2260
+ `Failed to install apt packages: ${apt.join(", ")}`,
2261
+ aptResult.stderr ? `stderr: ${aptResult.stderr}` : "",
2262
+ aptResult.stdout ? `stdout: ${aptResult.stdout}` : ""
1517
2263
  ].filter(Boolean).join("\n");
1518
2264
  throw new DeploymentError(details);
1519
2265
  }
1520
2266
  }
1521
- }
1522
- if (this.files.length > 0) {
1523
- for (const file of this.files) {
1524
- const destPath = file.path.startsWith("/") ? file.path : `${paths.homeDir}/${file.path}`;
1525
- const parentDir = destPath.substring(0, destPath.lastIndexOf("/"));
1526
- if (parentDir) {
1527
- await sandbox.runCommand(`mkdir -p ${shellEscape(parentDir)}`, {
1528
- timeoutMs: QUICK_COMMAND_TIMEOUT_MS
2267
+ if (commands && commands.length > 0) {
2268
+ for (const cmd of commands) {
2269
+ const cmdResult = await sandbox.runCommand(cmd, {
2270
+ timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS2
1529
2271
  });
1530
- }
1531
- const curlCmd = `curl -fsSL -o ${shellEscape(destPath)} ${shellEscape(file.url)}`;
1532
- const downloadResult = await sandbox.runCommand(curlCmd, {
1533
- timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
1534
- });
1535
- if (downloadResult.exitCode !== 0) {
1536
- const details = [
1537
- `Failed to download file from ${file.url} to ${destPath}`,
1538
- downloadResult.stderr ? `stderr: ${downloadResult.stderr}` : "",
1539
- downloadResult.stdout ? `stdout: ${downloadResult.stdout}` : ""
1540
- ].filter(Boolean).join("\n");
1541
- throw new DeploymentError(details);
2272
+ if (cmdResult.exitCode !== 0) {
2273
+ const details = [
2274
+ `Failed to run command: ${cmd}`,
2275
+ cmdResult.stderr ? `stderr: ${cmdResult.stderr}` : "",
2276
+ cmdResult.stdout ? `stdout: ${cmdResult.stdout}` : ""
2277
+ ].filter(Boolean).join("\n");
2278
+ throw new DeploymentError(details);
2279
+ }
1542
2280
  }
1543
2281
  }
1544
- }
1545
- if (this.claudeDir) {
1546
- const claudeFiles = readDirectoryRecursively(this.claudeDir);
1547
- await sandbox.runCommand(`mkdir -p ${shellEscape(paths.claudeDir)}`, {
1548
- timeoutMs: QUICK_COMMAND_TIMEOUT_MS
1549
- });
1550
- for (const file of claudeFiles) {
1551
- const destPath = `${paths.claudeDir}/${file.relativePath}`;
1552
- const parentDir = destPath.substring(0, destPath.lastIndexOf("/"));
1553
- if (parentDir && parentDir !== paths.claudeDir) {
1554
- await sandbox.runCommand(`mkdir -p ${shellEscape(parentDir)}`, {
1555
- timeoutMs: QUICK_COMMAND_TIMEOUT_MS
2282
+ if (this.files.length > 0) {
2283
+ for (const file of this.files) {
2284
+ const destPath = file.path.startsWith("/") ? file.path : `${paths.homeDir}/${file.path}`;
2285
+ const parentDir = destPath.substring(0, destPath.lastIndexOf("/"));
2286
+ if (parentDir) {
2287
+ await sandbox.runCommand(`mkdir -p ${shellQuote(parentDir)}`, {
2288
+ timeoutMs: QUICK_COMMAND_TIMEOUT_MS2
2289
+ });
2290
+ }
2291
+ const curlCmd = `curl -fsSL -o ${shellQuote(destPath)} ${shellQuote(file.url)}`;
2292
+ const downloadResult = await sandbox.runCommand(curlCmd, {
2293
+ timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS2
1556
2294
  });
2295
+ if (downloadResult.exitCode !== 0) {
2296
+ const details = [
2297
+ `Failed to download file from ${file.url} to ${destPath}`,
2298
+ downloadResult.stderr ? `stderr: ${downloadResult.stderr}` : "",
2299
+ downloadResult.stdout ? `stdout: ${downloadResult.stdout}` : ""
2300
+ ].filter(Boolean).join("\n");
2301
+ throw new DeploymentError(details);
2302
+ }
1557
2303
  }
1558
- await sandbox.writeFile(destPath, file.content);
1559
2304
  }
1560
- }
1561
- await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
1562
- await sandbox.writeFile(paths.serverModule, RUNTIME_SERVER_SOURCE);
1563
- const serverConfig = {
1564
- protocolVersion: RUNTIME_PROTOCOL_VERSION,
1565
- port: this._server?.port ?? DEFAULT_SERVER_PORT,
1566
- maxDurationMs: this.maxDuration * 1e3,
1567
- sandboxContext: {
1568
- provider: paths.provider,
1569
- homeDir: paths.homeDir,
1570
- workDir: paths.workDir,
1571
- agentDir: paths.agentDir,
1572
- ioDir: paths.ioDir,
1573
- inputJson: paths.inputJson,
1574
- outputJson: paths.outputJson
2305
+ for (const directory of localDirectoryUploads.directories) {
2306
+ await sandbox.makeDir(posix.join(paths.agentDir, directory));
1575
2307
  }
1576
- };
1577
- await sandbox.writeFile(paths.serverConfig, JSON.stringify(serverConfig));
1578
- if (collectedExternals.size > 0) {
1579
- const installable = Array.from(collectedExternals.values()).filter(isPackageCompatible);
1580
- const dependencies = Object.fromEntries(installable.map((info) => [info.name, info.version]));
1581
- if (Object.keys(dependencies).length > 0) {
1582
- const pkgJson = JSON.stringify({
1583
- name: "agent-sandbox",
1584
- type: "module",
1585
- dependencies
1586
- });
1587
- await sandbox.writeFile(paths.packageJson, pkgJson);
1588
- const installResult = await sandbox.runCommand("npm install --legacy-peer-deps", {
1589
- cwd: paths.agentDir,
1590
- timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
1591
- });
1592
- if (installResult.exitCode !== 0) {
1593
- const details = [
1594
- `Failed to install npm packages: ${Object.keys(dependencies).join(", ")}`,
1595
- installResult.stderr ? `stderr: ${installResult.stderr}` : "",
1596
- installResult.stdout ? `stdout: ${installResult.stdout}` : ""
1597
- ].filter(Boolean).join("\n");
1598
- throw new DeploymentError(details);
2308
+ for (const file of localDirectoryUploads.files) {
2309
+ await sandbox.writeFile(
2310
+ posix.join(paths.agentDir, file.targetPath),
2311
+ file.content
2312
+ );
2313
+ }
2314
+ await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
2315
+ await sandbox.writeFile(paths.serverModule, RUNTIME_SERVER_SOURCE);
2316
+ const serverConfig = {
2317
+ protocolVersion: RUNTIME_PROTOCOL_VERSION,
2318
+ port: this._server?.port ?? DEFAULT_SERVER_PORT,
2319
+ maxDurationMs: this.maxDuration * 1e3,
2320
+ sandboxContext: {
2321
+ provider: paths.provider,
2322
+ homeDir: paths.homeDir,
2323
+ workDir: paths.workDir,
2324
+ agentDir: paths.agentDir,
2325
+ ioDir: paths.ioDir,
2326
+ inputJson: paths.inputJson,
2327
+ outputJson: paths.outputJson
2328
+ }
2329
+ };
2330
+ await sandbox.writeFile(paths.serverConfig, JSON.stringify(serverConfig));
2331
+ if (collectedExternals.size > 0) {
2332
+ const installable = Array.from(collectedExternals.values()).filter(isPackageCompatible);
2333
+ const dependencies = Object.fromEntries(installable.map((info) => [info.name, info.version]));
2334
+ if (Object.keys(dependencies).length > 0) {
2335
+ const pkgJson = JSON.stringify({
2336
+ name: "agent-sandbox",
2337
+ type: "module",
2338
+ dependencies
2339
+ });
2340
+ await sandbox.writeFile(paths.packageJson, pkgJson);
2341
+ const installResult = await sandbox.runCommand("npm install --legacy-peer-deps", {
2342
+ cwd: paths.agentDir,
2343
+ timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS2
2344
+ });
2345
+ if (installResult.exitCode !== 0) {
2346
+ const details = [
2347
+ `Failed to install npm packages: ${Object.keys(dependencies).join(", ")}`,
2348
+ installResult.stderr ? `stderr: ${installResult.stderr}` : "",
2349
+ installResult.stdout ? `stdout: ${installResult.stdout}` : ""
2350
+ ].filter(Boolean).join("\n");
2351
+ throw new DeploymentError(details);
2352
+ }
1599
2353
  }
1600
2354
  }
1601
- }
1602
- const port = serverConfig.port;
1603
- const { sessionId, commandId } = await this.startRuntimeServer(sandbox);
1604
- const connection = await this.createRuntimeConnection(sandbox, port);
1605
- const healthUrl = this.healthUrlFor(connection);
1606
- try {
1607
- await waitForServerHealthy(healthUrl, connection);
1608
- } catch (err) {
1609
- const baseMessage = err instanceof Error ? err.message : String(err);
1610
- let logs = "";
1611
- if (commandId && sandbox.readSessionLogs) {
1612
- const captured = await sandbox.readSessionLogs(sessionId, commandId);
1613
- const parts = [];
1614
- if (captured.stdout.trim()) parts.push(`stdout:
1615
- ${captured.stdout}`);
1616
- if (captured.stderr.trim()) parts.push(`stderr:
1617
- ${captured.stderr}`);
1618
- if (parts.length > 0) {
1619
- logs = `
1620
- --- server logs ---
1621
- ${parts.join("\n\n")}`;
2355
+ const port = serverConfig.port;
2356
+ detachedCommand = await this.startRuntimeServer(sandbox);
2357
+ const connection = await this.createRuntimeConnection(sandbox, port);
2358
+ const healthUrl = this.healthUrlFor(connection);
2359
+ try {
2360
+ await waitForServerHealthy(healthUrl, connection);
2361
+ } catch (err) {
2362
+ const baseMessage = err instanceof Error ? err.message : String(err);
2363
+ const logs = await readServerFailureDiagnostics(
2364
+ sandbox,
2365
+ detachedCommand,
2366
+ this.envs
2367
+ );
2368
+ throw new DeploymentError(`${baseMessage}${logs}`);
2369
+ }
2370
+ if (!options?.fresh) {
2371
+ this._sandboxId = sandbox.id;
2372
+ this._serverRuntime = { detachedCommand, connection };
2373
+ }
2374
+ deploymentCompleted = true;
2375
+ return sandbox.id;
2376
+ } finally {
2377
+ if (!deploymentCompleted) {
2378
+ if (detachedCommand && sandbox.stopSession) {
2379
+ await sandbox.stopSession(detachedCommand).catch(() => void 0);
1622
2380
  }
2381
+ await sandbox.destroy().catch(() => void 0);
1623
2382
  }
1624
- throw new DeploymentError(`${baseMessage}${logs}`);
1625
- }
1626
- if (!options?.fresh) {
1627
- this._sandboxId = sandbox.id;
1628
- this._serverRuntime = { sessionId, commandId, connection };
1629
2383
  }
1630
- return sandbox.id;
1631
2384
  }
1632
2385
  /**
1633
2386
  * Executes the agent with the given input.
@@ -1658,7 +2411,7 @@ ${parts.join("\n\n")}`;
1658
2411
  ok: false,
1659
2412
  executionId,
1660
2413
  error: new ExecutionError(
1661
- "run() is only available on agents configured with a run handler. Use agent.invoke() for streaming agents."
2414
+ "run() is only available on agents configured with a run handler. Use agent.createSession() for streaming session agents."
1662
2415
  )
1663
2416
  };
1664
2417
  }
@@ -1670,7 +2423,7 @@ ${parts.join("\n\n")}`;
1670
2423
  } catch (error) {
1671
2424
  throw new ValidationError("Input validation failed.", asError(error));
1672
2425
  }
1673
- const { invokeServer } = await import("./invoke-client-XEH6FVRH.js");
2426
+ const { invokeServer } = await import("./invoke-client-D5TMTOYM.js");
1674
2427
  let output;
1675
2428
  let sawOutput = false;
1676
2429
  for await (const event of invokeServer(validatedInput, {
@@ -1709,17 +2462,74 @@ ${parts.join("\n\n")}`;
1709
2462
  }
1710
2463
  }
1711
2464
  /**
1712
- * Invoke a streaming agent. Streams user frames emitted by the in-sandbox
1713
- * handler as an async iterator.
2465
+ * Creates a caller-owned session against the persistent sandbox runtime.
2466
+ * The returned handle supports sequential prompts, active-turn cancellation,
2467
+ * and explicit close without destroying the reusable sandbox.
1714
2468
  */
1715
- async *invoke(input, options) {
2469
+ async createSession(options = {}) {
1716
2470
  if (this.mode !== "stream") {
1717
2471
  throw new ConfigurationError(
1718
- "invoke() is only available on agents configured with server.handler. Use agent.run() for run-output agents."
2472
+ "createSession() is only available on agents configured with session.handler (or deprecated server.handler). Use agent.run() for run-output agents."
2473
+ );
2474
+ }
2475
+ if (!options || typeof options !== "object") {
2476
+ throw new ConfigurationError("Agent.createSession() options must be an object.");
2477
+ }
2478
+ let optionsAreArray;
2479
+ try {
2480
+ optionsAreArray = Array.isArray(options);
2481
+ } catch {
2482
+ throw new ConfigurationError(
2483
+ "Agent.createSession() options must have readable values."
2484
+ );
2485
+ }
2486
+ if (optionsAreArray) {
2487
+ throw new ConfigurationError("Agent.createSession() options must be an object.");
2488
+ }
2489
+ let durability;
2490
+ let requestedSandboxId;
2491
+ let signal;
2492
+ try {
2493
+ durability = options.durability;
2494
+ requestedSandboxId = options.sandboxId;
2495
+ signal = options.signal;
2496
+ } catch {
2497
+ throw new ConfigurationError(
2498
+ "Agent.createSession() options must have readable values."
2499
+ );
2500
+ }
2501
+ if (durability !== void 0 && durability !== "attached") {
2502
+ throw new ConfigurationError(
2503
+ "Agent.createSession() creates caller-owned attached sessions. Use agent-neckbeard/supervisor durable-session APIs for gateway-owned sessions."
2504
+ );
2505
+ }
2506
+ if (requestedSandboxId !== void 0 && (typeof requestedSandboxId !== "string" || requestedSandboxId.trim() === "")) {
2507
+ throw new ConfigurationError(
2508
+ "Agent.createSession() sandboxId must be a non-empty string when provided."
2509
+ );
2510
+ }
2511
+ if (signal !== void 0 && !isAbortSignal(signal)) {
2512
+ throw new ConfigurationError(
2513
+ "Agent.createSession() signal must be an AbortSignal when provided."
1719
2514
  );
1720
2515
  }
1721
- const connection = await this.resolveRuntimeConnection(options?.sandboxId);
1722
- const { invokeServer } = await import("./invoke-client-XEH6FVRH.js");
2516
+ const sandboxId = requestedSandboxId ?? this._serverRuntime?.connection.sandboxId ?? this._sandboxId;
2517
+ if (!sandboxId) {
2518
+ throw new ConfigurationError("Agent not deployed. Call agent.deploy() first or pass sandboxId.");
2519
+ }
2520
+ return createAttachedAgentSession({
2521
+ sandboxId,
2522
+ runPrompt: (input, signal2) => this.streamSessionPrompt(input, sandboxId, signal2),
2523
+ ...signal === void 0 ? {} : { externalSignal: signal },
2524
+ configurationError: (message) => new ConfigurationError(message)
2525
+ });
2526
+ }
2527
+ async *streamSessionPrompt(input, sandboxId, signal) {
2528
+ const connection = await this.resolveRuntimeConnection(sandboxId, {
2529
+ signal,
2530
+ reuseMatchingCachedConnection: true
2531
+ });
2532
+ const { invokeServer } = await import("./invoke-client-D5TMTOYM.js");
1723
2533
  let validated;
1724
2534
  try {
1725
2535
  validated = this.inputSchema.parse(input);
@@ -1732,7 +2542,7 @@ ${parts.join("\n\n")}`;
1732
2542
  provider: connection.provider,
1733
2543
  trafficToken: getTrafficToken(connection),
1734
2544
  frameSchema: this.frameSchema,
1735
- signal: options?.signal
2545
+ signal
1736
2546
  })) {
1737
2547
  if (frame.kind === "frame") {
1738
2548
  yield frame.data;
@@ -1747,6 +2557,22 @@ ${parts.join("\n\n")}`;
1747
2557
  throw error instanceof Error ? error : new Error(String(error));
1748
2558
  }
1749
2559
  }
2560
+ /**
2561
+ * @deprecated Use `createSession()` and call `session.prompt(input)` instead.
2562
+ * This compatibility wrapper creates one attached session, streams one turn,
2563
+ * and closes the local handle afterward.
2564
+ */
2565
+ async *invoke(input, options) {
2566
+ const session = await this.createSession({
2567
+ ...options?.sandboxId === void 0 ? {} : { sandboxId: options.sandboxId },
2568
+ ...options?.signal === void 0 ? {} : { signal: options.signal }
2569
+ });
2570
+ try {
2571
+ yield* session.prompt(input);
2572
+ } finally {
2573
+ await session.close();
2574
+ }
2575
+ }
1750
2576
  };
1751
2577
  export {
1752
2578
  Agent,