agent-neckbeard 1.1.18 → 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,6 +1,25 @@
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";
@@ -26,7 +45,545 @@ import {
26
45
  import { builtinModules, createRequire } from "module";
27
46
 
28
47
  // src/runtime/server-source.generated.ts
29
- 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
+ };
30
587
 
31
588
  // src/index.ts
32
589
  function readPackageJson(path) {
@@ -36,8 +593,8 @@ var getEsbuild = () => import("esbuild");
36
593
  var getE2b = () => import("e2b");
37
594
  var getDaytona = () => import("@daytona/sdk");
38
595
  var DEFAULT_MAX_DURATION = 300;
39
- var SANDBOX_COMMAND_TIMEOUT_MS = 3e5;
40
- var QUICK_COMMAND_TIMEOUT_MS = 3e4;
596
+ var SANDBOX_COMMAND_TIMEOUT_MS2 = 3e5;
597
+ var QUICK_COMMAND_TIMEOUT_MS2 = 3e4;
41
598
  var DAYTONA_CREATE_TIMEOUT_SEC = 120;
42
599
  var NODE_TARGET = "node20";
43
600
  var DEFAULT_EXTERNALS = ["@anthropic-ai/claude-agent-sdk"];
@@ -49,9 +606,9 @@ var DEFAULT_SERVER_PORT = 3e3;
49
606
  var SERVER_HEALTH_TIMEOUT_MS = 12e4;
50
607
  var SERVER_RECONNECT_HEALTH_TIMEOUT_MS = 3e3;
51
608
  var SERVER_HEALTH_POLL_INTERVAL_MS = 1e3;
609
+ var SERVER_FAILURE_DIAGNOSTIC_TIMEOUT_MS = 1e3;
52
610
  var NATIVE_EXT_RE = /\.(node|wasm|gyp|c|cc|cpp|cxx|h|hpp|hxx)$/i;
53
611
  var TRACEABLE_SOURCE_EXT_RE = /\.(cjs|cts|js|jsx|mjs|mts|ts|tsx)$/i;
54
- var E2B_SANDBOX_HOME = "/home/user";
55
612
  var NeckbeardError = class extends Error {
56
613
  constructor(message) {
57
614
  super(message);
@@ -513,8 +1070,20 @@ function mergeTracingIncludes(existing, routeGlobs, sourceFiles) {
513
1070
  return includes;
514
1071
  }
515
1072
  var DEFAULT_DEPENDENCIES = {};
516
- function isServerAgentConfig(config) {
517
- 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;
518
1087
  }
519
1088
  function isSchemaLike(value) {
520
1089
  return Boolean(
@@ -527,6 +1096,20 @@ function requireSchemaLike(name, value) {
527
1096
  }
528
1097
  return value;
529
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
+ }
530
1113
  function normalizeLocalDirectoryDestination(destination, name) {
531
1114
  if (destination.trim() === "") {
532
1115
  throw new ConfigurationError(`${name}.destination must be a non-empty relative path.`);
@@ -595,21 +1178,19 @@ function validateAgentConfig(config) {
595
1178
  throw new ConfigurationError("sourceFile must be a non-empty string when provided.");
596
1179
  }
597
1180
  validateLocalDirectoriesConfig(config.localDirectories);
598
- if (isServerAgentConfig(config)) {
1181
+ if (isSessionAgentConfig(config)) {
599
1182
  if ("run" in config && typeof config.run === "function") {
600
- throw new ConfigurationError("Agent config must use either run or server.handler, not both.");
601
- }
602
- if (!config.server || typeof config.server !== "object") {
603
- throw new ConfigurationError("server must be an object.");
1183
+ throw new ConfigurationError("Agent config must use either run or session.handler, not both.");
604
1184
  }
605
- if (config.server.port !== void 0) {
606
- if (!Number.isInteger(config.server.port) || config.server.port < 1 || config.server.port > 65535) {
607
- 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.");
608
1189
  }
609
1190
  }
610
- requireSchemaLike("server.frameSchema", config.server.frameSchema);
611
- if (typeof config.server.handler !== "function") {
612
- 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.");
613
1194
  }
614
1195
  return;
615
1196
  }
@@ -634,24 +1215,86 @@ function trafficTokenHeaders(descriptor) {
634
1215
  }
635
1216
  return {};
636
1217
  }
637
- 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) {
638
1271
  const deadline = Date.now() + timeoutMs;
639
1272
  let lastError;
640
1273
  const urlWithToken = appendTrafficTokenToUrl(healthUrl, descriptor);
641
1274
  while (Date.now() < deadline) {
1275
+ throwIfAborted(signal);
642
1276
  try {
643
- const response = await fetch(urlWithToken, {
644
- headers: trafficTokenHeaders(descriptor)
645
- });
1277
+ const response = await awaitWithAbort(
1278
+ () => fetch(urlWithToken, {
1279
+ headers: trafficTokenHeaders(descriptor),
1280
+ ...signal === void 0 ? {} : { signal }
1281
+ }),
1282
+ signal
1283
+ );
646
1284
  if (response.ok) {
647
- await response.text().catch(() => void 0);
1285
+ try {
1286
+ await awaitWithAbort(() => response.text(), signal);
1287
+ } catch {
1288
+ throwIfAborted(signal);
1289
+ }
648
1290
  return;
649
1291
  }
650
1292
  lastError = new Error(`health check returned ${response.status}`);
651
1293
  } catch (error) {
1294
+ throwIfAborted(signal);
652
1295
  lastError = error;
653
1296
  }
654
- await new Promise((resolve2) => setTimeout(resolve2, SERVER_HEALTH_POLL_INTERVAL_MS));
1297
+ await delayWithAbort(SERVER_HEALTH_POLL_INTERVAL_MS, signal);
655
1298
  }
656
1299
  const message = lastError instanceof Error ? lastError.message : String(lastError);
657
1300
  throw new DeploymentError(
@@ -667,9 +1310,6 @@ function requireEnv(name) {
667
1310
  }
668
1311
  return value;
669
1312
  }
670
- function shellEscape(str) {
671
- return `'${str.replace(/'/g, "'\\''")}'`;
672
- }
673
1313
  var require2 = createRequire(join(process.cwd(), "__agent_neckbeard__.cjs"));
674
1314
  var packageRequire = createPackageRequire();
675
1315
  function createPackageRequire() {
@@ -724,325 +1364,163 @@ function resolvePackageInfoSync(importPath, resolveDir) {
724
1364
  break;
725
1365
  }
726
1366
  }
727
- const parent = dirname(root);
728
- if (parent === root) break;
729
- root = parent;
730
- }
731
- if (!packageJsonPath) return null;
732
- const packageJson = readPackageJson(packageJsonPath);
733
- if (!packageJson.name || !packageJson.version) return null;
734
- root = dirname(packageJsonPath);
735
- return {
736
- name: packageJson.name,
737
- version: packageJson.version,
738
- root,
739
- resolvedPath,
740
- packageJson
741
- };
742
- } catch {
743
- return null;
744
- }
745
- }
746
- function resolvePackageInfoFromResolvedPath(importPath, resolvedPath) {
747
- const packageName = packageNameForImportPath(importPath);
748
- let root = dirname(resolvedPath);
749
- while (true) {
750
- const packageJsonPath = join(root, "package.json");
751
- if (existsSync(packageJsonPath)) {
752
- const packageJson = readPackageJson(packageJsonPath);
753
- if (packageJson.name === packageName) {
754
- if (!packageJson.version) return null;
755
- return {
756
- name: packageJson.name,
757
- version: packageJson.version,
758
- root,
759
- resolvedPath,
760
- packageJson
761
- };
762
- }
763
- }
764
- const parent = dirname(root);
765
- if (parent === root) return null;
766
- root = parent;
767
- }
768
- }
769
- function hasNativeHints(info) {
770
- const files = Array.isArray(info.packageJson.files) ? info.packageJson.files : [];
771
- const fields = [info.packageJson.main, info.packageJson.module, info.packageJson.browser].filter(
772
- (f) => typeof f === "string"
773
- );
774
- return files.concat(fields).some((file) => NATIVE_EXT_RE.test(file));
775
- }
776
- function shouldAutoExternalize(info) {
777
- if (info.resolvedPath.endsWith(".node") || info.resolvedPath.endsWith(".wasm")) return true;
778
- if (hasNativeHints(info)) return true;
779
- if (existsSync(join(info.root, "binding.gyp"))) return true;
780
- return false;
781
- }
782
- function normalizeList(value) {
783
- if (Array.isArray(value)) return value.filter((v) => typeof v === "string");
784
- if (typeof value === "string") return [value];
785
- return null;
786
- }
787
- function listAllowsTarget(list, target) {
788
- if (!list || list.length === 0) return true;
789
- const negated = list.filter((v) => v.startsWith("!")).map((v) => v.slice(1));
790
- if (negated.includes(target)) return false;
791
- const positives = list.filter((v) => !v.startsWith("!"));
792
- if (positives.length === 0) return true;
793
- return positives.includes(target);
794
- }
795
- function isPackageCompatible(info) {
796
- const osList = normalizeList(info.packageJson.os);
797
- const cpuList = normalizeList(info.packageJson.cpu);
798
- return listAllowsTarget(osList, SANDBOX_PLATFORM) && listAllowsTarget(cpuList, SANDBOX_ARCH);
799
- }
800
- function filterDefinedEnvs(envs) {
801
- const filtered = {};
802
- for (const [key, value] of Object.entries(envs)) {
803
- if (value !== void 0) {
804
- filtered[key] = value;
805
- }
806
- }
807
- return filtered;
808
- }
809
- function arrayBufferToBuffer(value) {
810
- return Buffer.from(value);
811
- }
812
- function toDaytonaUploadContent(content) {
813
- if (typeof content === "string") return Buffer.from(content);
814
- if (Buffer.isBuffer(content)) return content;
815
- if (content instanceof Uint8Array) return Buffer.from(content);
816
- return arrayBufferToBuffer(content);
817
- }
818
- function toE2bWriteContent(content) {
819
- if (typeof content === "string") return content;
820
- if (content instanceof ArrayBuffer) return content;
821
- return Uint8Array.from(content).buffer;
822
- }
823
- function createSandboxPaths(provider, homeDir, workDir) {
824
- const agentDir = `${homeDir}/agent`;
825
- const ioDir = `${homeDir}/io`;
826
- return {
827
- provider,
828
- homeDir,
829
- workDir,
830
- agentDir,
831
- ioDir,
832
- inputJson: `${ioDir}/input.json`,
833
- outputJson: `${ioDir}/output.json`,
834
- agentModule: `${agentDir}/agent.mjs`,
835
- serverModule: `${agentDir}/server.mjs`,
836
- serverConfig: `${agentDir}/server-config.json`,
837
- claudeDir: `${agentDir}/.claude`,
838
- packageJson: `${agentDir}/package.json`
839
- };
840
- }
841
- function timeoutMsToSeconds(timeoutMs) {
842
- return Math.max(1, Math.ceil(timeoutMs / 1e3));
843
- }
844
- function asError(error) {
845
- return error instanceof Error ? error : new Error(String(error));
846
- }
847
- function errorMessage(error) {
848
- return error instanceof Error ? error.message : String(error);
849
- }
850
- async function resolveDaytonaPaths(sandbox) {
851
- const workDir = await sandbox.getWorkDir() ?? await sandbox.getUserHomeDir();
852
- const homeDir = await sandbox.getUserHomeDir() ?? workDir;
853
- if (!homeDir || !workDir) {
854
- throw new DeploymentError("Daytona sandbox did not report a home or working directory.");
855
- }
856
- return createSandboxPaths("daytona", homeDir, workDir);
857
- }
858
- function numberProperty(value, property) {
859
- if (typeof value !== "object" || value === null) return void 0;
860
- const propertyValue = Reflect.get(value, property);
861
- return typeof propertyValue === "number" ? propertyValue : void 0;
862
- }
863
- function stringProperty(value, property) {
864
- if (typeof value !== "object" || value === null) return void 0;
865
- const propertyValue = Reflect.get(value, property);
866
- return typeof propertyValue === "string" ? propertyValue : void 0;
867
- }
868
- async function runE2bCommand(sandbox, cmd, options) {
869
- let stdout = "";
870
- let stderr = "";
871
- try {
872
- const result = await sandbox.commands.run(cmd, {
873
- timeoutMs: options.timeoutMs,
874
- envs: options.envs,
875
- background: false,
876
- onStdout: (data) => {
877
- stdout += data;
878
- options.onStdout?.(data);
879
- },
880
- onStderr: (data) => {
881
- stderr += data;
882
- options.onStderr?.(data);
883
- }
884
- });
885
- return {
886
- exitCode: result.exitCode,
887
- stdout: stdout || result.stdout,
888
- stderr: stderr || result.stderr
889
- };
890
- } catch (error) {
891
- const exitCode = numberProperty(error, "exitCode") ?? 1;
892
- return {
893
- exitCode,
894
- stdout: stdout || stringProperty(error, "stdout") || "",
895
- stderr: stderr || stringProperty(error, "stderr") || errorMessage(error)
896
- };
897
- }
898
- }
899
- var E2bSandboxHandle = class {
900
- constructor(sandbox) {
901
- this.sandbox = sandbox;
902
- }
903
- provider = "e2b";
904
- paths = createSandboxPaths("e2b", E2B_SANDBOX_HOME, E2B_SANDBOX_HOME);
905
- get id() {
906
- return this.sandbox.sandboxId;
907
- }
908
- async makeDir(path) {
909
- await this.sandbox.files.makeDir(path);
910
- }
911
- writeFile(path, content) {
912
- return this.sandbox.files.write(path, toE2bWriteContent(content)).then(() => void 0);
913
- }
914
- readFile(path) {
915
- return this.sandbox.files.read(path, { format: "text" });
916
- }
917
- readFileBytes(path) {
918
- return this.sandbox.files.read(path, { format: "bytes" });
919
- }
920
- runCommand(cmd, options) {
921
- const command = options.cwd ? `cd ${shellEscape(options.cwd)} && ${cmd}` : cmd;
922
- return runE2bCommand(this.sandbox, command, options);
923
- }
924
- setTimeout(timeoutMs) {
925
- return this.sandbox.setTimeout(timeoutMs);
926
- }
927
- async startDetachedCommand(cmd, options) {
928
- const command = options.cwd ? `cd ${shellEscape(options.cwd)} && ${cmd}` : cmd;
929
- const handle = await this.sandbox.commands.run(command, {
930
- timeoutMs: 0,
931
- envs: options.envs,
932
- background: true
933
- });
934
- return { sessionId: `e2b:${handle.pid}`, commandId: String(handle.pid) };
935
- }
936
- async readSessionLogs(_sessionId, commandId) {
937
- try {
938
- const handle = await this.sandbox.commands.connect(Number(commandId));
939
- return { stdout: handle.stdout ?? "", stderr: handle.stderr ?? "" };
940
- } catch {
941
- return { stdout: "", stderr: "" };
942
- }
943
- }
944
- async stopSession(sessionId) {
945
- const pid = Number(sessionId.replace(/^e2b:/, ""));
946
- if (Number.isFinite(pid)) {
947
- await this.sandbox.commands.kill(pid);
1367
+ const parent = dirname(root);
1368
+ if (parent === root) break;
1369
+ root = parent;
948
1370
  }
949
- }
950
- async getServerEndpoint(port) {
1371
+ if (!packageJsonPath) return null;
1372
+ const packageJson = readPackageJson(packageJsonPath);
1373
+ if (!packageJson.name || !packageJson.version) return null;
1374
+ root = dirname(packageJsonPath);
951
1375
  return {
952
- url: `https://${this.sandbox.getHost(port)}`,
953
- trafficToken: this.sandbox.trafficAccessToken
1376
+ name: packageJson.name,
1377
+ version: packageJson.version,
1378
+ root,
1379
+ resolvedPath,
1380
+ packageJson
954
1381
  };
1382
+ } catch {
1383
+ return null;
955
1384
  }
956
- async destroy() {
957
- await this.sandbox.kill();
1385
+ }
1386
+ function resolvePackageInfoFromResolvedPath(importPath, resolvedPath) {
1387
+ const packageName = packageNameForImportPath(importPath);
1388
+ let root = dirname(resolvedPath);
1389
+ while (true) {
1390
+ const packageJsonPath = join(root, "package.json");
1391
+ if (existsSync(packageJsonPath)) {
1392
+ const packageJson = readPackageJson(packageJsonPath);
1393
+ if (packageJson.name === packageName) {
1394
+ if (!packageJson.version) return null;
1395
+ return {
1396
+ name: packageJson.name,
1397
+ version: packageJson.version,
1398
+ root,
1399
+ resolvedPath,
1400
+ packageJson
1401
+ };
1402
+ }
1403
+ }
1404
+ const parent = dirname(root);
1405
+ if (parent === root) return null;
1406
+ root = parent;
958
1407
  }
959
- };
960
- var DaytonaSandboxHandle = class _DaytonaSandboxHandle {
961
- constructor(sandbox, paths) {
962
- this.sandbox = sandbox;
963
- this.paths = paths;
1408
+ }
1409
+ function hasNativeHints(info) {
1410
+ const files = Array.isArray(info.packageJson.files) ? info.packageJson.files : [];
1411
+ const fields = [info.packageJson.main, info.packageJson.module, info.packageJson.browser].filter(
1412
+ (f) => typeof f === "string"
1413
+ );
1414
+ return files.concat(fields).some((file) => NATIVE_EXT_RE.test(file));
1415
+ }
1416
+ function shouldAutoExternalize(info) {
1417
+ if (info.resolvedPath.endsWith(".node") || info.resolvedPath.endsWith(".wasm")) return true;
1418
+ if (hasNativeHints(info)) return true;
1419
+ if (existsSync(join(info.root, "binding.gyp"))) return true;
1420
+ return false;
1421
+ }
1422
+ function normalizeList(value) {
1423
+ if (Array.isArray(value)) return value.filter((v) => typeof v === "string");
1424
+ if (typeof value === "string") return [value];
1425
+ return null;
1426
+ }
1427
+ function listAllowsTarget(list, target) {
1428
+ if (!list || list.length === 0) return true;
1429
+ const negated = list.filter((v) => v.startsWith("!")).map((v) => v.slice(1));
1430
+ if (negated.includes(target)) return false;
1431
+ const positives = list.filter((v) => !v.startsWith("!"));
1432
+ if (positives.length === 0) return true;
1433
+ return positives.includes(target);
1434
+ }
1435
+ function isPackageCompatible(info) {
1436
+ const osList = normalizeList(info.packageJson.os);
1437
+ const cpuList = normalizeList(info.packageJson.cpu);
1438
+ return listAllowsTarget(osList, SANDBOX_PLATFORM) && listAllowsTarget(cpuList, SANDBOX_ARCH);
1439
+ }
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);
964
1444
  }
965
- provider = "daytona";
966
- static async create(sandbox) {
967
- return new _DaytonaSandboxHandle(sandbox, await resolveDaytonaPaths(sandbox));
1445
+ let sessionId;
1446
+ let commandId;
1447
+ try {
1448
+ if (Array.isArray(value)) {
1449
+ throw new Error("invalid detached command handle");
1450
+ }
1451
+ sessionId = Reflect.get(value, "sessionId");
1452
+ commandId = Reflect.get(value, "commandId");
1453
+ } catch {
1454
+ throw new ConfigurationError(INVALID_DETACHED_COMMAND_HANDLE_MESSAGE);
968
1455
  }
969
- get id() {
970
- 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);
971
1458
  }
972
- async makeDir(path) {
973
- const result = await this.sandbox.process.executeCommand(
974
- `mkdir -p ${shellEscape(path)}`,
975
- void 0,
976
- void 0,
977
- timeoutMsToSeconds(QUICK_COMMAND_TIMEOUT_MS)
978
- );
979
- if (result.exitCode !== 0) {
980
- 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;
981
1466
  }
982
1467
  }
983
- writeFile(path, content) {
984
- return this.sandbox.fs.uploadFile(
985
- toDaytonaUploadContent(content),
986
- path,
987
- timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS)
988
- );
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);
989
1487
  }
990
- async readFile(path) {
991
- const content = await this.sandbox.fs.downloadFile(path, timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS));
992
- return content.toString("utf-8");
1488
+ let maximumSecretLength = 0;
1489
+ for (const secret of secrets) {
1490
+ maximumSecretLength = Math.max(maximumSecretLength, secret.length);
993
1491
  }
994
- async readFileBytes(path) {
995
- const content = await this.sandbox.fs.downloadFile(path, timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS));
996
- return new Uint8Array(content);
1492
+ if (mayStartAtTailBoundary && maximumSecretLength > 0 && redacted.length > 0) {
1493
+ redacted = redacted.slice(maximumSecretLength);
997
1494
  }
998
- async runCommand(cmd, options) {
999
- const result = await this.sandbox.process.executeCommand(
1000
- cmd,
1001
- options.cwd,
1002
- options.envs,
1003
- 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
1004
1503
  );
1005
- const stdout = result.artifacts?.stdout ?? result.result ?? "";
1006
- if (stdout) options.onStdout?.(stdout);
1007
- return {
1008
- exitCode: result.exitCode,
1009
- stdout,
1010
- stderr: ""
1011
- };
1012
- }
1013
- async startDetachedCommand(cmd, options) {
1014
- const sessionId = `neckbeard-server-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
1015
- await this.sandbox.process.createSession(sessionId);
1016
- const envPrefix = options.envs ? Object.entries(options.envs).map(([key, value]) => `${key}=${shellEscape(value)}`).join(" ") + " " : "";
1017
- const cwdPrefix = options.cwd ? `cd ${shellEscape(options.cwd)} && ` : "";
1018
- const result = await this.sandbox.process.executeSessionCommand(sessionId, {
1019
- command: `${cwdPrefix}${envPrefix}${cmd}`,
1020
- runAsync: true
1021
- });
1022
- return { sessionId, commandId: result.cmdId };
1023
- }
1024
- async readSessionLogs(sessionId, commandId) {
1025
- try {
1026
- const logs = await this.sandbox.process.getSessionCommandLogs(sessionId, commandId);
1027
- return {
1028
- stdout: logs.stdout ?? logs.output ?? "",
1029
- stderr: logs.stderr ?? ""
1030
- };
1031
- } catch {
1032
- return { stdout: "", stderr: "" };
1033
- }
1034
- }
1035
- stopSession(sessionId) {
1036
- return this.sandbox.process.deleteSession(sessionId);
1037
- }
1038
- async getServerEndpoint(port) {
1039
- const preview = await this.sandbox.getPreviewLink(port);
1040
- return { url: preview.url, trafficToken: preview.token };
1041
- }
1042
- destroy() {
1043
- 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 "";
1044
1522
  }
1045
- };
1523
+ }
1046
1524
  function providerApiKey(provider, explicitApiKey) {
1047
1525
  if (explicitApiKey) return explicitApiKey;
1048
1526
  return requireEnv(provider === "e2b" ? "E2B_API_KEY" : "DAYTONA_API_KEY");
@@ -1059,11 +1537,20 @@ async function createProviderSandboxHandle(options) {
1059
1537
  ...options.networkAllowList === void 0 ? {} : { networkAllowList: options.networkAllowList },
1060
1538
  ...options.domainAllowList === void 0 ? {} : { domainAllowList: options.domainAllowList },
1061
1539
  envVars: filterDefinedEnvs(options.envs ?? {}),
1540
+ autoStopInterval: options.autoStopInterval,
1062
1541
  autoDeleteInterval: options.autoDeleteInterval ?? -1
1063
1542
  },
1064
1543
  { timeout: options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC }
1065
1544
  );
1066
- 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
+ }
1067
1554
  }
1068
1555
  const apiKey = providerApiKey("e2b", options.apiKey);
1069
1556
  const { Sandbox } = await getE2b();
@@ -1075,7 +1562,7 @@ async function createProviderSandboxHandle(options) {
1075
1562
  network: options.allowPublicTraffic === void 0 ? void 0 : { allowPublicTraffic: options.allowPublicTraffic }
1076
1563
  };
1077
1564
  const sandbox = options.template ? await Sandbox.create(options.template, sandboxOptions) : await Sandbox.create(sandboxOptions);
1078
- return new E2bSandboxHandle(sandbox);
1565
+ return new E2bSandboxHandle(sandbox, (message) => new DeploymentError(message));
1079
1566
  }
1080
1567
  async function connectProviderSandboxHandle(options) {
1081
1568
  if (options.provider === "daytona") {
@@ -1090,7 +1577,7 @@ async function connectProviderSandboxHandle(options) {
1090
1577
  await sandbox2.start(options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC);
1091
1578
  }
1092
1579
  }
1093
- return DaytonaSandboxHandle.create(sandbox2);
1580
+ return DaytonaSandboxHandle.create(sandbox2, (message) => new DeploymentError(message));
1094
1581
  }
1095
1582
  const apiKey = providerApiKey("e2b", options.apiKey);
1096
1583
  const { Sandbox } = await getE2b();
@@ -1099,7 +1586,7 @@ async function connectProviderSandboxHandle(options) {
1099
1586
  timeoutMs: options.timeoutMs,
1100
1587
  requestTimeoutMs: options.requestTimeoutMs
1101
1588
  });
1102
- return new E2bSandboxHandle(sandbox);
1589
+ return new E2bSandboxHandle(sandbox, (message) => new DeploymentError(message));
1103
1590
  }
1104
1591
  var SandboxClient = class _SandboxClient {
1105
1592
  constructor(handle) {
@@ -1143,6 +1630,61 @@ var SandboxClient = class _SandboxClient {
1143
1630
  async runCommand(command, options) {
1144
1631
  return this.handle.runCommand(command, options);
1145
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
+ }
1146
1688
  async setTimeout(timeoutMs) {
1147
1689
  if (!this.handle.setTimeout) {
1148
1690
  throw new ConfigurationError(`Sandbox provider "${this.provider}" does not support setTimeout().`);
@@ -1170,17 +1712,26 @@ function normalizeStackFramePath(rawPath, cwd = process.cwd()) {
1170
1712
  }
1171
1713
  function getCallerFile() {
1172
1714
  const stack = new Error().stack?.split("\n") ?? [];
1173
- for (const line of stack.slice(2)) {
1715
+ let moduleFile;
1716
+ let bundledFallback;
1717
+ for (const line of stack.slice(1)) {
1174
1718
  const match = line.match(/\((.+?):\d+:\d+\)/) || line.match(/at (.+?):\d+:\d+/);
1175
1719
  if (!match) continue;
1176
1720
  const file = normalizeStackFramePath(match[1]);
1177
1721
  if (!file) continue;
1722
+ if (!moduleFile) {
1723
+ moduleFile = file;
1724
+ continue;
1725
+ }
1178
1726
  if (file.includes("node:")) continue;
1179
1727
  if (file.includes("node_modules/agent-neckbeard")) continue;
1180
- if (file.includes("agent-neckbeard/dist")) continue;
1181
- if (file.endsWith("/src/index.ts")) continue;
1728
+ if (file === moduleFile) {
1729
+ bundledFallback ??= file;
1730
+ continue;
1731
+ }
1182
1732
  return file;
1183
1733
  }
1734
+ if (bundledFallback) return bundledFallback;
1184
1735
  throw new Error("Could not determine source file");
1185
1736
  }
1186
1737
  function isFrameworkBuildOutputPath(file) {
@@ -1344,10 +1895,13 @@ var Agent = class {
1344
1895
  provider;
1345
1896
  template;
1346
1897
  inputSchema;
1347
- /** Only populated for run-output agents; undefined for streaming agents. */
1898
+ /** Only populated for structured-task agents; undefined for session agents. */
1348
1899
  outputSchema;
1349
- /** Only populated for streaming agents; undefined for run-output agents. */
1900
+ /** Only populated for attached-session agents; undefined for run-output agents. */
1350
1901
  frameSchema;
1902
+ /** User-facing execution shape. */
1903
+ kind;
1904
+ /** @deprecated Use `kind`; retained for compatibility with `run | stream` checks. */
1351
1905
  mode;
1352
1906
  maxDuration;
1353
1907
  dependencies;
@@ -1359,7 +1913,7 @@ var Agent = class {
1359
1913
  build;
1360
1914
  /** @internal Used by the in-sandbox server for run-output agents. */
1361
1915
  _run;
1362
- /** @internal Used by the in-sandbox server for streaming agents. */
1916
+ /** @internal Used by the in-sandbox server for attached-session agents. */
1363
1917
  _server;
1364
1918
  /** @internal Runtime state populated by deploy(). */
1365
1919
  _serverRuntime;
@@ -1379,11 +1933,14 @@ var Agent = class {
1379
1933
  this.claudeDir = config.claudeDir;
1380
1934
  this.envs = config.envs ?? {};
1381
1935
  this.build = config.build ?? {};
1382
- if (isServerAgentConfig(config)) {
1936
+ if (isSessionAgentConfig(config)) {
1937
+ const session = getSessionHandler(config);
1938
+ this.kind = "session";
1383
1939
  this.mode = "stream";
1384
- this._server = config.server;
1385
- this.frameSchema = config.server.frameSchema;
1940
+ this._server = session;
1941
+ this.frameSchema = session.frameSchema;
1386
1942
  } else {
1943
+ this.kind = "task";
1387
1944
  this.mode = "run";
1388
1945
  this._run = config.run;
1389
1946
  this.outputSchema = config.outputSchema;
@@ -1468,47 +2025,68 @@ var Agent = class {
1468
2025
  envs: this.sandboxEnv
1469
2026
  });
1470
2027
  }
1471
- async resolveRuntimeConnection(sandboxId) {
2028
+ async resolveRuntimeConnection(sandboxId, options = {}) {
2029
+ const { signal } = options;
2030
+ throwIfAborted(signal);
1472
2031
  const targetId = sandboxId ?? this._serverRuntime?.connection.sandboxId ?? this._sandboxId;
1473
2032
  if (!targetId) {
1474
2033
  throw new ConfigurationError("Agent not deployed. Call agent.deploy() first or pass sandboxId.");
1475
2034
  }
1476
- if (!sandboxId && this._serverRuntime?.connection.sandboxId === targetId) {
2035
+ if ((!sandboxId || options.reuseMatchingCachedConnection) && this._serverRuntime?.connection.sandboxId === targetId) {
1477
2036
  return this._serverRuntime.connection;
1478
2037
  }
1479
- const sandbox = await this.connectSandboxHandle(targetId);
1480
- 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
+ );
1481
2046
  const port = serverConfig?.port ?? this._server?.port ?? DEFAULT_SERVER_PORT;
1482
- const connection = await this.createRuntimeConnection(sandbox, port);
2047
+ const connection = await awaitWithAbort(
2048
+ () => this.createRuntimeConnection(sandbox, port),
2049
+ signal
2050
+ );
1483
2051
  const healthUrl = this.healthUrlFor(connection);
1484
2052
  try {
1485
- await waitForServerHealthy(healthUrl, connection, SERVER_RECONNECT_HEALTH_TIMEOUT_MS);
1486
- 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 };
1487
2062
  this._sandboxId = targetId;
1488
2063
  return connection;
1489
2064
  } catch {
1490
- const { sessionId, commandId } = await this.startRuntimeServer(sandbox);
2065
+ throwIfAborted(signal);
2066
+ const detachedCommand = await awaitWithAbort(
2067
+ () => this.startRuntimeServer(sandbox),
2068
+ signal
2069
+ );
1491
2070
  try {
1492
- await waitForServerHealthy(healthUrl, connection);
2071
+ await waitForServerHealthy(
2072
+ healthUrl,
2073
+ connection,
2074
+ SERVER_HEALTH_TIMEOUT_MS,
2075
+ signal
2076
+ );
1493
2077
  } catch (error) {
2078
+ throwIfAborted(signal);
1494
2079
  const baseMessage = error instanceof Error ? error.message : String(error);
1495
- let logs = "";
1496
- if (commandId && sandbox.readSessionLogs) {
1497
- const captured = await sandbox.readSessionLogs(sessionId, commandId);
1498
- const parts = [];
1499
- if (captured.stdout.trim()) parts.push(`stdout:
1500
- ${captured.stdout}`);
1501
- if (captured.stderr.trim()) parts.push(`stderr:
1502
- ${captured.stderr}`);
1503
- if (parts.length > 0) {
1504
- logs = `
1505
- --- server logs ---
1506
- ${parts.join("\n\n")}`;
1507
- }
1508
- }
2080
+ const logs = await readServerFailureDiagnostics(
2081
+ sandbox,
2082
+ detachedCommand,
2083
+ this.envs,
2084
+ signal
2085
+ );
1509
2086
  throw new DeploymentError(`${baseMessage}${logs}`);
1510
2087
  }
1511
- this._serverRuntime = { sessionId, commandId, connection };
2088
+ throwIfAborted(signal);
2089
+ this._serverRuntime = { detachedCommand, connection };
1512
2090
  this._sandboxId = targetId;
1513
2091
  return connection;
1514
2092
  }
@@ -1533,8 +2111,8 @@ ${parts.join("\n\n")}`;
1533
2111
  if (!targetId) return;
1534
2112
  try {
1535
2113
  const sandbox = await this.connectSandboxHandle(targetId);
1536
- if (this._serverRuntime && this._serverRuntime.connection.sandboxId === targetId && this._serverRuntime.sessionId && sandbox.stopSession) {
1537
- 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);
1538
2116
  }
1539
2117
  await sandbox.destroy();
1540
2118
  } catch {
@@ -1624,9 +2202,15 @@ var require = __neckbeard_createRequire(import.meta.url);
1624
2202
  this.outputSchema = config.outputSchema;
1625
2203
  this.maxDuration = config.maxDuration ?? 300;
1626
2204
  this._run = config.run;
1627
- if (config.server) {
1628
- this._server = config.server;
1629
- 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';
1630
2214
  }
1631
2215
  }
1632
2216
  }
