agent-neckbeard 1.1.26 → 1.1.28
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 +18 -0
- package/README.md +53 -459
- package/dist/build.cjs +5560 -0
- package/dist/build.d.cts +80 -0
- package/dist/build.d.ts +80 -0
- package/dist/build.js +17 -0
- package/dist/chunk-JF5YPOBY.js +4339 -0
- package/dist/chunk-KG6SJM74.js +97 -0
- package/dist/chunk-M3FISP7J.js +377 -0
- package/dist/chunk-M7XNBKG4.js +346 -0
- package/dist/cli.cjs +5606 -0
- package/dist/cli.d.cts +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +75 -0
- package/dist/index.cjs +1572 -149
- package/dist/index.d.cts +338 -6
- package/dist/index.d.ts +338 -6
- package/dist/index.js +36 -3272
- package/dist/{invoke-client-YKWOTQWG.js → invoke-client-P2CPBYTF.js} +2 -41
- package/dist/serve-Dan1HQKN.d.cts +89 -0
- package/dist/serve-Dan1HQKN.d.ts +89 -0
- package/dist/serve.cjs +337 -0
- package/dist/serve.d.cts +1 -0
- package/dist/serve.d.ts +1 -0
- package/dist/serve.js +8 -0
- package/docs/AGENT.md +173 -0
- package/docs/DAYTONA.md +56 -0
- package/docs/DOCKER.md +7 -7
- package/docs/E2B.md +11 -0
- package/docs/LEGACY.md +335 -0
- package/docs/MODAL.md +29 -13
- package/docs/SUPERVISOR.md +2 -2
- package/package.json +43 -3
- package/dist/chunk-6GCQOKYI.js +0 -48
|
@@ -0,0 +1,4339 @@
|
|
|
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-6P5I7ZCH.js";
|
|
19
|
+
import {
|
|
20
|
+
TURN_PROTOCOL_VERSION,
|
|
21
|
+
getPiTurnResult,
|
|
22
|
+
parseTurnHealth,
|
|
23
|
+
parseTurnRecord,
|
|
24
|
+
serve
|
|
25
|
+
} from "./chunk-M3FISP7J.js";
|
|
26
|
+
import {
|
|
27
|
+
IncompleteSseFrameError,
|
|
28
|
+
RUNTIME_ABORT_GRACE_MS,
|
|
29
|
+
RUNTIME_PROTOCOL_VERSION,
|
|
30
|
+
decodeSseStream
|
|
31
|
+
} from "./chunk-KG6SJM74.js";
|
|
32
|
+
|
|
33
|
+
// src/index.ts
|
|
34
|
+
import { fileURLToPath } from "url";
|
|
35
|
+
import {
|
|
36
|
+
existsSync,
|
|
37
|
+
lstatSync,
|
|
38
|
+
readdirSync,
|
|
39
|
+
readFileSync,
|
|
40
|
+
statSync,
|
|
41
|
+
writeFileSync
|
|
42
|
+
} from "fs";
|
|
43
|
+
import {
|
|
44
|
+
basename,
|
|
45
|
+
dirname,
|
|
46
|
+
isAbsolute,
|
|
47
|
+
join,
|
|
48
|
+
posix,
|
|
49
|
+
relative,
|
|
50
|
+
resolve,
|
|
51
|
+
sep,
|
|
52
|
+
win32
|
|
53
|
+
} from "path";
|
|
54
|
+
import { randomUUID } from "crypto";
|
|
55
|
+
import { builtinModules, createRequire as createRequire2 } from "module";
|
|
56
|
+
|
|
57
|
+
// src/runtime/server-source.generated.ts
|
|
58
|
+
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;\nvar RUNTIME_ABORT_GRACE_MS = 1e4;\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 getAbortGraceMs() {\n const raw = process.env.NECKBEARD_RUNTIME_ABORT_GRACE_MS;\n if (!raw) return RUNTIME_ABORT_GRACE_MS;\n const parsed = Number(raw);\n return Number.isFinite(parsed) && parsed >= 0 ? parsed : RUNTIME_ABORT_GRACE_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, signal) {\n if (res.destroyed) return;\n const canContinue = res.write(`data: ${JSON.stringify(event)}\n\n`);\n if (!canContinue && !signal.aborted) {\n await once(res, "drain", { signal }).catch(() => void 0);\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}\nfunction settleAfterAbort(task, signal, maxDurationMs) {\n return new Promise((resolve, reject) => {\n let aborted = false;\n const rejectAborted = () => reject(createTimeoutError(maxDurationMs));\n const onAbort = () => {\n aborted = true;\n const grace = setTimeout(rejectAborted, getAbortGraceMs());\n const stopped = () => {\n clearTimeout(grace);\n rejectAborted();\n };\n task.then(stopped, stopped);\n };\n if (signal.aborted) onAbort();\n else signal.addEventListener("abort", onAbort, { once: true });\n task.then(\n (value) => {\n if (aborted) return;\n signal.removeEventListener("abort", onAbort);\n resolve(value);\n },\n (error) => {\n if (aborted) return;\n signal.removeEventListener("abort", onAbort);\n reject(error);\n }\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 let activeInvocationId = null;\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 busy: activeInvocationId !== null\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 if (activeInvocationId !== null) {\n return sendJson(res, 409, {\n error: `invocation ${activeInvocationId} is still running`\n });\n }\n const invocationId = requestBody.invocationId;\n activeInvocationId = invocationId;\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 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 }, controller.signal);\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 let running;\n try {\n await emitHarnessEvent({ kind: "started", invocationId });\n const handler = agent._server ? () => 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 }) : agent._run ? () => agent._run(validatedInput, ctx) : () => {\n throw new Error("Agent has neither a run handler nor a server handler.");\n };\n if (controller.signal.aborted) throw createTimeoutError(CONFIG.maxDurationMs);\n running = Promise.resolve().then(handler);\n void running.catch(() => void 0).finally(() => {\n if (activeInvocationId === invocationId) activeInvocationId = null;\n });\n const output = await settleAfterAbort(running, controller.signal, CONFIG.maxDurationMs);\n if (agent._run && !agent._server) {\n const validatedOutput = agent.outputSchema ? agent.outputSchema.parse(output) : output;\n await emitHarnessEvent({ kind: "output", invocationId, output: validatedOutput });\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 (!running && activeInvocationId === invocationId) activeInvocationId = null;\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';
|
|
59
|
+
|
|
60
|
+
// src/attached-session.ts
|
|
61
|
+
function linkAbortSignals(signals) {
|
|
62
|
+
const controller = new AbortController();
|
|
63
|
+
const listeners = /* @__PURE__ */ new Map();
|
|
64
|
+
const abortFrom = (signal) => {
|
|
65
|
+
if (!controller.signal.aborted) controller.abort(signal.reason);
|
|
66
|
+
};
|
|
67
|
+
for (const signal of signals) {
|
|
68
|
+
if (signal.aborted) {
|
|
69
|
+
abortFrom(signal);
|
|
70
|
+
break;
|
|
71
|
+
}
|
|
72
|
+
const listener = () => abortFrom(signal);
|
|
73
|
+
listeners.set(signal, listener);
|
|
74
|
+
signal.addEventListener("abort", listener, { once: true });
|
|
75
|
+
}
|
|
76
|
+
return {
|
|
77
|
+
signal: controller.signal,
|
|
78
|
+
dispose: () => {
|
|
79
|
+
for (const [signal, listener] of listeners) {
|
|
80
|
+
signal.removeEventListener("abort", listener);
|
|
81
|
+
}
|
|
82
|
+
listeners.clear();
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
var AttachedAgentSessionImpl = class {
|
|
87
|
+
durability = "attached";
|
|
88
|
+
sandboxId;
|
|
89
|
+
lifetime = new AbortController();
|
|
90
|
+
runPrompt;
|
|
91
|
+
configurationError;
|
|
92
|
+
abortError;
|
|
93
|
+
activeTurn = null;
|
|
94
|
+
externalSignal = null;
|
|
95
|
+
externalAbortListener = null;
|
|
96
|
+
isClosed = false;
|
|
97
|
+
closePromise = null;
|
|
98
|
+
constructor(options) {
|
|
99
|
+
this.sandboxId = options.sandboxId;
|
|
100
|
+
this.runPrompt = options.runPrompt;
|
|
101
|
+
this.configurationError = options.configurationError;
|
|
102
|
+
this.abortError = options.abortError;
|
|
103
|
+
const { externalSignal } = options;
|
|
104
|
+
if (externalSignal?.aborted) {
|
|
105
|
+
this.isClosed = true;
|
|
106
|
+
this.lifetime.abort(externalSignal.reason);
|
|
107
|
+
} else if (externalSignal) {
|
|
108
|
+
this.externalSignal = externalSignal;
|
|
109
|
+
this.externalAbortListener = () => {
|
|
110
|
+
void this.closeWithReason(externalSignal.reason);
|
|
111
|
+
};
|
|
112
|
+
externalSignal.addEventListener("abort", this.externalAbortListener, { once: true });
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
get closed() {
|
|
116
|
+
return this.isClosed;
|
|
117
|
+
}
|
|
118
|
+
prompt(input) {
|
|
119
|
+
return this.runTurn(input);
|
|
120
|
+
}
|
|
121
|
+
async stop(reason = "attached_session_stopped") {
|
|
122
|
+
await this.stopActiveTurn(reason);
|
|
123
|
+
}
|
|
124
|
+
close() {
|
|
125
|
+
return this.closeWithReason("attached_session_closed");
|
|
126
|
+
}
|
|
127
|
+
async *runTurn(input) {
|
|
128
|
+
if (this.isClosed || this.lifetime.signal.aborted) {
|
|
129
|
+
throw this.configurationError("Attached session is closed.");
|
|
130
|
+
}
|
|
131
|
+
if (this.activeTurn) {
|
|
132
|
+
throw this.configurationError("Attached session already has an active turn.");
|
|
133
|
+
}
|
|
134
|
+
const controller = new AbortController();
|
|
135
|
+
const linked = linkAbortSignals([this.lifetime.signal, controller.signal]);
|
|
136
|
+
const iterator = this.runPrompt(input, linked.signal);
|
|
137
|
+
const turn = {
|
|
138
|
+
controller,
|
|
139
|
+
iterator,
|
|
140
|
+
dispose: linked.dispose
|
|
141
|
+
};
|
|
142
|
+
this.activeTurn = turn;
|
|
143
|
+
try {
|
|
144
|
+
while (true) {
|
|
145
|
+
const next = await iterator.next();
|
|
146
|
+
if (next.done) {
|
|
147
|
+
if (linked.signal.aborted) throw this.abortError(linked.signal);
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
yield next.value;
|
|
151
|
+
}
|
|
152
|
+
} finally {
|
|
153
|
+
controller.abort("attached_turn_closed");
|
|
154
|
+
await iterator.return(void 0).catch(() => void 0);
|
|
155
|
+
turn.dispose();
|
|
156
|
+
if (this.activeTurn === turn) this.activeTurn = null;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
async stopActiveTurn(reason) {
|
|
160
|
+
const turn = this.activeTurn;
|
|
161
|
+
if (!turn) return;
|
|
162
|
+
turn.controller.abort(reason);
|
|
163
|
+
await turn.iterator.return(void 0).catch(() => void 0);
|
|
164
|
+
turn.dispose();
|
|
165
|
+
if (this.activeTurn === turn) this.activeTurn = null;
|
|
166
|
+
}
|
|
167
|
+
closeWithReason(reason) {
|
|
168
|
+
if (this.closePromise) return this.closePromise;
|
|
169
|
+
this.closePromise = Promise.resolve().then(() => this.finishClose(reason));
|
|
170
|
+
this.isClosed = true;
|
|
171
|
+
this.lifetime.abort(reason);
|
|
172
|
+
return this.closePromise;
|
|
173
|
+
}
|
|
174
|
+
async finishClose(reason) {
|
|
175
|
+
await this.stopActiveTurn(reason);
|
|
176
|
+
if (this.externalSignal && this.externalAbortListener) {
|
|
177
|
+
this.externalSignal.removeEventListener("abort", this.externalAbortListener);
|
|
178
|
+
}
|
|
179
|
+
this.externalSignal = null;
|
|
180
|
+
this.externalAbortListener = null;
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
function createAttachedAgentSession(options) {
|
|
184
|
+
return new AttachedAgentSessionImpl(options);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// src/tar.ts
|
|
188
|
+
import { Buffer as Buffer2 } from "buffer";
|
|
189
|
+
import { promisify } from "util";
|
|
190
|
+
import { gzip } from "zlib";
|
|
191
|
+
var gzipAsync = promisify(gzip);
|
|
192
|
+
var BLOCK_SIZE = 512;
|
|
193
|
+
var MAX_OCTAL_SIZE = 8589934591;
|
|
194
|
+
function writeString(header2, value, offset, length) {
|
|
195
|
+
header2.write(value, offset, length, "utf8");
|
|
196
|
+
}
|
|
197
|
+
function writeOctal(header2, value, offset, length) {
|
|
198
|
+
header2.write(`${value.toString(8).padStart(length - 1, "0")}\0`, offset, length, "ascii");
|
|
199
|
+
}
|
|
200
|
+
function splitUstarPath(path2) {
|
|
201
|
+
if (Buffer2.byteLength(path2) <= 100) return { name: path2, prefix: "" };
|
|
202
|
+
for (let index = path2.indexOf("/"); index !== -1; index = path2.indexOf("/", index + 1)) {
|
|
203
|
+
const prefix = path2.slice(0, index);
|
|
204
|
+
const name = path2.slice(index + 1);
|
|
205
|
+
if (Buffer2.byteLength(prefix) <= 155 && Buffer2.byteLength(name) <= 100 && name) {
|
|
206
|
+
return { name, prefix };
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
return void 0;
|
|
210
|
+
}
|
|
211
|
+
function header(options) {
|
|
212
|
+
if (options.size > MAX_OCTAL_SIZE) {
|
|
213
|
+
throw new Error(`Archive entry ${options.name} is too large.`);
|
|
214
|
+
}
|
|
215
|
+
const block = Buffer2.alloc(BLOCK_SIZE);
|
|
216
|
+
writeString(block, options.name, 0, 100);
|
|
217
|
+
writeOctal(block, options.mode, 100, 8);
|
|
218
|
+
writeOctal(block, 0, 108, 8);
|
|
219
|
+
writeOctal(block, 0, 116, 8);
|
|
220
|
+
writeOctal(block, options.size, 124, 12);
|
|
221
|
+
writeOctal(block, options.mtime, 136, 12);
|
|
222
|
+
block.fill(" ", 148, 156);
|
|
223
|
+
writeString(block, options.type, 156, 1);
|
|
224
|
+
writeString(block, "ustar\0", 257, 6);
|
|
225
|
+
writeString(block, "00", 263, 2);
|
|
226
|
+
writeString(block, options.prefix ?? "", 345, 155);
|
|
227
|
+
let checksum = 0;
|
|
228
|
+
for (const byte of block) checksum += byte;
|
|
229
|
+
block.write(`${checksum.toString(8).padStart(6, "0")}\0 `, 148, 8, "ascii");
|
|
230
|
+
return block;
|
|
231
|
+
}
|
|
232
|
+
function padding(size) {
|
|
233
|
+
return Buffer2.alloc((BLOCK_SIZE - size % BLOCK_SIZE) % BLOCK_SIZE);
|
|
234
|
+
}
|
|
235
|
+
function paxPathRecord(path2) {
|
|
236
|
+
const body = ` path=${path2}
|
|
237
|
+
`;
|
|
238
|
+
let length = Buffer2.byteLength(body);
|
|
239
|
+
while (String(length).length + Buffer2.byteLength(body) !== length) {
|
|
240
|
+
length = String(length).length + Buffer2.byteLength(body);
|
|
241
|
+
}
|
|
242
|
+
return Buffer2.from(`${length}${body}`);
|
|
243
|
+
}
|
|
244
|
+
async function createTarGz(entries, mtime = Math.floor(Date.now() / 1e3)) {
|
|
245
|
+
const chunks = [];
|
|
246
|
+
for (const entry of entries) {
|
|
247
|
+
const isDirectory = entry.content === void 0;
|
|
248
|
+
const path2 = isDirectory ? `${entry.path.replace(/\/+$/u, "")}/` : entry.path;
|
|
249
|
+
const size = entry.content?.byteLength ?? 0;
|
|
250
|
+
const type = isDirectory ? "5" : "0";
|
|
251
|
+
const mode = isDirectory ? 493 : 420;
|
|
252
|
+
const split = splitUstarPath(path2);
|
|
253
|
+
if (split) {
|
|
254
|
+
chunks.push(header({ ...split, mode, size, mtime, type }));
|
|
255
|
+
} else {
|
|
256
|
+
const record = paxPathRecord(path2);
|
|
257
|
+
chunks.push(header({ name: "PaxHeader", mode: 420, size: record.byteLength, mtime, type: "x" }));
|
|
258
|
+
chunks.push(record, padding(record.byteLength));
|
|
259
|
+
chunks.push(header({ name: path2.slice(-100).replace(/^\/+/u, ""), mode, size, mtime, type }));
|
|
260
|
+
}
|
|
261
|
+
if (entry.content) {
|
|
262
|
+
chunks.push(Buffer2.from(entry.content.buffer, entry.content.byteOffset, entry.content.byteLength));
|
|
263
|
+
chunks.push(padding(size));
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
chunks.push(Buffer2.alloc(BLOCK_SIZE * 2));
|
|
267
|
+
return gzipAsync(Buffer2.concat(chunks));
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// src/providers/types.ts
|
|
271
|
+
function createProviderSandboxPaths(provider, homeDir, workDir) {
|
|
272
|
+
const agentDir = `${homeDir}/agent`;
|
|
273
|
+
const ioDir = `${homeDir}/io`;
|
|
274
|
+
return {
|
|
275
|
+
provider,
|
|
276
|
+
homeDir,
|
|
277
|
+
workDir,
|
|
278
|
+
agentDir,
|
|
279
|
+
ioDir,
|
|
280
|
+
inputJson: `${ioDir}/input.json`,
|
|
281
|
+
outputJson: `${ioDir}/output.json`,
|
|
282
|
+
agentModule: `${agentDir}/agent.mjs`,
|
|
283
|
+
serverModule: `${agentDir}/server.mjs`,
|
|
284
|
+
serverConfig: `${agentDir}/server-config.json`,
|
|
285
|
+
claudeDir: `${agentDir}/.claude`,
|
|
286
|
+
packageJson: `${agentDir}/package.json`
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
var PROVIDER_MAX_LIFETIME_MS = 864e5;
|
|
290
|
+
function validateProviderEnvs(label, value, failure) {
|
|
291
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || Object.entries(value).some(([name, item]) => !/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name) || item !== void 0 && (typeof item !== "string" || item.includes("\0")))) {
|
|
292
|
+
throw failure(`${label} envs must contain valid environment names and string values.`);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
function validateProviderOptions(label, options, allowedKeys, failure) {
|
|
296
|
+
const allowed = /* @__PURE__ */ new Set(["provider", ...allowedKeys]);
|
|
297
|
+
for (const [key, value] of Object.entries(options)) {
|
|
298
|
+
if (!allowed.has(key)) throw failure(`${label} does not support option "${key}".`);
|
|
299
|
+
if (value === void 0 || key === "provider") continue;
|
|
300
|
+
if (["timeoutMs", "cpu", "memoryMiB"].includes(key)) {
|
|
301
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0 || key === "timeoutMs" && (value % 1e3 !== 0 || value < 1e3 || value > PROVIDER_MAX_LIFETIME_MS) || key === "memoryMiB" && !Number.isInteger(value)) {
|
|
302
|
+
throw failure(`${label} ${key} must be positive${key === "timeoutMs" ? ` and a multiple of 1000 between 1000 and ${PROVIDER_MAX_LIFETIME_MS}` : ""}.`);
|
|
303
|
+
}
|
|
304
|
+
} else if (key === "envs") {
|
|
305
|
+
validateProviderEnvs(label, value, failure);
|
|
306
|
+
} else if (typeof value !== "string" || !value.trim() || value.includes("\0") || value.startsWith("-")) {
|
|
307
|
+
throw failure(`${label} ${key} must be a non-empty string without null bytes or a leading "-".`);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
function validateProviderCommand(label, command, options) {
|
|
312
|
+
if (typeof command !== "string" || command.includes("\0") || !options || Array.isArray(options) || !Number.isFinite(options.timeoutMs) || options.timeoutMs <= 0) {
|
|
313
|
+
throw new Error(`${label} commands require a string and a positive finite timeoutMs.`);
|
|
314
|
+
}
|
|
315
|
+
for (const key of Object.keys(options)) {
|
|
316
|
+
if (!["cwd", "envs", "timeoutMs", "onStdout", "onStderr"].includes(key)) {
|
|
317
|
+
throw new Error(`${label} commands do not support option "${key}".`);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
if (options.cwd !== void 0 && (typeof options.cwd !== "string" || !options.cwd.startsWith("/") || options.cwd.includes("\0")) || options.onStdout !== void 0 && typeof options.onStdout !== "function" || options.onStderr !== void 0 && typeof options.onStderr !== "function") {
|
|
321
|
+
throw new Error(`${label} command cwd must be absolute and output callbacks must be functions.`);
|
|
322
|
+
}
|
|
323
|
+
if (options.envs !== void 0) validateProviderEnvs(label, options.envs, (message) => new Error(message));
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// src/providers/daytona.ts
|
|
327
|
+
var SANDBOX_COMMAND_TIMEOUT_MS = 3e5;
|
|
328
|
+
var QUICK_COMMAND_TIMEOUT_MS = 3e4;
|
|
329
|
+
var LEGACY_DAYTONA_PROCESS_PATTERN = /^daytona-process:(\d+):(\d+):([a-z0-9-]+)$/iu;
|
|
330
|
+
function parseLegacyDaytonaProcessHandle(sessionId) {
|
|
331
|
+
const match = LEGACY_DAYTONA_PROCESS_PATTERN.exec(sessionId);
|
|
332
|
+
if (!match) return null;
|
|
333
|
+
const [, pid, startTicks, nonce] = match;
|
|
334
|
+
return pid && startTicks && nonce ? { pid, startTicks, nonce } : null;
|
|
335
|
+
}
|
|
336
|
+
var DaytonaSandboxHandle = class _DaytonaSandboxHandle {
|
|
337
|
+
constructor(sandbox, paths, failure) {
|
|
338
|
+
this.sandbox = sandbox;
|
|
339
|
+
this.paths = paths;
|
|
340
|
+
this.failure = failure;
|
|
341
|
+
this.detachedProcesses = createDaytonaDetachedProcessController(this.sandbox, {
|
|
342
|
+
homeDir: this.paths.homeDir,
|
|
343
|
+
readLegacyLogs: (command) => this.readLegacySessionLogs(command),
|
|
344
|
+
stopLegacy: (command) => this.stopLegacySession(command),
|
|
345
|
+
failure
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
provider = "daytona";
|
|
349
|
+
detachedProcesses;
|
|
350
|
+
static async create(sandbox, failure) {
|
|
351
|
+
const { homeDir, workDir } = await discoverDaytonaSandboxDirectories(
|
|
352
|
+
sandbox,
|
|
353
|
+
{ failure }
|
|
354
|
+
);
|
|
355
|
+
return new _DaytonaSandboxHandle(
|
|
356
|
+
sandbox,
|
|
357
|
+
createProviderSandboxPaths("daytona", homeDir, workDir),
|
|
358
|
+
failure
|
|
359
|
+
);
|
|
360
|
+
}
|
|
361
|
+
get id() {
|
|
362
|
+
return this.sandbox.id;
|
|
363
|
+
}
|
|
364
|
+
async makeDir(path2) {
|
|
365
|
+
const result = await makeDaytonaDirectory(this.sandbox, path2, {
|
|
366
|
+
timeoutMs: QUICK_COMMAND_TIMEOUT_MS
|
|
367
|
+
});
|
|
368
|
+
if (result.exitCode !== 0) {
|
|
369
|
+
throw this.failure(result.result || `Failed to create directory ${path2}`);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
writeFile(path2, content) {
|
|
373
|
+
return uploadDaytonaFile(this.sandbox, path2, content, {
|
|
374
|
+
timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
async readFile(path2) {
|
|
378
|
+
const content = await this.sandbox.fs.downloadFile(
|
|
379
|
+
path2,
|
|
380
|
+
daytonaTimeoutSeconds(SANDBOX_COMMAND_TIMEOUT_MS)
|
|
381
|
+
);
|
|
382
|
+
return content.toString("utf8");
|
|
383
|
+
}
|
|
384
|
+
async readFileBytes(path2) {
|
|
385
|
+
const content = await this.sandbox.fs.downloadFile(
|
|
386
|
+
path2,
|
|
387
|
+
daytonaTimeoutSeconds(SANDBOX_COMMAND_TIMEOUT_MS)
|
|
388
|
+
);
|
|
389
|
+
return new Uint8Array(content);
|
|
390
|
+
}
|
|
391
|
+
async runCommand(cmd, options) {
|
|
392
|
+
const result = await executeDaytonaCommand(this.sandbox, cmd, {
|
|
393
|
+
timeoutMs: options.timeoutMs,
|
|
394
|
+
...options.cwd === void 0 ? {} : { cwd: options.cwd },
|
|
395
|
+
...options.envs === void 0 ? {} : { envs: options.envs }
|
|
396
|
+
});
|
|
397
|
+
if (result.stdout) options.onStdout?.(result.stdout);
|
|
398
|
+
return result;
|
|
399
|
+
}
|
|
400
|
+
async startDetachedCommand(command, options = {}) {
|
|
401
|
+
return this.detachedProcesses.start(command, options);
|
|
402
|
+
}
|
|
403
|
+
async readSessionLogs(command) {
|
|
404
|
+
return this.detachedProcesses.readLogs(command);
|
|
405
|
+
}
|
|
406
|
+
async readLegacySessionLogs(command) {
|
|
407
|
+
const { sessionId, commandId } = command;
|
|
408
|
+
const legacy = parseLegacyDaytonaProcessHandle(sessionId);
|
|
409
|
+
if (legacy) {
|
|
410
|
+
try {
|
|
411
|
+
const result = await executeDaytonaCommand(
|
|
412
|
+
this.sandbox,
|
|
413
|
+
buildReadLegacyDetachedLogsCommand(legacy.nonce),
|
|
414
|
+
{ timeoutMs: QUICK_COMMAND_TIMEOUT_MS }
|
|
415
|
+
);
|
|
416
|
+
return result.exitCode === 0 ? parseDetachedProcessLogs(result.stdout) ?? { stdout: "", stderr: "" } : { stdout: "", stderr: "" };
|
|
417
|
+
} catch {
|
|
418
|
+
return { stdout: "", stderr: "" };
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
if (commandId === void 0) return { stdout: "", stderr: "" };
|
|
422
|
+
try {
|
|
423
|
+
const logs = await this.sandbox.process.getSessionCommandLogs(sessionId, commandId);
|
|
424
|
+
return {
|
|
425
|
+
stdout: boundDetachedProcessLog(logs.stdout ?? logs.output ?? ""),
|
|
426
|
+
stderr: boundDetachedProcessLog(logs.stderr ?? "")
|
|
427
|
+
};
|
|
428
|
+
} catch {
|
|
429
|
+
return { stdout: "", stderr: "" };
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
async stopSession(command) {
|
|
433
|
+
await this.detachedProcesses.stop(command);
|
|
434
|
+
}
|
|
435
|
+
async disposeSessionArtifacts(command) {
|
|
436
|
+
await this.detachedProcesses.dispose(command);
|
|
437
|
+
}
|
|
438
|
+
async stopLegacySession(command) {
|
|
439
|
+
const { sessionId } = command;
|
|
440
|
+
const detached = parseLegacyDaytonaProcessHandle(sessionId);
|
|
441
|
+
if (!detached) {
|
|
442
|
+
await this.sandbox.process.deleteSession(sessionId);
|
|
443
|
+
return;
|
|
444
|
+
}
|
|
445
|
+
const result = await executeRawDaytonaCommand(
|
|
446
|
+
this.sandbox,
|
|
447
|
+
buildLegacyDetachedStopCommand(detached.pid, detached.startTicks, "Daytona"),
|
|
448
|
+
{ timeoutMs: QUICK_COMMAND_TIMEOUT_MS }
|
|
449
|
+
);
|
|
450
|
+
if (result.exitCode !== 0) {
|
|
451
|
+
throw this.failure(
|
|
452
|
+
result.result || `Failed to stop detached Daytona process ${detached.pid}.`
|
|
453
|
+
);
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
async getServerEndpoint(port) {
|
|
457
|
+
const preview = await this.sandbox.getPreviewLink(port);
|
|
458
|
+
return { url: preview.url, trafficToken: preview.token };
|
|
459
|
+
}
|
|
460
|
+
destroy() {
|
|
461
|
+
return this.sandbox.delete(
|
|
462
|
+
daytonaTimeoutSeconds(SANDBOX_COMMAND_TIMEOUT_MS),
|
|
463
|
+
true
|
|
464
|
+
);
|
|
465
|
+
}
|
|
466
|
+
};
|
|
467
|
+
|
|
468
|
+
// src/timeout.ts
|
|
469
|
+
function settleOperation(operation, options = {}) {
|
|
470
|
+
const { abort, timeout } = options;
|
|
471
|
+
if (abort?.signal.aborted) throw abort.createError();
|
|
472
|
+
if (!abort && !timeout) {
|
|
473
|
+
try {
|
|
474
|
+
return Promise.resolve(operation());
|
|
475
|
+
} catch (error) {
|
|
476
|
+
return Promise.reject(error);
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
return new Promise((resolve2, reject) => {
|
|
480
|
+
let settled = false;
|
|
481
|
+
let timer;
|
|
482
|
+
const cleanup = () => {
|
|
483
|
+
if (timer !== void 0) {
|
|
484
|
+
clearTimeout(timer);
|
|
485
|
+
timer = void 0;
|
|
486
|
+
}
|
|
487
|
+
abort?.signal.removeEventListener("abort", onAbort);
|
|
488
|
+
};
|
|
489
|
+
const settle = (callback) => {
|
|
490
|
+
if (settled) return;
|
|
491
|
+
settled = true;
|
|
492
|
+
cleanup();
|
|
493
|
+
callback();
|
|
494
|
+
};
|
|
495
|
+
const onAbort = () => settle(() => reject(abort.createError()));
|
|
496
|
+
abort?.signal.addEventListener("abort", onAbort, { once: true });
|
|
497
|
+
if (timeout) {
|
|
498
|
+
timer = setTimeout(
|
|
499
|
+
() => settle(() => reject(timeout.createError())),
|
|
500
|
+
timeout.timeoutMs
|
|
501
|
+
);
|
|
502
|
+
}
|
|
503
|
+
let task;
|
|
504
|
+
try {
|
|
505
|
+
task = operation();
|
|
506
|
+
} catch (error) {
|
|
507
|
+
settle(() => reject(error));
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
510
|
+
void Promise.resolve(task).then(
|
|
511
|
+
(value) => settle(() => resolve2(value)),
|
|
512
|
+
(error) => settle(() => reject(error))
|
|
513
|
+
);
|
|
514
|
+
});
|
|
515
|
+
}
|
|
516
|
+
function withTimeout(task, timeoutMs, message) {
|
|
517
|
+
return settleOperation(() => task, {
|
|
518
|
+
timeout: {
|
|
519
|
+
timeoutMs,
|
|
520
|
+
createError: () => new Error(message)
|
|
521
|
+
}
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
// src/providers/e2b.ts
|
|
526
|
+
var E2B_SANDBOX_HOME = "/home/user";
|
|
527
|
+
var LEGACY_E2B_PROCESS_HANDLE_PATTERN = /^e2b:([1-9][0-9]*)$/u;
|
|
528
|
+
var LEGACY_E2B_EXIT_POLL_INTERVAL_MS = 100;
|
|
529
|
+
function parseLegacyE2bProcessHandle(value) {
|
|
530
|
+
const match = LEGACY_E2B_PROCESS_HANDLE_PATTERN.exec(value);
|
|
531
|
+
if (!match) return null;
|
|
532
|
+
const pid = Number(match[1]);
|
|
533
|
+
return Number.isSafeInteger(pid) && pid > 0 ? pid : null;
|
|
534
|
+
}
|
|
535
|
+
function remainingTimeoutMs(deadline) {
|
|
536
|
+
return Math.max(1, Math.ceil(deadline - performance.now()));
|
|
537
|
+
}
|
|
538
|
+
function delay(timeoutMs) {
|
|
539
|
+
return new Promise((resolve2) => setTimeout(resolve2, timeoutMs));
|
|
540
|
+
}
|
|
541
|
+
async function withinDeadline(operation, deadline) {
|
|
542
|
+
return withTimeout(
|
|
543
|
+
operation,
|
|
544
|
+
remainingTimeoutMs(deadline),
|
|
545
|
+
"E2B process control request timed out."
|
|
546
|
+
);
|
|
547
|
+
}
|
|
548
|
+
function numberProperty(value, property) {
|
|
549
|
+
if (typeof value !== "object" || value === null) return void 0;
|
|
550
|
+
const propertyValue = Reflect.get(value, property);
|
|
551
|
+
return typeof propertyValue === "number" ? propertyValue : void 0;
|
|
552
|
+
}
|
|
553
|
+
function stringProperty(value, property) {
|
|
554
|
+
if (typeof value !== "object" || value === null) return void 0;
|
|
555
|
+
const propertyValue = Reflect.get(value, property);
|
|
556
|
+
return typeof propertyValue === "string" ? propertyValue : void 0;
|
|
557
|
+
}
|
|
558
|
+
function messageFrom(error) {
|
|
559
|
+
return error instanceof Error ? error.message : String(error);
|
|
560
|
+
}
|
|
561
|
+
function writeContent(content) {
|
|
562
|
+
if (typeof content === "string") return content;
|
|
563
|
+
if (content instanceof ArrayBuffer) return content;
|
|
564
|
+
return Uint8Array.from(content).buffer;
|
|
565
|
+
}
|
|
566
|
+
async function runE2bCommand(sandbox, cmd, options) {
|
|
567
|
+
let stdout = "";
|
|
568
|
+
let stderr = "";
|
|
569
|
+
const command = options.cwd ? `cd ${shellQuote(options.cwd)} && ${cmd}` : cmd;
|
|
570
|
+
try {
|
|
571
|
+
const result = await sandbox.commands.run(command, {
|
|
572
|
+
timeoutMs: options.timeoutMs,
|
|
573
|
+
envs: options.envs,
|
|
574
|
+
background: false,
|
|
575
|
+
onStdout: (data) => {
|
|
576
|
+
stdout += data;
|
|
577
|
+
options.onStdout?.(data);
|
|
578
|
+
},
|
|
579
|
+
onStderr: (data) => {
|
|
580
|
+
stderr += data;
|
|
581
|
+
options.onStderr?.(data);
|
|
582
|
+
}
|
|
583
|
+
});
|
|
584
|
+
return {
|
|
585
|
+
exitCode: result.exitCode,
|
|
586
|
+
stdout: stdout || result.stdout,
|
|
587
|
+
stderr: stderr || result.stderr
|
|
588
|
+
};
|
|
589
|
+
} catch (error) {
|
|
590
|
+
return {
|
|
591
|
+
exitCode: numberProperty(error, "exitCode") ?? 1,
|
|
592
|
+
stdout: stdout || stringProperty(error, "stdout") || "",
|
|
593
|
+
stderr: stderr || stringProperty(error, "stderr") || messageFrom(error)
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
var E2bSandboxHandle = class {
|
|
598
|
+
constructor(sandbox, failure) {
|
|
599
|
+
this.sandbox = sandbox;
|
|
600
|
+
this.failure = failure;
|
|
601
|
+
this.detachedProcesses = new DetachedProcessController({
|
|
602
|
+
provider: "e2b",
|
|
603
|
+
genericPayloadEnvironmentDefaults: { HOME: this.paths.homeDir },
|
|
604
|
+
execute: async (command, options) => ({
|
|
605
|
+
state: "completed",
|
|
606
|
+
result: await runE2bCommand(this.sandbox, command, {
|
|
607
|
+
cwd: options?.cwd,
|
|
608
|
+
envs: options?.envs,
|
|
609
|
+
timeoutMs: DETACHED_PROCESS_CONTROL_TIMEOUT_MS
|
|
610
|
+
})
|
|
611
|
+
}),
|
|
612
|
+
readLegacyLogs: (command) => this.readLegacySessionLogs(command),
|
|
613
|
+
stopLegacy: (command) => this.stopLegacySession(command),
|
|
614
|
+
failure
|
|
615
|
+
});
|
|
616
|
+
}
|
|
617
|
+
provider = "e2b";
|
|
618
|
+
detachedProcesses;
|
|
619
|
+
paths = createProviderSandboxPaths(
|
|
620
|
+
"e2b",
|
|
621
|
+
E2B_SANDBOX_HOME,
|
|
622
|
+
E2B_SANDBOX_HOME
|
|
623
|
+
);
|
|
624
|
+
get id() {
|
|
625
|
+
return this.sandbox.sandboxId;
|
|
626
|
+
}
|
|
627
|
+
async makeDir(path2) {
|
|
628
|
+
await this.sandbox.files.makeDir(path2);
|
|
629
|
+
}
|
|
630
|
+
writeFile(path2, content) {
|
|
631
|
+
return this.sandbox.files.write(path2, writeContent(content)).then(() => void 0);
|
|
632
|
+
}
|
|
633
|
+
readFile(path2) {
|
|
634
|
+
return this.sandbox.files.read(path2, { format: "text" });
|
|
635
|
+
}
|
|
636
|
+
readFileBytes(path2) {
|
|
637
|
+
return this.sandbox.files.read(path2, { format: "bytes" });
|
|
638
|
+
}
|
|
639
|
+
runCommand(cmd, options) {
|
|
640
|
+
return runE2bCommand(this.sandbox, cmd, options);
|
|
641
|
+
}
|
|
642
|
+
setTimeout(timeoutMs) {
|
|
643
|
+
return this.sandbox.setTimeout(timeoutMs);
|
|
644
|
+
}
|
|
645
|
+
async startDetachedCommand(command, options = {}) {
|
|
646
|
+
return this.detachedProcesses.start(command, options);
|
|
647
|
+
}
|
|
648
|
+
async readSessionLogs(command) {
|
|
649
|
+
return this.detachedProcesses.readLogs(command);
|
|
650
|
+
}
|
|
651
|
+
async readLegacySessionLogs(command) {
|
|
652
|
+
const { commandId } = command;
|
|
653
|
+
if (commandId === void 0) return { stdout: "", stderr: "" };
|
|
654
|
+
try {
|
|
655
|
+
const handle = await this.sandbox.commands.connect(Number(commandId));
|
|
656
|
+
return {
|
|
657
|
+
stdout: boundDetachedProcessLog(handle.stdout ?? ""),
|
|
658
|
+
stderr: boundDetachedProcessLog(handle.stderr ?? "")
|
|
659
|
+
};
|
|
660
|
+
} catch {
|
|
661
|
+
return { stdout: "", stderr: "" };
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
async stopSession(command) {
|
|
665
|
+
await this.detachedProcesses.stop(command);
|
|
666
|
+
}
|
|
667
|
+
async disposeSessionArtifacts(command) {
|
|
668
|
+
await this.detachedProcesses.dispose(command);
|
|
669
|
+
}
|
|
670
|
+
async stopLegacySession(command) {
|
|
671
|
+
const { sessionId } = command;
|
|
672
|
+
const legacyPid = parseLegacyE2bProcessHandle(sessionId);
|
|
673
|
+
if (legacyPid === null) {
|
|
674
|
+
throw this.failure("Detached process handle is invalid for E2B.");
|
|
675
|
+
}
|
|
676
|
+
const deadline = performance.now() + DETACHED_PROCESS_CONTROL_TIMEOUT_MS;
|
|
677
|
+
let signalled;
|
|
678
|
+
try {
|
|
679
|
+
signalled = await withinDeadline(
|
|
680
|
+
this.sandbox.commands.kill(legacyPid, {
|
|
681
|
+
requestTimeoutMs: remainingTimeoutMs(deadline)
|
|
682
|
+
}),
|
|
683
|
+
deadline
|
|
684
|
+
);
|
|
685
|
+
} catch (error) {
|
|
686
|
+
throw this.failure(
|
|
687
|
+
`Failed to stop legacy detached E2B process ${legacyPid}: ${messageFrom(error)}`
|
|
688
|
+
);
|
|
689
|
+
}
|
|
690
|
+
if (!signalled) return;
|
|
691
|
+
while (performance.now() < deadline) {
|
|
692
|
+
let processes;
|
|
693
|
+
try {
|
|
694
|
+
processes = await withinDeadline(
|
|
695
|
+
this.sandbox.commands.list({
|
|
696
|
+
requestTimeoutMs: remainingTimeoutMs(deadline)
|
|
697
|
+
}),
|
|
698
|
+
deadline
|
|
699
|
+
);
|
|
700
|
+
} catch (error) {
|
|
701
|
+
throw this.failure(
|
|
702
|
+
`Failed to confirm legacy detached E2B process ${legacyPid} exit: ${messageFrom(error)}`
|
|
703
|
+
);
|
|
704
|
+
}
|
|
705
|
+
if (!processes.some((process2) => process2.pid === legacyPid)) return;
|
|
706
|
+
const remaining = deadline - performance.now();
|
|
707
|
+
if (remaining <= 0) break;
|
|
708
|
+
await delay(Math.min(LEGACY_E2B_EXIT_POLL_INTERVAL_MS, remaining));
|
|
709
|
+
}
|
|
710
|
+
throw this.failure(
|
|
711
|
+
`Failed to stop legacy detached E2B process ${legacyPid}: provider still reports it as running.`
|
|
712
|
+
);
|
|
713
|
+
}
|
|
714
|
+
async getServerEndpoint(port) {
|
|
715
|
+
return {
|
|
716
|
+
url: `https://${this.sandbox.getHost(port)}`,
|
|
717
|
+
trafficToken: this.sandbox.trafficAccessToken
|
|
718
|
+
};
|
|
719
|
+
}
|
|
720
|
+
async destroy() {
|
|
721
|
+
await this.sandbox.kill();
|
|
722
|
+
}
|
|
723
|
+
};
|
|
724
|
+
|
|
725
|
+
// src/providers/modal.ts
|
|
726
|
+
import { createHash } from "crypto";
|
|
727
|
+
|
|
728
|
+
// src/providers/modal-sdk.ts
|
|
729
|
+
import { createRequire } from "module";
|
|
730
|
+
function getModalSdk() {
|
|
731
|
+
const require3 = createRequire(typeof __filename === "string" ? __filename : import.meta.url);
|
|
732
|
+
return require3("modal");
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
// src/providers/modal.ts
|
|
736
|
+
var MODAL_DEFAULT_TEMPLATE = "node:22-bookworm";
|
|
737
|
+
var MODAL_DEFAULT_TIMEOUT_MS = 60 * 60 * 1e3;
|
|
738
|
+
function parseModalAllowList(value) {
|
|
739
|
+
return (value ?? "").split(",").map((entry) => entry.trim()).filter(Boolean);
|
|
740
|
+
}
|
|
741
|
+
function modalNetworkOptions(options) {
|
|
742
|
+
if (options.networkBlockAll) return { blockNetwork: true };
|
|
743
|
+
const cidrs = parseModalAllowList(options.networkAllowList);
|
|
744
|
+
const domains = parseModalAllowList(options.domainAllowList);
|
|
745
|
+
return {
|
|
746
|
+
...cidrs.length > 0 ? { outboundCidrAllowlist: cidrs } : {},
|
|
747
|
+
...domains.length > 0 ? { outboundDomainAllowlist: domains } : {}
|
|
748
|
+
};
|
|
749
|
+
}
|
|
750
|
+
function validateModalOptions(options, mode, failure) {
|
|
751
|
+
const { networkBlockAll, networkAllowList, domainAllowList, regions, command, ...rest } = options;
|
|
752
|
+
validateProviderOptions("Modal", mode === "connect" ? options : rest, ["environment", ...mode === "connect" ? ["sandboxId", "tokenId", "tokenSecret"] : [
|
|
753
|
+
"template",
|
|
754
|
+
"appName",
|
|
755
|
+
"timeoutMs",
|
|
756
|
+
"cpu",
|
|
757
|
+
"memoryMiB",
|
|
758
|
+
...mode === "create" ? ["tokenId", "tokenSecret", "envs", "registrySecret"] : []
|
|
759
|
+
]], failure);
|
|
760
|
+
if (command !== void 0 && (mode !== "create" || !Array.isArray(command) || command.length === 0 || command.some((part) => typeof part !== "string" || part.includes("\0")))) {
|
|
761
|
+
throw failure(mode === "create" ? "Modal command must be a non-empty array of strings without null bytes." : 'Modal does not support option "command".');
|
|
762
|
+
}
|
|
763
|
+
if (regions !== void 0 && (!Array.isArray(regions) || regions.length === 0 || regions.some((region) => typeof region !== "string" || !/^[a-z0-9-]+$/u.test(region)))) {
|
|
764
|
+
throw failure('Modal regions must be a non-empty array of region names such as "us" or "us-east".');
|
|
765
|
+
}
|
|
766
|
+
if (networkBlockAll !== void 0 && typeof networkBlockAll !== "boolean") {
|
|
767
|
+
throw failure("Modal networkBlockAll must be a boolean.");
|
|
768
|
+
}
|
|
769
|
+
for (const [key, value] of [["networkAllowList", networkAllowList], ["domainAllowList", domainAllowList]]) {
|
|
770
|
+
if (value !== void 0 && (typeof value !== "string" || parseModalAllowList(value).some((entry) => /[\s\0]/u.test(entry)))) {
|
|
771
|
+
throw failure(`Modal ${key} must be a comma-separated string without whitespace or null bytes in entries.`);
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
if (networkBlockAll && (parseModalAllowList(networkAllowList).length > 0 || parseModalAllowList(domainAllowList).length > 0)) {
|
|
775
|
+
throw failure("Modal networkBlockAll cannot be combined with non-empty allow lists.");
|
|
776
|
+
}
|
|
777
|
+
if (mode === "connect" && !("sandboxId" in options && options.sandboxId)) {
|
|
778
|
+
throw failure("Modal sandboxId is required.");
|
|
779
|
+
}
|
|
780
|
+
const credentials = options;
|
|
781
|
+
if (credentials.tokenId === void 0 !== (credentials.tokenSecret === void 0)) {
|
|
782
|
+
throw failure("Modal tokenId and tokenSecret must be supplied together.");
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
var modalClients = /* @__PURE__ */ new Map();
|
|
786
|
+
var MAX_MODAL_CLIENTS = 16;
|
|
787
|
+
async function sharedClient(credentials) {
|
|
788
|
+
if (Number(process.versions.node.split(".")[0]) < 22) {
|
|
789
|
+
throw new Error("The Modal provider requires Node.js 22 or later.");
|
|
790
|
+
}
|
|
791
|
+
const configuration = {
|
|
792
|
+
tokenId: credentials.tokenId,
|
|
793
|
+
tokenSecret: credentials.tokenSecret,
|
|
794
|
+
environment: credentials.environment,
|
|
795
|
+
logLevel: "error"
|
|
796
|
+
};
|
|
797
|
+
const key = createHash("sha256").update(JSON.stringify([
|
|
798
|
+
configuration,
|
|
799
|
+
Object.entries(process.env).filter(([name]) => name.startsWith("MODAL_")).sort(([left], [right]) => left.localeCompare(right))
|
|
800
|
+
])).digest("hex");
|
|
801
|
+
const existing = modalClients.get(key);
|
|
802
|
+
if (existing) return existing;
|
|
803
|
+
if (modalClients.size >= MAX_MODAL_CLIENTS) {
|
|
804
|
+
throw new Error("Modal client configuration limit reached (16 per module instance); use a separate worker for additional credentials or restart after credential rotation.");
|
|
805
|
+
}
|
|
806
|
+
let client;
|
|
807
|
+
try {
|
|
808
|
+
const { ModalClient } = getModalSdk();
|
|
809
|
+
client = Promise.resolve(new ModalClient(configuration));
|
|
810
|
+
} catch (error) {
|
|
811
|
+
client = Promise.reject(error);
|
|
812
|
+
}
|
|
813
|
+
modalClients.set(key, client);
|
|
814
|
+
return client;
|
|
815
|
+
}
|
|
816
|
+
var ModalSandboxHandle = class _ModalSandboxHandle {
|
|
817
|
+
constructor(id, client, failure) {
|
|
818
|
+
this.id = id;
|
|
819
|
+
this.client = client;
|
|
820
|
+
this.detachedProcesses = new DetachedProcessController({
|
|
821
|
+
provider: "modal",
|
|
822
|
+
genericPayloadEnvironmentDefaults: { HOME: this.paths.homeDir },
|
|
823
|
+
execute: async (command, options) => {
|
|
824
|
+
try {
|
|
825
|
+
return { state: "completed", result: await this.runCommand(command, {
|
|
826
|
+
...options,
|
|
827
|
+
timeoutMs: DETACHED_PROCESS_CONTROL_TIMEOUT_MS
|
|
828
|
+
}) };
|
|
829
|
+
} catch (error) {
|
|
830
|
+
return { state: "failed", error };
|
|
831
|
+
}
|
|
832
|
+
},
|
|
833
|
+
readLegacyLogs: async () => {
|
|
834
|
+
throw failure("Modal requires a managed detached process handle.");
|
|
835
|
+
},
|
|
836
|
+
stopLegacy: async () => {
|
|
837
|
+
throw failure("Modal requires a managed detached process handle.");
|
|
838
|
+
},
|
|
839
|
+
failure
|
|
840
|
+
});
|
|
841
|
+
}
|
|
842
|
+
provider = "modal";
|
|
843
|
+
paths = createProviderSandboxPaths("modal", "/root", "/root");
|
|
844
|
+
detachedProcesses;
|
|
845
|
+
static async create(options, failure) {
|
|
846
|
+
const credentials = {
|
|
847
|
+
tokenId: options.tokenId,
|
|
848
|
+
tokenSecret: options.tokenSecret,
|
|
849
|
+
environment: options.environment
|
|
850
|
+
};
|
|
851
|
+
const client = await sharedClient(credentials);
|
|
852
|
+
let sandbox;
|
|
853
|
+
try {
|
|
854
|
+
const app = await client.apps.fromName(options.appName ?? "agent-neckbeard", { createIfMissing: true });
|
|
855
|
+
const network = modalNetworkOptions(options);
|
|
856
|
+
const template = options.template ?? MODAL_DEFAULT_TEMPLATE;
|
|
857
|
+
const registryImage = options.registrySecret === void 0 ? client.images.fromRegistry(template) : client.images.fromRegistry(template, await client.secrets.fromName(options.registrySecret));
|
|
858
|
+
const image = options.command ? registryImage : registryImage.dockerfileCommands([
|
|
859
|
+
"USER root",
|
|
860
|
+
"RUN apt-get update && apt-get install -y --no-install-recommends bash python3 util-linux coreutils sudo curl ca-certificates && rm -rf /var/lib/apt/lists/*",
|
|
861
|
+
// The runtime starts with a fixed PATH, so images with Node elsewhere (say nvm) need links.
|
|
862
|
+
'RUN for bin in node npm npx; do target="$(command -v "$bin" || true)"; if [ -n "$target" ] && [ ! -e "/usr/local/bin/$bin" ]; then ln -s "$target" "/usr/local/bin/$bin"; fi; done',
|
|
863
|
+
// The domain allow list only passes TLS, so apt installs in the sandbox need HTTPS sources.
|
|
864
|
+
...network.outboundDomainAllowlist ? ["RUN find /etc/apt -name '*.list' -o -name '*.sources' | xargs -r sed -i 's|http://|https://|g'"] : [],
|
|
865
|
+
"WORKDIR /root"
|
|
866
|
+
]);
|
|
867
|
+
sandbox = await client.sandboxes.create(app, image, {
|
|
868
|
+
...network,
|
|
869
|
+
...options.regions ? { regions: options.regions } : {},
|
|
870
|
+
timeoutMs: options.timeoutMs ?? MODAL_DEFAULT_TIMEOUT_MS,
|
|
871
|
+
cpu: options.cpu,
|
|
872
|
+
memoryMiB: options.memoryMiB,
|
|
873
|
+
...options.command ? { command: options.command } : { workdir: "/root" },
|
|
874
|
+
env: Object.fromEntries(Object.entries(options.envs ?? {}).filter(
|
|
875
|
+
(entry) => entry[1] !== void 0
|
|
876
|
+
))
|
|
877
|
+
// No tunnels: all HTTP access requires a port-scoped Connect Token.
|
|
878
|
+
});
|
|
879
|
+
return new _ModalSandboxHandle(sandbox.sandboxId, client, failure);
|
|
880
|
+
} finally {
|
|
881
|
+
sandbox?.detach();
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
/** Terminates a sandbox by ID; one that is gone counts as terminated. */
|
|
885
|
+
static async destroyById(options, failure) {
|
|
886
|
+
const client = await sharedClient({
|
|
887
|
+
tokenId: options.tokenId,
|
|
888
|
+
tokenSecret: options.tokenSecret,
|
|
889
|
+
environment: options.environment
|
|
890
|
+
});
|
|
891
|
+
await new _ModalSandboxHandle(options.sandboxId, client, failure).destroy();
|
|
892
|
+
}
|
|
893
|
+
static async connect(options, failure) {
|
|
894
|
+
const client = await sharedClient({
|
|
895
|
+
tokenId: options.tokenId,
|
|
896
|
+
tokenSecret: options.tokenSecret,
|
|
897
|
+
environment: options.environment
|
|
898
|
+
});
|
|
899
|
+
const handle = new _ModalSandboxHandle(options.sandboxId, client, failure);
|
|
900
|
+
await handle.use(async (sandbox) => {
|
|
901
|
+
if (await sandbox.poll() !== null) throw failure("Modal sandbox is no longer running.");
|
|
902
|
+
});
|
|
903
|
+
return handle;
|
|
904
|
+
}
|
|
905
|
+
async use(operation, timeoutMs) {
|
|
906
|
+
const client = this.client;
|
|
907
|
+
let sandbox;
|
|
908
|
+
let active = true;
|
|
909
|
+
try {
|
|
910
|
+
const work = (async () => {
|
|
911
|
+
const connected = await client.sandboxes.fromId(this.id);
|
|
912
|
+
if (!active) {
|
|
913
|
+
connected.detach();
|
|
914
|
+
throw new Error("Modal command request already timed out.");
|
|
915
|
+
}
|
|
916
|
+
sandbox = connected;
|
|
917
|
+
return operation(sandbox);
|
|
918
|
+
})();
|
|
919
|
+
return await (timeoutMs === void 0 ? work : withTimeout(
|
|
920
|
+
work,
|
|
921
|
+
timeoutMs,
|
|
922
|
+
"Modal command request timed out; remote completion is unknown."
|
|
923
|
+
));
|
|
924
|
+
} finally {
|
|
925
|
+
active = false;
|
|
926
|
+
sandbox?.detach();
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
makeDir(path2) {
|
|
930
|
+
return this.use((sandbox) => sandbox.filesystem.makeDirectory(path2));
|
|
931
|
+
}
|
|
932
|
+
writeFile(path2, content) {
|
|
933
|
+
return this.use((sandbox) => typeof content === "string" ? sandbox.filesystem.writeText(content, path2) : sandbox.filesystem.writeBytes(content, path2));
|
|
934
|
+
}
|
|
935
|
+
readFile(path2) {
|
|
936
|
+
return this.use((sandbox) => sandbox.filesystem.readText(path2));
|
|
937
|
+
}
|
|
938
|
+
readFileBytes(path2) {
|
|
939
|
+
return this.use((sandbox) => sandbox.filesystem.readBytes(path2));
|
|
940
|
+
}
|
|
941
|
+
runCommand(command, options) {
|
|
942
|
+
try {
|
|
943
|
+
validateProviderCommand("Modal", command, options);
|
|
944
|
+
} catch (error) {
|
|
945
|
+
return Promise.reject(error);
|
|
946
|
+
}
|
|
947
|
+
return this.use(async (sandbox) => {
|
|
948
|
+
const process2 = await sandbox.exec(["/bin/bash", "--noprofile", "--norc", "-c", command], {
|
|
949
|
+
workdir: options.cwd ?? this.paths.workDir,
|
|
950
|
+
env: options.envs,
|
|
951
|
+
timeoutMs: Math.ceil(options.timeoutMs / 1e3) * 1e3
|
|
952
|
+
});
|
|
953
|
+
const read = async (stream, callback) => {
|
|
954
|
+
let output = "";
|
|
955
|
+
for await (const chunk of stream) {
|
|
956
|
+
output += chunk;
|
|
957
|
+
callback?.(chunk);
|
|
958
|
+
}
|
|
959
|
+
return output;
|
|
960
|
+
};
|
|
961
|
+
const [stdout, stderr, exitCode] = await Promise.all([
|
|
962
|
+
read(process2.stdout, options.onStdout),
|
|
963
|
+
read(process2.stderr, options.onStderr),
|
|
964
|
+
process2.wait()
|
|
965
|
+
]);
|
|
966
|
+
return { stdout, stderr, exitCode };
|
|
967
|
+
}, options.timeoutMs);
|
|
968
|
+
}
|
|
969
|
+
startDetachedCommand(command, options = {}) {
|
|
970
|
+
return this.detachedProcesses.start(command, options);
|
|
971
|
+
}
|
|
972
|
+
readSessionLogs(command) {
|
|
973
|
+
return this.detachedProcesses.readLogs(command);
|
|
974
|
+
}
|
|
975
|
+
stopSession(command) {
|
|
976
|
+
return this.detachedProcesses.stop(command);
|
|
977
|
+
}
|
|
978
|
+
disposeSessionArtifacts(command) {
|
|
979
|
+
return this.detachedProcesses.dispose(command);
|
|
980
|
+
}
|
|
981
|
+
getServerEndpoint(port) {
|
|
982
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
983
|
+
return Promise.reject(new Error("Modal endpoint port must be between 1 and 65535."));
|
|
984
|
+
}
|
|
985
|
+
return this.use(async (sandbox) => {
|
|
986
|
+
const credentials = await sandbox.createConnectToken({ port });
|
|
987
|
+
let url;
|
|
988
|
+
try {
|
|
989
|
+
url = new URL(credentials.url);
|
|
990
|
+
} catch {
|
|
991
|
+
throw new Error("Modal returned invalid private endpoint credentials.");
|
|
992
|
+
}
|
|
993
|
+
if (typeof credentials.token !== "string" || !credentials.token.trim() || /[\r\n]/u.test(credentials.token) || url.protocol !== "https:" || url.username || url.password) {
|
|
994
|
+
throw new Error("Modal returned invalid private endpoint credentials.");
|
|
995
|
+
}
|
|
996
|
+
return { url: credentials.url, trafficToken: credentials.token };
|
|
997
|
+
});
|
|
998
|
+
}
|
|
999
|
+
async destroy() {
|
|
1000
|
+
const { NotFoundError } = getModalSdk();
|
|
1001
|
+
try {
|
|
1002
|
+
await this.use(async (sandbox) => {
|
|
1003
|
+
await sandbox.terminate({ wait: true });
|
|
1004
|
+
});
|
|
1005
|
+
} catch (error) {
|
|
1006
|
+
const grpcNotFound = error instanceof Error && error.name === "ClientError" && Reflect.get(error, "code") === 5;
|
|
1007
|
+
if (!(error instanceof NotFoundError) && !grpcNotFound) throw error;
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
};
|
|
1011
|
+
|
|
1012
|
+
// src/define.ts
|
|
1013
|
+
import { mkdir } from "fs/promises";
|
|
1014
|
+
import os from "os";
|
|
1015
|
+
import path from "path";
|
|
1016
|
+
|
|
1017
|
+
// src/agent.ts
|
|
1018
|
+
import { createHash as createHash2 } from "crypto";
|
|
1019
|
+
var DEFAULT_COMMAND = ["node", "/app/agent.mjs"];
|
|
1020
|
+
var DEFAULT_PORT = 8080;
|
|
1021
|
+
var DEFAULT_START_TIMEOUT_MS = 12e4;
|
|
1022
|
+
var DEFAULT_PREPARE_TIMEOUT_MS = 30 * 6e4;
|
|
1023
|
+
var DEFAULT_RECONNECT_TIMEOUT_MS = 12e4;
|
|
1024
|
+
var HEALTH_POLL_INTERVAL_MS = 500;
|
|
1025
|
+
var RECONNECT_MIN_DELAY_MS = 250;
|
|
1026
|
+
var RECONNECT_MAX_DELAY_MS = 5e3;
|
|
1027
|
+
var REQUEST_TIMEOUT_MS = 3e4;
|
|
1028
|
+
var ARTIFACT_PREFIX = "nb-";
|
|
1029
|
+
function filterDefined(envs) {
|
|
1030
|
+
return Object.fromEntries(Object.entries(envs ?? {}).filter(
|
|
1031
|
+
(entry) => entry[1] !== void 0
|
|
1032
|
+
));
|
|
1033
|
+
}
|
|
1034
|
+
function delay2(ms, signal) {
|
|
1035
|
+
return new Promise((resolve2, reject) => {
|
|
1036
|
+
if (signal?.aborted) return reject(abortError(signal));
|
|
1037
|
+
const onAbort = () => {
|
|
1038
|
+
clearTimeout(timer);
|
|
1039
|
+
reject(abortError(signal));
|
|
1040
|
+
};
|
|
1041
|
+
const timer = setTimeout(() => {
|
|
1042
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1043
|
+
resolve2();
|
|
1044
|
+
}, ms);
|
|
1045
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1046
|
+
});
|
|
1047
|
+
}
|
|
1048
|
+
function untilDeadline(deadline, signal) {
|
|
1049
|
+
const timeout = AbortSignal.timeout(Math.max(0, deadline - Date.now()));
|
|
1050
|
+
return signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
1051
|
+
}
|
|
1052
|
+
function untilAborted(operation, signal) {
|
|
1053
|
+
if (signal?.aborted) return Promise.reject(abortError(signal));
|
|
1054
|
+
return settleOperation(operation, signal ? { abort: { signal, createError: () => abortError(signal) } } : {});
|
|
1055
|
+
}
|
|
1056
|
+
function abortError(signal) {
|
|
1057
|
+
if (signal.reason instanceof Error) return signal.reason;
|
|
1058
|
+
const error = new Error("Operation aborted.");
|
|
1059
|
+
error.name = "AbortError";
|
|
1060
|
+
return error;
|
|
1061
|
+
}
|
|
1062
|
+
async function* textChunks(body, onChunk) {
|
|
1063
|
+
const decoder = new TextDecoder();
|
|
1064
|
+
const reader = body.getReader();
|
|
1065
|
+
try {
|
|
1066
|
+
while (true) {
|
|
1067
|
+
const { done, value } = await reader.read();
|
|
1068
|
+
if (done) break;
|
|
1069
|
+
onChunk();
|
|
1070
|
+
yield decoder.decode(value, { stream: true });
|
|
1071
|
+
}
|
|
1072
|
+
} finally {
|
|
1073
|
+
await reader.cancel().catch(() => void 0);
|
|
1074
|
+
reader.releaseLock();
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
var EndpointRejectedError = class extends Error {
|
|
1078
|
+
};
|
|
1079
|
+
var Agent = class {
|
|
1080
|
+
constructor(options) {
|
|
1081
|
+
this.options = options;
|
|
1082
|
+
if (!options || typeof options !== "object") throw new ConfigurationError("Agent options must be an object.");
|
|
1083
|
+
if (typeof options.name !== "string" || !/^[a-z0-9]+(-[a-z0-9]+)*$/u.test(options.name)) {
|
|
1084
|
+
throw new ConfigurationError("Agent name must be lowercase letters, digits, and single dashes.");
|
|
1085
|
+
}
|
|
1086
|
+
if (typeof options.image !== "string" || !options.image.trim() || /\s/u.test(options.image)) {
|
|
1087
|
+
throw new ConfigurationError("Agent image must be a registry image reference.");
|
|
1088
|
+
}
|
|
1089
|
+
const provider = options.sandbox?.provider;
|
|
1090
|
+
if (provider !== "modal" && provider !== "daytona" && provider !== "e2b") {
|
|
1091
|
+
throw new ConfigurationError('Agent sandbox.provider must be "modal", "daytona", or "e2b".');
|
|
1092
|
+
}
|
|
1093
|
+
const command = options.command ?? DEFAULT_COMMAND;
|
|
1094
|
+
if (!Array.isArray(command) || command.length === 0 || command.some((part) => typeof part !== "string" || !part)) {
|
|
1095
|
+
throw new ConfigurationError("Agent command must be a non-empty array of non-empty strings.");
|
|
1096
|
+
}
|
|
1097
|
+
const port = options.port ?? DEFAULT_PORT;
|
|
1098
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
1099
|
+
throw new ConfigurationError("Agent port must be between 1 and 65535.");
|
|
1100
|
+
}
|
|
1101
|
+
this.name = options.name;
|
|
1102
|
+
this.image = options.image;
|
|
1103
|
+
this.command = [...command];
|
|
1104
|
+
this.port = port;
|
|
1105
|
+
}
|
|
1106
|
+
name;
|
|
1107
|
+
image;
|
|
1108
|
+
command;
|
|
1109
|
+
port;
|
|
1110
|
+
endpoints = /* @__PURE__ */ new Map();
|
|
1111
|
+
preparing;
|
|
1112
|
+
get provider() {
|
|
1113
|
+
return this.options.sandbox.provider;
|
|
1114
|
+
}
|
|
1115
|
+
/**
|
|
1116
|
+
* Name of the Daytona snapshot or E2B template for this image, command, and resources. Equal
|
|
1117
|
+
* inputs share one, so preparing again is a lookup.
|
|
1118
|
+
*/
|
|
1119
|
+
get artifactName() {
|
|
1120
|
+
const { sandbox } = this.options;
|
|
1121
|
+
const resources = sandbox.provider === "daytona" ? sandbox.resources : sandbox.provider === "e2b" ? { cpuCount: sandbox.cpuCount, memoryMB: sandbox.memoryMB } : void 0;
|
|
1122
|
+
const hash = createHash2("sha256").update(JSON.stringify([this.image, sandbox.provider === "daytona" ? this.command : [], resources ?? null])).digest("hex").slice(0, 16);
|
|
1123
|
+
return `${ARTIFACT_PREFIX}${this.name}-${hash}`;
|
|
1124
|
+
}
|
|
1125
|
+
/**
|
|
1126
|
+
* Creates the Daytona snapshot or E2B template for the image if it is missing and waits until
|
|
1127
|
+
* it can start sandboxes. Run it from CI after pushing the image so no sandbox waits on a
|
|
1128
|
+
* build. Modal pulls the image directly, so this does nothing there. `refresh` builds it again
|
|
1129
|
+
* even when it exists, as after pushing new contents under a tag it was built from, since its
|
|
1130
|
+
* name comes from the image's reference, not its contents.
|
|
1131
|
+
*/
|
|
1132
|
+
prepare(options = {}) {
|
|
1133
|
+
const { sandbox } = this.options;
|
|
1134
|
+
if (sandbox.provider === "modal") return Promise.resolve();
|
|
1135
|
+
if (options.signal?.aborted) return Promise.reject(abortError(options.signal));
|
|
1136
|
+
if (!this.preparing || options.refresh) {
|
|
1137
|
+
const timeoutMs = this.options.prepareTimeoutMs ?? DEFAULT_PREPARE_TIMEOUT_MS;
|
|
1138
|
+
const deadline = AbortSignal.timeout(timeoutMs);
|
|
1139
|
+
const steps = { signal: deadline, refresh: options.refresh ?? false, ...options.onLog ? { onLog: options.onLog } : {} };
|
|
1140
|
+
this.preparing = untilAborted(
|
|
1141
|
+
() => sandbox.provider === "daytona" ? this.prepareDaytonaSnapshot(sandbox, steps) : this.prepareE2bTemplate(sandbox, steps),
|
|
1142
|
+
deadline
|
|
1143
|
+
).catch((error) => {
|
|
1144
|
+
this.preparing = void 0;
|
|
1145
|
+
if (deadline.aborted) throw new DeploymentError(`Preparing ${this.artifactName} took longer than ${timeoutMs}ms.`);
|
|
1146
|
+
throw error;
|
|
1147
|
+
});
|
|
1148
|
+
this.preparing.catch(() => void 0);
|
|
1149
|
+
}
|
|
1150
|
+
const preparing = this.preparing;
|
|
1151
|
+
return untilAborted(() => preparing, options.signal);
|
|
1152
|
+
}
|
|
1153
|
+
/** Starts a sandbox from the image and waits for its runtime. Returns the sandbox ID. */
|
|
1154
|
+
async start(options = {}) {
|
|
1155
|
+
await this.prepare({ ...options.signal ? { signal: options.signal } : {} });
|
|
1156
|
+
const envs = {
|
|
1157
|
+
...filterDefined(this.options.envs),
|
|
1158
|
+
...filterDefined(options.envs),
|
|
1159
|
+
...options.sessionId === void 0 ? {} : { NECKBEARD_SESSION_ID: options.sessionId },
|
|
1160
|
+
NECKBEARD_PORT: String(this.port)
|
|
1161
|
+
};
|
|
1162
|
+
if (options.signal?.aborted) throw abortError(options.signal);
|
|
1163
|
+
let sandbox;
|
|
1164
|
+
try {
|
|
1165
|
+
sandbox = await this.createSandbox(envs);
|
|
1166
|
+
} catch (error) {
|
|
1167
|
+
this.preparing = void 0;
|
|
1168
|
+
throw error;
|
|
1169
|
+
}
|
|
1170
|
+
try {
|
|
1171
|
+
if (this.options.sandbox.provider === "e2b") await this.startE2bRuntime(this.options.sandbox, sandbox.id, envs);
|
|
1172
|
+
await this.waitForRuntime(sandbox.id, options.signal);
|
|
1173
|
+
return sandbox.id;
|
|
1174
|
+
} catch (error) {
|
|
1175
|
+
this.endpoints.delete(sandbox.id);
|
|
1176
|
+
try {
|
|
1177
|
+
await sandbox.destroy();
|
|
1178
|
+
} catch (cleanupError) {
|
|
1179
|
+
const startMessage = error instanceof Error ? error.message : String(error);
|
|
1180
|
+
const cleanupMessage = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
|
|
1181
|
+
throw new DeploymentError(
|
|
1182
|
+
`Sandbox ${sandbox.id} failed to start (${startMessage}), and deleting it failed (${cleanupMessage}); kill() it to retry.`,
|
|
1183
|
+
error instanceof Error ? error : void 0,
|
|
1184
|
+
sandbox.id
|
|
1185
|
+
);
|
|
1186
|
+
}
|
|
1187
|
+
throw error;
|
|
1188
|
+
}
|
|
1189
|
+
}
|
|
1190
|
+
/**
|
|
1191
|
+
* Starts a turn and streams its records until its `end` record. Starting a turn whose
|
|
1192
|
+
* `turnId` the runtime already has resumes it instead of running it again.
|
|
1193
|
+
*/
|
|
1194
|
+
async *prompt(sandboxId, turn, options = {}) {
|
|
1195
|
+
const response = await this.request(sandboxId, "POST", "/turns", turn, options.signal);
|
|
1196
|
+
if (response.status === 409) {
|
|
1197
|
+
const body = await response.json().catch(() => ({}));
|
|
1198
|
+
throw new RuntimeBusyError(`Sandbox ${sandboxId} is running another turn (${body.turnId ?? "unknown"}).`);
|
|
1199
|
+
}
|
|
1200
|
+
if (response.status !== 200 && response.status !== 202) {
|
|
1201
|
+
throw new ExecutionError(`Starting turn ${turn.turnId} failed with ${response.status}: ${await response.text()}`);
|
|
1202
|
+
}
|
|
1203
|
+
await response.body?.cancel();
|
|
1204
|
+
yield* this.events(sandboxId, turn.turnId, options);
|
|
1205
|
+
}
|
|
1206
|
+
/**
|
|
1207
|
+
* Runs a Pi turn to its end and returns its final assistant text, or null when it had none.
|
|
1208
|
+
* Throws `ExecutionError` when the turn did not complete or its model did not stop on its own.
|
|
1209
|
+
* Running a turn again with the same `turnId` replays its records from the start.
|
|
1210
|
+
*/
|
|
1211
|
+
async run(sandboxId, turn, options = {}) {
|
|
1212
|
+
const { onRecord, ...streamOptions } = options;
|
|
1213
|
+
const records = [];
|
|
1214
|
+
for await (const record of this.prompt(sandboxId, turn, streamOptions)) {
|
|
1215
|
+
records.push(record);
|
|
1216
|
+
await onRecord?.(record);
|
|
1217
|
+
}
|
|
1218
|
+
options.signal?.throwIfAborted();
|
|
1219
|
+
const result = getPiTurnResult(records);
|
|
1220
|
+
if (!result.completed) throw new ExecutionError(`Turn ${turn.turnId} did not finish: ${result.error}`);
|
|
1221
|
+
return result.text;
|
|
1222
|
+
}
|
|
1223
|
+
/**
|
|
1224
|
+
* Streams a turn's records after `options.after` until its `end` record, reconnecting when
|
|
1225
|
+
* the connection drops. Throws `TurnLostError` when the runtime no longer has the turn.
|
|
1226
|
+
*/
|
|
1227
|
+
async *events(sandboxId, turnId, options = {}) {
|
|
1228
|
+
let last = options.after ?? -1;
|
|
1229
|
+
const reconnectTimeoutMs = options.reconnectTimeoutMs ?? DEFAULT_RECONNECT_TIMEOUT_MS;
|
|
1230
|
+
let failingSince;
|
|
1231
|
+
let attempt = 0;
|
|
1232
|
+
while (true) {
|
|
1233
|
+
let lastError;
|
|
1234
|
+
const stalled = new AbortController();
|
|
1235
|
+
let watchdog;
|
|
1236
|
+
const armWatchdog = () => {
|
|
1237
|
+
clearTimeout(watchdog);
|
|
1238
|
+
const budget = failingSince === void 0 ? reconnectTimeoutMs : Math.max(0, failingSince + reconnectTimeoutMs - Date.now());
|
|
1239
|
+
watchdog = setTimeout(() => stalled.abort(new Error(`Turn stream sent nothing for ${budget}ms.`)), budget);
|
|
1240
|
+
};
|
|
1241
|
+
armWatchdog();
|
|
1242
|
+
try {
|
|
1243
|
+
const response = await this.request(
|
|
1244
|
+
sandboxId,
|
|
1245
|
+
"GET",
|
|
1246
|
+
`/turns/${encodeURIComponent(turnId)}/events?after=${last}`,
|
|
1247
|
+
void 0,
|
|
1248
|
+
options.signal ? AbortSignal.any([options.signal, stalled.signal]) : stalled.signal,
|
|
1249
|
+
{ stream: true }
|
|
1250
|
+
);
|
|
1251
|
+
if (response.status === 404) {
|
|
1252
|
+
await response.body?.cancel();
|
|
1253
|
+
throw new TurnLostError(`Sandbox ${sandboxId} has no turn ${turnId}.`);
|
|
1254
|
+
}
|
|
1255
|
+
if (!response.ok || !response.body) {
|
|
1256
|
+
await response.body?.cancel();
|
|
1257
|
+
throw new Error(`Turn stream returned ${response.status}.`);
|
|
1258
|
+
}
|
|
1259
|
+
try {
|
|
1260
|
+
const onChunk = () => {
|
|
1261
|
+
failingSince = void 0;
|
|
1262
|
+
armWatchdog();
|
|
1263
|
+
};
|
|
1264
|
+
for await (const frame of decodeSseStream(textChunks(response.body, onChunk))) {
|
|
1265
|
+
let record;
|
|
1266
|
+
try {
|
|
1267
|
+
record = parseTurnRecord(frame);
|
|
1268
|
+
} catch (error) {
|
|
1269
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1270
|
+
throw new ExecutionError(`Sandbox ${sandboxId} sent an invalid record for turn ${turnId}: ${message}`);
|
|
1271
|
+
}
|
|
1272
|
+
if (record.seq <= last) {
|
|
1273
|
+
if (record.type === "end") return;
|
|
1274
|
+
continue;
|
|
1275
|
+
}
|
|
1276
|
+
last = record.seq;
|
|
1277
|
+
failingSince = void 0;
|
|
1278
|
+
attempt = 0;
|
|
1279
|
+
clearTimeout(watchdog);
|
|
1280
|
+
yield record;
|
|
1281
|
+
armWatchdog();
|
|
1282
|
+
if (record.type === "end") return;
|
|
1283
|
+
}
|
|
1284
|
+
} catch (error) {
|
|
1285
|
+
if (error instanceof Error && error.message.startsWith("Malformed SSE data frame")) {
|
|
1286
|
+
throw new ExecutionError(`Sandbox ${sandboxId} sent a malformed frame for turn ${turnId}: ${error.message}`);
|
|
1287
|
+
}
|
|
1288
|
+
if (!(error instanceof IncompleteSseFrameError)) throw error;
|
|
1289
|
+
}
|
|
1290
|
+
lastError = new Error("Turn stream ended before the turn did.");
|
|
1291
|
+
} catch (error) {
|
|
1292
|
+
if (error instanceof TurnLostError || error instanceof ExecutionError) throw error;
|
|
1293
|
+
if (options.signal?.aborted) throw abortError(options.signal);
|
|
1294
|
+
if (error instanceof EndpointRejectedError) this.endpoints.delete(sandboxId);
|
|
1295
|
+
lastError = stalled.signal.aborted ? stalled.signal.reason : error;
|
|
1296
|
+
} finally {
|
|
1297
|
+
clearTimeout(watchdog);
|
|
1298
|
+
}
|
|
1299
|
+
failingSince ??= Date.now();
|
|
1300
|
+
if (Date.now() - failingSince > reconnectTimeoutMs) {
|
|
1301
|
+
const message = lastError instanceof Error ? lastError.message : String(lastError);
|
|
1302
|
+
throw new ExecutionError(`Lost the stream of turn ${turnId} for over ${reconnectTimeoutMs}ms: ${message}`);
|
|
1303
|
+
}
|
|
1304
|
+
attempt += 1;
|
|
1305
|
+
await delay2(Math.min(RECONNECT_MAX_DELAY_MS, RECONNECT_MIN_DELAY_MS * 2 ** (attempt - 1)), options.signal);
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
/** Asks the runtime to stop the turn; its stream then ends with an `aborted` record. */
|
|
1309
|
+
async abort(sandboxId, turnId, signal) {
|
|
1310
|
+
const response = await this.request(sandboxId, "POST", `/turns/${encodeURIComponent(turnId)}/abort`, void 0, signal);
|
|
1311
|
+
await response.body?.cancel();
|
|
1312
|
+
if (response.status !== 202 && response.status !== 404) {
|
|
1313
|
+
throw new ExecutionError(`Aborting turn ${turnId} failed with ${response.status}.`);
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
async health(sandboxId, signal) {
|
|
1317
|
+
const response = await this.request(sandboxId, "GET", "/health", void 0, signal);
|
|
1318
|
+
if (!response.ok) throw new ExecutionError(`Health check of sandbox ${sandboxId} returned ${response.status}.`);
|
|
1319
|
+
return parseTurnHealth(await response.json());
|
|
1320
|
+
}
|
|
1321
|
+
/** Waits until no turn runs, for example before reading files a turn writes. */
|
|
1322
|
+
async waitForIdle(sandboxId, options = {}) {
|
|
1323
|
+
const deadline = Date.now() + (options.timeoutMs ?? 6e4);
|
|
1324
|
+
while (true) {
|
|
1325
|
+
try {
|
|
1326
|
+
if (!(await this.health(sandboxId, untilDeadline(deadline, options.signal))).busy) return;
|
|
1327
|
+
} catch (error) {
|
|
1328
|
+
if (options.signal?.aborted) throw error;
|
|
1329
|
+
}
|
|
1330
|
+
if (Date.now() > deadline) throw new RuntimeBusyError(`Sandbox ${sandboxId} did not become idle.`);
|
|
1331
|
+
await delay2(HEALTH_POLL_INTERVAL_MS, options.signal);
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
/**
|
|
1335
|
+
* Deletes the sandbox without starting it. One that is already gone counts as deleted; any other
|
|
1336
|
+
* failure throws, so cleanup can be retried, since a Daytona sandbox need not expire on its own.
|
|
1337
|
+
*/
|
|
1338
|
+
async kill(sandboxId) {
|
|
1339
|
+
this.endpoints.delete(sandboxId);
|
|
1340
|
+
const { sandbox } = this.options;
|
|
1341
|
+
if (sandbox.provider === "modal") {
|
|
1342
|
+
await destroyProviderSandbox({
|
|
1343
|
+
provider: "modal",
|
|
1344
|
+
sandboxId,
|
|
1345
|
+
...sandbox.environment ? { environment: sandbox.environment } : {}
|
|
1346
|
+
});
|
|
1347
|
+
return;
|
|
1348
|
+
}
|
|
1349
|
+
await destroyProviderSandbox({ provider: sandbox.provider, sandboxId, ...sandbox.apiKey ? { apiKey: sandbox.apiKey } : {} });
|
|
1350
|
+
}
|
|
1351
|
+
/** File and command access to a sandbox, for staging inputs and reading results. */
|
|
1352
|
+
sandbox(sandboxId) {
|
|
1353
|
+
const { sandbox } = this.options;
|
|
1354
|
+
if (sandbox.provider === "modal") {
|
|
1355
|
+
return SandboxClient.connect({
|
|
1356
|
+
provider: "modal",
|
|
1357
|
+
sandboxId,
|
|
1358
|
+
...sandbox.environment ? { environment: sandbox.environment } : {}
|
|
1359
|
+
});
|
|
1360
|
+
}
|
|
1361
|
+
if (sandbox.provider === "e2b") {
|
|
1362
|
+
return SandboxClient.connect({
|
|
1363
|
+
provider: "e2b",
|
|
1364
|
+
sandboxId,
|
|
1365
|
+
...sandbox.apiKey ? { apiKey: sandbox.apiKey } : {},
|
|
1366
|
+
...sandbox.timeoutMs === void 0 ? {} : { timeoutMs: sandbox.timeoutMs }
|
|
1367
|
+
});
|
|
1368
|
+
}
|
|
1369
|
+
return SandboxClient.connect({ provider: "daytona", sandboxId, ...sandbox.apiKey ? { apiKey: sandbox.apiKey } : {} });
|
|
1370
|
+
}
|
|
1371
|
+
/**
|
|
1372
|
+
* Deletes this agent's Daytona snapshots or E2B templates except the newest `keep` and the
|
|
1373
|
+
* current one. Returns the names it deleted.
|
|
1374
|
+
*/
|
|
1375
|
+
async gc(options = {}) {
|
|
1376
|
+
const keep = options.keep ?? 3;
|
|
1377
|
+
if (!Number.isInteger(keep) || keep < 0) throw new ConfigurationError("gc keep must be a non-negative integer.");
|
|
1378
|
+
const { sandbox } = this.options;
|
|
1379
|
+
if (sandbox.provider === "modal") return [];
|
|
1380
|
+
const ownName = new RegExp(`^${ARTIFACT_PREFIX}${this.name}-[0-9a-f]{16}$`, "u");
|
|
1381
|
+
const protectedNames = /* @__PURE__ */ new Set([this.artifactName, ...options.alsoKeep ?? []]);
|
|
1382
|
+
const artifacts = sandbox.provider === "daytona" ? await this.listDaytonaSnapshots(sandbox, ownName) : await this.listE2bTemplates(sandbox, ownName);
|
|
1383
|
+
const stale = artifacts.sort((left, right) => right.createdAt - left.createdAt).filter((artifact) => !protectedNames.has(artifact.name)).slice(Math.max(0, keep - artifacts.filter((artifact) => protectedNames.has(artifact.name)).length));
|
|
1384
|
+
for (const artifact of stale) await artifact.delete();
|
|
1385
|
+
return stale.map((artifact) => artifact.name);
|
|
1386
|
+
}
|
|
1387
|
+
createSandbox(envs) {
|
|
1388
|
+
const { sandbox } = this.options;
|
|
1389
|
+
if (sandbox.provider === "modal") {
|
|
1390
|
+
const { provider: _provider, ...modal } = sandbox;
|
|
1391
|
+
return SandboxClient.create({ provider: "modal", ...modal, template: this.image, command: this.command, envs });
|
|
1392
|
+
}
|
|
1393
|
+
if (sandbox.provider === "daytona") {
|
|
1394
|
+
const { resources: _resources, ...daytona } = sandbox;
|
|
1395
|
+
return SandboxClient.create({ ...daytona, template: this.artifactName, envs });
|
|
1396
|
+
}
|
|
1397
|
+
const { cpuCount: _cpuCount, memoryMB: _memoryMB, registry: _registry, ...e2b } = sandbox;
|
|
1398
|
+
return SandboxClient.create({ ...e2b, template: this.artifactName, envs, allowPublicTraffic: false });
|
|
1399
|
+
}
|
|
1400
|
+
// An E2B template's start command runs once at build time, without each sandbox's environment.
|
|
1401
|
+
async startE2bRuntime(sandbox, sandboxId, envs) {
|
|
1402
|
+
const { Sandbox } = await import("e2b");
|
|
1403
|
+
const apiKey = sandbox.apiKey ?? process.env.E2B_API_KEY;
|
|
1404
|
+
const e2bSandbox = await Sandbox.connect(sandboxId, {
|
|
1405
|
+
...apiKey ? { apiKey } : {},
|
|
1406
|
+
...sandbox.timeoutMs === void 0 ? {} : { timeoutMs: sandbox.timeoutMs }
|
|
1407
|
+
});
|
|
1408
|
+
const command = await e2bSandbox.commands.run(this.command.map(shellQuote).join(" "), { background: true, envs, timeoutMs: 0 });
|
|
1409
|
+
await command.disconnect();
|
|
1410
|
+
}
|
|
1411
|
+
async waitForRuntime(sandboxId, signal) {
|
|
1412
|
+
const timeoutMs = this.options.startTimeoutMs ?? DEFAULT_START_TIMEOUT_MS;
|
|
1413
|
+
const deadline = Date.now() + timeoutMs;
|
|
1414
|
+
let lastError;
|
|
1415
|
+
while (Date.now() < deadline) {
|
|
1416
|
+
try {
|
|
1417
|
+
const health = await this.health(sandboxId, untilDeadline(deadline, signal));
|
|
1418
|
+
if (health.protocolVersion !== TURN_PROTOCOL_VERSION) {
|
|
1419
|
+
throw new DeploymentError(
|
|
1420
|
+
`Sandbox runtime speaks protocol ${health.protocolVersion}; this host speaks ${TURN_PROTOCOL_VERSION}.`
|
|
1421
|
+
);
|
|
1422
|
+
}
|
|
1423
|
+
return;
|
|
1424
|
+
} catch (error) {
|
|
1425
|
+
if (error instanceof DeploymentError || signal?.aborted) throw error;
|
|
1426
|
+
lastError = error;
|
|
1427
|
+
}
|
|
1428
|
+
await delay2(HEALTH_POLL_INTERVAL_MS, signal);
|
|
1429
|
+
}
|
|
1430
|
+
const message = lastError instanceof Error ? lastError.message : String(lastError);
|
|
1431
|
+
throw new DeploymentError(`Runtime in sandbox ${sandboxId} did not answer within ${timeoutMs}ms: ${message}`);
|
|
1432
|
+
}
|
|
1433
|
+
endpoint(sandboxId) {
|
|
1434
|
+
let endpoint = this.endpoints.get(sandboxId);
|
|
1435
|
+
if (!endpoint) {
|
|
1436
|
+
endpoint = this.sandbox(sandboxId).then((sandbox) => sandbox.getServerEndpoint(this.port));
|
|
1437
|
+
endpoint.catch(() => this.endpoints.delete(sandboxId));
|
|
1438
|
+
this.endpoints.set(sandboxId, endpoint);
|
|
1439
|
+
}
|
|
1440
|
+
return endpoint;
|
|
1441
|
+
}
|
|
1442
|
+
async request(sandboxId, method, path2, body, signal, options = {}) {
|
|
1443
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
1444
|
+
const endpoint = await untilAborted(() => this.endpoint(sandboxId), signal);
|
|
1445
|
+
const url = new URL(`${endpoint.url}${path2}`);
|
|
1446
|
+
for (const [name, value] of Object.entries(endpoint.query)) url.searchParams.set(name, value);
|
|
1447
|
+
const timeout = options.stream ? void 0 : AbortSignal.timeout(REQUEST_TIMEOUT_MS);
|
|
1448
|
+
const signals = [signal, timeout].filter((value) => value !== void 0);
|
|
1449
|
+
const response = await fetch(url, {
|
|
1450
|
+
method,
|
|
1451
|
+
headers: {
|
|
1452
|
+
...endpoint.headers,
|
|
1453
|
+
...body === void 0 ? {} : { "content-type": "application/json" },
|
|
1454
|
+
...options.stream ? { accept: "text/event-stream" } : {}
|
|
1455
|
+
},
|
|
1456
|
+
...body === void 0 ? {} : { body: JSON.stringify(body) },
|
|
1457
|
+
...signals.length ? { signal: AbortSignal.any(signals) } : {}
|
|
1458
|
+
});
|
|
1459
|
+
if (response.status === 401 || response.status === 403) {
|
|
1460
|
+
await response.body?.cancel();
|
|
1461
|
+
this.endpoints.delete(sandboxId);
|
|
1462
|
+
if (attempt === 0) continue;
|
|
1463
|
+
throw new EndpointRejectedError(`Sandbox ${sandboxId} rejected its endpoint credentials (${response.status}).`);
|
|
1464
|
+
}
|
|
1465
|
+
return response;
|
|
1466
|
+
}
|
|
1467
|
+
}
|
|
1468
|
+
async prepareDaytonaSnapshot(sandbox, options) {
|
|
1469
|
+
const { Daytona, DaytonaNotFoundError } = await import("@daytona/sdk");
|
|
1470
|
+
const daytona = new Daytona(sandbox.apiKey ? { apiKey: sandbox.apiKey } : {});
|
|
1471
|
+
const name = this.artifactName;
|
|
1472
|
+
const deadline = Date.now() + (this.options.prepareTimeoutMs ?? DEFAULT_PREPARE_TIMEOUT_MS);
|
|
1473
|
+
const find = () => untilAborted(() => daytona.snapshot.get(name), options.signal).catch((error) => {
|
|
1474
|
+
if (error instanceof DaytonaNotFoundError) return void 0;
|
|
1475
|
+
throw error;
|
|
1476
|
+
});
|
|
1477
|
+
const isFailed = (found) => found.state === "error" || found.state === "build_failed";
|
|
1478
|
+
const isGoing = (found) => isFailed(found) || found.state === "removing";
|
|
1479
|
+
let snapshot = await find();
|
|
1480
|
+
let replaced;
|
|
1481
|
+
if (snapshot && snapshot.state !== "removing" && (isFailed(snapshot) || options.refresh)) {
|
|
1482
|
+
const old = snapshot;
|
|
1483
|
+
replaced = old;
|
|
1484
|
+
await untilAborted(() => daytona.snapshot.delete(old), options.signal).catch((error) => {
|
|
1485
|
+
if (!(error instanceof DaytonaNotFoundError)) throw error;
|
|
1486
|
+
});
|
|
1487
|
+
}
|
|
1488
|
+
while (snapshot && (isGoing(snapshot) || replaced !== void 0 && snapshot.id === replaced.id)) {
|
|
1489
|
+
await delay2(1e3, options.signal);
|
|
1490
|
+
snapshot = await find();
|
|
1491
|
+
}
|
|
1492
|
+
if (!snapshot) {
|
|
1493
|
+
try {
|
|
1494
|
+
snapshot = await untilAborted(() => daytona.snapshot.create(
|
|
1495
|
+
{
|
|
1496
|
+
name,
|
|
1497
|
+
image: this.image,
|
|
1498
|
+
entrypoint: this.command,
|
|
1499
|
+
...sandbox.resources ? { resources: sandbox.resources } : {}
|
|
1500
|
+
},
|
|
1501
|
+
{
|
|
1502
|
+
timeout: Math.ceil((deadline - Date.now()) / 1e3),
|
|
1503
|
+
...options.onLog ? { onLogs: options.onLog } : {}
|
|
1504
|
+
}
|
|
1505
|
+
), options.signal);
|
|
1506
|
+
} catch (error) {
|
|
1507
|
+
if (options.signal.aborted) throw error;
|
|
1508
|
+
snapshot = await find();
|
|
1509
|
+
if (!snapshot) throw error;
|
|
1510
|
+
}
|
|
1511
|
+
}
|
|
1512
|
+
while (true) {
|
|
1513
|
+
if (snapshot.state === "active") return;
|
|
1514
|
+
if (snapshot.state === "inactive") {
|
|
1515
|
+
const inactive = snapshot;
|
|
1516
|
+
snapshot = await untilAborted(() => daytona.snapshot.activate(inactive), options.signal);
|
|
1517
|
+
continue;
|
|
1518
|
+
}
|
|
1519
|
+
if (isFailed(snapshot)) {
|
|
1520
|
+
throw new DeploymentError(`Daytona snapshot ${name} is ${snapshot.state}: ${snapshot.errorReason ?? "no reason given"}`);
|
|
1521
|
+
}
|
|
1522
|
+
await delay2(2e3, options.signal);
|
|
1523
|
+
snapshot = await find() ?? snapshot;
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
async prepareE2bTemplate(sandbox, { signal, refresh, onLog }) {
|
|
1527
|
+
const { Template } = await import("e2b");
|
|
1528
|
+
const name = this.artifactName;
|
|
1529
|
+
const apiKey = sandbox.apiKey ?? process.env.E2B_API_KEY;
|
|
1530
|
+
const connection = { ...apiKey ? { apiKey } : {}, signal };
|
|
1531
|
+
const timeoutMs = this.options.prepareTimeoutMs ?? DEFAULT_PREPARE_TIMEOUT_MS;
|
|
1532
|
+
const waitingGraceMs = Math.min(6e4, timeoutMs / 4);
|
|
1533
|
+
const pollMs = Math.min(2e3, waitingGraceMs / 4);
|
|
1534
|
+
let waitingSince;
|
|
1535
|
+
while (!refresh) {
|
|
1536
|
+
const { templates } = await this.e2bTemplates(sandbox, signal);
|
|
1537
|
+
const status = templates.find((template2) => [...template2.names ?? [], ...template2.aliases ?? []].includes(name))?.buildStatus;
|
|
1538
|
+
if (status === "ready") return;
|
|
1539
|
+
if (status === "waiting") {
|
|
1540
|
+
waitingSince ??= Date.now();
|
|
1541
|
+
if (Date.now() - waitingSince > waitingGraceMs) break;
|
|
1542
|
+
} else if (status !== "building") {
|
|
1543
|
+
break;
|
|
1544
|
+
}
|
|
1545
|
+
await delay2(pollMs, signal);
|
|
1546
|
+
}
|
|
1547
|
+
const template = Template().fromImage(
|
|
1548
|
+
this.image,
|
|
1549
|
+
...sandbox.registry ? [sandbox.registry] : []
|
|
1550
|
+
);
|
|
1551
|
+
await Template.build(template, name, {
|
|
1552
|
+
...connection,
|
|
1553
|
+
...sandbox.cpuCount === void 0 ? {} : { cpuCount: sandbox.cpuCount },
|
|
1554
|
+
...sandbox.memoryMB === void 0 ? {} : { memoryMB: sandbox.memoryMB },
|
|
1555
|
+
...onLog ? { onBuildLogs: (entry) => onLog(entry.toString()) } : {}
|
|
1556
|
+
});
|
|
1557
|
+
}
|
|
1558
|
+
async listDaytonaSnapshots(sandbox, ownName) {
|
|
1559
|
+
const { Daytona } = await import("@daytona/sdk");
|
|
1560
|
+
const daytona = new Daytona(sandbox.apiKey ? { apiKey: sandbox.apiKey } : {});
|
|
1561
|
+
const artifacts = [];
|
|
1562
|
+
for (let page = 1; ; page += 1) {
|
|
1563
|
+
const result = await daytona.snapshot.list({ page, limit: 100 });
|
|
1564
|
+
for (const snapshot of result.items) {
|
|
1565
|
+
if (!ownName.test(snapshot.name)) continue;
|
|
1566
|
+
artifacts.push({
|
|
1567
|
+
name: snapshot.name,
|
|
1568
|
+
createdAt: new Date(snapshot.createdAt).getTime(),
|
|
1569
|
+
delete: () => daytona.snapshot.delete(snapshot)
|
|
1570
|
+
});
|
|
1571
|
+
}
|
|
1572
|
+
if (page >= result.totalPages) return artifacts;
|
|
1573
|
+
}
|
|
1574
|
+
}
|
|
1575
|
+
async e2bTemplates(sandbox, signal) {
|
|
1576
|
+
const { ApiClient, ConnectionConfig } = await import("e2b");
|
|
1577
|
+
const apiKey = sandbox.apiKey ?? process.env.E2B_API_KEY;
|
|
1578
|
+
const client = new ApiClient(new ConnectionConfig(apiKey ? { apiKey } : {}));
|
|
1579
|
+
const { data, error } = await client.api.GET("/templates", signal ? { signal } : {});
|
|
1580
|
+
if (error || !data) throw new ExecutionError(`Listing E2B templates failed: ${JSON.stringify(error)}`);
|
|
1581
|
+
return { client, templates: data };
|
|
1582
|
+
}
|
|
1583
|
+
async listE2bTemplates(sandbox, ownName) {
|
|
1584
|
+
const { client, templates } = await this.e2bTemplates(sandbox);
|
|
1585
|
+
return templates.flatMap((template) => {
|
|
1586
|
+
const name = [...template.names ?? [], ...template.aliases ?? []].find((value) => ownName.test(value));
|
|
1587
|
+
if (!name) return [];
|
|
1588
|
+
return [{
|
|
1589
|
+
name,
|
|
1590
|
+
createdAt: new Date(template.createdAt).getTime(),
|
|
1591
|
+
delete: async () => {
|
|
1592
|
+
const result = await client.api.DELETE("/templates/{templateID}", {
|
|
1593
|
+
params: { path: { templateID: template.templateID } }
|
|
1594
|
+
});
|
|
1595
|
+
if (result.error) throw new ExecutionError(`Deleting E2B template ${name} failed: ${JSON.stringify(result.error)}`);
|
|
1596
|
+
}
|
|
1597
|
+
}];
|
|
1598
|
+
});
|
|
1599
|
+
}
|
|
1600
|
+
};
|
|
1601
|
+
|
|
1602
|
+
// src/braintrust.ts
|
|
1603
|
+
var API_KEY = "BRAINTRUST_API_KEY";
|
|
1604
|
+
var PROJECT_NAME = "BRAINTRUST_PROJECT_NAME";
|
|
1605
|
+
var FLUSH_TIMEOUT_MS = 1e4;
|
|
1606
|
+
var BRAINTRUST_PACKAGE = "braintrust";
|
|
1607
|
+
var BRAINTRUST_VERSIONS = ">=3.44.0 <4.0.0";
|
|
1608
|
+
function isSupportedBraintrustVersion(version) {
|
|
1609
|
+
const [major, minor = 0] = version.split(".").map(Number);
|
|
1610
|
+
return major === 3 && minor >= 44;
|
|
1611
|
+
}
|
|
1612
|
+
var warn = (message) => console.warn(`neckbeard: ${message}`);
|
|
1613
|
+
var errorText = (error) => error instanceof Error ? error.message : String(error);
|
|
1614
|
+
function readBraintrustSettings(env, where) {
|
|
1615
|
+
const apiKey = env[API_KEY]?.trim();
|
|
1616
|
+
const projectName = env[PROJECT_NAME]?.trim();
|
|
1617
|
+
if (apiKey && projectName) return { apiKey, projectName };
|
|
1618
|
+
if (apiKey) warn(`Braintrust logging isn't configured ${where}: ${PROJECT_NAME} is not set.`);
|
|
1619
|
+
return void 0;
|
|
1620
|
+
}
|
|
1621
|
+
async function startBraintrust({ apiKey, projectName }) {
|
|
1622
|
+
const notTracing = "Braintrust tracing is off in the sandbox";
|
|
1623
|
+
let sdk;
|
|
1624
|
+
try {
|
|
1625
|
+
sdk = await import(
|
|
1626
|
+
/* webpackIgnore: true */
|
|
1627
|
+
BRAINTRUST_PACKAGE
|
|
1628
|
+
);
|
|
1629
|
+
} catch (error) {
|
|
1630
|
+
if (errorText(error).includes(`Cannot find package '${BRAINTRUST_PACKAGE}'`)) {
|
|
1631
|
+
warn(`${notTracing}: add ${BRAINTRUST_PACKAGE} ${BRAINTRUST_VERSIONS} to the agent's package's dependencies so the image has it.`);
|
|
1632
|
+
} else {
|
|
1633
|
+
warn(`${notTracing}: ${BRAINTRUST_PACKAGE} failed to load: ${errorText(error)}`);
|
|
1634
|
+
}
|
|
1635
|
+
return void 0;
|
|
1636
|
+
}
|
|
1637
|
+
if (typeof sdk.wrapPiCodingAgentSDK !== "function") {
|
|
1638
|
+
warn(`${notTracing}: its ${BRAINTRUST_PACKAGE} can't trace Pi; use ${BRAINTRUST_VERSIONS}.`);
|
|
1639
|
+
return void 0;
|
|
1640
|
+
}
|
|
1641
|
+
try {
|
|
1642
|
+
sdk.initLogger({ projectName, apiKey });
|
|
1643
|
+
} catch (error) {
|
|
1644
|
+
warn(`${notTracing}: ${errorText(error)}`);
|
|
1645
|
+
return void 0;
|
|
1646
|
+
}
|
|
1647
|
+
return {
|
|
1648
|
+
wrapPi: (pi) => sdk.wrapPiCodingAgentSDK(pi),
|
|
1649
|
+
async flush() {
|
|
1650
|
+
try {
|
|
1651
|
+
await withTimeout(sdk.flush(), FLUSH_TIMEOUT_MS, `not sent within ${FLUSH_TIMEOUT_MS / 1e3} seconds; it may arrive later`);
|
|
1652
|
+
} catch (error) {
|
|
1653
|
+
warn(`could not send the turn's Braintrust trace: ${errorText(error)}`);
|
|
1654
|
+
}
|
|
1655
|
+
}
|
|
1656
|
+
};
|
|
1657
|
+
}
|
|
1658
|
+
|
|
1659
|
+
// src/define.ts
|
|
1660
|
+
var SKILLS_DIR = "/app/.agents/skills";
|
|
1661
|
+
var IMAGE_TAG_ENV_VARS = [
|
|
1662
|
+
"NECKBEARD_IMAGE_TAG",
|
|
1663
|
+
"GITHUB_SHA",
|
|
1664
|
+
"CI_COMMIT_SHA",
|
|
1665
|
+
"BITBUCKET_COMMIT",
|
|
1666
|
+
"CODEBUILD_RESOLVED_SOURCE_VERSION",
|
|
1667
|
+
"BUILDKITE_COMMIT",
|
|
1668
|
+
"CIRCLE_SHA1",
|
|
1669
|
+
"CF_PAGES_COMMIT_SHA",
|
|
1670
|
+
"HEROKU_BUILD_COMMIT",
|
|
1671
|
+
"HEROKU_SLUG_COMMIT",
|
|
1672
|
+
"RAILWAY_GIT_COMMIT_SHA",
|
|
1673
|
+
"RENDER_GIT_COMMIT",
|
|
1674
|
+
"VERCEL_GIT_COMMIT_SHA",
|
|
1675
|
+
"SOURCE_VERSION",
|
|
1676
|
+
"GIT_COMMIT"
|
|
1677
|
+
];
|
|
1678
|
+
function resolveImageTag(env = process.env) {
|
|
1679
|
+
for (const name of IMAGE_TAG_ENV_VARS) {
|
|
1680
|
+
const value = env[name]?.trim();
|
|
1681
|
+
if (value && value !== name) return value;
|
|
1682
|
+
}
|
|
1683
|
+
return void 0;
|
|
1684
|
+
}
|
|
1685
|
+
var PI_PACKAGE = "@earendil-works/pi-coding-agent";
|
|
1686
|
+
var definedAgentMarker = /* @__PURE__ */ Symbol.for("agent-neckbeard.DefinedAgent");
|
|
1687
|
+
var DefinedAgent = class {
|
|
1688
|
+
constructor(definition) {
|
|
1689
|
+
this.definition = definition;
|
|
1690
|
+
if (!definition || typeof definition !== "object") throw new ConfigurationError("Agent definition must be an object.");
|
|
1691
|
+
if (typeof definition.name !== "string" || !/^[a-z0-9]+(-[a-z0-9]+)*$/u.test(definition.name)) {
|
|
1692
|
+
throw new ConfigurationError("Agent name must be lowercase letters, digits, and single dashes.");
|
|
1693
|
+
}
|
|
1694
|
+
if (Boolean(definition.pi) === Boolean(definition.createSession)) {
|
|
1695
|
+
throw new ConfigurationError(`Agent ${definition.name} needs exactly one of pi and createSession.`);
|
|
1696
|
+
}
|
|
1697
|
+
if (!definition.image && !definition.registry) {
|
|
1698
|
+
throw new ConfigurationError(`Agent ${definition.name} needs a registry or an image.`);
|
|
1699
|
+
}
|
|
1700
|
+
}
|
|
1701
|
+
[definedAgentMarker] = true;
|
|
1702
|
+
client;
|
|
1703
|
+
braintrustChecked = false;
|
|
1704
|
+
get name() {
|
|
1705
|
+
return this.definition.name;
|
|
1706
|
+
}
|
|
1707
|
+
/** The image this host runs: `image`, else `<registry>/<name>:<tag>` with the tag `resolveImageTag()` finds. */
|
|
1708
|
+
imageRef(tag = resolveImageTag()) {
|
|
1709
|
+
const { image, registry, name } = this.definition;
|
|
1710
|
+
if (image) return image;
|
|
1711
|
+
if (!tag) {
|
|
1712
|
+
throw new ConfigurationError(
|
|
1713
|
+
`Set NECKBEARD_IMAGE_TAG to choose agent ${name}'s image, or deploy from a platform that names the commit, such as RENDER_GIT_COMMIT.`
|
|
1714
|
+
);
|
|
1715
|
+
}
|
|
1716
|
+
return `${registry.replace(/\/+$/u, "")}/${name}:${tag}`;
|
|
1717
|
+
}
|
|
1718
|
+
/** The `Agent` for an image, by default the one this host runs. */
|
|
1719
|
+
forImage(image = this.imageRef()) {
|
|
1720
|
+
const { definition } = this;
|
|
1721
|
+
const sandbox = typeof definition.sandbox === "function" ? definition.sandbox() : definition.sandbox;
|
|
1722
|
+
const envs = typeof definition.envs === "function" ? definition.envs() : definition.envs;
|
|
1723
|
+
return new Agent({
|
|
1724
|
+
name: definition.name,
|
|
1725
|
+
image,
|
|
1726
|
+
sandbox,
|
|
1727
|
+
...envs ? { envs } : {},
|
|
1728
|
+
...definition.command ? { command: definition.command } : {},
|
|
1729
|
+
...definition.port === void 0 ? {} : { port: definition.port },
|
|
1730
|
+
...definition.startTimeoutMs === void 0 ? {} : { startTimeoutMs: definition.startTimeoutMs },
|
|
1731
|
+
...definition.prepareTimeoutMs === void 0 ? {} : { prepareTimeoutMs: definition.prepareTimeoutMs }
|
|
1732
|
+
});
|
|
1733
|
+
}
|
|
1734
|
+
get agent() {
|
|
1735
|
+
this.client ??= this.forImage();
|
|
1736
|
+
return this.client;
|
|
1737
|
+
}
|
|
1738
|
+
get artifactName() {
|
|
1739
|
+
return this.agent.artifactName;
|
|
1740
|
+
}
|
|
1741
|
+
prepare(options) {
|
|
1742
|
+
return this.agent.prepare(options);
|
|
1743
|
+
}
|
|
1744
|
+
start(options) {
|
|
1745
|
+
if (this.definition.pi && !this.braintrustChecked) {
|
|
1746
|
+
this.braintrustChecked = true;
|
|
1747
|
+
const envs = typeof this.definition.envs === "function" ? this.definition.envs() : this.definition.envs;
|
|
1748
|
+
readBraintrustSettings({ ...filterDefined(envs), ...filterDefined(options?.envs) }, `for agent ${this.name}'s sandboxes`);
|
|
1749
|
+
}
|
|
1750
|
+
return this.agent.start(options);
|
|
1751
|
+
}
|
|
1752
|
+
prompt(sandboxId, turn, options) {
|
|
1753
|
+
return this.agent.prompt(sandboxId, turn, options);
|
|
1754
|
+
}
|
|
1755
|
+
run(sandboxId, turn, options) {
|
|
1756
|
+
return this.agent.run(sandboxId, turn, options);
|
|
1757
|
+
}
|
|
1758
|
+
events(sandboxId, turnId, options) {
|
|
1759
|
+
return this.agent.events(sandboxId, turnId, options);
|
|
1760
|
+
}
|
|
1761
|
+
abort(sandboxId, turnId, signal) {
|
|
1762
|
+
return this.agent.abort(sandboxId, turnId, signal);
|
|
1763
|
+
}
|
|
1764
|
+
health(sandboxId, signal) {
|
|
1765
|
+
return this.agent.health(sandboxId, signal);
|
|
1766
|
+
}
|
|
1767
|
+
waitForIdle(sandboxId, options) {
|
|
1768
|
+
return this.agent.waitForIdle(sandboxId, options);
|
|
1769
|
+
}
|
|
1770
|
+
kill(sandboxId) {
|
|
1771
|
+
return this.agent.kill(sandboxId);
|
|
1772
|
+
}
|
|
1773
|
+
sandbox(sandboxId) {
|
|
1774
|
+
return this.agent.sandbox(sandboxId);
|
|
1775
|
+
}
|
|
1776
|
+
gc(options) {
|
|
1777
|
+
return this.agent.gc(options);
|
|
1778
|
+
}
|
|
1779
|
+
/** Where a persisted session's file is in a sandbox whose home is `homeDir`, as for copying it out and back. */
|
|
1780
|
+
sessionFilePath(homeDir, sessionId) {
|
|
1781
|
+
return path.posix.join(homeDir, "agent", ".pi", "sessions", `${sessionId}.jsonl`);
|
|
1782
|
+
}
|
|
1783
|
+
/** Serves the agent's session; the image's entry point, which `neckbeard build` generates, calls it. */
|
|
1784
|
+
serve(options = {}) {
|
|
1785
|
+
const { definition } = this;
|
|
1786
|
+
const { pi } = definition;
|
|
1787
|
+
return serve({
|
|
1788
|
+
createSession: pi ? () => createPiSession(pi) : definition.createSession,
|
|
1789
|
+
...definition.maxTurnDurationMs === void 0 ? {} : { maxTurnDurationMs: definition.maxTurnDurationMs },
|
|
1790
|
+
...definition.abortGraceMs === void 0 ? {} : { abortGraceMs: definition.abortGraceMs },
|
|
1791
|
+
...options
|
|
1792
|
+
});
|
|
1793
|
+
}
|
|
1794
|
+
};
|
|
1795
|
+
function defineAgent(definition) {
|
|
1796
|
+
return new DefinedAgent(definition);
|
|
1797
|
+
}
|
|
1798
|
+
function isDefinedAgent(value) {
|
|
1799
|
+
return typeof value === "object" && value !== null && definedAgentMarker in value;
|
|
1800
|
+
}
|
|
1801
|
+
async function createPiSession(config) {
|
|
1802
|
+
const home = os.homedir();
|
|
1803
|
+
const cwd = path.resolve(home, config.cwd ?? "workspace");
|
|
1804
|
+
await mkdir(cwd, { recursive: true });
|
|
1805
|
+
process.env.NECKBEARD_CWD = cwd;
|
|
1806
|
+
const agentDir = path.join(home, "agent", ".pi");
|
|
1807
|
+
const loaded = await import(
|
|
1808
|
+
/* webpackIgnore: true */
|
|
1809
|
+
PI_PACKAGE
|
|
1810
|
+
);
|
|
1811
|
+
const braintrustSettings = readBraintrustSettings(process.env, "in the sandbox");
|
|
1812
|
+
const braintrust = braintrustSettings && await startBraintrust(braintrustSettings);
|
|
1813
|
+
const pi = braintrust ? braintrust.wrapPi(loaded) : loaded;
|
|
1814
|
+
const modelRuntime = await pi.ModelRuntime.create({ modelsPath: null });
|
|
1815
|
+
const separator = config.model.indexOf("/");
|
|
1816
|
+
const model = separator > 0 ? modelRuntime.getModel(config.model.slice(0, separator), config.model.slice(separator + 1)) : void 0;
|
|
1817
|
+
if (!model) throw new ConfigurationError(`Pi has no model ${config.model}; name it as provider/model.`);
|
|
1818
|
+
const settingsManager = pi.SettingsManager.inMemory();
|
|
1819
|
+
const resourceLoader = new pi.DefaultResourceLoader({
|
|
1820
|
+
cwd,
|
|
1821
|
+
agentDir,
|
|
1822
|
+
settingsManager,
|
|
1823
|
+
additionalSkillPaths: [SKILLS_DIR],
|
|
1824
|
+
noSkills: true,
|
|
1825
|
+
noExtensions: true,
|
|
1826
|
+
noPromptTemplates: true,
|
|
1827
|
+
noContextFiles: true,
|
|
1828
|
+
systemPrompt: config.systemPrompt
|
|
1829
|
+
});
|
|
1830
|
+
await resourceLoader.reload();
|
|
1831
|
+
let sessionManager;
|
|
1832
|
+
if (config.persist) {
|
|
1833
|
+
const sessionId = process.env.NECKBEARD_SESSION_ID;
|
|
1834
|
+
if (!sessionId) throw new ConfigurationError("A persisted Pi session needs the sessionId passed to start().");
|
|
1835
|
+
const sessionFile = path.join(agentDir, "sessions", `${sessionId}.jsonl`);
|
|
1836
|
+
sessionManager = pi.SessionManager.open(sessionFile, path.dirname(sessionFile), cwd);
|
|
1837
|
+
} else {
|
|
1838
|
+
sessionManager = pi.SessionManager.inMemory(cwd);
|
|
1839
|
+
}
|
|
1840
|
+
const { session } = await pi.createAgentSession({
|
|
1841
|
+
cwd,
|
|
1842
|
+
agentDir,
|
|
1843
|
+
model,
|
|
1844
|
+
modelRuntime,
|
|
1845
|
+
resourceLoader,
|
|
1846
|
+
settingsManager,
|
|
1847
|
+
sessionManager,
|
|
1848
|
+
...config.thinkingLevel ? { thinkingLevel: config.thinkingLevel } : {},
|
|
1849
|
+
...config.tools ? { tools: config.tools } : {}
|
|
1850
|
+
});
|
|
1851
|
+
if (!braintrust) return session;
|
|
1852
|
+
return {
|
|
1853
|
+
subscribe: (listener) => session.subscribe(listener),
|
|
1854
|
+
prompt: (text) => session.prompt(text),
|
|
1855
|
+
abort: () => session.abort(),
|
|
1856
|
+
afterTurn: () => braintrust.flush()
|
|
1857
|
+
};
|
|
1858
|
+
}
|
|
1859
|
+
|
|
1860
|
+
// src/providers/docker.ts
|
|
1861
|
+
import { spawn } from "child_process";
|
|
1862
|
+
import { createServer } from "net";
|
|
1863
|
+
import { StringDecoder } from "string_decoder";
|
|
1864
|
+
var DOCKER_DEFAULT_TEMPLATE = "node:22-bookworm";
|
|
1865
|
+
var DOCKER_DEFAULT_TIMEOUT_MS = 60 * 60 * 1e3;
|
|
1866
|
+
var DOCKER_MANAGED_LABEL = "agent-neckbeard.managed";
|
|
1867
|
+
var DOCKER_HOME = "/root";
|
|
1868
|
+
var DOCKER_ENV_FILE = `${DOCKER_HOME}/.neckbeard-env`;
|
|
1869
|
+
var DOCKER_CONTROL_TIMEOUT_MS = 3e4;
|
|
1870
|
+
var DOCKER_FILE_TIMEOUT_MS = 3e5;
|
|
1871
|
+
var DOCKER_CREATE_TIMEOUT_MS = 10 * 60 * 1e3;
|
|
1872
|
+
var DOCKER_BOOTSTRAP_TIMEOUT_MS = 5 * 60 * 1e3;
|
|
1873
|
+
var DOCKER_ORPHAN_GRACE_SECONDS = 2;
|
|
1874
|
+
var REQUIRED_TOOLS = ["bash", "python3", "flock", "setsid", "timeout", "curl"];
|
|
1875
|
+
function validateDockerOptions(options, mode, failure) {
|
|
1876
|
+
validateProviderOptions("Docker", options, mode === "connect" ? ["sandboxId"] : [
|
|
1877
|
+
"template",
|
|
1878
|
+
"network",
|
|
1879
|
+
"platform",
|
|
1880
|
+
"timeoutMs",
|
|
1881
|
+
"cpu",
|
|
1882
|
+
"memoryMiB",
|
|
1883
|
+
...mode === "create" ? ["envs"] : []
|
|
1884
|
+
], failure);
|
|
1885
|
+
if (mode === "connect" && !("sandboxId" in options && options.sandboxId)) {
|
|
1886
|
+
throw failure("Docker sandboxId is required.");
|
|
1887
|
+
}
|
|
1888
|
+
}
|
|
1889
|
+
function exportLines(envs) {
|
|
1890
|
+
return Object.entries(envs ?? {}).filter((entry) => entry[1] !== void 0).map(([name, value]) => `export ${name}=${shellQuote(value)}
|
|
1891
|
+
`).join("");
|
|
1892
|
+
}
|
|
1893
|
+
var runDockerCli = (args, options) => new Promise((resolve2, reject) => {
|
|
1894
|
+
const child = spawn("docker", args, { stdio: ["pipe", "pipe", "pipe"] });
|
|
1895
|
+
const stdout = [];
|
|
1896
|
+
const stdoutDecoder = new StringDecoder("utf8");
|
|
1897
|
+
const stderrDecoder = new StringDecoder("utf8");
|
|
1898
|
+
let stderr = "";
|
|
1899
|
+
let settled = false;
|
|
1900
|
+
const timer = setTimeout(() => {
|
|
1901
|
+
child.kill("SIGKILL");
|
|
1902
|
+
settle(() => reject(new Error("Docker command request timed out; remote completion is unknown.")));
|
|
1903
|
+
}, options.timeoutMs);
|
|
1904
|
+
const settle = (callback) => {
|
|
1905
|
+
if (settled) return;
|
|
1906
|
+
settled = true;
|
|
1907
|
+
clearTimeout(timer);
|
|
1908
|
+
callback();
|
|
1909
|
+
};
|
|
1910
|
+
child.stdout.on("data", (chunk) => {
|
|
1911
|
+
stdout.push(chunk);
|
|
1912
|
+
if (options.onStdout) {
|
|
1913
|
+
const text = stdoutDecoder.write(chunk);
|
|
1914
|
+
if (text) options.onStdout(text);
|
|
1915
|
+
}
|
|
1916
|
+
});
|
|
1917
|
+
child.stderr.on("data", (chunk) => {
|
|
1918
|
+
const text = stderrDecoder.write(chunk);
|
|
1919
|
+
stderr += text;
|
|
1920
|
+
if (text) options.onStderr?.(text);
|
|
1921
|
+
});
|
|
1922
|
+
child.on("error", (error) => settle(() => reject(
|
|
1923
|
+
Reflect.get(error, "code") === "ENOENT" ? new Error("The Docker provider requires the `docker` CLI on PATH.") : error
|
|
1924
|
+
)));
|
|
1925
|
+
child.on("close", (code) => settle(() => resolve2({
|
|
1926
|
+
exitCode: code ?? 1,
|
|
1927
|
+
stdout: Buffer.concat(stdout),
|
|
1928
|
+
stderr
|
|
1929
|
+
})));
|
|
1930
|
+
child.stdin.on("error", () => void 0);
|
|
1931
|
+
child.stdin.end(options.input);
|
|
1932
|
+
});
|
|
1933
|
+
var tunnels = /* @__PURE__ */ new Map();
|
|
1934
|
+
function relaySource(port) {
|
|
1935
|
+
return [
|
|
1936
|
+
"import os,socket,threading",
|
|
1937
|
+
`s=socket.create_connection(("127.0.0.1",${port}))`,
|
|
1938
|
+
"def up():",
|
|
1939
|
+
" while True:",
|
|
1940
|
+
" d=os.read(0,65536)",
|
|
1941
|
+
" if not d: break",
|
|
1942
|
+
" s.sendall(d)",
|
|
1943
|
+
" try: s.shutdown(socket.SHUT_WR)",
|
|
1944
|
+
" except OSError: pass",
|
|
1945
|
+
"threading.Thread(target=up,daemon=True).start()",
|
|
1946
|
+
"while True:",
|
|
1947
|
+
" d=s.recv(65536)",
|
|
1948
|
+
" if not d: break",
|
|
1949
|
+
" while d: d=d[os.write(1,d):]"
|
|
1950
|
+
].join("\n");
|
|
1951
|
+
}
|
|
1952
|
+
function openTunnel(containerId, port) {
|
|
1953
|
+
const key = `${containerId}:${port}`;
|
|
1954
|
+
const existing = tunnels.get(key);
|
|
1955
|
+
if (existing) return existing;
|
|
1956
|
+
const tunnel = new Promise((resolve2, reject) => {
|
|
1957
|
+
const server = createServer((socket) => {
|
|
1958
|
+
const relay = spawn("docker", [
|
|
1959
|
+
"exec",
|
|
1960
|
+
"-i",
|
|
1961
|
+
"--user",
|
|
1962
|
+
"root",
|
|
1963
|
+
containerId,
|
|
1964
|
+
"python3",
|
|
1965
|
+
"-u",
|
|
1966
|
+
"-c",
|
|
1967
|
+
relaySource(port)
|
|
1968
|
+
], { stdio: ["pipe", "pipe", "ignore"] });
|
|
1969
|
+
socket.pipe(relay.stdin);
|
|
1970
|
+
relay.stdout.pipe(socket);
|
|
1971
|
+
relay.stdin.on("error", () => void 0);
|
|
1972
|
+
relay.on("error", () => socket.destroy());
|
|
1973
|
+
relay.on("close", () => socket.destroy());
|
|
1974
|
+
socket.on("error", () => relay.kill("SIGKILL"));
|
|
1975
|
+
socket.on("close", () => relay.kill("SIGKILL"));
|
|
1976
|
+
});
|
|
1977
|
+
server.once("error", reject);
|
|
1978
|
+
server.listen(0, "127.0.0.1", () => {
|
|
1979
|
+
server.unref();
|
|
1980
|
+
resolve2(server);
|
|
1981
|
+
});
|
|
1982
|
+
});
|
|
1983
|
+
tunnels.set(key, tunnel);
|
|
1984
|
+
tunnel.catch(() => tunnels.delete(key));
|
|
1985
|
+
return tunnel;
|
|
1986
|
+
}
|
|
1987
|
+
async function closeTunnels(containerId) {
|
|
1988
|
+
for (const [key, tunnel] of tunnels) {
|
|
1989
|
+
if (!key.startsWith(`${containerId}:`)) continue;
|
|
1990
|
+
tunnels.delete(key);
|
|
1991
|
+
await tunnel.then((server) => server.close(), () => void 0);
|
|
1992
|
+
}
|
|
1993
|
+
}
|
|
1994
|
+
var DockerSandboxHandle = class _DockerSandboxHandle {
|
|
1995
|
+
constructor(id, managed, failure, cli = runDockerCli) {
|
|
1996
|
+
this.id = id;
|
|
1997
|
+
this.managed = managed;
|
|
1998
|
+
this.failure = failure;
|
|
1999
|
+
this.cli = cli;
|
|
2000
|
+
this.detachedProcesses = new DetachedProcessController({
|
|
2001
|
+
provider: "docker",
|
|
2002
|
+
genericPayloadEnvironmentDefaults: { HOME: this.paths.homeDir },
|
|
2003
|
+
execute: async (command, options) => {
|
|
2004
|
+
try {
|
|
2005
|
+
return { state: "completed", result: await this.runCommand(command, {
|
|
2006
|
+
...options,
|
|
2007
|
+
timeoutMs: DETACHED_PROCESS_CONTROL_TIMEOUT_MS
|
|
2008
|
+
}) };
|
|
2009
|
+
} catch (error) {
|
|
2010
|
+
return { state: "failed", error };
|
|
2011
|
+
}
|
|
2012
|
+
},
|
|
2013
|
+
readLegacyLogs: async () => {
|
|
2014
|
+
throw failure("Docker requires a managed detached process handle.");
|
|
2015
|
+
},
|
|
2016
|
+
stopLegacy: async () => {
|
|
2017
|
+
throw failure("Docker requires a managed detached process handle.");
|
|
2018
|
+
},
|
|
2019
|
+
failure
|
|
2020
|
+
});
|
|
2021
|
+
}
|
|
2022
|
+
provider = "docker";
|
|
2023
|
+
paths = createProviderSandboxPaths("docker", DOCKER_HOME, DOCKER_HOME);
|
|
2024
|
+
detachedProcesses;
|
|
2025
|
+
static async create(options, failure, cli = runDockerCli) {
|
|
2026
|
+
const lifetimeSeconds = (options.timeoutMs ?? DOCKER_DEFAULT_TIMEOUT_MS) / 1e3;
|
|
2027
|
+
const created = await cli([
|
|
2028
|
+
"run",
|
|
2029
|
+
"--detach",
|
|
2030
|
+
"--rm",
|
|
2031
|
+
"--init",
|
|
2032
|
+
"--label",
|
|
2033
|
+
`${DOCKER_MANAGED_LABEL}=true`,
|
|
2034
|
+
"--user",
|
|
2035
|
+
"root",
|
|
2036
|
+
"--workdir",
|
|
2037
|
+
DOCKER_HOME,
|
|
2038
|
+
...options.network ? ["--network", options.network] : [],
|
|
2039
|
+
...options.platform ? ["--platform", options.platform] : [],
|
|
2040
|
+
...options.cpu === void 0 ? [] : ["--cpus", String(options.cpu)],
|
|
2041
|
+
...options.memoryMiB === void 0 ? [] : ["--memory", `${options.memoryMiB}m`],
|
|
2042
|
+
// No published ports: HTTP access goes through a loopback exec tunnel.
|
|
2043
|
+
"--entrypoint",
|
|
2044
|
+
"sleep",
|
|
2045
|
+
options.template ?? DOCKER_DEFAULT_TEMPLATE,
|
|
2046
|
+
String(lifetimeSeconds)
|
|
2047
|
+
], { timeoutMs: DOCKER_CREATE_TIMEOUT_MS });
|
|
2048
|
+
const id = created.stdout.toString("utf8").trim().split("\n").pop() ?? "";
|
|
2049
|
+
if (created.exitCode !== 0 || !/^[a-f0-9]{12,64}$/u.test(id)) {
|
|
2050
|
+
throw failure(`Failed to create Docker sandbox: ${created.stderr.trim() || "no container ID returned."}`);
|
|
2051
|
+
}
|
|
2052
|
+
const handle = new _DockerSandboxHandle(id, true, failure, cli);
|
|
2053
|
+
try {
|
|
2054
|
+
await handle.writeFile(DOCKER_ENV_FILE, exportLines(options.envs));
|
|
2055
|
+
await handle.ensureTools();
|
|
2056
|
+
await handle.control(
|
|
2057
|
+
"Docker pip configuration",
|
|
2058
|
+
'[ -e /etc/pip.conf ] || printf "[global]\\nbreak-system-packages = true\\n" > /etc/pip.conf'
|
|
2059
|
+
);
|
|
2060
|
+
return handle;
|
|
2061
|
+
} catch (error) {
|
|
2062
|
+
await handle.destroy().catch(() => void 0);
|
|
2063
|
+
throw error;
|
|
2064
|
+
}
|
|
2065
|
+
}
|
|
2066
|
+
static async connect(options, failure, cli = runDockerCli) {
|
|
2067
|
+
const inspected = await cli([
|
|
2068
|
+
"inspect",
|
|
2069
|
+
"--type",
|
|
2070
|
+
"container",
|
|
2071
|
+
"--format",
|
|
2072
|
+
`{{.State.Running}} {{index .Config.Labels "${DOCKER_MANAGED_LABEL}"}}`,
|
|
2073
|
+
options.sandboxId
|
|
2074
|
+
], { timeoutMs: DOCKER_CONTROL_TIMEOUT_MS });
|
|
2075
|
+
if (inspected.exitCode !== 0) throw failure("Docker sandbox was not found.");
|
|
2076
|
+
const [running, managed] = inspected.stdout.toString("utf8").trim().split(" ");
|
|
2077
|
+
if (running !== "true") throw failure("Docker sandbox is no longer running.");
|
|
2078
|
+
const handle = new _DockerSandboxHandle(options.sandboxId, managed === "true", failure, cli);
|
|
2079
|
+
await handle.ensureTools();
|
|
2080
|
+
return handle;
|
|
2081
|
+
}
|
|
2082
|
+
/** Installs the detached-process and deploy prerequisites only when the image lacks them. */
|
|
2083
|
+
async ensureTools() {
|
|
2084
|
+
await this.control(
|
|
2085
|
+
"Docker sandbox tool preparation",
|
|
2086
|
+
`command -v sudo >/dev/null || { printf '#!/bin/sh\\nwhile [ "\${1#-}" != "$1" ]; do shift; done\\nexec "$@"\\n' > /usr/local/bin/sudo && chmod +x /usr/local/bin/sudo; }; for tool in ${REQUIRED_TOOLS.join(" ")}; do command -v "$tool" >/dev/null || missing=1; done; [ -z "$missing" ] || { apt-get update && apt-get install -y --no-install-recommends bash python3 util-linux coreutils curl ca-certificates && rm -rf /var/lib/apt/lists/*; }`,
|
|
2087
|
+
[],
|
|
2088
|
+
void 0,
|
|
2089
|
+
DOCKER_BOOTSTRAP_TIMEOUT_MS
|
|
2090
|
+
);
|
|
2091
|
+
}
|
|
2092
|
+
async control(label, script, args = [], input, timeoutMs = DOCKER_CONTROL_TIMEOUT_MS) {
|
|
2093
|
+
const result = await this.cli(
|
|
2094
|
+
["exec", "-i", "--user", "root", this.id, "/bin/sh", "-c", script, "sh", ...args],
|
|
2095
|
+
{ input, timeoutMs }
|
|
2096
|
+
);
|
|
2097
|
+
if (result.exitCode !== 0) {
|
|
2098
|
+
throw this.failure(`${label} failed: ${result.stderr.trim() || `exit code ${result.exitCode}`}`);
|
|
2099
|
+
}
|
|
2100
|
+
return result;
|
|
2101
|
+
}
|
|
2102
|
+
async makeDir(path2) {
|
|
2103
|
+
await this.control("Docker directory creation", 'mkdir -p -- "$1"', [path2]);
|
|
2104
|
+
}
|
|
2105
|
+
async writeFile(path2, content) {
|
|
2106
|
+
const input = typeof content === "string" ? content : content instanceof ArrayBuffer ? new Uint8Array(content) : content;
|
|
2107
|
+
await this.control("Docker file write", 'mkdir -p -- "$(dirname -- "$1")" && cat > "$1"', [path2], input, DOCKER_FILE_TIMEOUT_MS);
|
|
2108
|
+
}
|
|
2109
|
+
async readFile(path2) {
|
|
2110
|
+
return (await this.control("Docker file read", 'cat -- "$1"', [path2], void 0, DOCKER_FILE_TIMEOUT_MS)).stdout.toString("utf8");
|
|
2111
|
+
}
|
|
2112
|
+
async readFileBytes(path2) {
|
|
2113
|
+
return new Uint8Array((await this.control("Docker file read", 'cat -- "$1"', [path2], void 0, DOCKER_FILE_TIMEOUT_MS)).stdout);
|
|
2114
|
+
}
|
|
2115
|
+
async runCommand(command, options) {
|
|
2116
|
+
validateProviderCommand("Docker", command, options);
|
|
2117
|
+
const deadlineSeconds = Math.ceil(options.timeoutMs / 1e3) + DOCKER_ORPHAN_GRACE_SECONDS;
|
|
2118
|
+
const script = `[ -f ${DOCKER_ENV_FILE} ] && . ${DOCKER_ENV_FILE}
|
|
2119
|
+
` + exportLines(options.envs) + `cd -- ${shellQuote(options.cwd ?? this.paths.workDir)} || exit 1
|
|
2120
|
+
exec timeout --kill-after=1 ${deadlineSeconds} /bin/bash --noprofile --norc -c ${shellQuote(command)} </dev/null
|
|
2121
|
+
`;
|
|
2122
|
+
const result = await this.cli(["exec", "-i", "--user", "root", this.id, "/bin/bash", "--noprofile", "--norc", "-s"], {
|
|
2123
|
+
input: script,
|
|
2124
|
+
timeoutMs: options.timeoutMs,
|
|
2125
|
+
onStdout: options.onStdout,
|
|
2126
|
+
onStderr: options.onStderr
|
|
2127
|
+
});
|
|
2128
|
+
return { stdout: result.stdout.toString("utf8"), stderr: result.stderr, exitCode: result.exitCode };
|
|
2129
|
+
}
|
|
2130
|
+
startDetachedCommand(command, options = {}) {
|
|
2131
|
+
return this.detachedProcesses.start(command, options);
|
|
2132
|
+
}
|
|
2133
|
+
readSessionLogs(command) {
|
|
2134
|
+
return this.detachedProcesses.readLogs(command);
|
|
2135
|
+
}
|
|
2136
|
+
stopSession(command) {
|
|
2137
|
+
return this.detachedProcesses.stop(command);
|
|
2138
|
+
}
|
|
2139
|
+
disposeSessionArtifacts(command) {
|
|
2140
|
+
return this.detachedProcesses.dispose(command);
|
|
2141
|
+
}
|
|
2142
|
+
async getServerEndpoint(port) {
|
|
2143
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
2144
|
+
throw new Error("Docker endpoint port must be between 1 and 65535.");
|
|
2145
|
+
}
|
|
2146
|
+
const address = (await openTunnel(this.id, port)).address();
|
|
2147
|
+
if (!address || typeof address === "string") throw new Error("Docker tunnel has no loopback address.");
|
|
2148
|
+
return { url: `http://127.0.0.1:${address.port}` };
|
|
2149
|
+
}
|
|
2150
|
+
/** Removes containers this provider created; containers it attached to are left to their owner. */
|
|
2151
|
+
async destroy() {
|
|
2152
|
+
if (!this.managed) return;
|
|
2153
|
+
await closeTunnels(this.id);
|
|
2154
|
+
const result = await this.cli(["rm", "--force", "--volumes", this.id], { timeoutMs: DOCKER_CONTROL_TIMEOUT_MS });
|
|
2155
|
+
if (result.exitCode !== 0 && !/no such container|is already in progress/iu.test(result.stderr)) {
|
|
2156
|
+
throw this.failure(`Failed to remove Docker sandbox: ${result.stderr.trim()}`);
|
|
2157
|
+
}
|
|
2158
|
+
}
|
|
2159
|
+
};
|
|
2160
|
+
|
|
2161
|
+
// src/index.ts
|
|
2162
|
+
function readPackageJson(path2) {
|
|
2163
|
+
return JSON.parse(readFileSync(path2, "utf8"));
|
|
2164
|
+
}
|
|
2165
|
+
var getEsbuild = () => import("esbuild");
|
|
2166
|
+
var getE2b = () => import("e2b");
|
|
2167
|
+
var getDaytona = () => import("@daytona/sdk");
|
|
2168
|
+
var DEFAULT_MAX_DURATION = 300;
|
|
2169
|
+
var SANDBOX_COMMAND_TIMEOUT_MS2 = 3e5;
|
|
2170
|
+
var QUICK_COMMAND_TIMEOUT_MS2 = 3e4;
|
|
2171
|
+
var DAYTONA_CREATE_TIMEOUT_SEC = 120;
|
|
2172
|
+
var NODE_TARGET = "node20";
|
|
2173
|
+
var DEFAULT_EXTERNALS = ["@anthropic-ai/claude-agent-sdk"];
|
|
2174
|
+
var NECKBEARD_PACKAGE_NAME = "agent-neckbeard";
|
|
2175
|
+
var NECKBEARD_SANDBOX_RUNTIME_ENV = "AGENT_NECKBEARD_SANDBOX_RUNTIME";
|
|
2176
|
+
var SANDBOX_PLATFORM = process.env.NECKBEARD_SANDBOX_PLATFORM ?? "linux";
|
|
2177
|
+
var SANDBOX_ARCH = process.env.NECKBEARD_SANDBOX_ARCH ?? "x64";
|
|
2178
|
+
var DEFAULT_SERVER_PORT = 3e3;
|
|
2179
|
+
var SERVER_HEALTH_TIMEOUT_MS = 12e4;
|
|
2180
|
+
var SERVER_RECONNECT_HEALTH_TIMEOUT_MS = 3e3;
|
|
2181
|
+
var SERVER_HEALTH_POLL_INTERVAL_MS = 1e3;
|
|
2182
|
+
var DEFAULT_IDLE_TIMEOUT_MS = RUNTIME_ABORT_GRACE_MS + 3e4;
|
|
2183
|
+
var SERVER_FAILURE_DIAGNOSTIC_TIMEOUT_MS = 1e3;
|
|
2184
|
+
var NATIVE_EXT_RE = /\.(node|wasm|gyp|c|cc|cpp|cxx|h|hpp|hxx)$/i;
|
|
2185
|
+
var TRACEABLE_SOURCE_EXT_RE = /\.(cjs|cts|js|jsx|mjs|mts|ts|tsx)$/i;
|
|
2186
|
+
var NeckbeardError = class extends Error {
|
|
2187
|
+
constructor(message) {
|
|
2188
|
+
super(message);
|
|
2189
|
+
this.name = "NeckbeardError";
|
|
2190
|
+
}
|
|
2191
|
+
};
|
|
2192
|
+
var DeploymentError = class extends NeckbeardError {
|
|
2193
|
+
/** A sandbox the failure left behind, for `kill()`. */
|
|
2194
|
+
constructor(message, cause, sandboxId) {
|
|
2195
|
+
super(message);
|
|
2196
|
+
this.cause = cause;
|
|
2197
|
+
this.sandboxId = sandboxId;
|
|
2198
|
+
this.name = "DeploymentError";
|
|
2199
|
+
}
|
|
2200
|
+
};
|
|
2201
|
+
var ValidationError = class extends NeckbeardError {
|
|
2202
|
+
constructor(message, cause) {
|
|
2203
|
+
super(message);
|
|
2204
|
+
this.cause = cause;
|
|
2205
|
+
this.name = "ValidationError";
|
|
2206
|
+
}
|
|
2207
|
+
};
|
|
2208
|
+
var ExecutionError = class extends NeckbeardError {
|
|
2209
|
+
constructor(message, cause) {
|
|
2210
|
+
super(message);
|
|
2211
|
+
this.cause = cause;
|
|
2212
|
+
this.name = "ExecutionError";
|
|
2213
|
+
}
|
|
2214
|
+
};
|
|
2215
|
+
var RuntimeBusyError = class extends ExecutionError {
|
|
2216
|
+
constructor(message) {
|
|
2217
|
+
super(message);
|
|
2218
|
+
this.name = "RuntimeBusyError";
|
|
2219
|
+
}
|
|
2220
|
+
};
|
|
2221
|
+
var TurnLostError = class extends ExecutionError {
|
|
2222
|
+
constructor(message) {
|
|
2223
|
+
super(message);
|
|
2224
|
+
this.name = "TurnLostError";
|
|
2225
|
+
}
|
|
2226
|
+
};
|
|
2227
|
+
var ConfigurationError = class extends NeckbeardError {
|
|
2228
|
+
constructor(message) {
|
|
2229
|
+
super(message);
|
|
2230
|
+
this.name = "ConfigurationError";
|
|
2231
|
+
}
|
|
2232
|
+
};
|
|
2233
|
+
function resolveAgentSourceFile(candidates, options = {}) {
|
|
2234
|
+
const normalizedCandidates = normalizeNonEmptyStrings("candidates", candidates);
|
|
2235
|
+
const sourceFile = normalizedCandidates.find((candidate) => existsSync(candidate));
|
|
2236
|
+
if (sourceFile) {
|
|
2237
|
+
return sourceFile;
|
|
2238
|
+
}
|
|
2239
|
+
if (process.env[NECKBEARD_SANDBOX_RUNTIME_ENV] === "1") {
|
|
2240
|
+
const sandboxSourceFile = options.sandboxSourceFile ?? resolve(process.cwd(), "agent.mjs");
|
|
2241
|
+
if (existsSync(sandboxSourceFile)) {
|
|
2242
|
+
return sandboxSourceFile;
|
|
2243
|
+
}
|
|
2244
|
+
}
|
|
2245
|
+
throw new ConfigurationError(
|
|
2246
|
+
options.errorMessage ?? `Could not resolve agent source file. Checked: ${candidates.join(", ")}`
|
|
2247
|
+
);
|
|
2248
|
+
}
|
|
2249
|
+
function withNeckbeardNextConfig(nextConfig, options) {
|
|
2250
|
+
const sourceFiles = normalizeNonEmptyStrings("sourceFiles", options.sourceFiles);
|
|
2251
|
+
const routeGlobs = normalizeNonEmptyStrings("routeGlob", options.routeGlob ?? "/*");
|
|
2252
|
+
const traceSourceDependencies = options.traceSourceDependencies ?? true;
|
|
2253
|
+
const traceIncludeFiles = traceIncludeFilesForConfig(
|
|
2254
|
+
process.cwd(),
|
|
2255
|
+
sourceFiles,
|
|
2256
|
+
traceSourceDependencies
|
|
2257
|
+
);
|
|
2258
|
+
const result = {
|
|
2259
|
+
...nextConfig,
|
|
2260
|
+
serverExternalPackages: mergeStringArray(nextConfig.serverExternalPackages, [
|
|
2261
|
+
NECKBEARD_PACKAGE_NAME,
|
|
2262
|
+
"modal"
|
|
2263
|
+
]),
|
|
2264
|
+
outputFileTracingIncludes: mergeTracingIncludes(
|
|
2265
|
+
nextConfig.outputFileTracingIncludes,
|
|
2266
|
+
routeGlobs,
|
|
2267
|
+
traceIncludeFiles
|
|
2268
|
+
)
|
|
2269
|
+
};
|
|
2270
|
+
if (nextConfig.webpack) {
|
|
2271
|
+
result.webpack = withNextTraceIncludeWebpack(
|
|
2272
|
+
nextConfig.webpack,
|
|
2273
|
+
sourceFiles,
|
|
2274
|
+
routeGlobs,
|
|
2275
|
+
traceSourceDependencies
|
|
2276
|
+
);
|
|
2277
|
+
}
|
|
2278
|
+
if (options.outputFileTracingRoot !== void 0) {
|
|
2279
|
+
result.outputFileTracingRoot = options.outputFileTracingRoot;
|
|
2280
|
+
}
|
|
2281
|
+
return result;
|
|
2282
|
+
}
|
|
2283
|
+
var NextTraceIncludePlugin = class {
|
|
2284
|
+
constructor(appDir, sourceFiles, routeGlobs, traceSourceDependencies) {
|
|
2285
|
+
this.appDir = appDir;
|
|
2286
|
+
this.sourceFiles = sourceFiles;
|
|
2287
|
+
this.routeGlobs = routeGlobs;
|
|
2288
|
+
this.traceSourceDependencies = traceSourceDependencies;
|
|
2289
|
+
}
|
|
2290
|
+
apply(compiler) {
|
|
2291
|
+
const compilationHook = compiler.hooks?.compilation;
|
|
2292
|
+
if (typeof compilationHook?.tap === "function") {
|
|
2293
|
+
compilationHook.tap("NeckbeardNextTraceIncludePlugin", (compilation) => {
|
|
2294
|
+
const processAssets = compilation.hooks?.processAssets;
|
|
2295
|
+
if (typeof processAssets?.tap !== "function") {
|
|
2296
|
+
return;
|
|
2297
|
+
}
|
|
2298
|
+
processAssets.tap({
|
|
2299
|
+
name: "NeckbeardNextTraceIncludePlugin",
|
|
2300
|
+
stage: compiler.webpack?.Compilation?.PROCESS_ASSETS_STAGE_REPORT ?? 5e3
|
|
2301
|
+
}, (assets) => {
|
|
2302
|
+
appendIncludesToTraceAssets({
|
|
2303
|
+
appDir: this.appDir,
|
|
2304
|
+
assets,
|
|
2305
|
+
outputPath: compilation.outputOptions?.path ?? compiler.outputPath ?? "",
|
|
2306
|
+
rawSource: compiler.webpack?.sources?.RawSource,
|
|
2307
|
+
routeGlobs: this.routeGlobs,
|
|
2308
|
+
sourceFiles: this.sourceFiles,
|
|
2309
|
+
traceSourceDependencies: this.traceSourceDependencies,
|
|
2310
|
+
updateAsset: compilation.updateAsset?.bind(compilation)
|
|
2311
|
+
});
|
|
2312
|
+
});
|
|
2313
|
+
});
|
|
2314
|
+
}
|
|
2315
|
+
const afterEmit = compiler.hooks?.afterEmit;
|
|
2316
|
+
const done = compiler.hooks?.done;
|
|
2317
|
+
if (typeof afterEmit?.tap !== "function" && typeof done?.tap !== "function") {
|
|
2318
|
+
return;
|
|
2319
|
+
}
|
|
2320
|
+
if (!compiler.outputPath) {
|
|
2321
|
+
return;
|
|
2322
|
+
}
|
|
2323
|
+
const appendIncludes = () => {
|
|
2324
|
+
appendIncludesToTraceFiles(
|
|
2325
|
+
compiler.outputPath ?? "",
|
|
2326
|
+
this.appDir,
|
|
2327
|
+
this.sourceFiles,
|
|
2328
|
+
this.routeGlobs,
|
|
2329
|
+
this.traceSourceDependencies
|
|
2330
|
+
);
|
|
2331
|
+
};
|
|
2332
|
+
if (typeof afterEmit?.tap === "function") {
|
|
2333
|
+
afterEmit.tap("NeckbeardNextTraceIncludePlugin", appendIncludes);
|
|
2334
|
+
}
|
|
2335
|
+
if (typeof done?.tap === "function") {
|
|
2336
|
+
done.tap("NeckbeardNextTraceIncludePlugin", appendIncludes);
|
|
2337
|
+
}
|
|
2338
|
+
}
|
|
2339
|
+
};
|
|
2340
|
+
function appendIncludesToTraceAssets({
|
|
2341
|
+
appDir,
|
|
2342
|
+
assets,
|
|
2343
|
+
outputPath,
|
|
2344
|
+
rawSource,
|
|
2345
|
+
routeGlobs,
|
|
2346
|
+
sourceFiles,
|
|
2347
|
+
traceSourceDependencies,
|
|
2348
|
+
updateAsset
|
|
2349
|
+
}) {
|
|
2350
|
+
const includedFiles = expandTraceIncludeFiles(appDir, sourceFiles, traceSourceDependencies);
|
|
2351
|
+
if (includedFiles.length === 0) {
|
|
2352
|
+
return;
|
|
2353
|
+
}
|
|
2354
|
+
for (const [assetName, asset] of Object.entries(assets)) {
|
|
2355
|
+
if (!assetName.endsWith(".nft.json")) {
|
|
2356
|
+
continue;
|
|
2357
|
+
}
|
|
2358
|
+
const routePath = routePathFromTraceAsset(outputPath, assetName);
|
|
2359
|
+
if (!routePath || !routeGlobs.some((routeGlob) => routeGlobMatches(routeGlob, routePath))) {
|
|
2360
|
+
continue;
|
|
2361
|
+
}
|
|
2362
|
+
const traceDir = dirname(join(outputPath, assetName));
|
|
2363
|
+
const nextSource = traceWithIncludedFiles(String(asset.source()), traceDir, includedFiles);
|
|
2364
|
+
if (rawSource && updateAsset) {
|
|
2365
|
+
updateAsset(assetName, new rawSource(nextSource));
|
|
2366
|
+
} else {
|
|
2367
|
+
assets[assetName] = {
|
|
2368
|
+
source: () => nextSource,
|
|
2369
|
+
size: () => Buffer.byteLength(nextSource)
|
|
2370
|
+
};
|
|
2371
|
+
}
|
|
2372
|
+
}
|
|
2373
|
+
}
|
|
2374
|
+
function withNextTraceIncludeWebpack(originalWebpack, sourceFiles, routeGlobs, traceSourceDependencies) {
|
|
2375
|
+
return (config, context) => {
|
|
2376
|
+
const nextConfig = originalWebpack ? originalWebpack(config, context) : config;
|
|
2377
|
+
if (!context.isServer || context.dev) {
|
|
2378
|
+
return nextConfig;
|
|
2379
|
+
}
|
|
2380
|
+
nextConfig.externals = withNeckbeardExternal(nextConfig.externals);
|
|
2381
|
+
nextConfig.plugins = [
|
|
2382
|
+
...Array.isArray(nextConfig.plugins) ? nextConfig.plugins : [],
|
|
2383
|
+
new NextTraceIncludePlugin(
|
|
2384
|
+
context.dir ?? process.cwd(),
|
|
2385
|
+
sourceFiles,
|
|
2386
|
+
routeGlobs,
|
|
2387
|
+
traceSourceDependencies
|
|
2388
|
+
)
|
|
2389
|
+
];
|
|
2390
|
+
return nextConfig;
|
|
2391
|
+
};
|
|
2392
|
+
}
|
|
2393
|
+
function withNeckbeardExternal(externals) {
|
|
2394
|
+
return [
|
|
2395
|
+
neckbeardExternal,
|
|
2396
|
+
...Array.isArray(externals) ? externals : externals ? [externals] : []
|
|
2397
|
+
];
|
|
2398
|
+
}
|
|
2399
|
+
function neckbeardExternal(contextOrRequest, requestOrCallback) {
|
|
2400
|
+
const legacyCallback = arguments[2];
|
|
2401
|
+
const request = typeof requestOrCallback === "string" ? requestOrCallback : typeof contextOrRequest === "string" ? contextOrRequest : contextOrRequest.request;
|
|
2402
|
+
const callback = typeof requestOrCallback === "function" ? requestOrCallback : legacyCallback;
|
|
2403
|
+
if (request === NECKBEARD_PACKAGE_NAME || request === "modal") {
|
|
2404
|
+
const result = `commonjs ${request}`;
|
|
2405
|
+
if (callback) {
|
|
2406
|
+
callback(null, result);
|
|
2407
|
+
return;
|
|
2408
|
+
}
|
|
2409
|
+
return result;
|
|
2410
|
+
}
|
|
2411
|
+
if (callback) {
|
|
2412
|
+
callback();
|
|
2413
|
+
}
|
|
2414
|
+
}
|
|
2415
|
+
function appendIncludesToTraceFiles(outputPath, appDir, sourceFiles, routeGlobs, traceSourceDependencies) {
|
|
2416
|
+
if (!outputPath || !existsSync(outputPath)) {
|
|
2417
|
+
return;
|
|
2418
|
+
}
|
|
2419
|
+
const includedFiles = expandTraceIncludeFiles(appDir, sourceFiles, traceSourceDependencies);
|
|
2420
|
+
if (includedFiles.length === 0) {
|
|
2421
|
+
return;
|
|
2422
|
+
}
|
|
2423
|
+
for (const traceFile of findTraceFiles(outputPath)) {
|
|
2424
|
+
const routePath = routePathFromTraceFile(outputPath, traceFile);
|
|
2425
|
+
if (!routePath || !routeGlobs.some((routeGlob) => routeGlobMatches(routeGlob, routePath))) {
|
|
2426
|
+
continue;
|
|
2427
|
+
}
|
|
2428
|
+
appendFilesToTrace(traceFile, includedFiles);
|
|
2429
|
+
}
|
|
2430
|
+
}
|
|
2431
|
+
function appendFilesToTrace(traceFile, includedFiles) {
|
|
2432
|
+
const nextSource = traceWithIncludedFiles(
|
|
2433
|
+
readFileSync(traceFile, "utf8"),
|
|
2434
|
+
dirname(traceFile),
|
|
2435
|
+
includedFiles
|
|
2436
|
+
);
|
|
2437
|
+
writeFileSync(traceFile, nextSource);
|
|
2438
|
+
}
|
|
2439
|
+
function traceWithIncludedFiles(traceSource, traceDir, includedFiles) {
|
|
2440
|
+
const trace = JSON.parse(traceSource);
|
|
2441
|
+
const files = Array.isArray(trace.files) ? trace.files.filter((file) => typeof file === "string") : [];
|
|
2442
|
+
const nextFiles = new Set(files);
|
|
2443
|
+
for (const includedFile of includedFiles) {
|
|
2444
|
+
nextFiles.add(relative(traceDir, includedFile).replace(/\\/g, "/"));
|
|
2445
|
+
}
|
|
2446
|
+
return JSON.stringify({
|
|
2447
|
+
version: trace.version ?? 1,
|
|
2448
|
+
files: [...nextFiles]
|
|
2449
|
+
});
|
|
2450
|
+
}
|
|
2451
|
+
function expandTraceIncludeFiles(appDir, sourceFiles, traceSourceDependencies = true) {
|
|
2452
|
+
const files = /* @__PURE__ */ new Set();
|
|
2453
|
+
for (const sourceFile of sourceFiles) {
|
|
2454
|
+
for (const file of expandTraceIncludePattern(appDir, sourceFile)) {
|
|
2455
|
+
files.add(file);
|
|
2456
|
+
}
|
|
2457
|
+
}
|
|
2458
|
+
if (traceSourceDependencies) {
|
|
2459
|
+
for (const file of traceSourceDependencyFiles(appDir, [...files])) {
|
|
2460
|
+
files.add(file);
|
|
2461
|
+
}
|
|
2462
|
+
}
|
|
2463
|
+
return [...files];
|
|
2464
|
+
}
|
|
2465
|
+
function traceIncludeFilesForConfig(appDir, sourceFiles, traceSourceDependencies) {
|
|
2466
|
+
const tracedFiles = expandTraceIncludeFiles(appDir, sourceFiles, traceSourceDependencies).map((file) => toNextTraceIncludePath(appDir, file));
|
|
2467
|
+
return mergeStringArray(sourceFiles, tracedFiles);
|
|
2468
|
+
}
|
|
2469
|
+
function toNextTraceIncludePath(appDir, file) {
|
|
2470
|
+
const relativePath = relative(appDir, file).replace(/\\/g, "/");
|
|
2471
|
+
if (relativePath.startsWith("..")) {
|
|
2472
|
+
return relativePath;
|
|
2473
|
+
}
|
|
2474
|
+
return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
|
|
2475
|
+
}
|
|
2476
|
+
function expandTraceIncludePattern(appDir, sourceFile) {
|
|
2477
|
+
const normalized = sourceFile.replace(/\\/g, "/").replace(/^\.\//, "");
|
|
2478
|
+
if (normalized.endsWith("/**/*")) {
|
|
2479
|
+
const dir = resolve(appDir, normalized.slice(0, -5));
|
|
2480
|
+
return findFiles(dir);
|
|
2481
|
+
}
|
|
2482
|
+
if (normalized.endsWith("/*")) {
|
|
2483
|
+
const dir = resolve(appDir, normalized.slice(0, -2));
|
|
2484
|
+
return directFiles(dir);
|
|
2485
|
+
}
|
|
2486
|
+
const file = resolve(appDir, normalized);
|
|
2487
|
+
return existsSync(file) && statSync(file).isFile() ? [file] : [];
|
|
2488
|
+
}
|
|
2489
|
+
function traceSourceDependencyFiles(appDir, sourceFiles) {
|
|
2490
|
+
const entryPoints = sourceFiles.filter((file) => TRACEABLE_SOURCE_EXT_RE.test(file));
|
|
2491
|
+
if (entryPoints.length === 0) {
|
|
2492
|
+
return [];
|
|
2493
|
+
}
|
|
2494
|
+
try {
|
|
2495
|
+
const esbuild = getEsbuildSync();
|
|
2496
|
+
const result = esbuild.buildSync({
|
|
2497
|
+
absWorkingDir: appDir,
|
|
2498
|
+
bundle: true,
|
|
2499
|
+
entryPoints,
|
|
2500
|
+
external: [...DEFAULT_EXTERNALS, NECKBEARD_PACKAGE_NAME],
|
|
2501
|
+
format: "esm",
|
|
2502
|
+
logLevel: "silent",
|
|
2503
|
+
metafile: true,
|
|
2504
|
+
platform: "node",
|
|
2505
|
+
preserveSymlinks: true,
|
|
2506
|
+
target: NODE_TARGET,
|
|
2507
|
+
treeShaking: false,
|
|
2508
|
+
write: false
|
|
2509
|
+
});
|
|
2510
|
+
const metafile = result.metafile;
|
|
2511
|
+
if (!metafile) {
|
|
2512
|
+
return [];
|
|
2513
|
+
}
|
|
2514
|
+
const files = /* @__PURE__ */ new Set();
|
|
2515
|
+
const addFile = (file) => {
|
|
2516
|
+
if (file && existsSync(file) && statSync(file).isFile()) {
|
|
2517
|
+
files.add(file);
|
|
2518
|
+
}
|
|
2519
|
+
};
|
|
2520
|
+
for (const [inputPath, input] of Object.entries(metafile.inputs)) {
|
|
2521
|
+
const absoluteInput = resolveMetafileInput(appDir, inputPath);
|
|
2522
|
+
addFile(absoluteInput);
|
|
2523
|
+
for (const importRecord of input.imports ?? []) {
|
|
2524
|
+
const importPath = importRecord.original ?? importRecord.path;
|
|
2525
|
+
if (!isBareModuleImport(importPath) || isBuiltinModule(importPath)) {
|
|
2526
|
+
continue;
|
|
2527
|
+
}
|
|
2528
|
+
if (importPath === NECKBEARD_PACKAGE_NAME) {
|
|
2529
|
+
continue;
|
|
2530
|
+
}
|
|
2531
|
+
const resolvedImportPath = importRecord.external ? void 0 : resolveMetafileInput(appDir, importRecord.path);
|
|
2532
|
+
const packageInfo = resolvedImportPath ? resolvePackageInfoFromResolvedPath(importPath, resolvedImportPath) : resolvePackageInfoSync(importPath, dirname(absoluteInput));
|
|
2533
|
+
if (!packageInfo) {
|
|
2534
|
+
continue;
|
|
2535
|
+
}
|
|
2536
|
+
addFile(packageInfo.resolvedPath);
|
|
2537
|
+
addFile(join(packageInfo.root, "package.json"));
|
|
2538
|
+
}
|
|
2539
|
+
}
|
|
2540
|
+
return [...files];
|
|
2541
|
+
} catch (error) {
|
|
2542
|
+
throw new ConfigurationError(
|
|
2543
|
+
`Failed to trace Neckbeard source dependencies for Next.js output tracing: ${errorMessage(error)}`
|
|
2544
|
+
);
|
|
2545
|
+
}
|
|
2546
|
+
}
|
|
2547
|
+
function getEsbuildSync() {
|
|
2548
|
+
return packageRequire("esbuild");
|
|
2549
|
+
}
|
|
2550
|
+
function resolveMetafileInput(absWorkingDir, inputPath) {
|
|
2551
|
+
return resolve(absWorkingDir, inputPath);
|
|
2552
|
+
}
|
|
2553
|
+
function findTraceFiles(root) {
|
|
2554
|
+
return findFiles(root).filter((file) => file.endsWith(".nft.json"));
|
|
2555
|
+
}
|
|
2556
|
+
function findFiles(root) {
|
|
2557
|
+
if (!existsSync(root)) {
|
|
2558
|
+
return [];
|
|
2559
|
+
}
|
|
2560
|
+
const stat = statSync(root);
|
|
2561
|
+
if (stat.isFile()) {
|
|
2562
|
+
return [root];
|
|
2563
|
+
}
|
|
2564
|
+
if (!stat.isDirectory()) {
|
|
2565
|
+
return [];
|
|
2566
|
+
}
|
|
2567
|
+
const files = [];
|
|
2568
|
+
for (const entry of readdirSync(root)) {
|
|
2569
|
+
files.push(...findFiles(join(root, entry)));
|
|
2570
|
+
}
|
|
2571
|
+
return files;
|
|
2572
|
+
}
|
|
2573
|
+
function directFiles(root) {
|
|
2574
|
+
if (!existsSync(root) || !statSync(root).isDirectory()) {
|
|
2575
|
+
return [];
|
|
2576
|
+
}
|
|
2577
|
+
return readdirSync(root).map((entry) => join(root, entry)).filter((file) => statSync(file).isFile());
|
|
2578
|
+
}
|
|
2579
|
+
function routePathFromTraceFile(outputPath, traceFile) {
|
|
2580
|
+
const relativeTrace = relative(outputPath, traceFile).replace(/\\/g, "/");
|
|
2581
|
+
return routePathFromRelativeTrace(outputPath, relativeTrace);
|
|
2582
|
+
}
|
|
2583
|
+
function routePathFromTraceAsset(outputPath, assetName) {
|
|
2584
|
+
return routePathFromRelativeTrace(outputPath, assetName.replace(/\\/g, "/"));
|
|
2585
|
+
}
|
|
2586
|
+
function routePathFromRelativeTrace(outputPath, relativeTrace) {
|
|
2587
|
+
const normalizedTrace = relativeTrace.replace(/^(\.\.\/)+/, "");
|
|
2588
|
+
if (relativeTrace.startsWith("app/")) {
|
|
2589
|
+
return normalizeTraceRoute(relativeTrace.slice("app/".length));
|
|
2590
|
+
}
|
|
2591
|
+
if (relativeTrace.startsWith("pages/")) {
|
|
2592
|
+
return normalizeTraceRoute(relativeTrace.slice("pages/".length));
|
|
2593
|
+
}
|
|
2594
|
+
if (normalizedTrace.startsWith("app/")) {
|
|
2595
|
+
return normalizeTraceRoute(normalizedTrace.slice("app/".length));
|
|
2596
|
+
}
|
|
2597
|
+
if (normalizedTrace.startsWith("pages/")) {
|
|
2598
|
+
return normalizeTraceRoute(normalizedTrace.slice("pages/".length));
|
|
2599
|
+
}
|
|
2600
|
+
if (basename(outputPath) === "app" || basename(outputPath) === "pages") {
|
|
2601
|
+
return normalizeTraceRoute(relativeTrace);
|
|
2602
|
+
}
|
|
2603
|
+
return void 0;
|
|
2604
|
+
}
|
|
2605
|
+
function normalizeTraceRoute(relativeTrace) {
|
|
2606
|
+
const withoutTraceSuffix = relativeTrace.replace(/\.js\.nft\.json$/, "");
|
|
2607
|
+
const route = withoutTraceSuffix.replace(/\/route$/, "").replace(/\/page$/, "").replace(/\/index$/, "");
|
|
2608
|
+
return `/${route}`;
|
|
2609
|
+
}
|
|
2610
|
+
function routeGlobMatches(routeGlob, routePath) {
|
|
2611
|
+
if (routeGlob === "/*") {
|
|
2612
|
+
return true;
|
|
2613
|
+
}
|
|
2614
|
+
return routeGlobToRegExp(routeGlob).test(routePath);
|
|
2615
|
+
}
|
|
2616
|
+
function routeGlobToRegExp(glob) {
|
|
2617
|
+
let pattern = "";
|
|
2618
|
+
for (let index = 0; index < glob.length; index += 1) {
|
|
2619
|
+
const char = glob[index];
|
|
2620
|
+
const nextChar = glob[index + 1];
|
|
2621
|
+
if (char === "*" && nextChar === "*") {
|
|
2622
|
+
pattern += ".*";
|
|
2623
|
+
index += 1;
|
|
2624
|
+
} else if (char === "*") {
|
|
2625
|
+
pattern += "[^/]*";
|
|
2626
|
+
} else {
|
|
2627
|
+
pattern += escapeRegExp(char);
|
|
2628
|
+
}
|
|
2629
|
+
}
|
|
2630
|
+
return new RegExp(`^${pattern}$`);
|
|
2631
|
+
}
|
|
2632
|
+
function escapeRegExp(value) {
|
|
2633
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
2634
|
+
}
|
|
2635
|
+
function asRecord(value) {
|
|
2636
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
2637
|
+
}
|
|
2638
|
+
function normalizeNonEmptyStrings(name, value) {
|
|
2639
|
+
const values = Array.isArray(value) ? value : [value];
|
|
2640
|
+
if (values.length === 0) {
|
|
2641
|
+
throw new ConfigurationError(`${name} must contain at least one entry.`);
|
|
2642
|
+
}
|
|
2643
|
+
for (const entry of values) {
|
|
2644
|
+
if (typeof entry !== "string" || entry.trim() === "") {
|
|
2645
|
+
throw new ConfigurationError(`${name} entries must be non-empty strings.`);
|
|
2646
|
+
}
|
|
2647
|
+
}
|
|
2648
|
+
return values;
|
|
2649
|
+
}
|
|
2650
|
+
function mergeStringArray(existing, values) {
|
|
2651
|
+
const current = Array.isArray(existing) ? existing.filter((value) => typeof value === "string") : [];
|
|
2652
|
+
return [.../* @__PURE__ */ new Set([...current, ...values])];
|
|
2653
|
+
}
|
|
2654
|
+
function mergeTracingIncludes(existing, routeGlobs, sourceFiles) {
|
|
2655
|
+
const includes = { ...asRecord(existing) };
|
|
2656
|
+
for (const routeGlob of routeGlobs) {
|
|
2657
|
+
includes[routeGlob] = mergeStringArray(includes[routeGlob], sourceFiles);
|
|
2658
|
+
}
|
|
2659
|
+
return includes;
|
|
2660
|
+
}
|
|
2661
|
+
var DEFAULT_DEPENDENCIES = {};
|
|
2662
|
+
function isSessionAgentConfig(config) {
|
|
2663
|
+
return "session" in config && config.session !== void 0 || "server" in config && config.server !== void 0;
|
|
2664
|
+
}
|
|
2665
|
+
function getSessionHandler(config) {
|
|
2666
|
+
const session = "session" in config ? config.session : void 0;
|
|
2667
|
+
const server = "server" in config ? config.server : void 0;
|
|
2668
|
+
if (session && server) {
|
|
2669
|
+
throw new ConfigurationError("Agent config must use session or deprecated server, not both.");
|
|
2670
|
+
}
|
|
2671
|
+
const handler = session ?? server;
|
|
2672
|
+
if (!handler || typeof handler !== "object") {
|
|
2673
|
+
throw new ConfigurationError("session must be an object.");
|
|
2674
|
+
}
|
|
2675
|
+
return handler;
|
|
2676
|
+
}
|
|
2677
|
+
function isSchemaLike(value) {
|
|
2678
|
+
return Boolean(
|
|
2679
|
+
value && typeof value === "object" && typeof value.parse === "function"
|
|
2680
|
+
);
|
|
2681
|
+
}
|
|
2682
|
+
function requireSchemaLike(name, value) {
|
|
2683
|
+
if (!isSchemaLike(value)) {
|
|
2684
|
+
throw new ConfigurationError(`${name} must be an object with a parse(value) function.`);
|
|
2685
|
+
}
|
|
2686
|
+
return value;
|
|
2687
|
+
}
|
|
2688
|
+
function isAbortSignal(value) {
|
|
2689
|
+
if (!value || typeof value !== "object") return false;
|
|
2690
|
+
try {
|
|
2691
|
+
const abortedGetter = Object.getOwnPropertyDescriptor(
|
|
2692
|
+
AbortSignal.prototype,
|
|
2693
|
+
"aborted"
|
|
2694
|
+
)?.get;
|
|
2695
|
+
if (!abortedGetter || typeof abortedGetter.call(value) !== "boolean") return false;
|
|
2696
|
+
const candidate = value;
|
|
2697
|
+
return typeof candidate.aborted === "boolean" && typeof candidate.addEventListener === "function" && typeof candidate.removeEventListener === "function";
|
|
2698
|
+
} catch {
|
|
2699
|
+
return false;
|
|
2700
|
+
}
|
|
2701
|
+
}
|
|
2702
|
+
function normalizeLocalDirectoryDestination(destination, name) {
|
|
2703
|
+
if (destination.trim() === "") {
|
|
2704
|
+
throw new ConfigurationError(`${name}.destination must be a non-empty relative path.`);
|
|
2705
|
+
}
|
|
2706
|
+
if (destination.includes("\0")) {
|
|
2707
|
+
throw new ConfigurationError(`${name}.destination must not contain null bytes.`);
|
|
2708
|
+
}
|
|
2709
|
+
const sandboxPath = destination.replace(/\\/g, "/");
|
|
2710
|
+
if (isAbsolute(destination) || posix.isAbsolute(sandboxPath) || win32.isAbsolute(destination)) {
|
|
2711
|
+
throw new ConfigurationError(
|
|
2712
|
+
`${name}.destination must be relative to the sandbox agent directory.`
|
|
2713
|
+
);
|
|
2714
|
+
}
|
|
2715
|
+
if (sandboxPath.split("/").includes("..")) {
|
|
2716
|
+
throw new ConfigurationError(
|
|
2717
|
+
`${name}.destination must not traverse outside the sandbox agent directory.`
|
|
2718
|
+
);
|
|
2719
|
+
}
|
|
2720
|
+
const normalized = posix.normalize(sandboxPath);
|
|
2721
|
+
if (normalized === ".") {
|
|
2722
|
+
throw new ConfigurationError(`${name}.destination must not be ".".`);
|
|
2723
|
+
}
|
|
2724
|
+
return normalized;
|
|
2725
|
+
}
|
|
2726
|
+
function validateLocalDirectoriesConfig(value) {
|
|
2727
|
+
if (value === void 0) return;
|
|
2728
|
+
if (!Array.isArray(value)) {
|
|
2729
|
+
throw new ConfigurationError("localDirectories must be an array when provided.");
|
|
2730
|
+
}
|
|
2731
|
+
for (const [index, entry] of value.entries()) {
|
|
2732
|
+
const name = `localDirectories[${index}]`;
|
|
2733
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
|
|
2734
|
+
throw new ConfigurationError(`${name} must be an object.`);
|
|
2735
|
+
}
|
|
2736
|
+
const candidate = entry;
|
|
2737
|
+
if (typeof candidate.source !== "string" || candidate.source.trim() === "") {
|
|
2738
|
+
throw new ConfigurationError(`${name}.source must be a non-empty string.`);
|
|
2739
|
+
}
|
|
2740
|
+
if (candidate.source.includes("\0")) {
|
|
2741
|
+
throw new ConfigurationError(`${name}.source must not contain null bytes.`);
|
|
2742
|
+
}
|
|
2743
|
+
if (typeof candidate.destination !== "string") {
|
|
2744
|
+
throw new ConfigurationError(`${name}.destination must be a string.`);
|
|
2745
|
+
}
|
|
2746
|
+
normalizeLocalDirectoryDestination(candidate.destination, name);
|
|
2747
|
+
}
|
|
2748
|
+
}
|
|
2749
|
+
function validateAgentConfig(config) {
|
|
2750
|
+
if (!config || typeof config !== "object") {
|
|
2751
|
+
throw new ConfigurationError("Agent config must be an object.");
|
|
2752
|
+
}
|
|
2753
|
+
if (!config.sandbox || typeof config.sandbox !== "object") {
|
|
2754
|
+
throw new ConfigurationError("Agent config requires sandbox settings.");
|
|
2755
|
+
}
|
|
2756
|
+
if (config.sandbox.provider !== "e2b" && config.sandbox.provider !== "daytona" && config.sandbox.provider !== "modal" && config.sandbox.provider !== "docker") {
|
|
2757
|
+
throw new ConfigurationError('sandbox.provider must be "e2b", "daytona", "modal", or "docker".');
|
|
2758
|
+
}
|
|
2759
|
+
if (config.sandbox.provider === "modal") {
|
|
2760
|
+
validateModalOptions(config.sandbox, "agent", (message) => new ConfigurationError(message));
|
|
2761
|
+
} else if (config.sandbox.provider === "docker") {
|
|
2762
|
+
validateDockerOptions(config.sandbox, "agent", (message) => new ConfigurationError(message));
|
|
2763
|
+
} else if (typeof config.sandbox.template !== "string" || config.sandbox.template.trim() === "") {
|
|
2764
|
+
throw new ConfigurationError("sandbox.template must be a non-empty string.");
|
|
2765
|
+
}
|
|
2766
|
+
if (config.sandbox.provider === "daytona") {
|
|
2767
|
+
const { autoStopInterval, autoDeleteInterval } = config.sandbox;
|
|
2768
|
+
if (autoStopInterval !== void 0 && (!Number.isInteger(autoStopInterval) || autoStopInterval < 0)) {
|
|
2769
|
+
throw new ConfigurationError("sandbox.autoStopInterval must be a non-negative integer number of minutes.");
|
|
2770
|
+
}
|
|
2771
|
+
if (autoDeleteInterval !== void 0 && !Number.isInteger(autoDeleteInterval)) {
|
|
2772
|
+
throw new ConfigurationError("sandbox.autoDeleteInterval must be an integer number of minutes.");
|
|
2773
|
+
}
|
|
2774
|
+
}
|
|
2775
|
+
requireSchemaLike("inputSchema", config.inputSchema);
|
|
2776
|
+
if (config.maxDuration !== void 0 && (!Number.isFinite(config.maxDuration) || config.maxDuration <= 0)) {
|
|
2777
|
+
throw new ConfigurationError("maxDuration must be a positive finite number of seconds.");
|
|
2778
|
+
}
|
|
2779
|
+
if (config.sourceFile !== void 0 && (typeof config.sourceFile !== "string" || config.sourceFile.trim() === "")) {
|
|
2780
|
+
throw new ConfigurationError("sourceFile must be a non-empty string when provided.");
|
|
2781
|
+
}
|
|
2782
|
+
validateLocalDirectoriesConfig(config.localDirectories);
|
|
2783
|
+
if (isSessionAgentConfig(config)) {
|
|
2784
|
+
if ("run" in config && typeof config.run === "function") {
|
|
2785
|
+
throw new ConfigurationError("Agent config must use either run or session.handler, not both.");
|
|
2786
|
+
}
|
|
2787
|
+
const session = getSessionHandler(config);
|
|
2788
|
+
if (session.port !== void 0) {
|
|
2789
|
+
if (!Number.isInteger(session.port) || session.port < 1 || session.port > 65535) {
|
|
2790
|
+
throw new ConfigurationError("session.port must be an integer between 1 and 65535.");
|
|
2791
|
+
}
|
|
2792
|
+
}
|
|
2793
|
+
requireSchemaLike("session.frameSchema", session.frameSchema);
|
|
2794
|
+
if (typeof session.handler !== "function") {
|
|
2795
|
+
throw new ConfigurationError("session.handler must be a function.");
|
|
2796
|
+
}
|
|
2797
|
+
return;
|
|
2798
|
+
}
|
|
2799
|
+
if (typeof config.run !== "function") {
|
|
2800
|
+
throw new ConfigurationError("run must be a function for run-output agents.");
|
|
2801
|
+
}
|
|
2802
|
+
requireSchemaLike("outputSchema", config.outputSchema);
|
|
2803
|
+
}
|
|
2804
|
+
function getTrafficToken(descriptor) {
|
|
2805
|
+
return descriptor.trafficToken;
|
|
2806
|
+
}
|
|
2807
|
+
function appendTrafficTokenToUrl(url, descriptor) {
|
|
2808
|
+
const token = getTrafficToken(descriptor);
|
|
2809
|
+
if (descriptor.provider !== "daytona" || !token) return url;
|
|
2810
|
+
const separator = url.includes("?") ? "&" : "?";
|
|
2811
|
+
return `${url}${separator}DAYTONA_SANDBOX_AUTH_KEY=${encodeURIComponent(token)}`;
|
|
2812
|
+
}
|
|
2813
|
+
function trafficTokenHeaders(descriptor) {
|
|
2814
|
+
const token = getTrafficToken(descriptor);
|
|
2815
|
+
if (descriptor.provider === "modal") {
|
|
2816
|
+
if (!token) throw new ConfigurationError("Modal HTTP requests require a Connect Token.");
|
|
2817
|
+
return { authorization: `Bearer ${token}` };
|
|
2818
|
+
}
|
|
2819
|
+
if (descriptor.provider === "e2b" && token) {
|
|
2820
|
+
return { "e2b-traffic-access-token": token };
|
|
2821
|
+
}
|
|
2822
|
+
return {};
|
|
2823
|
+
}
|
|
2824
|
+
function abortSignalError(signal) {
|
|
2825
|
+
if (signal.reason instanceof Error) return signal.reason;
|
|
2826
|
+
const error = new Error(
|
|
2827
|
+
signal.reason === void 0 ? "Operation aborted." : String(signal.reason)
|
|
2828
|
+
);
|
|
2829
|
+
error.name = "AbortError";
|
|
2830
|
+
return error;
|
|
2831
|
+
}
|
|
2832
|
+
function throwIfAborted(signal) {
|
|
2833
|
+
if (signal?.aborted) throw abortSignalError(signal);
|
|
2834
|
+
}
|
|
2835
|
+
function awaitWithAbort(operation, signal) {
|
|
2836
|
+
return settleOperation(operation, {
|
|
2837
|
+
...signal ? {
|
|
2838
|
+
abort: {
|
|
2839
|
+
signal,
|
|
2840
|
+
createError: () => abortSignalError(signal)
|
|
2841
|
+
}
|
|
2842
|
+
} : {}
|
|
2843
|
+
});
|
|
2844
|
+
}
|
|
2845
|
+
function awaitDiagnosticRead(operation, signal) {
|
|
2846
|
+
return settleOperation(operation, {
|
|
2847
|
+
...signal ? {
|
|
2848
|
+
abort: {
|
|
2849
|
+
signal,
|
|
2850
|
+
createError: () => abortSignalError(signal)
|
|
2851
|
+
}
|
|
2852
|
+
} : {},
|
|
2853
|
+
timeout: {
|
|
2854
|
+
timeoutMs: SERVER_FAILURE_DIAGNOSTIC_TIMEOUT_MS,
|
|
2855
|
+
createError: () => new Error("Server diagnostic read timed out.")
|
|
2856
|
+
}
|
|
2857
|
+
});
|
|
2858
|
+
}
|
|
2859
|
+
function delayWithAbort(delayMs, signal) {
|
|
2860
|
+
if (!signal) {
|
|
2861
|
+
return new Promise((resolve2) => setTimeout(resolve2, delayMs));
|
|
2862
|
+
}
|
|
2863
|
+
throwIfAborted(signal);
|
|
2864
|
+
return new Promise((resolve2, reject) => {
|
|
2865
|
+
const onAbort = () => {
|
|
2866
|
+
clearTimeout(timer);
|
|
2867
|
+
reject(abortSignalError(signal));
|
|
2868
|
+
};
|
|
2869
|
+
const timer = setTimeout(() => {
|
|
2870
|
+
signal.removeEventListener("abort", onAbort);
|
|
2871
|
+
resolve2();
|
|
2872
|
+
}, delayMs);
|
|
2873
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
2874
|
+
});
|
|
2875
|
+
}
|
|
2876
|
+
async function waitForServerHealthy(healthUrl, descriptor, timeoutMs = SERVER_HEALTH_TIMEOUT_MS, signal) {
|
|
2877
|
+
const deadline = Date.now() + timeoutMs;
|
|
2878
|
+
let lastError;
|
|
2879
|
+
const urlWithToken = appendTrafficTokenToUrl(healthUrl, descriptor);
|
|
2880
|
+
while (Date.now() < deadline) {
|
|
2881
|
+
throwIfAborted(signal);
|
|
2882
|
+
try {
|
|
2883
|
+
const response = await awaitWithAbort(
|
|
2884
|
+
() => fetch(urlWithToken, {
|
|
2885
|
+
headers: trafficTokenHeaders(descriptor),
|
|
2886
|
+
...signal === void 0 ? {} : { signal }
|
|
2887
|
+
}),
|
|
2888
|
+
signal
|
|
2889
|
+
);
|
|
2890
|
+
if (response.ok) {
|
|
2891
|
+
try {
|
|
2892
|
+
await awaitWithAbort(() => response.text(), signal);
|
|
2893
|
+
} catch {
|
|
2894
|
+
throwIfAborted(signal);
|
|
2895
|
+
}
|
|
2896
|
+
return;
|
|
2897
|
+
}
|
|
2898
|
+
lastError = new Error(`health check returned ${response.status}`);
|
|
2899
|
+
} catch (error) {
|
|
2900
|
+
throwIfAborted(signal);
|
|
2901
|
+
lastError = error;
|
|
2902
|
+
}
|
|
2903
|
+
await delayWithAbort(SERVER_HEALTH_POLL_INTERVAL_MS, signal);
|
|
2904
|
+
}
|
|
2905
|
+
const message = lastError instanceof Error ? lastError.message : String(lastError);
|
|
2906
|
+
throw new DeploymentError(
|
|
2907
|
+
`Server did not become healthy at ${healthUrl} within ${timeoutMs}ms: ${message}`
|
|
2908
|
+
);
|
|
2909
|
+
}
|
|
2910
|
+
function requireEnv(name) {
|
|
2911
|
+
const value = process.env[name];
|
|
2912
|
+
if (!value) {
|
|
2913
|
+
throw new ConfigurationError(
|
|
2914
|
+
`${name} environment variable is required. Please set it before calling deploy() or run().`
|
|
2915
|
+
);
|
|
2916
|
+
}
|
|
2917
|
+
return value;
|
|
2918
|
+
}
|
|
2919
|
+
var require2 = createRequire2(join(process.cwd(), "__agent_neckbeard__.cjs"));
|
|
2920
|
+
var packageRequire = createPackageRequire();
|
|
2921
|
+
function createPackageRequire() {
|
|
2922
|
+
const cwdPackageJsonPath = join(process.cwd(), "package.json");
|
|
2923
|
+
try {
|
|
2924
|
+
if (existsSync(cwdPackageJsonPath) && readPackageJson(cwdPackageJsonPath).name === NECKBEARD_PACKAGE_NAME) {
|
|
2925
|
+
return createRequire2(cwdPackageJsonPath);
|
|
2926
|
+
}
|
|
2927
|
+
} catch {
|
|
2928
|
+
}
|
|
2929
|
+
try {
|
|
2930
|
+
return createRequire2(require2.resolve(NECKBEARD_PACKAGE_NAME));
|
|
2931
|
+
} catch {
|
|
2932
|
+
return require2;
|
|
2933
|
+
}
|
|
2934
|
+
}
|
|
2935
|
+
function isBareModuleImport(path2) {
|
|
2936
|
+
const excludes = [".", "/", "~", "file:", "data:"];
|
|
2937
|
+
return !excludes.some((exclude) => path2.startsWith(exclude));
|
|
2938
|
+
}
|
|
2939
|
+
function isBuiltinModule(path2) {
|
|
2940
|
+
return builtinModules.includes(path2.replace("node:", ""));
|
|
2941
|
+
}
|
|
2942
|
+
function packageNameForImportPath(importPath) {
|
|
2943
|
+
if (importPath.startsWith("@")) {
|
|
2944
|
+
return importPath.split("/").slice(0, 2).join("/");
|
|
2945
|
+
}
|
|
2946
|
+
return importPath.split("/")[0];
|
|
2947
|
+
}
|
|
2948
|
+
function globToRegExp(pattern) {
|
|
2949
|
+
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
|
|
2950
|
+
return new RegExp(`^${escaped}$`);
|
|
2951
|
+
}
|
|
2952
|
+
function matchesExternal(matchers, pkgName) {
|
|
2953
|
+
return matchers.some((re) => re.test(pkgName));
|
|
2954
|
+
}
|
|
2955
|
+
async function resolvePackageInfo(importPath, resolveDir) {
|
|
2956
|
+
return resolvePackageInfoSync(importPath, resolveDir);
|
|
2957
|
+
}
|
|
2958
|
+
function resolvePackageInfoSync(importPath, resolveDir) {
|
|
2959
|
+
try {
|
|
2960
|
+
const resolvedPath = require2.resolve(importPath, { paths: [resolveDir] });
|
|
2961
|
+
const packageName = packageNameForImportPath(importPath);
|
|
2962
|
+
let root = dirname(resolvedPath);
|
|
2963
|
+
let packageJsonPath = null;
|
|
2964
|
+
while (true) {
|
|
2965
|
+
const candidate = join(root, "package.json");
|
|
2966
|
+
if (existsSync(candidate)) {
|
|
2967
|
+
const candidatePackageJson = readPackageJson(candidate);
|
|
2968
|
+
if (candidatePackageJson.name === packageName) {
|
|
2969
|
+
packageJsonPath = candidate;
|
|
2970
|
+
break;
|
|
2971
|
+
}
|
|
2972
|
+
}
|
|
2973
|
+
const parent = dirname(root);
|
|
2974
|
+
if (parent === root) break;
|
|
2975
|
+
root = parent;
|
|
2976
|
+
}
|
|
2977
|
+
if (!packageJsonPath) return null;
|
|
2978
|
+
const packageJson = readPackageJson(packageJsonPath);
|
|
2979
|
+
if (!packageJson.name || !packageJson.version) return null;
|
|
2980
|
+
root = dirname(packageJsonPath);
|
|
2981
|
+
return {
|
|
2982
|
+
name: packageJson.name,
|
|
2983
|
+
version: packageJson.version,
|
|
2984
|
+
root,
|
|
2985
|
+
resolvedPath,
|
|
2986
|
+
packageJson
|
|
2987
|
+
};
|
|
2988
|
+
} catch {
|
|
2989
|
+
return null;
|
|
2990
|
+
}
|
|
2991
|
+
}
|
|
2992
|
+
function resolvePackageInfoFromResolvedPath(importPath, resolvedPath) {
|
|
2993
|
+
const packageName = packageNameForImportPath(importPath);
|
|
2994
|
+
let root = dirname(resolvedPath);
|
|
2995
|
+
while (true) {
|
|
2996
|
+
const packageJsonPath = join(root, "package.json");
|
|
2997
|
+
if (existsSync(packageJsonPath)) {
|
|
2998
|
+
const packageJson = readPackageJson(packageJsonPath);
|
|
2999
|
+
if (packageJson.name === packageName) {
|
|
3000
|
+
if (!packageJson.version) return null;
|
|
3001
|
+
return {
|
|
3002
|
+
name: packageJson.name,
|
|
3003
|
+
version: packageJson.version,
|
|
3004
|
+
root,
|
|
3005
|
+
resolvedPath,
|
|
3006
|
+
packageJson
|
|
3007
|
+
};
|
|
3008
|
+
}
|
|
3009
|
+
}
|
|
3010
|
+
const parent = dirname(root);
|
|
3011
|
+
if (parent === root) return null;
|
|
3012
|
+
root = parent;
|
|
3013
|
+
}
|
|
3014
|
+
}
|
|
3015
|
+
function hasNativeHints(info) {
|
|
3016
|
+
const files = Array.isArray(info.packageJson.files) ? info.packageJson.files : [];
|
|
3017
|
+
const fields = [info.packageJson.main, info.packageJson.module, info.packageJson.browser].filter(
|
|
3018
|
+
(f) => typeof f === "string"
|
|
3019
|
+
);
|
|
3020
|
+
return files.concat(fields).some((file) => NATIVE_EXT_RE.test(file));
|
|
3021
|
+
}
|
|
3022
|
+
function shouldAutoExternalize(info) {
|
|
3023
|
+
if (info.resolvedPath.endsWith(".node") || info.resolvedPath.endsWith(".wasm")) return true;
|
|
3024
|
+
if (hasNativeHints(info)) return true;
|
|
3025
|
+
if (existsSync(join(info.root, "binding.gyp"))) return true;
|
|
3026
|
+
return false;
|
|
3027
|
+
}
|
|
3028
|
+
function normalizeList(value) {
|
|
3029
|
+
if (Array.isArray(value)) return value.filter((v) => typeof v === "string");
|
|
3030
|
+
if (typeof value === "string") return [value];
|
|
3031
|
+
return null;
|
|
3032
|
+
}
|
|
3033
|
+
function listAllowsTarget(list, target) {
|
|
3034
|
+
if (!list || list.length === 0) return true;
|
|
3035
|
+
const negated = list.filter((v) => v.startsWith("!")).map((v) => v.slice(1));
|
|
3036
|
+
if (negated.includes(target)) return false;
|
|
3037
|
+
const positives = list.filter((v) => !v.startsWith("!"));
|
|
3038
|
+
if (positives.length === 0) return true;
|
|
3039
|
+
return positives.includes(target);
|
|
3040
|
+
}
|
|
3041
|
+
function isPackageCompatible(info) {
|
|
3042
|
+
const osList = normalizeList(info.packageJson.os);
|
|
3043
|
+
const cpuList = normalizeList(info.packageJson.cpu);
|
|
3044
|
+
return listAllowsTarget(osList, SANDBOX_PLATFORM) && listAllowsTarget(cpuList, SANDBOX_ARCH);
|
|
3045
|
+
}
|
|
3046
|
+
var INVALID_DETACHED_COMMAND_HANDLE_MESSAGE = "Detached process handle must contain a non-empty sessionId string and an optional commandId string.";
|
|
3047
|
+
function normalizeDetachedCommandHandle(value) {
|
|
3048
|
+
if (!value || typeof value !== "object") {
|
|
3049
|
+
throw new ConfigurationError(INVALID_DETACHED_COMMAND_HANDLE_MESSAGE);
|
|
3050
|
+
}
|
|
3051
|
+
let sessionId;
|
|
3052
|
+
let commandId;
|
|
3053
|
+
try {
|
|
3054
|
+
if (Array.isArray(value)) {
|
|
3055
|
+
throw new Error("invalid detached command handle");
|
|
3056
|
+
}
|
|
3057
|
+
sessionId = Reflect.get(value, "sessionId");
|
|
3058
|
+
commandId = Reflect.get(value, "commandId");
|
|
3059
|
+
} catch {
|
|
3060
|
+
throw new ConfigurationError(INVALID_DETACHED_COMMAND_HANDLE_MESSAGE);
|
|
3061
|
+
}
|
|
3062
|
+
if (typeof sessionId !== "string" || sessionId.length === 0 || commandId !== void 0 && typeof commandId !== "string") {
|
|
3063
|
+
throw new ConfigurationError(INVALID_DETACHED_COMMAND_HANDLE_MESSAGE);
|
|
3064
|
+
}
|
|
3065
|
+
return commandId === void 0 ? { sessionId } : { sessionId, commandId };
|
|
3066
|
+
}
|
|
3067
|
+
function filterDefinedEnvs(envs) {
|
|
3068
|
+
const filtered = {};
|
|
3069
|
+
for (const [key, value] of Object.entries(envs)) {
|
|
3070
|
+
if (value !== void 0) {
|
|
3071
|
+
filtered[key] = value;
|
|
3072
|
+
}
|
|
3073
|
+
}
|
|
3074
|
+
return filtered;
|
|
3075
|
+
}
|
|
3076
|
+
function asError(error) {
|
|
3077
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
3078
|
+
}
|
|
3079
|
+
function errorMessage(error) {
|
|
3080
|
+
return error instanceof Error ? error.message : String(error);
|
|
3081
|
+
}
|
|
3082
|
+
var MINIMUM_BULK_DIAGNOSTIC_REDACTION_LENGTH = 8;
|
|
3083
|
+
var CREDENTIAL_ENV_NAME_PATTERN = /(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)/iu;
|
|
3084
|
+
function isConfiguredDiagnosticSecret(name, value) {
|
|
3085
|
+
return CREDENTIAL_ENV_NAME_PATTERN.test(name) || value.length >= MINIMUM_BULK_DIAGNOSTIC_REDACTION_LENGTH;
|
|
3086
|
+
}
|
|
3087
|
+
function redactServerFailureDiagnosticStream(value, secrets) {
|
|
3088
|
+
const mayStartAtTailBoundary = Buffer.byteLength(value, "utf8") >= DETACHED_PROCESS_LOG_MAX_BYTES - 3;
|
|
3089
|
+
let redacted = boundDetachedProcessLog(value);
|
|
3090
|
+
for (const secret of secrets) {
|
|
3091
|
+
const replacement = secret.length < "[REDACTED]".length ? "*" : "[REDACTED]";
|
|
3092
|
+
redacted = redacted.split(secret).join(replacement);
|
|
3093
|
+
}
|
|
3094
|
+
let maximumSecretLength = 0;
|
|
3095
|
+
for (const secret of secrets) {
|
|
3096
|
+
maximumSecretLength = Math.max(maximumSecretLength, secret.length);
|
|
3097
|
+
}
|
|
3098
|
+
if (mayStartAtTailBoundary && maximumSecretLength > 0 && redacted.length > 0) {
|
|
3099
|
+
redacted = redacted.slice(maximumSecretLength);
|
|
3100
|
+
}
|
|
3101
|
+
return boundDetachedProcessLog(redacted);
|
|
3102
|
+
}
|
|
3103
|
+
async function readServerFailureDiagnostics(sandbox, command, environment, signal) {
|
|
3104
|
+
if (!sandbox.readSessionLogs) return "";
|
|
3105
|
+
try {
|
|
3106
|
+
const captured = await awaitDiagnosticRead(
|
|
3107
|
+
() => sandbox.readSessionLogs(command),
|
|
3108
|
+
signal
|
|
3109
|
+
);
|
|
3110
|
+
const secrets = Object.entries(environment).filter(
|
|
3111
|
+
(entry) => Boolean(entry[1]) && isConfiguredDiagnosticSecret(entry[0], entry[1])
|
|
3112
|
+
).map(([, value]) => value);
|
|
3113
|
+
secrets.sort((left, right) => right.length - left.length);
|
|
3114
|
+
const stdout = redactServerFailureDiagnosticStream(captured.stdout, secrets);
|
|
3115
|
+
const stderr = redactServerFailureDiagnosticStream(captured.stderr, secrets);
|
|
3116
|
+
const parts = [];
|
|
3117
|
+
if (stdout.trim()) parts.push(`stdout:
|
|
3118
|
+
${stdout}`);
|
|
3119
|
+
if (stderr.trim()) parts.push(`stderr:
|
|
3120
|
+
${stderr}`);
|
|
3121
|
+
if (parts.length === 0) return "";
|
|
3122
|
+
return boundDetachedProcessLog(`
|
|
3123
|
+
--- server logs ---
|
|
3124
|
+
${parts.join("\n\n")}`);
|
|
3125
|
+
} catch {
|
|
3126
|
+
throwIfAborted(signal);
|
|
3127
|
+
return "";
|
|
3128
|
+
}
|
|
3129
|
+
}
|
|
3130
|
+
function providerApiKey(provider, explicitApiKey) {
|
|
3131
|
+
if (explicitApiKey) return explicitApiKey;
|
|
3132
|
+
return requireEnv(provider === "e2b" ? "E2B_API_KEY" : "DAYTONA_API_KEY");
|
|
3133
|
+
}
|
|
3134
|
+
async function createProviderSandboxHandle(options) {
|
|
3135
|
+
if (options.provider === "modal") {
|
|
3136
|
+
validateModalOptions(options, "create", (message) => new ConfigurationError(message));
|
|
3137
|
+
return ModalSandboxHandle.create(options, (message) => new DeploymentError(message));
|
|
3138
|
+
}
|
|
3139
|
+
if (options.provider === "docker") {
|
|
3140
|
+
validateDockerOptions(options, "create", (message) => new ConfigurationError(message));
|
|
3141
|
+
return DockerSandboxHandle.create(options, (message) => new DeploymentError(message));
|
|
3142
|
+
}
|
|
3143
|
+
if (options.provider === "daytona") {
|
|
3144
|
+
const apiKey2 = providerApiKey("daytona", options.apiKey);
|
|
3145
|
+
const { Daytona } = await getDaytona();
|
|
3146
|
+
const daytona = new Daytona({ apiKey: apiKey2 });
|
|
3147
|
+
const sandbox2 = await daytona.create(
|
|
3148
|
+
{
|
|
3149
|
+
...options.template ? { snapshot: options.template } : {},
|
|
3150
|
+
...options.networkBlockAll === void 0 ? {} : { networkBlockAll: options.networkBlockAll },
|
|
3151
|
+
...options.networkAllowList === void 0 ? {} : { networkAllowList: options.networkAllowList },
|
|
3152
|
+
...options.domainAllowList === void 0 ? {} : { domainAllowList: options.domainAllowList },
|
|
3153
|
+
envVars: filterDefinedEnvs(options.envs ?? {}),
|
|
3154
|
+
autoStopInterval: options.autoStopInterval,
|
|
3155
|
+
autoDeleteInterval: options.autoDeleteInterval ?? -1
|
|
3156
|
+
},
|
|
3157
|
+
{ timeout: options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC }
|
|
3158
|
+
);
|
|
3159
|
+
try {
|
|
3160
|
+
return await DaytonaSandboxHandle.create(
|
|
3161
|
+
sandbox2,
|
|
3162
|
+
(message) => new DeploymentError(message)
|
|
3163
|
+
);
|
|
3164
|
+
} catch (error) {
|
|
3165
|
+
await sandbox2.delete(
|
|
3166
|
+
options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC,
|
|
3167
|
+
true
|
|
3168
|
+
).catch(() => void 0);
|
|
3169
|
+
throw error;
|
|
3170
|
+
}
|
|
3171
|
+
}
|
|
3172
|
+
const apiKey = providerApiKey("e2b", options.apiKey);
|
|
3173
|
+
const { Sandbox } = await getE2b();
|
|
3174
|
+
const sandboxOptions = {
|
|
3175
|
+
apiKey,
|
|
3176
|
+
envs: filterDefinedEnvs(options.envs ?? {}),
|
|
3177
|
+
timeoutMs: options.timeoutMs,
|
|
3178
|
+
requestTimeoutMs: options.requestTimeoutMs,
|
|
3179
|
+
network: options.allowPublicTraffic === void 0 ? void 0 : { allowPublicTraffic: options.allowPublicTraffic }
|
|
3180
|
+
};
|
|
3181
|
+
const sandbox = options.template ? await Sandbox.create(options.template, sandboxOptions) : await Sandbox.create(sandboxOptions);
|
|
3182
|
+
return new E2bSandboxHandle(sandbox, (message) => new DeploymentError(message));
|
|
3183
|
+
}
|
|
3184
|
+
async function connectProviderSandboxHandle(options) {
|
|
3185
|
+
if (options.provider === "modal") {
|
|
3186
|
+
validateModalOptions(options, "connect", (message) => new ConfigurationError(message));
|
|
3187
|
+
return ModalSandboxHandle.connect(options, (message) => new DeploymentError(message));
|
|
3188
|
+
}
|
|
3189
|
+
if (options.provider === "docker") {
|
|
3190
|
+
validateDockerOptions(options, "connect", (message) => new ConfigurationError(message));
|
|
3191
|
+
return DockerSandboxHandle.connect(options, (message) => new DeploymentError(message));
|
|
3192
|
+
}
|
|
3193
|
+
if (options.provider === "daytona") {
|
|
3194
|
+
const apiKey2 = providerApiKey("daytona", options.apiKey);
|
|
3195
|
+
const { Daytona } = await getDaytona();
|
|
3196
|
+
const daytona = new Daytona({ apiKey: apiKey2 });
|
|
3197
|
+
const sandbox2 = await daytona.get(options.sandboxId);
|
|
3198
|
+
if (sandbox2.state !== "started") {
|
|
3199
|
+
if (sandbox2.state === "starting" || sandbox2.state === "creating" || sandbox2.state === "restoring") {
|
|
3200
|
+
await sandbox2.waitUntilStarted(options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC);
|
|
3201
|
+
} else {
|
|
3202
|
+
await sandbox2.start(options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC);
|
|
3203
|
+
}
|
|
3204
|
+
}
|
|
3205
|
+
return DaytonaSandboxHandle.create(sandbox2, (message) => new DeploymentError(message));
|
|
3206
|
+
}
|
|
3207
|
+
const apiKey = providerApiKey("e2b", options.apiKey);
|
|
3208
|
+
const { Sandbox } = await getE2b();
|
|
3209
|
+
const sandbox = await Sandbox.connect(options.sandboxId, {
|
|
3210
|
+
apiKey,
|
|
3211
|
+
timeoutMs: options.timeoutMs,
|
|
3212
|
+
requestTimeoutMs: options.requestTimeoutMs
|
|
3213
|
+
});
|
|
3214
|
+
return new E2bSandboxHandle(sandbox, (message) => new DeploymentError(message));
|
|
3215
|
+
}
|
|
3216
|
+
async function destroyProviderSandbox(options) {
|
|
3217
|
+
if (options.provider === "modal") {
|
|
3218
|
+
validateModalOptions(options, "connect", (message) => new ConfigurationError(message));
|
|
3219
|
+
return ModalSandboxHandle.destroyById(options, (message) => new DeploymentError(message));
|
|
3220
|
+
}
|
|
3221
|
+
if (options.provider === "daytona") {
|
|
3222
|
+
const { Daytona, DaytonaNotFoundError } = await getDaytona();
|
|
3223
|
+
const daytona = new Daytona({ apiKey: providerApiKey("daytona", options.apiKey) });
|
|
3224
|
+
try {
|
|
3225
|
+
await (await daytona.get(options.sandboxId)).delete(Math.ceil(SANDBOX_COMMAND_TIMEOUT_MS2 / 1e3), true);
|
|
3226
|
+
} catch (error) {
|
|
3227
|
+
if (!(error instanceof DaytonaNotFoundError)) throw error;
|
|
3228
|
+
}
|
|
3229
|
+
return;
|
|
3230
|
+
}
|
|
3231
|
+
const { Sandbox } = await getE2b();
|
|
3232
|
+
await Sandbox.kill(options.sandboxId, { apiKey: providerApiKey("e2b", options.apiKey) });
|
|
3233
|
+
}
|
|
3234
|
+
var SandboxClient = class _SandboxClient {
|
|
3235
|
+
constructor(handle) {
|
|
3236
|
+
this.handle = handle;
|
|
3237
|
+
}
|
|
3238
|
+
static async create(options) {
|
|
3239
|
+
return new _SandboxClient(await createProviderSandboxHandle(options));
|
|
3240
|
+
}
|
|
3241
|
+
static async connect(options) {
|
|
3242
|
+
return new _SandboxClient(await connectProviderSandboxHandle(options));
|
|
3243
|
+
}
|
|
3244
|
+
get id() {
|
|
3245
|
+
return this.handle.id;
|
|
3246
|
+
}
|
|
3247
|
+
get provider() {
|
|
3248
|
+
return this.handle.provider;
|
|
3249
|
+
}
|
|
3250
|
+
get paths() {
|
|
3251
|
+
return {
|
|
3252
|
+
provider: this.handle.paths.provider,
|
|
3253
|
+
homeDir: this.handle.paths.homeDir,
|
|
3254
|
+
workDir: this.handle.paths.workDir,
|
|
3255
|
+
agentDir: this.handle.paths.agentDir,
|
|
3256
|
+
ioDir: this.handle.paths.ioDir,
|
|
3257
|
+
inputJson: this.handle.paths.inputJson,
|
|
3258
|
+
outputJson: this.handle.paths.outputJson
|
|
3259
|
+
};
|
|
3260
|
+
}
|
|
3261
|
+
async makeDir(path2) {
|
|
3262
|
+
await this.handle.makeDir(path2);
|
|
3263
|
+
}
|
|
3264
|
+
async writeFile(path2, content) {
|
|
3265
|
+
await this.handle.writeFile(path2, content);
|
|
3266
|
+
}
|
|
3267
|
+
async readFile(path2) {
|
|
3268
|
+
return this.handle.readFile(path2);
|
|
3269
|
+
}
|
|
3270
|
+
async readFileBytes(path2) {
|
|
3271
|
+
return this.handle.readFileBytes(path2);
|
|
3272
|
+
}
|
|
3273
|
+
async runCommand(command, options) {
|
|
3274
|
+
return this.handle.runCommand(command, options);
|
|
3275
|
+
}
|
|
3276
|
+
async startDetachedCommand(command, options = {}) {
|
|
3277
|
+
if (!this.handle.startDetachedCommand) {
|
|
3278
|
+
throw new ConfigurationError(
|
|
3279
|
+
`Sandbox provider "${this.provider}" does not support startDetachedCommand().`
|
|
3280
|
+
);
|
|
3281
|
+
}
|
|
3282
|
+
if (typeof command !== "string") {
|
|
3283
|
+
throw new ConfigurationError("Detached command must be a string.");
|
|
3284
|
+
}
|
|
3285
|
+
const normalized = normalizeProviderSandboxDetachedCommandOptions(
|
|
3286
|
+
options,
|
|
3287
|
+
(message) => new ConfigurationError(message),
|
|
3288
|
+
{ requireObject: true }
|
|
3289
|
+
);
|
|
3290
|
+
return this.handle.startDetachedCommand(command, normalized.options);
|
|
3291
|
+
}
|
|
3292
|
+
async readSessionLogs(commandOrSessionId, legacyCommandId) {
|
|
3293
|
+
if (!this.handle.readSessionLogs) {
|
|
3294
|
+
throw new ConfigurationError(
|
|
3295
|
+
`Sandbox provider "${this.provider}" does not support readSessionLogs().`
|
|
3296
|
+
);
|
|
3297
|
+
}
|
|
3298
|
+
if (typeof commandOrSessionId === "string" && legacyCommandId === void 0) {
|
|
3299
|
+
throw new ConfigurationError(
|
|
3300
|
+
"Legacy detached session log reads require a command ID."
|
|
3301
|
+
);
|
|
3302
|
+
}
|
|
3303
|
+
const command = typeof commandOrSessionId === "string" ? { sessionId: commandOrSessionId, commandId: legacyCommandId } : normalizeDetachedCommandHandle(commandOrSessionId);
|
|
3304
|
+
return this.handle.readSessionLogs(command);
|
|
3305
|
+
}
|
|
3306
|
+
async stopSession(commandOrSessionId) {
|
|
3307
|
+
if (!this.handle.stopSession) {
|
|
3308
|
+
throw new ConfigurationError(
|
|
3309
|
+
`Sandbox provider "${this.provider}" does not support stopSession().`
|
|
3310
|
+
);
|
|
3311
|
+
}
|
|
3312
|
+
const command = typeof commandOrSessionId === "string" ? { sessionId: commandOrSessionId } : normalizeDetachedCommandHandle(commandOrSessionId);
|
|
3313
|
+
await this.handle.stopSession(command);
|
|
3314
|
+
}
|
|
3315
|
+
/**
|
|
3316
|
+
* Irreversibly removes private lifecycle state and captured diagnostics for
|
|
3317
|
+
* one managed detached command. Call `stopSession()` first, then perform any
|
|
3318
|
+
* final `readSessionLogs()` before disposal. Disposal is idempotent after a
|
|
3319
|
+
* confirmed stop but is not itself evidence that the process stopped.
|
|
3320
|
+
*/
|
|
3321
|
+
async disposeSessionArtifacts(command) {
|
|
3322
|
+
if (!this.handle.disposeSessionArtifacts) {
|
|
3323
|
+
throw new ConfigurationError(
|
|
3324
|
+
`Sandbox provider "${this.provider}" does not support disposeSessionArtifacts().`
|
|
3325
|
+
);
|
|
3326
|
+
}
|
|
3327
|
+
await this.handle.disposeSessionArtifacts(
|
|
3328
|
+
normalizeDetachedCommandHandle(command)
|
|
3329
|
+
);
|
|
3330
|
+
}
|
|
3331
|
+
async setTimeout(timeoutMs) {
|
|
3332
|
+
if (!this.handle.setTimeout) {
|
|
3333
|
+
throw new ConfigurationError(`Sandbox provider "${this.provider}" does not support setTimeout().`);
|
|
3334
|
+
}
|
|
3335
|
+
await this.handle.setTimeout(timeoutMs);
|
|
3336
|
+
}
|
|
3337
|
+
/**
|
|
3338
|
+
* Where to reach an HTTP server the sandbox runs on `port`, with the provider's auth: send
|
|
3339
|
+
* `headers` with every request and add `query` to every URL.
|
|
3340
|
+
*/
|
|
3341
|
+
async getServerEndpoint(port) {
|
|
3342
|
+
if (!this.handle.getServerEndpoint) {
|
|
3343
|
+
throw new ConfigurationError(`Sandbox provider "${this.provider}" does not expose server ports.`);
|
|
3344
|
+
}
|
|
3345
|
+
const { url, trafficToken } = await this.handle.getServerEndpoint(port);
|
|
3346
|
+
const descriptor = { provider: this.provider, trafficToken };
|
|
3347
|
+
return {
|
|
3348
|
+
url: url.replace(/\/+$/u, ""),
|
|
3349
|
+
headers: trafficTokenHeaders(descriptor),
|
|
3350
|
+
query: this.provider === "daytona" && trafficToken ? { DAYTONA_SANDBOX_AUTH_KEY: trafficToken } : {}
|
|
3351
|
+
};
|
|
3352
|
+
}
|
|
3353
|
+
async kill() {
|
|
3354
|
+
await this.handle.destroy();
|
|
3355
|
+
}
|
|
3356
|
+
async destroy() {
|
|
3357
|
+
await this.kill();
|
|
3358
|
+
}
|
|
3359
|
+
};
|
|
3360
|
+
function normalizeStackFramePath(rawPath, cwd = process.cwd()) {
|
|
3361
|
+
if (rawPath.startsWith("file://")) {
|
|
3362
|
+
return fileURLToPath(rawPath);
|
|
3363
|
+
}
|
|
3364
|
+
if (rawPath.startsWith("webpack-internal:")) {
|
|
3365
|
+
const afterScheme = rawPath.replace(/^webpack-internal:\/+/, "");
|
|
3366
|
+
const afterLayer = afterScheme.replace(/^\([^)]+\)\//, "");
|
|
3367
|
+
const resolved = resolve(cwd, afterLayer);
|
|
3368
|
+
return existsSync(resolved) ? resolved : null;
|
|
3369
|
+
}
|
|
3370
|
+
return rawPath;
|
|
3371
|
+
}
|
|
3372
|
+
function getCallerFile() {
|
|
3373
|
+
const stack = new Error().stack?.split("\n") ?? [];
|
|
3374
|
+
let moduleFile;
|
|
3375
|
+
let bundledFallback;
|
|
3376
|
+
for (const line of stack.slice(1)) {
|
|
3377
|
+
const match = line.match(/\((.+?):\d+:\d+\)/) || line.match(/at (.+?):\d+:\d+/);
|
|
3378
|
+
if (!match) continue;
|
|
3379
|
+
const file = normalizeStackFramePath(match[1]);
|
|
3380
|
+
if (!file) continue;
|
|
3381
|
+
if (!moduleFile) {
|
|
3382
|
+
moduleFile = file;
|
|
3383
|
+
continue;
|
|
3384
|
+
}
|
|
3385
|
+
if (file.includes("node:")) continue;
|
|
3386
|
+
if (file.includes("node_modules/agent-neckbeard")) continue;
|
|
3387
|
+
if (file === moduleFile) {
|
|
3388
|
+
bundledFallback ??= file;
|
|
3389
|
+
continue;
|
|
3390
|
+
}
|
|
3391
|
+
return file;
|
|
3392
|
+
}
|
|
3393
|
+
if (bundledFallback) return bundledFallback;
|
|
3394
|
+
throw new Error("Could not determine source file");
|
|
3395
|
+
}
|
|
3396
|
+
function isFrameworkBuildOutputPath(file) {
|
|
3397
|
+
const normalized = file.replace(/\\/g, "/");
|
|
3398
|
+
return normalized.includes("/.next/server/chunks/") || normalized.includes("/.next/server/app/") || normalized.includes("/.next/server/pages/");
|
|
3399
|
+
}
|
|
3400
|
+
function frameworkBuildOutputError(file) {
|
|
3401
|
+
return new ConfigurationError(
|
|
3402
|
+
`Agent source resolved to framework build output (${file}). Set sourceFile to the original agent module so deploy() bundles your agent source instead of a framework chunk.`
|
|
3403
|
+
);
|
|
3404
|
+
}
|
|
3405
|
+
function resolveSourceFile(sourceFile) {
|
|
3406
|
+
if (!sourceFile) {
|
|
3407
|
+
const inferred = getCallerFile();
|
|
3408
|
+
if (isFrameworkBuildOutputPath(inferred)) {
|
|
3409
|
+
throw frameworkBuildOutputError(inferred);
|
|
3410
|
+
}
|
|
3411
|
+
return inferred;
|
|
3412
|
+
}
|
|
3413
|
+
const normalized = normalizeStackFramePath(sourceFile);
|
|
3414
|
+
if (!normalized) {
|
|
3415
|
+
throw new ConfigurationError(`sourceFile could not be resolved: ${sourceFile}`);
|
|
3416
|
+
}
|
|
3417
|
+
const resolved = resolve(normalized);
|
|
3418
|
+
if (isFrameworkBuildOutputPath(resolved)) {
|
|
3419
|
+
throw frameworkBuildOutputError(resolved);
|
|
3420
|
+
}
|
|
3421
|
+
if (!existsSync(resolved)) {
|
|
3422
|
+
throw new ConfigurationError(`sourceFile does not exist: ${resolved}`);
|
|
3423
|
+
}
|
|
3424
|
+
return resolved;
|
|
3425
|
+
}
|
|
3426
|
+
function localPathStats(localPath, upload, isSourceRoot = false) {
|
|
3427
|
+
let stats;
|
|
3428
|
+
try {
|
|
3429
|
+
stats = lstatSync(localPath);
|
|
3430
|
+
} catch (error) {
|
|
3431
|
+
const code = error.code;
|
|
3432
|
+
const detail = isSourceRoot && code === "ENOENT" ? "source does not exist" : "could not read local path";
|
|
3433
|
+
throw new ConfigurationError(
|
|
3434
|
+
`${upload.name} ${detail}: ${localPath} (${errorMessage(error)})`
|
|
3435
|
+
);
|
|
3436
|
+
}
|
|
3437
|
+
if (!stats.isSymbolicLink()) return stats;
|
|
3438
|
+
if (upload.rejectSymlinks) {
|
|
3439
|
+
throw new ConfigurationError(
|
|
3440
|
+
`${upload.name} source tree contains a symbolic link: ${localPath}`
|
|
3441
|
+
);
|
|
3442
|
+
}
|
|
3443
|
+
try {
|
|
3444
|
+
return statSync(localPath);
|
|
3445
|
+
} catch (error) {
|
|
3446
|
+
throw new ConfigurationError(
|
|
3447
|
+
`${upload.name} could not follow legacy symbolic link: ${localPath} (${errorMessage(error)})`
|
|
3448
|
+
);
|
|
3449
|
+
}
|
|
3450
|
+
}
|
|
3451
|
+
function readConfiguredLocalDirectory(upload) {
|
|
3452
|
+
const rootPath = resolve(process.cwd(), upload.source);
|
|
3453
|
+
const rootStats = localPathStats(rootPath, upload, true);
|
|
3454
|
+
if (!rootStats.isDirectory()) {
|
|
3455
|
+
throw new ConfigurationError(`${upload.name}.source must be a directory: ${rootPath}`);
|
|
3456
|
+
}
|
|
3457
|
+
const destination = normalizeLocalDirectoryDestination(upload.destination, upload.name);
|
|
3458
|
+
const files = [];
|
|
3459
|
+
function walk(currentPath) {
|
|
3460
|
+
let entries;
|
|
3461
|
+
try {
|
|
3462
|
+
entries = readdirSync(currentPath).sort((left, right) => left.localeCompare(right));
|
|
3463
|
+
} catch (error) {
|
|
3464
|
+
throw new ConfigurationError(
|
|
3465
|
+
`${upload.name} could not read local directory: ${currentPath} (${errorMessage(error)})`
|
|
3466
|
+
);
|
|
3467
|
+
}
|
|
3468
|
+
for (const entry of entries) {
|
|
3469
|
+
const localPath = join(currentPath, entry);
|
|
3470
|
+
const stats = localPathStats(localPath, upload);
|
|
3471
|
+
if (stats.isDirectory()) {
|
|
3472
|
+
walk(localPath);
|
|
3473
|
+
continue;
|
|
3474
|
+
}
|
|
3475
|
+
if (!stats.isFile()) {
|
|
3476
|
+
throw new ConfigurationError(
|
|
3477
|
+
`${upload.name} source tree contains an unsupported filesystem entry: ${localPath}`
|
|
3478
|
+
);
|
|
3479
|
+
}
|
|
3480
|
+
const relativePath = relative(rootPath, localPath).split(sep).join("/");
|
|
3481
|
+
const targetPath = posix.join(destination, relativePath);
|
|
3482
|
+
let content;
|
|
3483
|
+
try {
|
|
3484
|
+
content = readFileSync(localPath);
|
|
3485
|
+
} catch (error) {
|
|
3486
|
+
throw new ConfigurationError(
|
|
3487
|
+
`${upload.name} could not read local file: ${localPath} (${errorMessage(error)})`
|
|
3488
|
+
);
|
|
3489
|
+
}
|
|
3490
|
+
files.push({ localPath, targetPath, content });
|
|
3491
|
+
}
|
|
3492
|
+
}
|
|
3493
|
+
walk(rootPath);
|
|
3494
|
+
return { rootPath, files };
|
|
3495
|
+
}
|
|
3496
|
+
function prepareLocalDirectoryUploads(localDirectories, claudeDir) {
|
|
3497
|
+
const uploads = localDirectories.map((entry, index) => ({
|
|
3498
|
+
...entry,
|
|
3499
|
+
name: `localDirectories[${index}]`,
|
|
3500
|
+
rejectSymlinks: true,
|
|
3501
|
+
preserveRootDirectory: false
|
|
3502
|
+
}));
|
|
3503
|
+
if (claudeDir) {
|
|
3504
|
+
uploads.push({
|
|
3505
|
+
source: claudeDir,
|
|
3506
|
+
destination: ".claude",
|
|
3507
|
+
name: "claudeDir",
|
|
3508
|
+
rejectSymlinks: false,
|
|
3509
|
+
preserveRootDirectory: true
|
|
3510
|
+
});
|
|
3511
|
+
}
|
|
3512
|
+
const filesByTarget = /* @__PURE__ */ new Map();
|
|
3513
|
+
const requiredDirectories = /* @__PURE__ */ new Set();
|
|
3514
|
+
for (const upload of uploads) {
|
|
3515
|
+
const prepared = readConfiguredLocalDirectory(upload);
|
|
3516
|
+
const destination = normalizeLocalDirectoryDestination(upload.destination, upload.name);
|
|
3517
|
+
if (upload.preserveRootDirectory) {
|
|
3518
|
+
requiredDirectories.add(destination);
|
|
3519
|
+
}
|
|
3520
|
+
for (const file of prepared.files) {
|
|
3521
|
+
const existing = filesByTarget.get(file.targetPath);
|
|
3522
|
+
if (existing) {
|
|
3523
|
+
throw new ConfigurationError(
|
|
3524
|
+
`Duplicate sandbox target "${file.targetPath}" from local files "${existing.localPath}" and "${file.localPath}".`
|
|
3525
|
+
);
|
|
3526
|
+
}
|
|
3527
|
+
filesByTarget.set(file.targetPath, file);
|
|
3528
|
+
}
|
|
3529
|
+
}
|
|
3530
|
+
for (const file of filesByTarget.values()) {
|
|
3531
|
+
let parent = posix.dirname(file.targetPath);
|
|
3532
|
+
while (parent !== ".") {
|
|
3533
|
+
const parentFile = filesByTarget.get(parent);
|
|
3534
|
+
if (parentFile) {
|
|
3535
|
+
throw new ConfigurationError(
|
|
3536
|
+
`Sandbox target collision: local file "${parentFile.localPath}" maps to "${parent}", which must be a directory for "${file.localPath}".`
|
|
3537
|
+
);
|
|
3538
|
+
}
|
|
3539
|
+
requiredDirectories.add(parent);
|
|
3540
|
+
parent = posix.dirname(parent);
|
|
3541
|
+
}
|
|
3542
|
+
}
|
|
3543
|
+
const directories = [...requiredDirectories].sort((left, right) => {
|
|
3544
|
+
const depthDifference = left.split("/").length - right.split("/").length;
|
|
3545
|
+
return depthDifference || left.localeCompare(right);
|
|
3546
|
+
});
|
|
3547
|
+
const files = [...filesByTarget.values()].sort(
|
|
3548
|
+
(left, right) => left.targetPath.localeCompare(right.targetPath)
|
|
3549
|
+
);
|
|
3550
|
+
return { directories, files };
|
|
3551
|
+
}
|
|
3552
|
+
var LegacyBundledAgent = class {
|
|
3553
|
+
sandbox;
|
|
3554
|
+
provider;
|
|
3555
|
+
template;
|
|
3556
|
+
inputSchema;
|
|
3557
|
+
/** Only populated for structured-task agents; undefined for session agents. */
|
|
3558
|
+
outputSchema;
|
|
3559
|
+
/** Only populated for attached-session agents; undefined for run-output agents. */
|
|
3560
|
+
frameSchema;
|
|
3561
|
+
/** User-facing execution shape. */
|
|
3562
|
+
kind;
|
|
3563
|
+
/** @deprecated Use `kind`; retained for compatibility with `run | stream` checks. */
|
|
3564
|
+
mode;
|
|
3565
|
+
maxDuration;
|
|
3566
|
+
dependencies;
|
|
3567
|
+
files;
|
|
3568
|
+
localDirectories;
|
|
3569
|
+
/** @deprecated Use `localDirectories` with destination `.claude` instead. */
|
|
3570
|
+
claudeDir;
|
|
3571
|
+
envs;
|
|
3572
|
+
build;
|
|
3573
|
+
/** @internal Used by the in-sandbox server for run-output agents. */
|
|
3574
|
+
_run;
|
|
3575
|
+
/** @internal Used by the in-sandbox server for attached-session agents. */
|
|
3576
|
+
_server;
|
|
3577
|
+
/** @internal Runtime state populated by deploy(). */
|
|
3578
|
+
_serverRuntime;
|
|
3579
|
+
_sandboxId;
|
|
3580
|
+
_sourceFile;
|
|
3581
|
+
constructor(config) {
|
|
3582
|
+
validateAgentConfig(config);
|
|
3583
|
+
this.sandbox = config.sandbox;
|
|
3584
|
+
this.provider = config.sandbox.provider;
|
|
3585
|
+
this.template = config.sandbox.template ?? (config.sandbox.provider === "docker" ? DOCKER_DEFAULT_TEMPLATE : MODAL_DEFAULT_TEMPLATE);
|
|
3586
|
+
this.inputSchema = config.inputSchema;
|
|
3587
|
+
this.maxDuration = config.maxDuration ?? DEFAULT_MAX_DURATION;
|
|
3588
|
+
this._sourceFile = resolveSourceFile(config.sourceFile);
|
|
3589
|
+
this.dependencies = config.dependencies ?? DEFAULT_DEPENDENCIES;
|
|
3590
|
+
this.files = config.files ?? [];
|
|
3591
|
+
this.localDirectories = (config.localDirectories ?? []).map((entry) => ({ ...entry }));
|
|
3592
|
+
this.claudeDir = config.claudeDir;
|
|
3593
|
+
this.envs = config.envs ?? {};
|
|
3594
|
+
this.build = config.build ?? {};
|
|
3595
|
+
if (isSessionAgentConfig(config)) {
|
|
3596
|
+
const session = getSessionHandler(config);
|
|
3597
|
+
this.kind = "session";
|
|
3598
|
+
this.mode = "stream";
|
|
3599
|
+
this._server = session;
|
|
3600
|
+
this.frameSchema = session.frameSchema;
|
|
3601
|
+
} else {
|
|
3602
|
+
this.kind = "task";
|
|
3603
|
+
this.mode = "run";
|
|
3604
|
+
this._run = config.run;
|
|
3605
|
+
this.outputSchema = config.outputSchema;
|
|
3606
|
+
}
|
|
3607
|
+
}
|
|
3608
|
+
get sandboxId() {
|
|
3609
|
+
return this._serverRuntime?.connection.sandboxId ?? this._sandboxId;
|
|
3610
|
+
}
|
|
3611
|
+
get sandboxEnv() {
|
|
3612
|
+
return {
|
|
3613
|
+
...filterDefinedEnvs(this.envs),
|
|
3614
|
+
[NECKBEARD_SANDBOX_RUNTIME_ENV]: "1"
|
|
3615
|
+
};
|
|
3616
|
+
}
|
|
3617
|
+
async createSandboxHandle() {
|
|
3618
|
+
if (this.sandbox.provider === "modal" || this.sandbox.provider === "docker") {
|
|
3619
|
+
return createProviderSandboxHandle({ ...this.sandbox, envs: this.sandboxEnv });
|
|
3620
|
+
}
|
|
3621
|
+
if (this.provider === "e2b") {
|
|
3622
|
+
return createProviderSandboxHandle({
|
|
3623
|
+
provider: "e2b",
|
|
3624
|
+
template: this.template,
|
|
3625
|
+
envs: this.sandboxEnv,
|
|
3626
|
+
allowPublicTraffic: false
|
|
3627
|
+
});
|
|
3628
|
+
}
|
|
3629
|
+
const sandbox = this.sandbox;
|
|
3630
|
+
return createProviderSandboxHandle({
|
|
3631
|
+
provider: "daytona",
|
|
3632
|
+
template: this.template,
|
|
3633
|
+
envs: this.sandboxEnv,
|
|
3634
|
+
networkBlockAll: sandbox.networkBlockAll,
|
|
3635
|
+
networkAllowList: sandbox.networkAllowList,
|
|
3636
|
+
domainAllowList: sandbox.domainAllowList,
|
|
3637
|
+
autoStopInterval: sandbox.autoStopInterval,
|
|
3638
|
+
autoDeleteInterval: sandbox.autoDeleteInterval
|
|
3639
|
+
});
|
|
3640
|
+
}
|
|
3641
|
+
async connectSandboxHandle(sandboxId) {
|
|
3642
|
+
if (this.sandbox.provider === "modal") {
|
|
3643
|
+
return connectProviderSandboxHandle({
|
|
3644
|
+
provider: "modal",
|
|
3645
|
+
sandboxId,
|
|
3646
|
+
environment: this.sandbox.environment
|
|
3647
|
+
});
|
|
3648
|
+
}
|
|
3649
|
+
if (this.sandbox.provider === "docker") {
|
|
3650
|
+
return connectProviderSandboxHandle({ provider: "docker", sandboxId });
|
|
3651
|
+
}
|
|
3652
|
+
if (this.provider === "e2b") {
|
|
3653
|
+
return connectProviderSandboxHandle({
|
|
3654
|
+
provider: "e2b",
|
|
3655
|
+
sandboxId
|
|
3656
|
+
});
|
|
3657
|
+
}
|
|
3658
|
+
return connectProviderSandboxHandle({
|
|
3659
|
+
provider: "daytona",
|
|
3660
|
+
sandboxId
|
|
3661
|
+
});
|
|
3662
|
+
}
|
|
3663
|
+
async readRuntimeServerConfig(sandbox) {
|
|
3664
|
+
try {
|
|
3665
|
+
return JSON.parse(await sandbox.readFile(sandbox.paths.serverConfig));
|
|
3666
|
+
} catch {
|
|
3667
|
+
return void 0;
|
|
3668
|
+
}
|
|
3669
|
+
}
|
|
3670
|
+
async createRuntimeConnection(sandbox, port) {
|
|
3671
|
+
if (!sandbox.getServerEndpoint) {
|
|
3672
|
+
throw new DeploymentError(
|
|
3673
|
+
"Persistent agents require a sandbox provider that supports public port endpoints."
|
|
3674
|
+
);
|
|
3675
|
+
}
|
|
3676
|
+
const endpoint = await sandbox.getServerEndpoint(port);
|
|
3677
|
+
const baseServerUrl = endpoint.url.replace(/\/$/, "");
|
|
3678
|
+
return {
|
|
3679
|
+
provider: this.provider,
|
|
3680
|
+
sandboxId: sandbox.id,
|
|
3681
|
+
serverUrl: `${baseServerUrl}/invoke`,
|
|
3682
|
+
trafficToken: endpoint.trafficToken
|
|
3683
|
+
};
|
|
3684
|
+
}
|
|
3685
|
+
healthUrlFor(connection) {
|
|
3686
|
+
const url = new URL(connection.serverUrl);
|
|
3687
|
+
url.pathname = url.pathname.replace(/\/invoke$/, "/health");
|
|
3688
|
+
url.search = "";
|
|
3689
|
+
return url.toString();
|
|
3690
|
+
}
|
|
3691
|
+
async startRuntimeServer(sandbox) {
|
|
3692
|
+
if (!sandbox.startDetachedCommand) {
|
|
3693
|
+
throw new DeploymentError(
|
|
3694
|
+
"Persistent agents require a sandbox provider that supports background commands."
|
|
3695
|
+
);
|
|
3696
|
+
}
|
|
3697
|
+
return sandbox.startDetachedCommand("node server.mjs", {
|
|
3698
|
+
cwd: sandbox.paths.agentDir,
|
|
3699
|
+
envs: this.sandboxEnv
|
|
3700
|
+
});
|
|
3701
|
+
}
|
|
3702
|
+
async resolveRuntimeConnection(sandboxId, options = {}) {
|
|
3703
|
+
const { signal } = options;
|
|
3704
|
+
throwIfAborted(signal);
|
|
3705
|
+
const targetId = sandboxId ?? this._serverRuntime?.connection.sandboxId ?? this._sandboxId;
|
|
3706
|
+
if (!targetId) {
|
|
3707
|
+
throw new ConfigurationError("Agent not deployed. Call agent.deploy() first or pass sandboxId.");
|
|
3708
|
+
}
|
|
3709
|
+
if ((!sandboxId || options.reuseMatchingCachedConnection) && this._serverRuntime?.connection.sandboxId === targetId) {
|
|
3710
|
+
return this._serverRuntime.connection;
|
|
3711
|
+
}
|
|
3712
|
+
const sandbox = await awaitWithAbort(() => this.connectSandboxHandle(targetId), signal);
|
|
3713
|
+
if (sandbox.id !== targetId) {
|
|
3714
|
+
throw new DeploymentError("Sandbox provider returned an unexpected runtime identity.");
|
|
3715
|
+
}
|
|
3716
|
+
const serverConfig = await awaitWithAbort(
|
|
3717
|
+
() => this.readRuntimeServerConfig(sandbox),
|
|
3718
|
+
signal
|
|
3719
|
+
);
|
|
3720
|
+
const port = serverConfig?.port ?? this._server?.port ?? DEFAULT_SERVER_PORT;
|
|
3721
|
+
const connection = await awaitWithAbort(
|
|
3722
|
+
() => this.createRuntimeConnection(sandbox, port),
|
|
3723
|
+
signal
|
|
3724
|
+
);
|
|
3725
|
+
const healthUrl = this.healthUrlFor(connection);
|
|
3726
|
+
try {
|
|
3727
|
+
await waitForServerHealthy(
|
|
3728
|
+
healthUrl,
|
|
3729
|
+
connection,
|
|
3730
|
+
SERVER_RECONNECT_HEALTH_TIMEOUT_MS,
|
|
3731
|
+
signal
|
|
3732
|
+
);
|
|
3733
|
+
throwIfAborted(signal);
|
|
3734
|
+
const cachedRuntime = this._serverRuntime;
|
|
3735
|
+
this._serverRuntime = cachedRuntime?.connection.sandboxId === targetId ? { ...cachedRuntime, connection } : { connection };
|
|
3736
|
+
this._sandboxId = targetId;
|
|
3737
|
+
return connection;
|
|
3738
|
+
} catch {
|
|
3739
|
+
throwIfAborted(signal);
|
|
3740
|
+
const detachedCommand = await awaitWithAbort(
|
|
3741
|
+
() => this.startRuntimeServer(sandbox),
|
|
3742
|
+
signal
|
|
3743
|
+
);
|
|
3744
|
+
try {
|
|
3745
|
+
await waitForServerHealthy(
|
|
3746
|
+
healthUrl,
|
|
3747
|
+
connection,
|
|
3748
|
+
SERVER_HEALTH_TIMEOUT_MS,
|
|
3749
|
+
signal
|
|
3750
|
+
);
|
|
3751
|
+
} catch (error) {
|
|
3752
|
+
throwIfAborted(signal);
|
|
3753
|
+
const baseMessage = error instanceof Error ? error.message : String(error);
|
|
3754
|
+
const logs = await readServerFailureDiagnostics(
|
|
3755
|
+
sandbox,
|
|
3756
|
+
detachedCommand,
|
|
3757
|
+
this.envs,
|
|
3758
|
+
signal
|
|
3759
|
+
);
|
|
3760
|
+
throw new DeploymentError(`${baseMessage}${logs}`);
|
|
3761
|
+
}
|
|
3762
|
+
throwIfAborted(signal);
|
|
3763
|
+
this._serverRuntime = { detachedCommand, connection };
|
|
3764
|
+
this._sandboxId = targetId;
|
|
3765
|
+
return connection;
|
|
3766
|
+
}
|
|
3767
|
+
}
|
|
3768
|
+
/**
|
|
3769
|
+
* Kills the current sandbox and resets the cached runtime.
|
|
3770
|
+
*
|
|
3771
|
+
* Use this to clean up sandbox resources after a run, especially when
|
|
3772
|
+
* running multiple evaluations that each need their own sandbox.
|
|
3773
|
+
*
|
|
3774
|
+
* @param target - Optional sandbox ID to kill. Defaults to the cached sandbox.
|
|
3775
|
+
*
|
|
3776
|
+
* @example
|
|
3777
|
+
* ```typescript
|
|
3778
|
+
* const sandboxId = await agent.deploy();
|
|
3779
|
+
* const result = await agent.run(input, { sandboxId });
|
|
3780
|
+
* await agent.kill(sandboxId);
|
|
3781
|
+
* ```
|
|
3782
|
+
*/
|
|
3783
|
+
async kill(target) {
|
|
3784
|
+
const targetId = target ?? this._serverRuntime?.connection.sandboxId ?? this._sandboxId;
|
|
3785
|
+
if (!targetId) return;
|
|
3786
|
+
try {
|
|
3787
|
+
const sandbox = await this.connectSandboxHandle(targetId);
|
|
3788
|
+
if (this._serverRuntime && this._serverRuntime.connection.sandboxId === targetId && this._serverRuntime.detachedCommand && sandbox.stopSession) {
|
|
3789
|
+
await sandbox.stopSession(this._serverRuntime.detachedCommand).catch(() => void 0);
|
|
3790
|
+
}
|
|
3791
|
+
await sandbox.destroy();
|
|
3792
|
+
} catch {
|
|
3793
|
+
}
|
|
3794
|
+
if (targetId === this._sandboxId) {
|
|
3795
|
+
this._sandboxId = void 0;
|
|
3796
|
+
}
|
|
3797
|
+
if (targetId === this._serverRuntime?.connection.sandboxId) {
|
|
3798
|
+
this._serverRuntime = void 0;
|
|
3799
|
+
}
|
|
3800
|
+
}
|
|
3801
|
+
/**
|
|
3802
|
+
* Deploys the agent to a sandbox provider.
|
|
3803
|
+
*
|
|
3804
|
+
* This method bundles the agent code using esbuild, creates a new sandbox,
|
|
3805
|
+
* installs any specified OS dependencies, downloads configured files, and
|
|
3806
|
+
* uploads the agent and runtime server code, then starts a long-running HTTP
|
|
3807
|
+
* server inside the sandbox.
|
|
3808
|
+
*
|
|
3809
|
+
* @param options.fresh - When true, always creates a new sandbox without caching.
|
|
3810
|
+
* Useful for concurrent evaluations where each run needs its own sandbox.
|
|
3811
|
+
* The returned sandbox ID won't be stored on the instance.
|
|
3812
|
+
* @returns The sandbox ID. Persist this ID when another host process should reuse the sandbox.
|
|
3813
|
+
* @throws {ConfigurationError} If the selected provider credentials are not set
|
|
3814
|
+
* @throws {DeploymentError} If sandbox creation, dependency installation, or file upload fails
|
|
3815
|
+
*
|
|
3816
|
+
* @example
|
|
3817
|
+
* ```typescript
|
|
3818
|
+
* const agent = new LegacyBundledAgent({ ... });
|
|
3819
|
+
* const sandboxId = await agent.deploy();
|
|
3820
|
+
* console.log(`Deployed to sandbox: ${sandboxId}`);
|
|
3821
|
+
*
|
|
3822
|
+
* // For concurrent evals: each call gets its own sandbox
|
|
3823
|
+
* const sandboxId = await agent.deploy({ fresh: true });
|
|
3824
|
+
* const result = await agent.run(input, { sandboxId });
|
|
3825
|
+
* await agent.kill(sandboxId);
|
|
3826
|
+
* ```
|
|
3827
|
+
*/
|
|
3828
|
+
async deploy(options) {
|
|
3829
|
+
return this._deploy(options);
|
|
3830
|
+
}
|
|
3831
|
+
async _deploy(options) {
|
|
3832
|
+
if (!options?.fresh && this._serverRuntime) return this._serverRuntime.connection.sandboxId;
|
|
3833
|
+
const localDirectoryUploads = prepareLocalDirectoryUploads(
|
|
3834
|
+
this.localDirectories,
|
|
3835
|
+
this.claudeDir
|
|
3836
|
+
);
|
|
3837
|
+
const esbuild = await getEsbuild();
|
|
3838
|
+
const externalPatterns = Array.from(
|
|
3839
|
+
/* @__PURE__ */ new Set([...DEFAULT_EXTERNALS, ...this.build.external ?? []])
|
|
3840
|
+
);
|
|
3841
|
+
const externalMatchers = externalPatterns.map(globToRegExp);
|
|
3842
|
+
const autoDetectExternal = this.build.autoDetectExternal ?? true;
|
|
3843
|
+
const collectedExternals = /* @__PURE__ */ new Map();
|
|
3844
|
+
const result = await esbuild.build({
|
|
3845
|
+
entryPoints: [this._sourceFile],
|
|
3846
|
+
bundle: true,
|
|
3847
|
+
platform: "node",
|
|
3848
|
+
target: NODE_TARGET,
|
|
3849
|
+
format: "esm",
|
|
3850
|
+
write: false,
|
|
3851
|
+
minify: true,
|
|
3852
|
+
keepNames: true,
|
|
3853
|
+
treeShaking: false,
|
|
3854
|
+
// Preserve exports for the runtime server to import
|
|
3855
|
+
banner: {
|
|
3856
|
+
js: `import { fileURLToPath as __neckbeard_fileURLToPath } from 'node:url';
|
|
3857
|
+
import { dirname as __neckbeard_dirname } from 'node:path';
|
|
3858
|
+
import { createRequire as __neckbeard_createRequire } from 'node:module';
|
|
3859
|
+
var __filename = __neckbeard_fileURLToPath(import.meta.url);
|
|
3860
|
+
var __dirname = __neckbeard_dirname(__filename);
|
|
3861
|
+
var require = __neckbeard_createRequire(import.meta.url);
|
|
3862
|
+
`
|
|
3863
|
+
},
|
|
3864
|
+
plugins: [{
|
|
3865
|
+
name: "agent-neckbeard-externals",
|
|
3866
|
+
setup(build) {
|
|
3867
|
+
build.onResolve({ filter: /^agent-neckbeard$/ }, () => ({
|
|
3868
|
+
path: "agent-neckbeard",
|
|
3869
|
+
namespace: "agent-shim"
|
|
3870
|
+
}));
|
|
3871
|
+
build.onLoad({ filter: /.*/, namespace: "agent-shim" }, () => ({
|
|
3872
|
+
contents: `
|
|
3873
|
+
export class LegacyBundledAgent {
|
|
3874
|
+
constructor(config) {
|
|
3875
|
+
this.inputSchema = config.inputSchema;
|
|
3876
|
+
this.outputSchema = config.outputSchema;
|
|
3877
|
+
this.maxDuration = config.maxDuration ?? 300;
|
|
3878
|
+
this._run = config.run;
|
|
3879
|
+
const session = config.session ?? config.server;
|
|
3880
|
+
if (session) {
|
|
3881
|
+
this.kind = 'session';
|
|
3882
|
+
this.mode = 'stream';
|
|
3883
|
+
this._server = session;
|
|
3884
|
+
this.frameSchema = session.frameSchema;
|
|
3885
|
+
} else {
|
|
3886
|
+
this.kind = 'task';
|
|
3887
|
+
this.mode = 'run';
|
|
3888
|
+
}
|
|
3889
|
+
}
|
|
3890
|
+
}
|
|
3891
|
+
export function resolveAgentSourceFile(_candidates, options = {}) {
|
|
3892
|
+
return options.sandboxSourceFile ?? process.cwd() + '/agent.mjs';
|
|
3893
|
+
}
|
|
3894
|
+
`,
|
|
3895
|
+
loader: "js"
|
|
3896
|
+
}));
|
|
3897
|
+
build.onResolve({ filter: /^[^.\/]|^\.[^.\/]|^\.\.[^\/]/ }, async (args) => {
|
|
3898
|
+
if (args.path.startsWith("node:")) return null;
|
|
3899
|
+
if (builtinModules.includes(args.path.replace("node:", ""))) return null;
|
|
3900
|
+
if (!isBareModuleImport(args.path)) return null;
|
|
3901
|
+
const pkgName = packageNameForImportPath(args.path);
|
|
3902
|
+
if (externalMatchers.length && matchesExternal(externalMatchers, pkgName)) {
|
|
3903
|
+
const info2 = await resolvePackageInfo(args.path, args.resolveDir);
|
|
3904
|
+
if (!info2) return null;
|
|
3905
|
+
collectedExternals.set(info2.name, info2);
|
|
3906
|
+
return { external: true };
|
|
3907
|
+
}
|
|
3908
|
+
if (!autoDetectExternal) return null;
|
|
3909
|
+
const info = await resolvePackageInfo(args.path, args.resolveDir);
|
|
3910
|
+
if (!info) return null;
|
|
3911
|
+
if (!shouldAutoExternalize(info)) return null;
|
|
3912
|
+
collectedExternals.set(info.name, info);
|
|
3913
|
+
return { external: true };
|
|
3914
|
+
});
|
|
3915
|
+
}
|
|
3916
|
+
}]
|
|
3917
|
+
});
|
|
3918
|
+
const sandbox = await this.createSandboxHandle();
|
|
3919
|
+
let deploymentCompleted = false;
|
|
3920
|
+
let detachedCommand;
|
|
3921
|
+
try {
|
|
3922
|
+
const { paths } = sandbox;
|
|
3923
|
+
await sandbox.runCommand(`mkdir -p ${shellQuote(paths.agentDir)}`, {
|
|
3924
|
+
timeoutMs: QUICK_COMMAND_TIMEOUT_MS2
|
|
3925
|
+
});
|
|
3926
|
+
const { apt, commands } = this.dependencies;
|
|
3927
|
+
if (apt && apt.length > 0) {
|
|
3928
|
+
const aptCmd = `sudo apt-get update && sudo apt-get install -y ${apt.join(" ")}`;
|
|
3929
|
+
const aptResult = await sandbox.runCommand(aptCmd, {
|
|
3930
|
+
timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS2
|
|
3931
|
+
});
|
|
3932
|
+
if (aptResult.exitCode !== 0) {
|
|
3933
|
+
const details = [
|
|
3934
|
+
`Failed to install apt packages: ${apt.join(", ")}`,
|
|
3935
|
+
aptResult.stderr ? `stderr: ${aptResult.stderr}` : "",
|
|
3936
|
+
aptResult.stdout ? `stdout: ${aptResult.stdout}` : ""
|
|
3937
|
+
].filter(Boolean).join("\n");
|
|
3938
|
+
throw new DeploymentError(details);
|
|
3939
|
+
}
|
|
3940
|
+
}
|
|
3941
|
+
if (commands && commands.length > 0) {
|
|
3942
|
+
for (const cmd of commands) {
|
|
3943
|
+
const cmdResult = await sandbox.runCommand(cmd, {
|
|
3944
|
+
timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS2
|
|
3945
|
+
});
|
|
3946
|
+
if (cmdResult.exitCode !== 0) {
|
|
3947
|
+
const details = [
|
|
3948
|
+
`Failed to run command: ${cmd}`,
|
|
3949
|
+
cmdResult.stderr ? `stderr: ${cmdResult.stderr}` : "",
|
|
3950
|
+
cmdResult.stdout ? `stdout: ${cmdResult.stdout}` : ""
|
|
3951
|
+
].filter(Boolean).join("\n");
|
|
3952
|
+
throw new DeploymentError(details);
|
|
3953
|
+
}
|
|
3954
|
+
}
|
|
3955
|
+
}
|
|
3956
|
+
if (this.files.length > 0) {
|
|
3957
|
+
for (const file of this.files) {
|
|
3958
|
+
const destPath = file.path.startsWith("/") ? file.path : `${paths.homeDir}/${file.path}`;
|
|
3959
|
+
const parentDir = destPath.substring(0, destPath.lastIndexOf("/"));
|
|
3960
|
+
if (parentDir) {
|
|
3961
|
+
await sandbox.runCommand(`mkdir -p ${shellQuote(parentDir)}`, {
|
|
3962
|
+
timeoutMs: QUICK_COMMAND_TIMEOUT_MS2
|
|
3963
|
+
});
|
|
3964
|
+
}
|
|
3965
|
+
const curlCmd = `curl -fsSL -o ${shellQuote(destPath)} ${shellQuote(file.url)}`;
|
|
3966
|
+
const downloadResult = await sandbox.runCommand(curlCmd, {
|
|
3967
|
+
timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS2
|
|
3968
|
+
});
|
|
3969
|
+
if (downloadResult.exitCode !== 0) {
|
|
3970
|
+
const details = [
|
|
3971
|
+
`Failed to download file from ${file.url} to ${destPath}`,
|
|
3972
|
+
downloadResult.stderr ? `stderr: ${downloadResult.stderr}` : "",
|
|
3973
|
+
downloadResult.stdout ? `stdout: ${downloadResult.stdout}` : ""
|
|
3974
|
+
].filter(Boolean).join("\n");
|
|
3975
|
+
throw new DeploymentError(details);
|
|
3976
|
+
}
|
|
3977
|
+
}
|
|
3978
|
+
}
|
|
3979
|
+
if (localDirectoryUploads.directories.length > 0 || localDirectoryUploads.files.length > 0) {
|
|
3980
|
+
const archivePath = posix.join(paths.agentDir, `.neckbeard-local-directories-${randomUUID()}.tar.gz`);
|
|
3981
|
+
await sandbox.writeFile(archivePath, await createTarGz([
|
|
3982
|
+
...localDirectoryUploads.directories.map((directory) => ({ path: directory })),
|
|
3983
|
+
...localDirectoryUploads.files.map((file) => ({ path: file.targetPath, content: file.content }))
|
|
3984
|
+
]));
|
|
3985
|
+
const extractResult = await sandbox.runCommand(
|
|
3986
|
+
`tar -xzf ${shellQuote(archivePath)} --no-same-owner -C ${shellQuote(paths.agentDir)} && rm -f ${shellQuote(archivePath)}`,
|
|
3987
|
+
{ timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS2 }
|
|
3988
|
+
);
|
|
3989
|
+
if (extractResult.exitCode !== 0) {
|
|
3990
|
+
throw new DeploymentError(
|
|
3991
|
+
`Failed to extract local directories: ${extractResult.stderr || extractResult.stdout}`
|
|
3992
|
+
);
|
|
3993
|
+
}
|
|
3994
|
+
}
|
|
3995
|
+
await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
|
|
3996
|
+
await sandbox.writeFile(paths.serverModule, RUNTIME_SERVER_SOURCE);
|
|
3997
|
+
const serverConfig = {
|
|
3998
|
+
protocolVersion: RUNTIME_PROTOCOL_VERSION,
|
|
3999
|
+
port: this._server?.port ?? DEFAULT_SERVER_PORT,
|
|
4000
|
+
maxDurationMs: this.maxDuration * 1e3,
|
|
4001
|
+
sandboxContext: {
|
|
4002
|
+
provider: paths.provider,
|
|
4003
|
+
homeDir: paths.homeDir,
|
|
4004
|
+
workDir: paths.workDir,
|
|
4005
|
+
agentDir: paths.agentDir,
|
|
4006
|
+
ioDir: paths.ioDir,
|
|
4007
|
+
inputJson: paths.inputJson,
|
|
4008
|
+
outputJson: paths.outputJson
|
|
4009
|
+
}
|
|
4010
|
+
};
|
|
4011
|
+
await sandbox.writeFile(paths.serverConfig, JSON.stringify(serverConfig));
|
|
4012
|
+
if (collectedExternals.size > 0) {
|
|
4013
|
+
const installable = Array.from(collectedExternals.values()).filter(isPackageCompatible);
|
|
4014
|
+
const dependencies = Object.fromEntries(installable.map((info) => [info.name, info.version]));
|
|
4015
|
+
if (Object.keys(dependencies).length > 0) {
|
|
4016
|
+
const pkgJson = JSON.stringify({
|
|
4017
|
+
name: "agent-sandbox",
|
|
4018
|
+
type: "module",
|
|
4019
|
+
dependencies
|
|
4020
|
+
});
|
|
4021
|
+
await sandbox.writeFile(paths.packageJson, pkgJson);
|
|
4022
|
+
const installResult = await sandbox.runCommand("npm install --legacy-peer-deps", {
|
|
4023
|
+
cwd: paths.agentDir,
|
|
4024
|
+
timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS2
|
|
4025
|
+
});
|
|
4026
|
+
if (installResult.exitCode !== 0) {
|
|
4027
|
+
const details = [
|
|
4028
|
+
`Failed to install npm packages: ${Object.keys(dependencies).join(", ")}`,
|
|
4029
|
+
installResult.stderr ? `stderr: ${installResult.stderr}` : "",
|
|
4030
|
+
installResult.stdout ? `stdout: ${installResult.stdout}` : ""
|
|
4031
|
+
].filter(Boolean).join("\n");
|
|
4032
|
+
throw new DeploymentError(details);
|
|
4033
|
+
}
|
|
4034
|
+
}
|
|
4035
|
+
}
|
|
4036
|
+
const port = serverConfig.port;
|
|
4037
|
+
detachedCommand = await this.startRuntimeServer(sandbox);
|
|
4038
|
+
const connection = await this.createRuntimeConnection(sandbox, port);
|
|
4039
|
+
const healthUrl = this.healthUrlFor(connection);
|
|
4040
|
+
try {
|
|
4041
|
+
await waitForServerHealthy(healthUrl, connection);
|
|
4042
|
+
} catch (err) {
|
|
4043
|
+
const baseMessage = err instanceof Error ? err.message : String(err);
|
|
4044
|
+
const logs = await readServerFailureDiagnostics(
|
|
4045
|
+
sandbox,
|
|
4046
|
+
detachedCommand,
|
|
4047
|
+
this.envs
|
|
4048
|
+
);
|
|
4049
|
+
throw new DeploymentError(`${baseMessage}${logs}`);
|
|
4050
|
+
}
|
|
4051
|
+
if (!options?.fresh) {
|
|
4052
|
+
this._sandboxId = sandbox.id;
|
|
4053
|
+
this._serverRuntime = { detachedCommand, connection };
|
|
4054
|
+
}
|
|
4055
|
+
deploymentCompleted = true;
|
|
4056
|
+
return sandbox.id;
|
|
4057
|
+
} finally {
|
|
4058
|
+
if (!deploymentCompleted) {
|
|
4059
|
+
if (detachedCommand && sandbox.stopSession) {
|
|
4060
|
+
await sandbox.stopSession(detachedCommand).catch(() => void 0);
|
|
4061
|
+
}
|
|
4062
|
+
await sandbox.destroy().catch(() => void 0);
|
|
4063
|
+
}
|
|
4064
|
+
}
|
|
4065
|
+
}
|
|
4066
|
+
/**
|
|
4067
|
+
* Executes the agent with the given input.
|
|
4068
|
+
*
|
|
4069
|
+
* The agent must be deployed before calling this method, or a sandbox ID
|
|
4070
|
+
* must be provided in the options. Input is validated against the input
|
|
4071
|
+
* schema, then POSTed to the in-sandbox server. Output is validated against
|
|
4072
|
+
* the output schema before being returned.
|
|
4073
|
+
*
|
|
4074
|
+
* @param input - The input data for the agent, must conform to inputSchema
|
|
4075
|
+
* @param options - Optional configuration for this run
|
|
4076
|
+
* @param options.sandboxId - Sandbox ID to use, overrides the cached sandbox
|
|
4077
|
+
* @returns A result object indicating success or failure with output or error
|
|
4078
|
+
*
|
|
4079
|
+
* @example
|
|
4080
|
+
* ```typescript
|
|
4081
|
+
* // Using deployed sandbox
|
|
4082
|
+
* const result = await agent.run({ prompt: 'Hello, world!' });
|
|
4083
|
+
*
|
|
4084
|
+
* // Reconnecting from another process
|
|
4085
|
+
* const result = await agent.run({ prompt: 'Hello!' }, { sandboxId });
|
|
4086
|
+
* ```
|
|
4087
|
+
*/
|
|
4088
|
+
async run(input, options) {
|
|
4089
|
+
const executionId = `exec_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
|
4090
|
+
if (this.mode !== "run") {
|
|
4091
|
+
return {
|
|
4092
|
+
ok: false,
|
|
4093
|
+
executionId,
|
|
4094
|
+
error: new ExecutionError(
|
|
4095
|
+
"run() is only available on agents configured with a run handler. Use agent.createSession() for streaming session agents."
|
|
4096
|
+
)
|
|
4097
|
+
};
|
|
4098
|
+
}
|
|
4099
|
+
try {
|
|
4100
|
+
const connection = await this.resolveRuntimeConnection(options?.sandboxId);
|
|
4101
|
+
let validatedInput;
|
|
4102
|
+
try {
|
|
4103
|
+
validatedInput = this.inputSchema.parse(input);
|
|
4104
|
+
} catch (error) {
|
|
4105
|
+
throw new ValidationError("Input validation failed.", asError(error));
|
|
4106
|
+
}
|
|
4107
|
+
const { invokeServer } = await import("./invoke-client-P2CPBYTF.js");
|
|
4108
|
+
let output;
|
|
4109
|
+
let sawOutput = false;
|
|
4110
|
+
for await (const event of invokeServer(validatedInput, {
|
|
4111
|
+
serverUrl: connection.serverUrl,
|
|
4112
|
+
provider: connection.provider,
|
|
4113
|
+
trafficToken: getTrafficToken(connection),
|
|
4114
|
+
invocationId: executionId,
|
|
4115
|
+
signal: AbortSignal.timeout(this.maxDuration * 1e3 + RUNTIME_ABORT_GRACE_MS + 5e3)
|
|
4116
|
+
})) {
|
|
4117
|
+
if (event.kind === "error") {
|
|
4118
|
+
const err = new ExecutionError(event.error.message);
|
|
4119
|
+
err.stack = event.error.stack;
|
|
4120
|
+
return { ok: false, executionId, error: err };
|
|
4121
|
+
}
|
|
4122
|
+
if (event.kind === "output") {
|
|
4123
|
+
output = event.output;
|
|
4124
|
+
sawOutput = true;
|
|
4125
|
+
}
|
|
4126
|
+
}
|
|
4127
|
+
if (!sawOutput) {
|
|
4128
|
+
return {
|
|
4129
|
+
ok: false,
|
|
4130
|
+
executionId,
|
|
4131
|
+
error: new ExecutionError("Agent server completed without returning output.")
|
|
4132
|
+
};
|
|
4133
|
+
}
|
|
4134
|
+
let validated;
|
|
4135
|
+
try {
|
|
4136
|
+
validated = this.outputSchema ? this.outputSchema.parse(output) : output;
|
|
4137
|
+
} catch (error) {
|
|
4138
|
+
throw new ValidationError("Output validation failed.", asError(error));
|
|
4139
|
+
}
|
|
4140
|
+
return { ok: true, executionId, output: validated };
|
|
4141
|
+
} catch (err) {
|
|
4142
|
+
const { InvokeHttpError } = await import("./invoke-client-P2CPBYTF.js");
|
|
4143
|
+
if (err instanceof InvokeHttpError && err.status === 409) {
|
|
4144
|
+
return { ok: false, executionId, error: new RuntimeBusyError(err.message) };
|
|
4145
|
+
}
|
|
4146
|
+
return { ok: false, executionId, error: err instanceof Error ? err : new Error(String(err)) };
|
|
4147
|
+
}
|
|
4148
|
+
}
|
|
4149
|
+
/**
|
|
4150
|
+
* Creates a caller-owned session against the persistent sandbox runtime.
|
|
4151
|
+
* The returned handle supports sequential prompts, active-turn cancellation,
|
|
4152
|
+
* and explicit close without destroying the reusable sandbox.
|
|
4153
|
+
*/
|
|
4154
|
+
async createSession(options = {}) {
|
|
4155
|
+
if (this.mode !== "stream") {
|
|
4156
|
+
throw new ConfigurationError(
|
|
4157
|
+
"createSession() is only available on agents configured with session.handler (or deprecated server.handler). Use agent.run() for run-output agents."
|
|
4158
|
+
);
|
|
4159
|
+
}
|
|
4160
|
+
if (!options || typeof options !== "object") {
|
|
4161
|
+
throw new ConfigurationError("LegacyBundledAgent.createSession() options must be an object.");
|
|
4162
|
+
}
|
|
4163
|
+
let optionsAreArray;
|
|
4164
|
+
try {
|
|
4165
|
+
optionsAreArray = Array.isArray(options);
|
|
4166
|
+
} catch {
|
|
4167
|
+
throw new ConfigurationError(
|
|
4168
|
+
"LegacyBundledAgent.createSession() options must have readable values."
|
|
4169
|
+
);
|
|
4170
|
+
}
|
|
4171
|
+
if (optionsAreArray) {
|
|
4172
|
+
throw new ConfigurationError("LegacyBundledAgent.createSession() options must be an object.");
|
|
4173
|
+
}
|
|
4174
|
+
let durability;
|
|
4175
|
+
let requestedSandboxId;
|
|
4176
|
+
let signal;
|
|
4177
|
+
try {
|
|
4178
|
+
durability = options.durability;
|
|
4179
|
+
requestedSandboxId = options.sandboxId;
|
|
4180
|
+
signal = options.signal;
|
|
4181
|
+
} catch {
|
|
4182
|
+
throw new ConfigurationError(
|
|
4183
|
+
"LegacyBundledAgent.createSession() options must have readable values."
|
|
4184
|
+
);
|
|
4185
|
+
}
|
|
4186
|
+
if (durability !== void 0 && durability !== "attached") {
|
|
4187
|
+
throw new ConfigurationError(
|
|
4188
|
+
"LegacyBundledAgent.createSession() creates caller-owned attached sessions. Gateway-owned durable sessions use the deprecated agent-neckbeard/supervisor APIs."
|
|
4189
|
+
);
|
|
4190
|
+
}
|
|
4191
|
+
if (requestedSandboxId !== void 0 && (typeof requestedSandboxId !== "string" || requestedSandboxId.trim() === "")) {
|
|
4192
|
+
throw new ConfigurationError(
|
|
4193
|
+
"LegacyBundledAgent.createSession() sandboxId must be a non-empty string when provided."
|
|
4194
|
+
);
|
|
4195
|
+
}
|
|
4196
|
+
if (signal !== void 0 && !isAbortSignal(signal)) {
|
|
4197
|
+
throw new ConfigurationError(
|
|
4198
|
+
"LegacyBundledAgent.createSession() signal must be an AbortSignal when provided."
|
|
4199
|
+
);
|
|
4200
|
+
}
|
|
4201
|
+
const sandboxId = requestedSandboxId ?? this._serverRuntime?.connection.sandboxId ?? this._sandboxId;
|
|
4202
|
+
if (!sandboxId) {
|
|
4203
|
+
throw new ConfigurationError("Agent not deployed. Call agent.deploy() first or pass sandboxId.");
|
|
4204
|
+
}
|
|
4205
|
+
return createAttachedAgentSession({
|
|
4206
|
+
sandboxId,
|
|
4207
|
+
runPrompt: (input, signal2) => this.streamSessionPrompt(input, sandboxId, signal2),
|
|
4208
|
+
...signal === void 0 ? {} : { externalSignal: signal },
|
|
4209
|
+
configurationError: (message) => new ConfigurationError(message),
|
|
4210
|
+
abortError: abortSignalError
|
|
4211
|
+
});
|
|
4212
|
+
}
|
|
4213
|
+
async *streamSessionPrompt(input, sandboxId, signal) {
|
|
4214
|
+
const connection = await this.resolveRuntimeConnection(sandboxId, {
|
|
4215
|
+
signal,
|
|
4216
|
+
reuseMatchingCachedConnection: true
|
|
4217
|
+
});
|
|
4218
|
+
const { invokeServer, InvokeHttpError } = await import("./invoke-client-P2CPBYTF.js");
|
|
4219
|
+
let validated;
|
|
4220
|
+
try {
|
|
4221
|
+
validated = this.inputSchema.parse(input);
|
|
4222
|
+
} catch (error) {
|
|
4223
|
+
throw new ValidationError("Input validation failed.", asError(error));
|
|
4224
|
+
}
|
|
4225
|
+
try {
|
|
4226
|
+
let finished = false;
|
|
4227
|
+
for await (const frame of invokeServer(validated, {
|
|
4228
|
+
serverUrl: connection.serverUrl,
|
|
4229
|
+
provider: connection.provider,
|
|
4230
|
+
trafficToken: getTrafficToken(connection),
|
|
4231
|
+
frameSchema: this.frameSchema,
|
|
4232
|
+
signal
|
|
4233
|
+
})) {
|
|
4234
|
+
if (frame.kind === "frame") {
|
|
4235
|
+
yield frame.data;
|
|
4236
|
+
} else if (frame.kind === "error") {
|
|
4237
|
+
const err = new ExecutionError(frame.error.message);
|
|
4238
|
+
err.stack = frame.error.stack;
|
|
4239
|
+
throw err;
|
|
4240
|
+
} else if (frame.kind === "done") {
|
|
4241
|
+
finished = true;
|
|
4242
|
+
}
|
|
4243
|
+
}
|
|
4244
|
+
if (!finished) {
|
|
4245
|
+
throwIfAborted(signal);
|
|
4246
|
+
throw new ExecutionError("Runtime stream ended before the turn finished.");
|
|
4247
|
+
}
|
|
4248
|
+
} catch (error) {
|
|
4249
|
+
if (error instanceof ExecutionError) throw error;
|
|
4250
|
+
if (error instanceof InvokeHttpError && error.status === 409) {
|
|
4251
|
+
throw new RuntimeBusyError(error.message);
|
|
4252
|
+
}
|
|
4253
|
+
throw error instanceof Error ? error : new Error(String(error));
|
|
4254
|
+
}
|
|
4255
|
+
}
|
|
4256
|
+
/**
|
|
4257
|
+
* Waits until the sandbox runtime has no handler running. An aborted turn rejects on the host
|
|
4258
|
+
* at once, while its handler can keep running in the sandbox until it notices the abort, so call
|
|
4259
|
+
* this before reading state the handler writes, such as a transcript. Throws `RuntimeBusyError`
|
|
4260
|
+
* if a handler is still running, or the runtime doesn't answer, after `timeoutMs`.
|
|
4261
|
+
*/
|
|
4262
|
+
async waitForIdle(options = {}) {
|
|
4263
|
+
const { signal, timeoutMs = DEFAULT_IDLE_TIMEOUT_MS } = options;
|
|
4264
|
+
const connection = await this.resolveRuntimeConnection(options.sandboxId, {
|
|
4265
|
+
signal,
|
|
4266
|
+
reuseMatchingCachedConnection: true
|
|
4267
|
+
});
|
|
4268
|
+
const healthUrl = appendTrafficTokenToUrl(this.healthUrlFor(connection), connection);
|
|
4269
|
+
const deadline = Date.now() + timeoutMs;
|
|
4270
|
+
while (true) {
|
|
4271
|
+
let busy = true;
|
|
4272
|
+
try {
|
|
4273
|
+
const response = await awaitWithAbort(
|
|
4274
|
+
() => fetch(healthUrl, {
|
|
4275
|
+
headers: trafficTokenHeaders(connection),
|
|
4276
|
+
signal: signal === void 0 ? AbortSignal.timeout(SERVER_HEALTH_POLL_INTERVAL_MS * 5) : AbortSignal.any([signal, AbortSignal.timeout(SERVER_HEALTH_POLL_INTERVAL_MS * 5)])
|
|
4277
|
+
}),
|
|
4278
|
+
signal
|
|
4279
|
+
);
|
|
4280
|
+
if (response.ok) {
|
|
4281
|
+
const body = await awaitWithAbort(() => response.json(), signal);
|
|
4282
|
+
busy = body.ok !== true || body.busy === true;
|
|
4283
|
+
} else {
|
|
4284
|
+
await response.body?.cancel().catch(() => void 0);
|
|
4285
|
+
}
|
|
4286
|
+
} catch {
|
|
4287
|
+
throwIfAborted(signal);
|
|
4288
|
+
}
|
|
4289
|
+
if (!busy) return;
|
|
4290
|
+
if (Date.now() >= deadline) {
|
|
4291
|
+
throw new RuntimeBusyError(`Sandbox runtime still busy after ${timeoutMs}ms.`);
|
|
4292
|
+
}
|
|
4293
|
+
await delayWithAbort(SERVER_HEALTH_POLL_INTERVAL_MS, signal);
|
|
4294
|
+
}
|
|
4295
|
+
}
|
|
4296
|
+
/**
|
|
4297
|
+
* @deprecated Use `createSession()` and call `session.prompt(input)` instead.
|
|
4298
|
+
* This compatibility wrapper creates one attached session, streams one turn,
|
|
4299
|
+
* and closes the local handle afterward.
|
|
4300
|
+
*/
|
|
4301
|
+
async *invoke(input, options) {
|
|
4302
|
+
const session = await this.createSession({
|
|
4303
|
+
...options?.sandboxId === void 0 ? {} : { sandboxId: options.sandboxId },
|
|
4304
|
+
...options?.signal === void 0 ? {} : { signal: options.signal }
|
|
4305
|
+
});
|
|
4306
|
+
try {
|
|
4307
|
+
yield* session.prompt(input);
|
|
4308
|
+
} finally {
|
|
4309
|
+
await session.close();
|
|
4310
|
+
}
|
|
4311
|
+
}
|
|
4312
|
+
};
|
|
4313
|
+
|
|
4314
|
+
export {
|
|
4315
|
+
Agent,
|
|
4316
|
+
BRAINTRUST_PACKAGE,
|
|
4317
|
+
BRAINTRUST_VERSIONS,
|
|
4318
|
+
isSupportedBraintrustVersion,
|
|
4319
|
+
SKILLS_DIR,
|
|
4320
|
+
resolveImageTag,
|
|
4321
|
+
PI_PACKAGE,
|
|
4322
|
+
DefinedAgent,
|
|
4323
|
+
defineAgent,
|
|
4324
|
+
isDefinedAgent,
|
|
4325
|
+
NeckbeardError,
|
|
4326
|
+
DeploymentError,
|
|
4327
|
+
ValidationError,
|
|
4328
|
+
ExecutionError,
|
|
4329
|
+
RuntimeBusyError,
|
|
4330
|
+
TurnLostError,
|
|
4331
|
+
ConfigurationError,
|
|
4332
|
+
resolveAgentSourceFile,
|
|
4333
|
+
withNeckbeardNextConfig,
|
|
4334
|
+
DEFAULT_DEPENDENCIES,
|
|
4335
|
+
destroyProviderSandbox,
|
|
4336
|
+
SandboxClient,
|
|
4337
|
+
normalizeStackFramePath,
|
|
4338
|
+
LegacyBundledAgent
|
|
4339
|
+
};
|