agent-neckbeard 1.1.18 → 1.1.20
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/CHANGELOG.md +32 -0
- package/README.md +171 -67
- package/dist/chunk-33IXN6MM.js +21 -0
- package/dist/chunk-3EB4CT5S.js +2516 -0
- package/dist/{chunk-AM2J5KBI.js → chunk-DHFC3O44.js} +4 -8
- package/dist/index.cjs +3652 -535
- package/dist/index.d.cts +150 -56
- package/dist/index.d.ts +150 -56
- package/dist/index.js +1167 -501
- package/dist/{invoke-client-XEH6FVRH.js → invoke-client-D5TMTOYM.js} +2 -1
- package/dist/sandbox-capabilities-CFjnZ_kB.d.cts +77 -0
- package/dist/sandbox-capabilities-CFjnZ_kB.d.ts +77 -0
- package/dist/supervisor.cjs +6043 -0
- package/dist/supervisor.d.cts +470 -0
- package/dist/supervisor.d.ts +470 -0
- package/dist/supervisor.js +3535 -0
- package/docs/SUPERVISOR.md +248 -0
- package/package.json +20 -8
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-
|
|
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,548 @@ 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(
|
|
328
|
+
daytonaTimeoutSeconds(SANDBOX_COMMAND_TIMEOUT_MS),
|
|
329
|
+
true
|
|
330
|
+
);
|
|
331
|
+
}
|
|
332
|
+
};
|
|
333
|
+
|
|
334
|
+
// src/timeout.ts
|
|
335
|
+
function settleOperation(operation, options = {}) {
|
|
336
|
+
const { abort, timeout } = options;
|
|
337
|
+
if (abort?.signal.aborted) throw abort.createError();
|
|
338
|
+
if (!abort && !timeout) {
|
|
339
|
+
try {
|
|
340
|
+
return Promise.resolve(operation());
|
|
341
|
+
} catch (error) {
|
|
342
|
+
return Promise.reject(error);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
return new Promise((resolve2, reject) => {
|
|
346
|
+
let settled = false;
|
|
347
|
+
let timer;
|
|
348
|
+
const cleanup = () => {
|
|
349
|
+
if (timer !== void 0) {
|
|
350
|
+
clearTimeout(timer);
|
|
351
|
+
timer = void 0;
|
|
352
|
+
}
|
|
353
|
+
abort?.signal.removeEventListener("abort", onAbort);
|
|
354
|
+
};
|
|
355
|
+
const settle = (callback) => {
|
|
356
|
+
if (settled) return;
|
|
357
|
+
settled = true;
|
|
358
|
+
cleanup();
|
|
359
|
+
callback();
|
|
360
|
+
};
|
|
361
|
+
const onAbort = () => settle(() => reject(abort.createError()));
|
|
362
|
+
abort?.signal.addEventListener("abort", onAbort, { once: true });
|
|
363
|
+
if (timeout) {
|
|
364
|
+
timer = setTimeout(
|
|
365
|
+
() => settle(() => reject(timeout.createError())),
|
|
366
|
+
timeout.timeoutMs
|
|
367
|
+
);
|
|
368
|
+
}
|
|
369
|
+
let task;
|
|
370
|
+
try {
|
|
371
|
+
task = operation();
|
|
372
|
+
} catch (error) {
|
|
373
|
+
settle(() => reject(error));
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
void Promise.resolve(task).then(
|
|
377
|
+
(value) => settle(() => resolve2(value)),
|
|
378
|
+
(error) => settle(() => reject(error))
|
|
379
|
+
);
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
function withTimeout(task, timeoutMs, message) {
|
|
383
|
+
return settleOperation(() => task, {
|
|
384
|
+
timeout: {
|
|
385
|
+
timeoutMs,
|
|
386
|
+
createError: () => new Error(message)
|
|
387
|
+
}
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// src/providers/e2b.ts
|
|
392
|
+
var E2B_SANDBOX_HOME = "/home/user";
|
|
393
|
+
var LEGACY_E2B_PROCESS_HANDLE_PATTERN = /^e2b:([1-9][0-9]*)$/u;
|
|
394
|
+
var LEGACY_E2B_EXIT_POLL_INTERVAL_MS = 100;
|
|
395
|
+
function parseLegacyE2bProcessHandle(value) {
|
|
396
|
+
const match = LEGACY_E2B_PROCESS_HANDLE_PATTERN.exec(value);
|
|
397
|
+
if (!match) return null;
|
|
398
|
+
const pid = Number(match[1]);
|
|
399
|
+
return Number.isSafeInteger(pid) && pid > 0 ? pid : null;
|
|
400
|
+
}
|
|
401
|
+
function remainingTimeoutMs(deadline) {
|
|
402
|
+
return Math.max(1, Math.ceil(deadline - performance.now()));
|
|
403
|
+
}
|
|
404
|
+
function delay(timeoutMs) {
|
|
405
|
+
return new Promise((resolve2) => setTimeout(resolve2, timeoutMs));
|
|
406
|
+
}
|
|
407
|
+
async function withinDeadline(operation, deadline) {
|
|
408
|
+
return withTimeout(
|
|
409
|
+
operation,
|
|
410
|
+
remainingTimeoutMs(deadline),
|
|
411
|
+
"E2B process control request timed out."
|
|
412
|
+
);
|
|
413
|
+
}
|
|
414
|
+
function numberProperty(value, property) {
|
|
415
|
+
if (typeof value !== "object" || value === null) return void 0;
|
|
416
|
+
const propertyValue = Reflect.get(value, property);
|
|
417
|
+
return typeof propertyValue === "number" ? propertyValue : void 0;
|
|
418
|
+
}
|
|
419
|
+
function stringProperty(value, property) {
|
|
420
|
+
if (typeof value !== "object" || value === null) return void 0;
|
|
421
|
+
const propertyValue = Reflect.get(value, property);
|
|
422
|
+
return typeof propertyValue === "string" ? propertyValue : void 0;
|
|
423
|
+
}
|
|
424
|
+
function messageFrom(error) {
|
|
425
|
+
return error instanceof Error ? error.message : String(error);
|
|
426
|
+
}
|
|
427
|
+
function writeContent(content) {
|
|
428
|
+
if (typeof content === "string") return content;
|
|
429
|
+
if (content instanceof ArrayBuffer) return content;
|
|
430
|
+
return Uint8Array.from(content).buffer;
|
|
431
|
+
}
|
|
432
|
+
async function runE2bCommand(sandbox, cmd, options) {
|
|
433
|
+
let stdout = "";
|
|
434
|
+
let stderr = "";
|
|
435
|
+
const command = options.cwd ? `cd ${shellQuote(options.cwd)} && ${cmd}` : cmd;
|
|
436
|
+
try {
|
|
437
|
+
const result = await sandbox.commands.run(command, {
|
|
438
|
+
timeoutMs: options.timeoutMs,
|
|
439
|
+
envs: options.envs,
|
|
440
|
+
background: false,
|
|
441
|
+
onStdout: (data) => {
|
|
442
|
+
stdout += data;
|
|
443
|
+
options.onStdout?.(data);
|
|
444
|
+
},
|
|
445
|
+
onStderr: (data) => {
|
|
446
|
+
stderr += data;
|
|
447
|
+
options.onStderr?.(data);
|
|
448
|
+
}
|
|
449
|
+
});
|
|
450
|
+
return {
|
|
451
|
+
exitCode: result.exitCode,
|
|
452
|
+
stdout: stdout || result.stdout,
|
|
453
|
+
stderr: stderr || result.stderr
|
|
454
|
+
};
|
|
455
|
+
} catch (error) {
|
|
456
|
+
return {
|
|
457
|
+
exitCode: numberProperty(error, "exitCode") ?? 1,
|
|
458
|
+
stdout: stdout || stringProperty(error, "stdout") || "",
|
|
459
|
+
stderr: stderr || stringProperty(error, "stderr") || messageFrom(error)
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
var E2bSandboxHandle = class {
|
|
464
|
+
constructor(sandbox, failure) {
|
|
465
|
+
this.sandbox = sandbox;
|
|
466
|
+
this.failure = failure;
|
|
467
|
+
this.detachedProcesses = new DetachedProcessController({
|
|
468
|
+
provider: "e2b",
|
|
469
|
+
genericPayloadEnvironmentDefaults: { HOME: this.paths.homeDir },
|
|
470
|
+
execute: async (command, options) => ({
|
|
471
|
+
state: "completed",
|
|
472
|
+
result: await runE2bCommand(this.sandbox, command, {
|
|
473
|
+
cwd: options?.cwd,
|
|
474
|
+
envs: options?.envs,
|
|
475
|
+
timeoutMs: DETACHED_PROCESS_CONTROL_TIMEOUT_MS
|
|
476
|
+
})
|
|
477
|
+
}),
|
|
478
|
+
readLegacyLogs: (command) => this.readLegacySessionLogs(command),
|
|
479
|
+
stopLegacy: (command) => this.stopLegacySession(command),
|
|
480
|
+
failure
|
|
481
|
+
});
|
|
482
|
+
}
|
|
483
|
+
provider = "e2b";
|
|
484
|
+
detachedProcesses;
|
|
485
|
+
paths = createProviderSandboxPaths(
|
|
486
|
+
"e2b",
|
|
487
|
+
E2B_SANDBOX_HOME,
|
|
488
|
+
E2B_SANDBOX_HOME
|
|
489
|
+
);
|
|
490
|
+
get id() {
|
|
491
|
+
return this.sandbox.sandboxId;
|
|
492
|
+
}
|
|
493
|
+
async makeDir(path) {
|
|
494
|
+
await this.sandbox.files.makeDir(path);
|
|
495
|
+
}
|
|
496
|
+
writeFile(path, content) {
|
|
497
|
+
return this.sandbox.files.write(path, writeContent(content)).then(() => void 0);
|
|
498
|
+
}
|
|
499
|
+
readFile(path) {
|
|
500
|
+
return this.sandbox.files.read(path, { format: "text" });
|
|
501
|
+
}
|
|
502
|
+
readFileBytes(path) {
|
|
503
|
+
return this.sandbox.files.read(path, { format: "bytes" });
|
|
504
|
+
}
|
|
505
|
+
runCommand(cmd, options) {
|
|
506
|
+
return runE2bCommand(this.sandbox, cmd, options);
|
|
507
|
+
}
|
|
508
|
+
setTimeout(timeoutMs) {
|
|
509
|
+
return this.sandbox.setTimeout(timeoutMs);
|
|
510
|
+
}
|
|
511
|
+
async startDetachedCommand(command, options = {}) {
|
|
512
|
+
return this.detachedProcesses.start(command, options);
|
|
513
|
+
}
|
|
514
|
+
async readSessionLogs(command) {
|
|
515
|
+
return this.detachedProcesses.readLogs(command);
|
|
516
|
+
}
|
|
517
|
+
async readLegacySessionLogs(command) {
|
|
518
|
+
const { commandId } = command;
|
|
519
|
+
if (commandId === void 0) return { stdout: "", stderr: "" };
|
|
520
|
+
try {
|
|
521
|
+
const handle = await this.sandbox.commands.connect(Number(commandId));
|
|
522
|
+
return {
|
|
523
|
+
stdout: boundDetachedProcessLog(handle.stdout ?? ""),
|
|
524
|
+
stderr: boundDetachedProcessLog(handle.stderr ?? "")
|
|
525
|
+
};
|
|
526
|
+
} catch {
|
|
527
|
+
return { stdout: "", stderr: "" };
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
async stopSession(command) {
|
|
531
|
+
await this.detachedProcesses.stop(command);
|
|
532
|
+
}
|
|
533
|
+
async disposeSessionArtifacts(command) {
|
|
534
|
+
await this.detachedProcesses.dispose(command);
|
|
535
|
+
}
|
|
536
|
+
async stopLegacySession(command) {
|
|
537
|
+
const { sessionId } = command;
|
|
538
|
+
const legacyPid = parseLegacyE2bProcessHandle(sessionId);
|
|
539
|
+
if (legacyPid === null) {
|
|
540
|
+
throw this.failure("Detached process handle is invalid for E2B.");
|
|
541
|
+
}
|
|
542
|
+
const deadline = performance.now() + DETACHED_PROCESS_CONTROL_TIMEOUT_MS;
|
|
543
|
+
let signalled;
|
|
544
|
+
try {
|
|
545
|
+
signalled = await withinDeadline(
|
|
546
|
+
this.sandbox.commands.kill(legacyPid, {
|
|
547
|
+
requestTimeoutMs: remainingTimeoutMs(deadline)
|
|
548
|
+
}),
|
|
549
|
+
deadline
|
|
550
|
+
);
|
|
551
|
+
} catch (error) {
|
|
552
|
+
throw this.failure(
|
|
553
|
+
`Failed to stop legacy detached E2B process ${legacyPid}: ${messageFrom(error)}`
|
|
554
|
+
);
|
|
555
|
+
}
|
|
556
|
+
if (!signalled) return;
|
|
557
|
+
while (performance.now() < deadline) {
|
|
558
|
+
let processes;
|
|
559
|
+
try {
|
|
560
|
+
processes = await withinDeadline(
|
|
561
|
+
this.sandbox.commands.list({
|
|
562
|
+
requestTimeoutMs: remainingTimeoutMs(deadline)
|
|
563
|
+
}),
|
|
564
|
+
deadline
|
|
565
|
+
);
|
|
566
|
+
} catch (error) {
|
|
567
|
+
throw this.failure(
|
|
568
|
+
`Failed to confirm legacy detached E2B process ${legacyPid} exit: ${messageFrom(error)}`
|
|
569
|
+
);
|
|
570
|
+
}
|
|
571
|
+
if (!processes.some((process2) => process2.pid === legacyPid)) return;
|
|
572
|
+
const remaining = deadline - performance.now();
|
|
573
|
+
if (remaining <= 0) break;
|
|
574
|
+
await delay(Math.min(LEGACY_E2B_EXIT_POLL_INTERVAL_MS, remaining));
|
|
575
|
+
}
|
|
576
|
+
throw this.failure(
|
|
577
|
+
`Failed to stop legacy detached E2B process ${legacyPid}: provider still reports it as running.`
|
|
578
|
+
);
|
|
579
|
+
}
|
|
580
|
+
async getServerEndpoint(port) {
|
|
581
|
+
return {
|
|
582
|
+
url: `https://${this.sandbox.getHost(port)}`,
|
|
583
|
+
trafficToken: this.sandbox.trafficAccessToken
|
|
584
|
+
};
|
|
585
|
+
}
|
|
586
|
+
async destroy() {
|
|
587
|
+
await this.sandbox.kill();
|
|
588
|
+
}
|
|
589
|
+
};
|
|
30
590
|
|
|
31
591
|
// src/index.ts
|
|
32
592
|
function readPackageJson(path) {
|
|
@@ -36,8 +596,8 @@ var getEsbuild = () => import("esbuild");
|
|
|
36
596
|
var getE2b = () => import("e2b");
|
|
37
597
|
var getDaytona = () => import("@daytona/sdk");
|
|
38
598
|
var DEFAULT_MAX_DURATION = 300;
|
|
39
|
-
var
|
|
40
|
-
var
|
|
599
|
+
var SANDBOX_COMMAND_TIMEOUT_MS2 = 3e5;
|
|
600
|
+
var QUICK_COMMAND_TIMEOUT_MS2 = 3e4;
|
|
41
601
|
var DAYTONA_CREATE_TIMEOUT_SEC = 120;
|
|
42
602
|
var NODE_TARGET = "node20";
|
|
43
603
|
var DEFAULT_EXTERNALS = ["@anthropic-ai/claude-agent-sdk"];
|
|
@@ -49,9 +609,9 @@ var DEFAULT_SERVER_PORT = 3e3;
|
|
|
49
609
|
var SERVER_HEALTH_TIMEOUT_MS = 12e4;
|
|
50
610
|
var SERVER_RECONNECT_HEALTH_TIMEOUT_MS = 3e3;
|
|
51
611
|
var SERVER_HEALTH_POLL_INTERVAL_MS = 1e3;
|
|
612
|
+
var SERVER_FAILURE_DIAGNOSTIC_TIMEOUT_MS = 1e3;
|
|
52
613
|
var NATIVE_EXT_RE = /\.(node|wasm|gyp|c|cc|cpp|cxx|h|hpp|hxx)$/i;
|
|
53
614
|
var TRACEABLE_SOURCE_EXT_RE = /\.(cjs|cts|js|jsx|mjs|mts|ts|tsx)$/i;
|
|
54
|
-
var E2B_SANDBOX_HOME = "/home/user";
|
|
55
615
|
var NeckbeardError = class extends Error {
|
|
56
616
|
constructor(message) {
|
|
57
617
|
super(message);
|
|
@@ -513,8 +1073,20 @@ function mergeTracingIncludes(existing, routeGlobs, sourceFiles) {
|
|
|
513
1073
|
return includes;
|
|
514
1074
|
}
|
|
515
1075
|
var DEFAULT_DEPENDENCIES = {};
|
|
516
|
-
function
|
|
517
|
-
return "server" in config && config.server !== void 0;
|
|
1076
|
+
function isSessionAgentConfig(config) {
|
|
1077
|
+
return "session" in config && config.session !== void 0 || "server" in config && config.server !== void 0;
|
|
1078
|
+
}
|
|
1079
|
+
function getSessionHandler(config) {
|
|
1080
|
+
const session = "session" in config ? config.session : void 0;
|
|
1081
|
+
const server = "server" in config ? config.server : void 0;
|
|
1082
|
+
if (session && server) {
|
|
1083
|
+
throw new ConfigurationError("Agent config must use session or deprecated server, not both.");
|
|
1084
|
+
}
|
|
1085
|
+
const handler = session ?? server;
|
|
1086
|
+
if (!handler || typeof handler !== "object") {
|
|
1087
|
+
throw new ConfigurationError("session must be an object.");
|
|
1088
|
+
}
|
|
1089
|
+
return handler;
|
|
518
1090
|
}
|
|
519
1091
|
function isSchemaLike(value) {
|
|
520
1092
|
return Boolean(
|
|
@@ -527,6 +1099,20 @@ function requireSchemaLike(name, value) {
|
|
|
527
1099
|
}
|
|
528
1100
|
return value;
|
|
529
1101
|
}
|
|
1102
|
+
function isAbortSignal(value) {
|
|
1103
|
+
if (!value || typeof value !== "object") return false;
|
|
1104
|
+
try {
|
|
1105
|
+
const abortedGetter = Object.getOwnPropertyDescriptor(
|
|
1106
|
+
AbortSignal.prototype,
|
|
1107
|
+
"aborted"
|
|
1108
|
+
)?.get;
|
|
1109
|
+
if (!abortedGetter || typeof abortedGetter.call(value) !== "boolean") return false;
|
|
1110
|
+
const candidate = value;
|
|
1111
|
+
return typeof candidate.aborted === "boolean" && typeof candidate.addEventListener === "function" && typeof candidate.removeEventListener === "function";
|
|
1112
|
+
} catch {
|
|
1113
|
+
return false;
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
530
1116
|
function normalizeLocalDirectoryDestination(destination, name) {
|
|
531
1117
|
if (destination.trim() === "") {
|
|
532
1118
|
throw new ConfigurationError(`${name}.destination must be a non-empty relative path.`);
|
|
@@ -595,21 +1181,19 @@ function validateAgentConfig(config) {
|
|
|
595
1181
|
throw new ConfigurationError("sourceFile must be a non-empty string when provided.");
|
|
596
1182
|
}
|
|
597
1183
|
validateLocalDirectoriesConfig(config.localDirectories);
|
|
598
|
-
if (
|
|
1184
|
+
if (isSessionAgentConfig(config)) {
|
|
599
1185
|
if ("run" in config && typeof config.run === "function") {
|
|
600
|
-
throw new ConfigurationError("Agent config must use either run or
|
|
601
|
-
}
|
|
602
|
-
if (!config.server || typeof config.server !== "object") {
|
|
603
|
-
throw new ConfigurationError("server must be an object.");
|
|
1186
|
+
throw new ConfigurationError("Agent config must use either run or session.handler, not both.");
|
|
604
1187
|
}
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
1188
|
+
const session = getSessionHandler(config);
|
|
1189
|
+
if (session.port !== void 0) {
|
|
1190
|
+
if (!Number.isInteger(session.port) || session.port < 1 || session.port > 65535) {
|
|
1191
|
+
throw new ConfigurationError("session.port must be an integer between 1 and 65535.");
|
|
608
1192
|
}
|
|
609
1193
|
}
|
|
610
|
-
requireSchemaLike("
|
|
611
|
-
if (typeof
|
|
612
|
-
throw new ConfigurationError("
|
|
1194
|
+
requireSchemaLike("session.frameSchema", session.frameSchema);
|
|
1195
|
+
if (typeof session.handler !== "function") {
|
|
1196
|
+
throw new ConfigurationError("session.handler must be a function.");
|
|
613
1197
|
}
|
|
614
1198
|
return;
|
|
615
1199
|
}
|
|
@@ -634,24 +1218,86 @@ function trafficTokenHeaders(descriptor) {
|
|
|
634
1218
|
}
|
|
635
1219
|
return {};
|
|
636
1220
|
}
|
|
637
|
-
|
|
1221
|
+
function abortSignalError(signal) {
|
|
1222
|
+
if (signal.reason instanceof Error) return signal.reason;
|
|
1223
|
+
const error = new Error(
|
|
1224
|
+
signal.reason === void 0 ? "Operation aborted." : String(signal.reason)
|
|
1225
|
+
);
|
|
1226
|
+
error.name = "AbortError";
|
|
1227
|
+
return error;
|
|
1228
|
+
}
|
|
1229
|
+
function throwIfAborted(signal) {
|
|
1230
|
+
if (signal?.aborted) throw abortSignalError(signal);
|
|
1231
|
+
}
|
|
1232
|
+
function awaitWithAbort(operation, signal) {
|
|
1233
|
+
return settleOperation(operation, {
|
|
1234
|
+
...signal ? {
|
|
1235
|
+
abort: {
|
|
1236
|
+
signal,
|
|
1237
|
+
createError: () => abortSignalError(signal)
|
|
1238
|
+
}
|
|
1239
|
+
} : {}
|
|
1240
|
+
});
|
|
1241
|
+
}
|
|
1242
|
+
function awaitDiagnosticRead(operation, signal) {
|
|
1243
|
+
return settleOperation(operation, {
|
|
1244
|
+
...signal ? {
|
|
1245
|
+
abort: {
|
|
1246
|
+
signal,
|
|
1247
|
+
createError: () => abortSignalError(signal)
|
|
1248
|
+
}
|
|
1249
|
+
} : {},
|
|
1250
|
+
timeout: {
|
|
1251
|
+
timeoutMs: SERVER_FAILURE_DIAGNOSTIC_TIMEOUT_MS,
|
|
1252
|
+
createError: () => new Error("Server diagnostic read timed out.")
|
|
1253
|
+
}
|
|
1254
|
+
});
|
|
1255
|
+
}
|
|
1256
|
+
function delayWithAbort(delayMs, signal) {
|
|
1257
|
+
if (!signal) {
|
|
1258
|
+
return new Promise((resolve2) => setTimeout(resolve2, delayMs));
|
|
1259
|
+
}
|
|
1260
|
+
throwIfAborted(signal);
|
|
1261
|
+
return new Promise((resolve2, reject) => {
|
|
1262
|
+
const onAbort = () => {
|
|
1263
|
+
clearTimeout(timer);
|
|
1264
|
+
reject(abortSignalError(signal));
|
|
1265
|
+
};
|
|
1266
|
+
const timer = setTimeout(() => {
|
|
1267
|
+
signal.removeEventListener("abort", onAbort);
|
|
1268
|
+
resolve2();
|
|
1269
|
+
}, delayMs);
|
|
1270
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1271
|
+
});
|
|
1272
|
+
}
|
|
1273
|
+
async function waitForServerHealthy(healthUrl, descriptor, timeoutMs = SERVER_HEALTH_TIMEOUT_MS, signal) {
|
|
638
1274
|
const deadline = Date.now() + timeoutMs;
|
|
639
1275
|
let lastError;
|
|
640
1276
|
const urlWithToken = appendTrafficTokenToUrl(healthUrl, descriptor);
|
|
641
1277
|
while (Date.now() < deadline) {
|
|
1278
|
+
throwIfAborted(signal);
|
|
642
1279
|
try {
|
|
643
|
-
const response = await
|
|
644
|
-
|
|
645
|
-
|
|
1280
|
+
const response = await awaitWithAbort(
|
|
1281
|
+
() => fetch(urlWithToken, {
|
|
1282
|
+
headers: trafficTokenHeaders(descriptor),
|
|
1283
|
+
...signal === void 0 ? {} : { signal }
|
|
1284
|
+
}),
|
|
1285
|
+
signal
|
|
1286
|
+
);
|
|
646
1287
|
if (response.ok) {
|
|
647
|
-
|
|
1288
|
+
try {
|
|
1289
|
+
await awaitWithAbort(() => response.text(), signal);
|
|
1290
|
+
} catch {
|
|
1291
|
+
throwIfAborted(signal);
|
|
1292
|
+
}
|
|
648
1293
|
return;
|
|
649
1294
|
}
|
|
650
1295
|
lastError = new Error(`health check returned ${response.status}`);
|
|
651
1296
|
} catch (error) {
|
|
1297
|
+
throwIfAborted(signal);
|
|
652
1298
|
lastError = error;
|
|
653
1299
|
}
|
|
654
|
-
await
|
|
1300
|
+
await delayWithAbort(SERVER_HEALTH_POLL_INTERVAL_MS, signal);
|
|
655
1301
|
}
|
|
656
1302
|
const message = lastError instanceof Error ? lastError.message : String(lastError);
|
|
657
1303
|
throw new DeploymentError(
|
|
@@ -667,9 +1313,6 @@ function requireEnv(name) {
|
|
|
667
1313
|
}
|
|
668
1314
|
return value;
|
|
669
1315
|
}
|
|
670
|
-
function shellEscape(str) {
|
|
671
|
-
return `'${str.replace(/'/g, "'\\''")}'`;
|
|
672
|
-
}
|
|
673
1316
|
var require2 = createRequire(join(process.cwd(), "__agent_neckbeard__.cjs"));
|
|
674
1317
|
var packageRequire = createPackageRequire();
|
|
675
1318
|
function createPackageRequire() {
|
|
@@ -724,325 +1367,163 @@ function resolvePackageInfoSync(importPath, resolveDir) {
|
|
|
724
1367
|
break;
|
|
725
1368
|
}
|
|
726
1369
|
}
|
|
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);
|
|
1370
|
+
const parent = dirname(root);
|
|
1371
|
+
if (parent === root) break;
|
|
1372
|
+
root = parent;
|
|
948
1373
|
}
|
|
949
|
-
|
|
950
|
-
|
|
1374
|
+
if (!packageJsonPath) return null;
|
|
1375
|
+
const packageJson = readPackageJson(packageJsonPath);
|
|
1376
|
+
if (!packageJson.name || !packageJson.version) return null;
|
|
1377
|
+
root = dirname(packageJsonPath);
|
|
951
1378
|
return {
|
|
952
|
-
|
|
953
|
-
|
|
1379
|
+
name: packageJson.name,
|
|
1380
|
+
version: packageJson.version,
|
|
1381
|
+
root,
|
|
1382
|
+
resolvedPath,
|
|
1383
|
+
packageJson
|
|
954
1384
|
};
|
|
1385
|
+
} catch {
|
|
1386
|
+
return null;
|
|
955
1387
|
}
|
|
956
|
-
|
|
957
|
-
|
|
1388
|
+
}
|
|
1389
|
+
function resolvePackageInfoFromResolvedPath(importPath, resolvedPath) {
|
|
1390
|
+
const packageName = packageNameForImportPath(importPath);
|
|
1391
|
+
let root = dirname(resolvedPath);
|
|
1392
|
+
while (true) {
|
|
1393
|
+
const packageJsonPath = join(root, "package.json");
|
|
1394
|
+
if (existsSync(packageJsonPath)) {
|
|
1395
|
+
const packageJson = readPackageJson(packageJsonPath);
|
|
1396
|
+
if (packageJson.name === packageName) {
|
|
1397
|
+
if (!packageJson.version) return null;
|
|
1398
|
+
return {
|
|
1399
|
+
name: packageJson.name,
|
|
1400
|
+
version: packageJson.version,
|
|
1401
|
+
root,
|
|
1402
|
+
resolvedPath,
|
|
1403
|
+
packageJson
|
|
1404
|
+
};
|
|
1405
|
+
}
|
|
1406
|
+
}
|
|
1407
|
+
const parent = dirname(root);
|
|
1408
|
+
if (parent === root) return null;
|
|
1409
|
+
root = parent;
|
|
958
1410
|
}
|
|
959
|
-
}
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
1411
|
+
}
|
|
1412
|
+
function hasNativeHints(info) {
|
|
1413
|
+
const files = Array.isArray(info.packageJson.files) ? info.packageJson.files : [];
|
|
1414
|
+
const fields = [info.packageJson.main, info.packageJson.module, info.packageJson.browser].filter(
|
|
1415
|
+
(f) => typeof f === "string"
|
|
1416
|
+
);
|
|
1417
|
+
return files.concat(fields).some((file) => NATIVE_EXT_RE.test(file));
|
|
1418
|
+
}
|
|
1419
|
+
function shouldAutoExternalize(info) {
|
|
1420
|
+
if (info.resolvedPath.endsWith(".node") || info.resolvedPath.endsWith(".wasm")) return true;
|
|
1421
|
+
if (hasNativeHints(info)) return true;
|
|
1422
|
+
if (existsSync(join(info.root, "binding.gyp"))) return true;
|
|
1423
|
+
return false;
|
|
1424
|
+
}
|
|
1425
|
+
function normalizeList(value) {
|
|
1426
|
+
if (Array.isArray(value)) return value.filter((v) => typeof v === "string");
|
|
1427
|
+
if (typeof value === "string") return [value];
|
|
1428
|
+
return null;
|
|
1429
|
+
}
|
|
1430
|
+
function listAllowsTarget(list, target) {
|
|
1431
|
+
if (!list || list.length === 0) return true;
|
|
1432
|
+
const negated = list.filter((v) => v.startsWith("!")).map((v) => v.slice(1));
|
|
1433
|
+
if (negated.includes(target)) return false;
|
|
1434
|
+
const positives = list.filter((v) => !v.startsWith("!"));
|
|
1435
|
+
if (positives.length === 0) return true;
|
|
1436
|
+
return positives.includes(target);
|
|
1437
|
+
}
|
|
1438
|
+
function isPackageCompatible(info) {
|
|
1439
|
+
const osList = normalizeList(info.packageJson.os);
|
|
1440
|
+
const cpuList = normalizeList(info.packageJson.cpu);
|
|
1441
|
+
return listAllowsTarget(osList, SANDBOX_PLATFORM) && listAllowsTarget(cpuList, SANDBOX_ARCH);
|
|
1442
|
+
}
|
|
1443
|
+
var INVALID_DETACHED_COMMAND_HANDLE_MESSAGE = "Detached process handle must contain a non-empty sessionId string and an optional commandId string.";
|
|
1444
|
+
function normalizeDetachedCommandHandle(value) {
|
|
1445
|
+
if (!value || typeof value !== "object") {
|
|
1446
|
+
throw new ConfigurationError(INVALID_DETACHED_COMMAND_HANDLE_MESSAGE);
|
|
964
1447
|
}
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
1448
|
+
let sessionId;
|
|
1449
|
+
let commandId;
|
|
1450
|
+
try {
|
|
1451
|
+
if (Array.isArray(value)) {
|
|
1452
|
+
throw new Error("invalid detached command handle");
|
|
1453
|
+
}
|
|
1454
|
+
sessionId = Reflect.get(value, "sessionId");
|
|
1455
|
+
commandId = Reflect.get(value, "commandId");
|
|
1456
|
+
} catch {
|
|
1457
|
+
throw new ConfigurationError(INVALID_DETACHED_COMMAND_HANDLE_MESSAGE);
|
|
968
1458
|
}
|
|
969
|
-
|
|
970
|
-
|
|
1459
|
+
if (typeof sessionId !== "string" || sessionId.length === 0 || commandId !== void 0 && typeof commandId !== "string") {
|
|
1460
|
+
throw new ConfigurationError(INVALID_DETACHED_COMMAND_HANDLE_MESSAGE);
|
|
971
1461
|
}
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
if (result.exitCode !== 0) {
|
|
980
|
-
throw new DeploymentError(result.result || `Failed to create directory ${path}`);
|
|
1462
|
+
return commandId === void 0 ? { sessionId } : { sessionId, commandId };
|
|
1463
|
+
}
|
|
1464
|
+
function filterDefinedEnvs(envs) {
|
|
1465
|
+
const filtered = {};
|
|
1466
|
+
for (const [key, value] of Object.entries(envs)) {
|
|
1467
|
+
if (value !== void 0) {
|
|
1468
|
+
filtered[key] = value;
|
|
981
1469
|
}
|
|
982
1470
|
}
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
1471
|
+
return filtered;
|
|
1472
|
+
}
|
|
1473
|
+
function asError(error) {
|
|
1474
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
1475
|
+
}
|
|
1476
|
+
function errorMessage(error) {
|
|
1477
|
+
return error instanceof Error ? error.message : String(error);
|
|
1478
|
+
}
|
|
1479
|
+
var MINIMUM_BULK_DIAGNOSTIC_REDACTION_LENGTH = 8;
|
|
1480
|
+
var CREDENTIAL_ENV_NAME_PATTERN = /(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)/iu;
|
|
1481
|
+
function isConfiguredDiagnosticSecret(name, value) {
|
|
1482
|
+
return CREDENTIAL_ENV_NAME_PATTERN.test(name) || value.length >= MINIMUM_BULK_DIAGNOSTIC_REDACTION_LENGTH;
|
|
1483
|
+
}
|
|
1484
|
+
function redactServerFailureDiagnosticStream(value, secrets) {
|
|
1485
|
+
const mayStartAtTailBoundary = Buffer.byteLength(value, "utf8") >= DETACHED_PROCESS_LOG_MAX_BYTES - 3;
|
|
1486
|
+
let redacted = boundDetachedProcessLog(value);
|
|
1487
|
+
for (const secret of secrets) {
|
|
1488
|
+
const replacement = secret.length < "[REDACTED]".length ? "*" : "[REDACTED]";
|
|
1489
|
+
redacted = redacted.split(secret).join(replacement);
|
|
989
1490
|
}
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
1491
|
+
let maximumSecretLength = 0;
|
|
1492
|
+
for (const secret of secrets) {
|
|
1493
|
+
maximumSecretLength = Math.max(maximumSecretLength, secret.length);
|
|
993
1494
|
}
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
return new Uint8Array(content);
|
|
1495
|
+
if (mayStartAtTailBoundary && maximumSecretLength > 0 && redacted.length > 0) {
|
|
1496
|
+
redacted = redacted.slice(maximumSecretLength);
|
|
997
1497
|
}
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1498
|
+
return boundDetachedProcessLog(redacted);
|
|
1499
|
+
}
|
|
1500
|
+
async function readServerFailureDiagnostics(sandbox, command, environment, signal) {
|
|
1501
|
+
if (!sandbox.readSessionLogs) return "";
|
|
1502
|
+
try {
|
|
1503
|
+
const captured = await awaitDiagnosticRead(
|
|
1504
|
+
() => sandbox.readSessionLogs(command),
|
|
1505
|
+
signal
|
|
1004
1506
|
);
|
|
1005
|
-
const
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
return
|
|
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));
|
|
1507
|
+
const secrets = Object.entries(environment).filter(
|
|
1508
|
+
(entry) => Boolean(entry[1]) && isConfiguredDiagnosticSecret(entry[0], entry[1])
|
|
1509
|
+
).map(([, value]) => value);
|
|
1510
|
+
secrets.sort((left, right) => right.length - left.length);
|
|
1511
|
+
const stdout = redactServerFailureDiagnosticStream(captured.stdout, secrets);
|
|
1512
|
+
const stderr = redactServerFailureDiagnosticStream(captured.stderr, secrets);
|
|
1513
|
+
const parts = [];
|
|
1514
|
+
if (stdout.trim()) parts.push(`stdout:
|
|
1515
|
+
${stdout}`);
|
|
1516
|
+
if (stderr.trim()) parts.push(`stderr:
|
|
1517
|
+
${stderr}`);
|
|
1518
|
+
if (parts.length === 0) return "";
|
|
1519
|
+
return boundDetachedProcessLog(`
|
|
1520
|
+
--- server logs ---
|
|
1521
|
+
${parts.join("\n\n")}`);
|
|
1522
|
+
} catch {
|
|
1523
|
+
throwIfAborted(signal);
|
|
1524
|
+
return "";
|
|
1044
1525
|
}
|
|
1045
|
-
}
|
|
1526
|
+
}
|
|
1046
1527
|
function providerApiKey(provider, explicitApiKey) {
|
|
1047
1528
|
if (explicitApiKey) return explicitApiKey;
|
|
1048
1529
|
return requireEnv(provider === "e2b" ? "E2B_API_KEY" : "DAYTONA_API_KEY");
|
|
@@ -1059,11 +1540,23 @@ async function createProviderSandboxHandle(options) {
|
|
|
1059
1540
|
...options.networkAllowList === void 0 ? {} : { networkAllowList: options.networkAllowList },
|
|
1060
1541
|
...options.domainAllowList === void 0 ? {} : { domainAllowList: options.domainAllowList },
|
|
1061
1542
|
envVars: filterDefinedEnvs(options.envs ?? {}),
|
|
1543
|
+
autoStopInterval: options.autoStopInterval,
|
|
1062
1544
|
autoDeleteInterval: options.autoDeleteInterval ?? -1
|
|
1063
1545
|
},
|
|
1064
1546
|
{ timeout: options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC }
|
|
1065
1547
|
);
|
|
1066
|
-
|
|
1548
|
+
try {
|
|
1549
|
+
return await DaytonaSandboxHandle.create(
|
|
1550
|
+
sandbox2,
|
|
1551
|
+
(message) => new DeploymentError(message)
|
|
1552
|
+
);
|
|
1553
|
+
} catch (error) {
|
|
1554
|
+
await sandbox2.delete(
|
|
1555
|
+
options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC,
|
|
1556
|
+
true
|
|
1557
|
+
).catch(() => void 0);
|
|
1558
|
+
throw error;
|
|
1559
|
+
}
|
|
1067
1560
|
}
|
|
1068
1561
|
const apiKey = providerApiKey("e2b", options.apiKey);
|
|
1069
1562
|
const { Sandbox } = await getE2b();
|
|
@@ -1075,7 +1568,7 @@ async function createProviderSandboxHandle(options) {
|
|
|
1075
1568
|
network: options.allowPublicTraffic === void 0 ? void 0 : { allowPublicTraffic: options.allowPublicTraffic }
|
|
1076
1569
|
};
|
|
1077
1570
|
const sandbox = options.template ? await Sandbox.create(options.template, sandboxOptions) : await Sandbox.create(sandboxOptions);
|
|
1078
|
-
return new E2bSandboxHandle(sandbox);
|
|
1571
|
+
return new E2bSandboxHandle(sandbox, (message) => new DeploymentError(message));
|
|
1079
1572
|
}
|
|
1080
1573
|
async function connectProviderSandboxHandle(options) {
|
|
1081
1574
|
if (options.provider === "daytona") {
|
|
@@ -1090,7 +1583,7 @@ async function connectProviderSandboxHandle(options) {
|
|
|
1090
1583
|
await sandbox2.start(options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC);
|
|
1091
1584
|
}
|
|
1092
1585
|
}
|
|
1093
|
-
return DaytonaSandboxHandle.create(sandbox2);
|
|
1586
|
+
return DaytonaSandboxHandle.create(sandbox2, (message) => new DeploymentError(message));
|
|
1094
1587
|
}
|
|
1095
1588
|
const apiKey = providerApiKey("e2b", options.apiKey);
|
|
1096
1589
|
const { Sandbox } = await getE2b();
|
|
@@ -1099,7 +1592,7 @@ async function connectProviderSandboxHandle(options) {
|
|
|
1099
1592
|
timeoutMs: options.timeoutMs,
|
|
1100
1593
|
requestTimeoutMs: options.requestTimeoutMs
|
|
1101
1594
|
});
|
|
1102
|
-
return new E2bSandboxHandle(sandbox);
|
|
1595
|
+
return new E2bSandboxHandle(sandbox, (message) => new DeploymentError(message));
|
|
1103
1596
|
}
|
|
1104
1597
|
var SandboxClient = class _SandboxClient {
|
|
1105
1598
|
constructor(handle) {
|
|
@@ -1143,6 +1636,61 @@ var SandboxClient = class _SandboxClient {
|
|
|
1143
1636
|
async runCommand(command, options) {
|
|
1144
1637
|
return this.handle.runCommand(command, options);
|
|
1145
1638
|
}
|
|
1639
|
+
async startDetachedCommand(command, options = {}) {
|
|
1640
|
+
if (!this.handle.startDetachedCommand) {
|
|
1641
|
+
throw new ConfigurationError(
|
|
1642
|
+
`Sandbox provider "${this.provider}" does not support startDetachedCommand().`
|
|
1643
|
+
);
|
|
1644
|
+
}
|
|
1645
|
+
if (typeof command !== "string") {
|
|
1646
|
+
throw new ConfigurationError("Detached command must be a string.");
|
|
1647
|
+
}
|
|
1648
|
+
const normalized = normalizeProviderSandboxDetachedCommandOptions(
|
|
1649
|
+
options,
|
|
1650
|
+
(message) => new ConfigurationError(message),
|
|
1651
|
+
{ requireObject: true }
|
|
1652
|
+
);
|
|
1653
|
+
return this.handle.startDetachedCommand(command, normalized.options);
|
|
1654
|
+
}
|
|
1655
|
+
async readSessionLogs(commandOrSessionId, legacyCommandId) {
|
|
1656
|
+
if (!this.handle.readSessionLogs) {
|
|
1657
|
+
throw new ConfigurationError(
|
|
1658
|
+
`Sandbox provider "${this.provider}" does not support readSessionLogs().`
|
|
1659
|
+
);
|
|
1660
|
+
}
|
|
1661
|
+
if (typeof commandOrSessionId === "string" && legacyCommandId === void 0) {
|
|
1662
|
+
throw new ConfigurationError(
|
|
1663
|
+
"Legacy detached session log reads require a command ID."
|
|
1664
|
+
);
|
|
1665
|
+
}
|
|
1666
|
+
const command = typeof commandOrSessionId === "string" ? { sessionId: commandOrSessionId, commandId: legacyCommandId } : normalizeDetachedCommandHandle(commandOrSessionId);
|
|
1667
|
+
return this.handle.readSessionLogs(command);
|
|
1668
|
+
}
|
|
1669
|
+
async stopSession(commandOrSessionId) {
|
|
1670
|
+
if (!this.handle.stopSession) {
|
|
1671
|
+
throw new ConfigurationError(
|
|
1672
|
+
`Sandbox provider "${this.provider}" does not support stopSession().`
|
|
1673
|
+
);
|
|
1674
|
+
}
|
|
1675
|
+
const command = typeof commandOrSessionId === "string" ? { sessionId: commandOrSessionId } : normalizeDetachedCommandHandle(commandOrSessionId);
|
|
1676
|
+
await this.handle.stopSession(command);
|
|
1677
|
+
}
|
|
1678
|
+
/**
|
|
1679
|
+
* Irreversibly removes private lifecycle state and captured diagnostics for
|
|
1680
|
+
* one managed detached command. Call `stopSession()` first, then perform any
|
|
1681
|
+
* final `readSessionLogs()` before disposal. Disposal is idempotent after a
|
|
1682
|
+
* confirmed stop but is not itself evidence that the process stopped.
|
|
1683
|
+
*/
|
|
1684
|
+
async disposeSessionArtifacts(command) {
|
|
1685
|
+
if (!this.handle.disposeSessionArtifacts) {
|
|
1686
|
+
throw new ConfigurationError(
|
|
1687
|
+
`Sandbox provider "${this.provider}" does not support disposeSessionArtifacts().`
|
|
1688
|
+
);
|
|
1689
|
+
}
|
|
1690
|
+
await this.handle.disposeSessionArtifacts(
|
|
1691
|
+
normalizeDetachedCommandHandle(command)
|
|
1692
|
+
);
|
|
1693
|
+
}
|
|
1146
1694
|
async setTimeout(timeoutMs) {
|
|
1147
1695
|
if (!this.handle.setTimeout) {
|
|
1148
1696
|
throw new ConfigurationError(`Sandbox provider "${this.provider}" does not support setTimeout().`);
|
|
@@ -1170,17 +1718,26 @@ function normalizeStackFramePath(rawPath, cwd = process.cwd()) {
|
|
|
1170
1718
|
}
|
|
1171
1719
|
function getCallerFile() {
|
|
1172
1720
|
const stack = new Error().stack?.split("\n") ?? [];
|
|
1173
|
-
|
|
1721
|
+
let moduleFile;
|
|
1722
|
+
let bundledFallback;
|
|
1723
|
+
for (const line of stack.slice(1)) {
|
|
1174
1724
|
const match = line.match(/\((.+?):\d+:\d+\)/) || line.match(/at (.+?):\d+:\d+/);
|
|
1175
1725
|
if (!match) continue;
|
|
1176
1726
|
const file = normalizeStackFramePath(match[1]);
|
|
1177
1727
|
if (!file) continue;
|
|
1728
|
+
if (!moduleFile) {
|
|
1729
|
+
moduleFile = file;
|
|
1730
|
+
continue;
|
|
1731
|
+
}
|
|
1178
1732
|
if (file.includes("node:")) continue;
|
|
1179
1733
|
if (file.includes("node_modules/agent-neckbeard")) continue;
|
|
1180
|
-
if (file
|
|
1181
|
-
|
|
1734
|
+
if (file === moduleFile) {
|
|
1735
|
+
bundledFallback ??= file;
|
|
1736
|
+
continue;
|
|
1737
|
+
}
|
|
1182
1738
|
return file;
|
|
1183
1739
|
}
|
|
1740
|
+
if (bundledFallback) return bundledFallback;
|
|
1184
1741
|
throw new Error("Could not determine source file");
|
|
1185
1742
|
}
|
|
1186
1743
|
function isFrameworkBuildOutputPath(file) {
|
|
@@ -1344,10 +1901,13 @@ var Agent = class {
|
|
|
1344
1901
|
provider;
|
|
1345
1902
|
template;
|
|
1346
1903
|
inputSchema;
|
|
1347
|
-
/** Only populated for
|
|
1904
|
+
/** Only populated for structured-task agents; undefined for session agents. */
|
|
1348
1905
|
outputSchema;
|
|
1349
|
-
/** Only populated for
|
|
1906
|
+
/** Only populated for attached-session agents; undefined for run-output agents. */
|
|
1350
1907
|
frameSchema;
|
|
1908
|
+
/** User-facing execution shape. */
|
|
1909
|
+
kind;
|
|
1910
|
+
/** @deprecated Use `kind`; retained for compatibility with `run | stream` checks. */
|
|
1351
1911
|
mode;
|
|
1352
1912
|
maxDuration;
|
|
1353
1913
|
dependencies;
|
|
@@ -1359,7 +1919,7 @@ var Agent = class {
|
|
|
1359
1919
|
build;
|
|
1360
1920
|
/** @internal Used by the in-sandbox server for run-output agents. */
|
|
1361
1921
|
_run;
|
|
1362
|
-
/** @internal Used by the in-sandbox server for
|
|
1922
|
+
/** @internal Used by the in-sandbox server for attached-session agents. */
|
|
1363
1923
|
_server;
|
|
1364
1924
|
/** @internal Runtime state populated by deploy(). */
|
|
1365
1925
|
_serverRuntime;
|
|
@@ -1379,11 +1939,14 @@ var Agent = class {
|
|
|
1379
1939
|
this.claudeDir = config.claudeDir;
|
|
1380
1940
|
this.envs = config.envs ?? {};
|
|
1381
1941
|
this.build = config.build ?? {};
|
|
1382
|
-
if (
|
|
1942
|
+
if (isSessionAgentConfig(config)) {
|
|
1943
|
+
const session = getSessionHandler(config);
|
|
1944
|
+
this.kind = "session";
|
|
1383
1945
|
this.mode = "stream";
|
|
1384
|
-
this._server =
|
|
1385
|
-
this.frameSchema =
|
|
1946
|
+
this._server = session;
|
|
1947
|
+
this.frameSchema = session.frameSchema;
|
|
1386
1948
|
} else {
|
|
1949
|
+
this.kind = "task";
|
|
1387
1950
|
this.mode = "run";
|
|
1388
1951
|
this._run = config.run;
|
|
1389
1952
|
this.outputSchema = config.outputSchema;
|
|
@@ -1468,47 +2031,68 @@ var Agent = class {
|
|
|
1468
2031
|
envs: this.sandboxEnv
|
|
1469
2032
|
});
|
|
1470
2033
|
}
|
|
1471
|
-
async resolveRuntimeConnection(sandboxId) {
|
|
2034
|
+
async resolveRuntimeConnection(sandboxId, options = {}) {
|
|
2035
|
+
const { signal } = options;
|
|
2036
|
+
throwIfAborted(signal);
|
|
1472
2037
|
const targetId = sandboxId ?? this._serverRuntime?.connection.sandboxId ?? this._sandboxId;
|
|
1473
2038
|
if (!targetId) {
|
|
1474
2039
|
throw new ConfigurationError("Agent not deployed. Call agent.deploy() first or pass sandboxId.");
|
|
1475
2040
|
}
|
|
1476
|
-
if (!sandboxId && this._serverRuntime?.connection.sandboxId === targetId) {
|
|
2041
|
+
if ((!sandboxId || options.reuseMatchingCachedConnection) && this._serverRuntime?.connection.sandboxId === targetId) {
|
|
1477
2042
|
return this._serverRuntime.connection;
|
|
1478
2043
|
}
|
|
1479
|
-
const sandbox = await this.connectSandboxHandle(targetId);
|
|
1480
|
-
|
|
2044
|
+
const sandbox = await awaitWithAbort(() => this.connectSandboxHandle(targetId), signal);
|
|
2045
|
+
if (sandbox.id !== targetId) {
|
|
2046
|
+
throw new DeploymentError("Sandbox provider returned an unexpected runtime identity.");
|
|
2047
|
+
}
|
|
2048
|
+
const serverConfig = await awaitWithAbort(
|
|
2049
|
+
() => this.readRuntimeServerConfig(sandbox),
|
|
2050
|
+
signal
|
|
2051
|
+
);
|
|
1481
2052
|
const port = serverConfig?.port ?? this._server?.port ?? DEFAULT_SERVER_PORT;
|
|
1482
|
-
const connection = await
|
|
2053
|
+
const connection = await awaitWithAbort(
|
|
2054
|
+
() => this.createRuntimeConnection(sandbox, port),
|
|
2055
|
+
signal
|
|
2056
|
+
);
|
|
1483
2057
|
const healthUrl = this.healthUrlFor(connection);
|
|
1484
2058
|
try {
|
|
1485
|
-
await waitForServerHealthy(
|
|
1486
|
-
|
|
2059
|
+
await waitForServerHealthy(
|
|
2060
|
+
healthUrl,
|
|
2061
|
+
connection,
|
|
2062
|
+
SERVER_RECONNECT_HEALTH_TIMEOUT_MS,
|
|
2063
|
+
signal
|
|
2064
|
+
);
|
|
2065
|
+
throwIfAborted(signal);
|
|
2066
|
+
const cachedRuntime = this._serverRuntime;
|
|
2067
|
+
this._serverRuntime = cachedRuntime?.connection.sandboxId === targetId ? { ...cachedRuntime, connection } : { connection };
|
|
1487
2068
|
this._sandboxId = targetId;
|
|
1488
2069
|
return connection;
|
|
1489
2070
|
} catch {
|
|
1490
|
-
|
|
2071
|
+
throwIfAborted(signal);
|
|
2072
|
+
const detachedCommand = await awaitWithAbort(
|
|
2073
|
+
() => this.startRuntimeServer(sandbox),
|
|
2074
|
+
signal
|
|
2075
|
+
);
|
|
1491
2076
|
try {
|
|
1492
|
-
await waitForServerHealthy(
|
|
2077
|
+
await waitForServerHealthy(
|
|
2078
|
+
healthUrl,
|
|
2079
|
+
connection,
|
|
2080
|
+
SERVER_HEALTH_TIMEOUT_MS,
|
|
2081
|
+
signal
|
|
2082
|
+
);
|
|
1493
2083
|
} catch (error) {
|
|
2084
|
+
throwIfAborted(signal);
|
|
1494
2085
|
const baseMessage = error instanceof Error ? error.message : String(error);
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
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
|
-
}
|
|
2086
|
+
const logs = await readServerFailureDiagnostics(
|
|
2087
|
+
sandbox,
|
|
2088
|
+
detachedCommand,
|
|
2089
|
+
this.envs,
|
|
2090
|
+
signal
|
|
2091
|
+
);
|
|
1509
2092
|
throw new DeploymentError(`${baseMessage}${logs}`);
|
|
1510
2093
|
}
|
|
1511
|
-
|
|
2094
|
+
throwIfAborted(signal);
|
|
2095
|
+
this._serverRuntime = { detachedCommand, connection };
|
|
1512
2096
|
this._sandboxId = targetId;
|
|
1513
2097
|
return connection;
|
|
1514
2098
|
}
|
|
@@ -1533,8 +2117,8 @@ ${parts.join("\n\n")}`;
|
|
|
1533
2117
|
if (!targetId) return;
|
|
1534
2118
|
try {
|
|
1535
2119
|
const sandbox = await this.connectSandboxHandle(targetId);
|
|
1536
|
-
if (this._serverRuntime && this._serverRuntime.connection.sandboxId === targetId && this._serverRuntime.
|
|
1537
|
-
await sandbox.stopSession(this._serverRuntime.
|
|
2120
|
+
if (this._serverRuntime && this._serverRuntime.connection.sandboxId === targetId && this._serverRuntime.detachedCommand && sandbox.stopSession) {
|
|
2121
|
+
await sandbox.stopSession(this._serverRuntime.detachedCommand).catch(() => void 0);
|
|
1538
2122
|
}
|
|
1539
2123
|
await sandbox.destroy();
|
|
1540
2124
|
} catch {
|
|
@@ -1624,9 +2208,15 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
1624
2208
|
this.outputSchema = config.outputSchema;
|
|
1625
2209
|
this.maxDuration = config.maxDuration ?? 300;
|
|
1626
2210
|
this._run = config.run;
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
this.
|
|
2211
|
+
const session = config.session ?? config.server;
|
|
2212
|
+
if (session) {
|
|
2213
|
+
this.kind = 'session';
|
|
2214
|
+
this.mode = 'stream';
|
|
2215
|
+
this._server = session;
|
|
2216
|
+
this.frameSchema = session.frameSchema;
|
|
2217
|
+
} else {
|
|
2218
|
+
this.kind = 'task';
|
|
2219
|
+
this.mode = 'run';
|
|
1630
2220
|
}
|
|
1631
2221
|
}
|
|
1632
2222
|
}
|
|
@@ -1658,142 +2248,145 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
1658
2248
|
}]
|
|
1659
2249
|
});
|
|
1660
2250
|
const sandbox = await this.createSandboxHandle();
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
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
|
|
2251
|
+
let deploymentCompleted = false;
|
|
2252
|
+
let detachedCommand;
|
|
2253
|
+
try {
|
|
2254
|
+
const { paths } = sandbox;
|
|
2255
|
+
await sandbox.runCommand(`mkdir -p ${shellQuote(paths.agentDir)}`, {
|
|
2256
|
+
timeoutMs: QUICK_COMMAND_TIMEOUT_MS2
|
|
1670
2257
|
});
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
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
|
|
2258
|
+
const { apt, commands } = this.dependencies;
|
|
2259
|
+
if (apt && apt.length > 0) {
|
|
2260
|
+
const aptCmd = `sudo apt-get update && sudo apt-get install -y ${apt.join(" ")}`;
|
|
2261
|
+
const aptResult = await sandbox.runCommand(aptCmd, {
|
|
2262
|
+
timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS2
|
|
1684
2263
|
});
|
|
1685
|
-
if (
|
|
2264
|
+
if (aptResult.exitCode !== 0) {
|
|
1686
2265
|
const details = [
|
|
1687
|
-
`Failed to
|
|
1688
|
-
|
|
1689
|
-
|
|
2266
|
+
`Failed to install apt packages: ${apt.join(", ")}`,
|
|
2267
|
+
aptResult.stderr ? `stderr: ${aptResult.stderr}` : "",
|
|
2268
|
+
aptResult.stdout ? `stdout: ${aptResult.stdout}` : ""
|
|
1690
2269
|
].filter(Boolean).join("\n");
|
|
1691
2270
|
throw new DeploymentError(details);
|
|
1692
2271
|
}
|
|
1693
2272
|
}
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
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
|
|
2273
|
+
if (commands && commands.length > 0) {
|
|
2274
|
+
for (const cmd of commands) {
|
|
2275
|
+
const cmdResult = await sandbox.runCommand(cmd, {
|
|
2276
|
+
timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS2
|
|
1702
2277
|
});
|
|
2278
|
+
if (cmdResult.exitCode !== 0) {
|
|
2279
|
+
const details = [
|
|
2280
|
+
`Failed to run command: ${cmd}`,
|
|
2281
|
+
cmdResult.stderr ? `stderr: ${cmdResult.stderr}` : "",
|
|
2282
|
+
cmdResult.stdout ? `stdout: ${cmdResult.stdout}` : ""
|
|
2283
|
+
].filter(Boolean).join("\n");
|
|
2284
|
+
throw new DeploymentError(details);
|
|
2285
|
+
}
|
|
1703
2286
|
}
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
`
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
2287
|
+
}
|
|
2288
|
+
if (this.files.length > 0) {
|
|
2289
|
+
for (const file of this.files) {
|
|
2290
|
+
const destPath = file.path.startsWith("/") ? file.path : `${paths.homeDir}/${file.path}`;
|
|
2291
|
+
const parentDir = destPath.substring(0, destPath.lastIndexOf("/"));
|
|
2292
|
+
if (parentDir) {
|
|
2293
|
+
await sandbox.runCommand(`mkdir -p ${shellQuote(parentDir)}`, {
|
|
2294
|
+
timeoutMs: QUICK_COMMAND_TIMEOUT_MS2
|
|
2295
|
+
});
|
|
2296
|
+
}
|
|
2297
|
+
const curlCmd = `curl -fsSL -o ${shellQuote(destPath)} ${shellQuote(file.url)}`;
|
|
2298
|
+
const downloadResult = await sandbox.runCommand(curlCmd, {
|
|
2299
|
+
timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS2
|
|
2300
|
+
});
|
|
2301
|
+
if (downloadResult.exitCode !== 0) {
|
|
2302
|
+
const details = [
|
|
2303
|
+
`Failed to download file from ${file.url} to ${destPath}`,
|
|
2304
|
+
downloadResult.stderr ? `stderr: ${downloadResult.stderr}` : "",
|
|
2305
|
+
downloadResult.stdout ? `stdout: ${downloadResult.stdout}` : ""
|
|
2306
|
+
].filter(Boolean).join("\n");
|
|
2307
|
+
throw new DeploymentError(details);
|
|
2308
|
+
}
|
|
1715
2309
|
}
|
|
1716
2310
|
}
|
|
1717
|
-
|
|
1718
|
-
|
|
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
|
|
2311
|
+
for (const directory of localDirectoryUploads.directories) {
|
|
2312
|
+
await sandbox.makeDir(posix.join(paths.agentDir, directory));
|
|
1741
2313
|
}
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
2314
|
+
for (const file of localDirectoryUploads.files) {
|
|
2315
|
+
await sandbox.writeFile(
|
|
2316
|
+
posix.join(paths.agentDir, file.targetPath),
|
|
2317
|
+
file.content
|
|
2318
|
+
);
|
|
2319
|
+
}
|
|
2320
|
+
await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
|
|
2321
|
+
await sandbox.writeFile(paths.serverModule, RUNTIME_SERVER_SOURCE);
|
|
2322
|
+
const serverConfig = {
|
|
2323
|
+
protocolVersion: RUNTIME_PROTOCOL_VERSION,
|
|
2324
|
+
port: this._server?.port ?? DEFAULT_SERVER_PORT,
|
|
2325
|
+
maxDurationMs: this.maxDuration * 1e3,
|
|
2326
|
+
sandboxContext: {
|
|
2327
|
+
provider: paths.provider,
|
|
2328
|
+
homeDir: paths.homeDir,
|
|
2329
|
+
workDir: paths.workDir,
|
|
2330
|
+
agentDir: paths.agentDir,
|
|
2331
|
+
ioDir: paths.ioDir,
|
|
2332
|
+
inputJson: paths.inputJson,
|
|
2333
|
+
outputJson: paths.outputJson
|
|
2334
|
+
}
|
|
2335
|
+
};
|
|
2336
|
+
await sandbox.writeFile(paths.serverConfig, JSON.stringify(serverConfig));
|
|
2337
|
+
if (collectedExternals.size > 0) {
|
|
2338
|
+
const installable = Array.from(collectedExternals.values()).filter(isPackageCompatible);
|
|
2339
|
+
const dependencies = Object.fromEntries(installable.map((info) => [info.name, info.version]));
|
|
2340
|
+
if (Object.keys(dependencies).length > 0) {
|
|
2341
|
+
const pkgJson = JSON.stringify({
|
|
2342
|
+
name: "agent-sandbox",
|
|
2343
|
+
type: "module",
|
|
2344
|
+
dependencies
|
|
2345
|
+
});
|
|
2346
|
+
await sandbox.writeFile(paths.packageJson, pkgJson);
|
|
2347
|
+
const installResult = await sandbox.runCommand("npm install --legacy-peer-deps", {
|
|
2348
|
+
cwd: paths.agentDir,
|
|
2349
|
+
timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS2
|
|
2350
|
+
});
|
|
2351
|
+
if (installResult.exitCode !== 0) {
|
|
2352
|
+
const details = [
|
|
2353
|
+
`Failed to install npm packages: ${Object.keys(dependencies).join(", ")}`,
|
|
2354
|
+
installResult.stderr ? `stderr: ${installResult.stderr}` : "",
|
|
2355
|
+
installResult.stdout ? `stdout: ${installResult.stdout}` : ""
|
|
2356
|
+
].filter(Boolean).join("\n");
|
|
2357
|
+
throw new DeploymentError(details);
|
|
2358
|
+
}
|
|
1765
2359
|
}
|
|
1766
2360
|
}
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
2361
|
+
const port = serverConfig.port;
|
|
2362
|
+
detachedCommand = await this.startRuntimeServer(sandbox);
|
|
2363
|
+
const connection = await this.createRuntimeConnection(sandbox, port);
|
|
2364
|
+
const healthUrl = this.healthUrlFor(connection);
|
|
2365
|
+
try {
|
|
2366
|
+
await waitForServerHealthy(healthUrl, connection);
|
|
2367
|
+
} catch (err) {
|
|
2368
|
+
const baseMessage = err instanceof Error ? err.message : String(err);
|
|
2369
|
+
const logs = await readServerFailureDiagnostics(
|
|
2370
|
+
sandbox,
|
|
2371
|
+
detachedCommand,
|
|
2372
|
+
this.envs
|
|
2373
|
+
);
|
|
2374
|
+
throw new DeploymentError(`${baseMessage}${logs}`);
|
|
2375
|
+
}
|
|
2376
|
+
if (!options?.fresh) {
|
|
2377
|
+
this._sandboxId = sandbox.id;
|
|
2378
|
+
this._serverRuntime = { detachedCommand, connection };
|
|
2379
|
+
}
|
|
2380
|
+
deploymentCompleted = true;
|
|
2381
|
+
return sandbox.id;
|
|
2382
|
+
} finally {
|
|
2383
|
+
if (!deploymentCompleted) {
|
|
2384
|
+
if (detachedCommand && sandbox.stopSession) {
|
|
2385
|
+
await sandbox.stopSession(detachedCommand).catch(() => void 0);
|
|
1788
2386
|
}
|
|
2387
|
+
await sandbox.destroy().catch(() => void 0);
|
|
1789
2388
|
}
|
|
1790
|
-
throw new DeploymentError(`${baseMessage}${logs}`);
|
|
1791
|
-
}
|
|
1792
|
-
if (!options?.fresh) {
|
|
1793
|
-
this._sandboxId = sandbox.id;
|
|
1794
|
-
this._serverRuntime = { sessionId, commandId, connection };
|
|
1795
2389
|
}
|
|
1796
|
-
return sandbox.id;
|
|
1797
2390
|
}
|
|
1798
2391
|
/**
|
|
1799
2392
|
* Executes the agent with the given input.
|
|
@@ -1824,7 +2417,7 @@ ${parts.join("\n\n")}`;
|
|
|
1824
2417
|
ok: false,
|
|
1825
2418
|
executionId,
|
|
1826
2419
|
error: new ExecutionError(
|
|
1827
|
-
"run() is only available on agents configured with a run handler. Use agent.
|
|
2420
|
+
"run() is only available on agents configured with a run handler. Use agent.createSession() for streaming session agents."
|
|
1828
2421
|
)
|
|
1829
2422
|
};
|
|
1830
2423
|
}
|
|
@@ -1836,7 +2429,7 @@ ${parts.join("\n\n")}`;
|
|
|
1836
2429
|
} catch (error) {
|
|
1837
2430
|
throw new ValidationError("Input validation failed.", asError(error));
|
|
1838
2431
|
}
|
|
1839
|
-
const { invokeServer } = await import("./invoke-client-
|
|
2432
|
+
const { invokeServer } = await import("./invoke-client-D5TMTOYM.js");
|
|
1840
2433
|
let output;
|
|
1841
2434
|
let sawOutput = false;
|
|
1842
2435
|
for await (const event of invokeServer(validatedInput, {
|
|
@@ -1875,17 +2468,74 @@ ${parts.join("\n\n")}`;
|
|
|
1875
2468
|
}
|
|
1876
2469
|
}
|
|
1877
2470
|
/**
|
|
1878
|
-
*
|
|
1879
|
-
*
|
|
2471
|
+
* Creates a caller-owned session against the persistent sandbox runtime.
|
|
2472
|
+
* The returned handle supports sequential prompts, active-turn cancellation,
|
|
2473
|
+
* and explicit close without destroying the reusable sandbox.
|
|
1880
2474
|
*/
|
|
1881
|
-
async
|
|
2475
|
+
async createSession(options = {}) {
|
|
1882
2476
|
if (this.mode !== "stream") {
|
|
1883
2477
|
throw new ConfigurationError(
|
|
1884
|
-
"
|
|
2478
|
+
"createSession() is only available on agents configured with session.handler (or deprecated server.handler). Use agent.run() for run-output agents."
|
|
2479
|
+
);
|
|
2480
|
+
}
|
|
2481
|
+
if (!options || typeof options !== "object") {
|
|
2482
|
+
throw new ConfigurationError("Agent.createSession() options must be an object.");
|
|
2483
|
+
}
|
|
2484
|
+
let optionsAreArray;
|
|
2485
|
+
try {
|
|
2486
|
+
optionsAreArray = Array.isArray(options);
|
|
2487
|
+
} catch {
|
|
2488
|
+
throw new ConfigurationError(
|
|
2489
|
+
"Agent.createSession() options must have readable values."
|
|
2490
|
+
);
|
|
2491
|
+
}
|
|
2492
|
+
if (optionsAreArray) {
|
|
2493
|
+
throw new ConfigurationError("Agent.createSession() options must be an object.");
|
|
2494
|
+
}
|
|
2495
|
+
let durability;
|
|
2496
|
+
let requestedSandboxId;
|
|
2497
|
+
let signal;
|
|
2498
|
+
try {
|
|
2499
|
+
durability = options.durability;
|
|
2500
|
+
requestedSandboxId = options.sandboxId;
|
|
2501
|
+
signal = options.signal;
|
|
2502
|
+
} catch {
|
|
2503
|
+
throw new ConfigurationError(
|
|
2504
|
+
"Agent.createSession() options must have readable values."
|
|
2505
|
+
);
|
|
2506
|
+
}
|
|
2507
|
+
if (durability !== void 0 && durability !== "attached") {
|
|
2508
|
+
throw new ConfigurationError(
|
|
2509
|
+
"Agent.createSession() creates caller-owned attached sessions. Use agent-neckbeard/supervisor durable-session APIs for gateway-owned sessions."
|
|
2510
|
+
);
|
|
2511
|
+
}
|
|
2512
|
+
if (requestedSandboxId !== void 0 && (typeof requestedSandboxId !== "string" || requestedSandboxId.trim() === "")) {
|
|
2513
|
+
throw new ConfigurationError(
|
|
2514
|
+
"Agent.createSession() sandboxId must be a non-empty string when provided."
|
|
2515
|
+
);
|
|
2516
|
+
}
|
|
2517
|
+
if (signal !== void 0 && !isAbortSignal(signal)) {
|
|
2518
|
+
throw new ConfigurationError(
|
|
2519
|
+
"Agent.createSession() signal must be an AbortSignal when provided."
|
|
1885
2520
|
);
|
|
1886
2521
|
}
|
|
1887
|
-
const
|
|
1888
|
-
|
|
2522
|
+
const sandboxId = requestedSandboxId ?? this._serverRuntime?.connection.sandboxId ?? this._sandboxId;
|
|
2523
|
+
if (!sandboxId) {
|
|
2524
|
+
throw new ConfigurationError("Agent not deployed. Call agent.deploy() first or pass sandboxId.");
|
|
2525
|
+
}
|
|
2526
|
+
return createAttachedAgentSession({
|
|
2527
|
+
sandboxId,
|
|
2528
|
+
runPrompt: (input, signal2) => this.streamSessionPrompt(input, sandboxId, signal2),
|
|
2529
|
+
...signal === void 0 ? {} : { externalSignal: signal },
|
|
2530
|
+
configurationError: (message) => new ConfigurationError(message)
|
|
2531
|
+
});
|
|
2532
|
+
}
|
|
2533
|
+
async *streamSessionPrompt(input, sandboxId, signal) {
|
|
2534
|
+
const connection = await this.resolveRuntimeConnection(sandboxId, {
|
|
2535
|
+
signal,
|
|
2536
|
+
reuseMatchingCachedConnection: true
|
|
2537
|
+
});
|
|
2538
|
+
const { invokeServer } = await import("./invoke-client-D5TMTOYM.js");
|
|
1889
2539
|
let validated;
|
|
1890
2540
|
try {
|
|
1891
2541
|
validated = this.inputSchema.parse(input);
|
|
@@ -1898,7 +2548,7 @@ ${parts.join("\n\n")}`;
|
|
|
1898
2548
|
provider: connection.provider,
|
|
1899
2549
|
trafficToken: getTrafficToken(connection),
|
|
1900
2550
|
frameSchema: this.frameSchema,
|
|
1901
|
-
signal
|
|
2551
|
+
signal
|
|
1902
2552
|
})) {
|
|
1903
2553
|
if (frame.kind === "frame") {
|
|
1904
2554
|
yield frame.data;
|
|
@@ -1913,6 +2563,22 @@ ${parts.join("\n\n")}`;
|
|
|
1913
2563
|
throw error instanceof Error ? error : new Error(String(error));
|
|
1914
2564
|
}
|
|
1915
2565
|
}
|
|
2566
|
+
/**
|
|
2567
|
+
* @deprecated Use `createSession()` and call `session.prompt(input)` instead.
|
|
2568
|
+
* This compatibility wrapper creates one attached session, streams one turn,
|
|
2569
|
+
* and closes the local handle afterward.
|
|
2570
|
+
*/
|
|
2571
|
+
async *invoke(input, options) {
|
|
2572
|
+
const session = await this.createSession({
|
|
2573
|
+
...options?.sandboxId === void 0 ? {} : { sandboxId: options.sandboxId },
|
|
2574
|
+
...options?.signal === void 0 ? {} : { signal: options.signal }
|
|
2575
|
+
});
|
|
2576
|
+
try {
|
|
2577
|
+
yield* session.prompt(input);
|
|
2578
|
+
} finally {
|
|
2579
|
+
await session.close();
|
|
2580
|
+
}
|
|
2581
|
+
}
|
|
1916
2582
|
};
|
|
1917
2583
|
export {
|
|
1918
2584
|
Agent,
|