@@ -1658,142 +2242,145 @@ var require = __neckbeard_createRequire(import.meta.url);
1658
2242
  }]
1659
2243
  });
1660
2244
  const sandbox = await this.createSandboxHandle();
1661
- const { paths } = sandbox;
1662
- await sandbox.runCommand(`mkdir -p ${shellEscape(paths.agentDir)}`, {
1663
- timeoutMs: QUICK_COMMAND_TIMEOUT_MS
1664
- });
1665
- const { apt, commands } = this.dependencies;
1666
- if (apt && apt.length > 0) {
1667
- const aptCmd = `sudo apt-get update && sudo apt-get install -y ${apt.join(" ")}`;
1668
- const aptResult = await sandbox.runCommand(aptCmd, {
1669
- 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
1670
2251
  });
1671
- if (aptResult.exitCode !== 0) {
1672
- const details = [
1673
- `Failed to install apt packages: ${apt.join(", ")}`,
1674
- aptResult.stderr ? `stderr: ${aptResult.stderr}` : "",
1675
- aptResult.stdout ? `stdout: ${aptResult.stdout}` : ""
1676
- ].filter(Boolean).join("\n");
1677
- throw new DeploymentError(details);
1678
- }
1679
- }
1680
- if (commands && commands.length > 0) {
1681
- for (const cmd of commands) {
1682
- const cmdResult = await sandbox.runCommand(cmd, {
1683
- 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
1684
2257
  });
1685
- if (cmdResult.exitCode !== 0) {
2258
+ if (aptResult.exitCode !== 0) {
1686
2259
  const details = [
1687
- `Failed to run command: ${cmd}`,
1688
- cmdResult.stderr ? `stderr: ${cmdResult.stderr}` : "",
1689
- 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}` : ""
1690
2263
  ].filter(Boolean).join("\n");
1691
2264
  throw new DeploymentError(details);
1692
2265
  }
1693
2266
  }
1694
- }
1695
- if (this.files.length > 0) {
1696
- for (const file of this.files) {
1697
- const destPath = file.path.startsWith("/") ? file.path : `${paths.homeDir}/${file.path}`;
1698
- const parentDir = destPath.substring(0, destPath.lastIndexOf("/"));
1699
- if (parentDir) {
1700
- await sandbox.runCommand(`mkdir -p ${shellEscape(parentDir)}`, {
1701
- 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
1702
2271
  });
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
+ }
1703
2280
  }
1704
- const curlCmd = `curl -fsSL -o ${shellEscape(destPath)} ${shellEscape(file.url)}`;
1705
- const downloadResult = await sandbox.runCommand(curlCmd, {
1706
- timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
1707
- });
1708
- if (downloadResult.exitCode !== 0) {
1709
- const details = [
1710
- `Failed to download file from ${file.url} to ${destPath}`,
1711
- downloadResult.stderr ? `stderr: ${downloadResult.stderr}` : "",
1712
- downloadResult.stdout ? `stdout: ${downloadResult.stdout}` : ""
1713
- ].filter(Boolean).join("\n");
1714
- throw new DeploymentError(details);
2281
+ }
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
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
+ }
1715
2303
  }
1716
2304
  }
1717
- }
1718
- for (const directory of localDirectoryUploads.directories) {
1719
- await sandbox.makeDir(posix.join(paths.agentDir, directory));
1720
- }
1721
- for (const file of localDirectoryUploads.files) {
1722
- await sandbox.writeFile(
1723
- posix.join(paths.agentDir, file.targetPath),
1724
- file.content
1725
- );
1726
- }
1727
- await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
1728
- await sandbox.writeFile(paths.serverModule, RUNTIME_SERVER_SOURCE);
1729
- const serverConfig = {
1730
- protocolVersion: RUNTIME_PROTOCOL_VERSION,
1731
- port: this._server?.port ?? DEFAULT_SERVER_PORT,
1732
- maxDurationMs: this.maxDuration * 1e3,
1733
- sandboxContext: {
1734
- provider: paths.provider,
1735
- homeDir: paths.homeDir,
1736
- workDir: paths.workDir,
1737
- agentDir: paths.agentDir,
1738
- ioDir: paths.ioDir,
1739
- inputJson: paths.inputJson,
1740
- outputJson: paths.outputJson
2305
+ for (const directory of localDirectoryUploads.directories) {
2306
+ await sandbox.makeDir(posix.join(paths.agentDir, directory));
1741
2307
  }
1742
- };
1743
- await sandbox.writeFile(paths.serverConfig, JSON.stringify(serverConfig));
1744
- if (collectedExternals.size > 0) {
1745
- const installable = Array.from(collectedExternals.values()).filter(isPackageCompatible);
1746
- const dependencies = Object.fromEntries(installable.map((info) => [info.name, info.version]));
1747
- if (Object.keys(dependencies).length > 0) {
1748
- const pkgJson = JSON.stringify({
1749
- name: "agent-sandbox",
1750
- type: "module",
1751
- dependencies
1752
- });
1753
- await sandbox.writeFile(paths.packageJson, pkgJson);
1754
- const installResult = await sandbox.runCommand("npm install --legacy-peer-deps", {
1755
- cwd: paths.agentDir,
1756
- timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
1757
- });
1758
- if (installResult.exitCode !== 0) {
1759
- const details = [
1760
- `Failed to install npm packages: ${Object.keys(dependencies).join(", ")}`,
1761
- installResult.stderr ? `stderr: ${installResult.stderr}` : "",
1762
- installResult.stdout ? `stdout: ${installResult.stdout}` : ""
1763
- ].filter(Boolean).join("\n");
1764
- 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
+ }
1765
2353
  }
1766
2354
  }
1767
- }
1768
- const port = serverConfig.port;
1769
- const { sessionId, commandId } = await this.startRuntimeServer(sandbox);
1770
- const connection = await this.createRuntimeConnection(sandbox, port);
1771
- const healthUrl = this.healthUrlFor(connection);
1772
- try {
1773
- await waitForServerHealthy(healthUrl, connection);
1774
- } catch (err) {
1775
- const baseMessage = err instanceof Error ? err.message : String(err);
1776
- let logs = "";
1777
- if (commandId && sandbox.readSessionLogs) {
1778
- const captured = await sandbox.readSessionLogs(sessionId, commandId);
1779
- const parts = [];
1780
- if (captured.stdout.trim()) parts.push(`stdout:
1781
- ${captured.stdout}`);
1782
- if (captured.stderr.trim()) parts.push(`stderr:
1783
- ${captured.stderr}`);
1784
- if (parts.length > 0) {
1785
- logs = `
1786
- --- server logs ---
1787
- ${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);
1788
2380
  }
2381
+ await sandbox.destroy().catch(() => void 0);
1789
2382
  }
1790
- throw new DeploymentError(`${baseMessage}${logs}`);
1791
- }
1792
- if (!options?.fresh) {
1793
- this._sandboxId = sandbox.id;
1794
- this._serverRuntime = { sessionId, commandId, connection };
1795
2383
  }
1796
- return sandbox.id;
1797
2384
  }
1798
2385
  /**
1799
2386
  * Executes the agent with the given input.
@@ -1824,7 +2411,7 @@ ${parts.join("\n\n")}`;
1824
2411
  ok: false,
1825
2412
  executionId,
1826
2413
  error: new ExecutionError(
1827
- "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."
1828
2415
  )
1829
2416
  };
1830
2417
  }
@@ -1836,7 +2423,7 @@ ${parts.join("\n\n")}`;
1836
2423
  } catch (error) {
1837
2424
  throw new ValidationError("Input validation failed.", asError(error));
1838
2425
  }
1839
- const { invokeServer } = await import("./invoke-client-XEH6FVRH.js");
2426
+ const { invokeServer } = await import("./invoke-client-D5TMTOYM.js");
1840
2427
  let output;
1841
2428
  let sawOutput = false;
1842
2429
  for await (const event of invokeServer(validatedInput, {
@@ -1875,17 +2462,74 @@ ${parts.join("\n\n")}`;
1875
2462
  }
1876
2463
  }
1877
2464
  /**
1878
- * Invoke a streaming agent. Streams user frames emitted by the in-sandbox
1879
- * 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.
1880
2468
  */
1881
- async *invoke(input, options) {
2469
+ async createSession(options = {}) {
1882
2470
  if (this.mode !== "stream") {
1883
2471
  throw new ConfigurationError(
1884
- "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."
1885
2514
  );
1886
2515
  }
1887
- const connection = await this.resolveRuntimeConnection(options?.sandboxId);
1888
- 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");
1889
2533
  let validated;
1890
2534
  try {
1891
2535
  validated = this.inputSchema.parse(input);
@@ -1898,7 +2542,7 @@ ${parts.join("\n\n")}`;
1898
2542
  provider: connection.provider,
1899
2543
  trafficToken: getTrafficToken(connection),
1900
2544
  frameSchema: this.frameSchema,
1901
- signal: options?.signal
2545
+ signal
1902
2546
  })) {
1903
2547
  if (frame.kind === "frame") {
1904
2548
  yield frame.data;
@@ -1913,6 +2557,22 @@ ${parts.join("\n\n")}`;
1913
2557
  throw error instanceof Error ? error : new Error(String(error));
1914
2558
  }
1915
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
+ }
1916
2576
  };
1917
2577
  export {
1918
2578
  Agent,