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/dist/index.js CHANGED
@@ -1,3289 +1,53 @@
1
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";
2
+ Agent,
3
+ ConfigurationError,
4
+ DEFAULT_DEPENDENCIES,
5
+ DefinedAgent,
6
+ DeploymentError,
7
+ ExecutionError,
8
+ LegacyBundledAgent,
9
+ NeckbeardError,
10
+ RuntimeBusyError,
11
+ SKILLS_DIR,
12
+ SandboxClient,
13
+ TurnLostError,
14
+ ValidationError,
15
+ defineAgent,
16
+ destroyProviderSandbox,
17
+ isDefinedAgent,
18
+ normalizeStackFramePath,
19
+ resolveAgentSourceFile,
20
+ resolveImageTag,
21
+ withNeckbeardNextConfig
22
+ } from "./chunk-JF5YPOBY.js";
23
+ import "./chunk-6P5I7ZCH.js";
19
24
  import {
20
- RUNTIME_ABORT_GRACE_MS,
21
- RUNTIME_PROTOCOL_VERSION
22
- } from "./chunk-6GCQOKYI.js";
25
+ TURN_PROTOCOL_VERSION,
26
+ getPiTurnResult
27
+ } from "./chunk-M3FISP7J.js";
28
+ import "./chunk-KG6SJM74.js";
23
29
  import "./chunk-33IXN6MM.js";
24
-
25
- // src/index.ts
26
- import { fileURLToPath } from "url";
27
- import {
28
- existsSync,
29
- lstatSync,
30
- readdirSync,
31
- readFileSync,
32
- statSync,
33
- writeFileSync
34
- } from "fs";
35
- import {
36
- basename,
37
- dirname,
38
- isAbsolute,
39
- join,
40
- posix,
41
- relative,
42
- resolve,
43
- sep,
44
- win32
45
- } from "path";
46
- import { builtinModules, createRequire as createRequire2 } from "module";
47
-
48
- // src/runtime/server-source.generated.ts
49
- 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';
50
-
51
- // src/attached-session.ts
52
- function linkAbortSignals(signals) {
53
- const controller = new AbortController();
54
- const listeners = /* @__PURE__ */ new Map();
55
- const abortFrom = (signal) => {
56
- if (!controller.signal.aborted) controller.abort(signal.reason);
57
- };
58
- for (const signal of signals) {
59
- if (signal.aborted) {
60
- abortFrom(signal);
61
- break;
62
- }
63
- const listener = () => abortFrom(signal);
64
- listeners.set(signal, listener);
65
- signal.addEventListener("abort", listener, { once: true });
66
- }
67
- return {
68
- signal: controller.signal,
69
- dispose: () => {
70
- for (const [signal, listener] of listeners) {
71
- signal.removeEventListener("abort", listener);
72
- }
73
- listeners.clear();
74
- }
75
- };
76
- }
77
- var AttachedAgentSessionImpl = class {
78
- durability = "attached";
79
- sandboxId;
80
- lifetime = new AbortController();
81
- runPrompt;
82
- configurationError;
83
- abortError;
84
- activeTurn = null;
85
- externalSignal = null;
86
- externalAbortListener = null;
87
- isClosed = false;
88
- closePromise = null;
89
- constructor(options) {
90
- this.sandboxId = options.sandboxId;
91
- this.runPrompt = options.runPrompt;
92
- this.configurationError = options.configurationError;
93
- this.abortError = options.abortError;
94
- const { externalSignal } = options;
95
- if (externalSignal?.aborted) {
96
- this.isClosed = true;
97
- this.lifetime.abort(externalSignal.reason);
98
- } else if (externalSignal) {
99
- this.externalSignal = externalSignal;
100
- this.externalAbortListener = () => {
101
- void this.closeWithReason(externalSignal.reason);
102
- };
103
- externalSignal.addEventListener("abort", this.externalAbortListener, { once: true });
104
- }
105
- }
106
- get closed() {
107
- return this.isClosed;
108
- }
109
- prompt(input) {
110
- return this.runTurn(input);
111
- }
112
- async stop(reason = "attached_session_stopped") {
113
- await this.stopActiveTurn(reason);
114
- }
115
- close() {
116
- return this.closeWithReason("attached_session_closed");
117
- }
118
- async *runTurn(input) {
119
- if (this.isClosed || this.lifetime.signal.aborted) {
120
- throw this.configurationError("Attached session is closed.");
121
- }
122
- if (this.activeTurn) {
123
- throw this.configurationError("Attached session already has an active turn.");
124
- }
125
- const controller = new AbortController();
126
- const linked = linkAbortSignals([this.lifetime.signal, controller.signal]);
127
- const iterator = this.runPrompt(input, linked.signal);
128
- const turn = {
129
- controller,
130
- iterator,
131
- dispose: linked.dispose
132
- };
133
- this.activeTurn = turn;
134
- try {
135
- while (true) {
136
- const next = await iterator.next();
137
- if (next.done) {
138
- if (linked.signal.aborted) throw this.abortError(linked.signal);
139
- return;
140
- }
141
- yield next.value;
142
- }
143
- } finally {
144
- controller.abort("attached_turn_closed");
145
- await iterator.return(void 0).catch(() => void 0);
146
- turn.dispose();
147
- if (this.activeTurn === turn) this.activeTurn = null;
148
- }
149
- }
150
- async stopActiveTurn(reason) {
151
- const turn = this.activeTurn;
152
- if (!turn) return;
153
- turn.controller.abort(reason);
154
- await turn.iterator.return(void 0).catch(() => void 0);
155
- turn.dispose();
156
- if (this.activeTurn === turn) this.activeTurn = null;
157
- }
158
- closeWithReason(reason) {
159
- if (this.closePromise) return this.closePromise;
160
- this.closePromise = Promise.resolve().then(() => this.finishClose(reason));
161
- this.isClosed = true;
162
- this.lifetime.abort(reason);
163
- return this.closePromise;
164
- }
165
- async finishClose(reason) {
166
- await this.stopActiveTurn(reason);
167
- if (this.externalSignal && this.externalAbortListener) {
168
- this.externalSignal.removeEventListener("abort", this.externalAbortListener);
169
- }
170
- this.externalSignal = null;
171
- this.externalAbortListener = null;
172
- }
173
- };
174
- function createAttachedAgentSession(options) {
175
- return new AttachedAgentSessionImpl(options);
176
- }
177
-
178
- // src/providers/types.ts
179
- function createProviderSandboxPaths(provider, homeDir, workDir) {
180
- const agentDir = `${homeDir}/agent`;
181
- const ioDir = `${homeDir}/io`;
182
- return {
183
- provider,
184
- homeDir,
185
- workDir,
186
- agentDir,
187
- ioDir,
188
- inputJson: `${ioDir}/input.json`,
189
- outputJson: `${ioDir}/output.json`,
190
- agentModule: `${agentDir}/agent.mjs`,
191
- serverModule: `${agentDir}/server.mjs`,
192
- serverConfig: `${agentDir}/server-config.json`,
193
- claudeDir: `${agentDir}/.claude`,
194
- packageJson: `${agentDir}/package.json`
195
- };
196
- }
197
- var PROVIDER_MAX_LIFETIME_MS = 864e5;
198
- function validateProviderEnvs(label, value, failure) {
199
- 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")))) {
200
- throw failure(`${label} envs must contain valid environment names and string values.`);
201
- }
202
- }
203
- function validateProviderOptions(label, options, allowedKeys, failure) {
204
- const allowed = /* @__PURE__ */ new Set(["provider", ...allowedKeys]);
205
- for (const [key, value] of Object.entries(options)) {
206
- if (!allowed.has(key)) throw failure(`${label} does not support option "${key}".`);
207
- if (value === void 0 || key === "provider") continue;
208
- if (["timeoutMs", "cpu", "memoryMiB"].includes(key)) {
209
- 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)) {
210
- throw failure(`${label} ${key} must be positive${key === "timeoutMs" ? ` and a multiple of 1000 between 1000 and ${PROVIDER_MAX_LIFETIME_MS}` : ""}.`);
211
- }
212
- } else if (key === "envs") {
213
- validateProviderEnvs(label, value, failure);
214
- } else if (typeof value !== "string" || !value.trim() || value.includes("\0") || value.startsWith("-")) {
215
- throw failure(`${label} ${key} must be a non-empty string without null bytes or a leading "-".`);
216
- }
217
- }
218
- }
219
- function validateProviderCommand(label, command, options) {
220
- if (typeof command !== "string" || command.includes("\0") || !options || Array.isArray(options) || !Number.isFinite(options.timeoutMs) || options.timeoutMs <= 0) {
221
- throw new Error(`${label} commands require a string and a positive finite timeoutMs.`);
222
- }
223
- for (const key of Object.keys(options)) {
224
- if (!["cwd", "envs", "timeoutMs", "onStdout", "onStderr"].includes(key)) {
225
- throw new Error(`${label} commands do not support option "${key}".`);
226
- }
227
- }
228
- 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") {
229
- throw new Error(`${label} command cwd must be absolute and output callbacks must be functions.`);
230
- }
231
- if (options.envs !== void 0) validateProviderEnvs(label, options.envs, (message) => new Error(message));
232
- }
233
-
234
- // src/providers/daytona.ts
235
- var SANDBOX_COMMAND_TIMEOUT_MS = 3e5;
236
- var QUICK_COMMAND_TIMEOUT_MS = 3e4;
237
- var LEGACY_DAYTONA_PROCESS_PATTERN = /^daytona-process:(\d+):(\d+):([a-z0-9-]+)$/iu;
238
- function parseLegacyDaytonaProcessHandle(sessionId) {
239
- const match = LEGACY_DAYTONA_PROCESS_PATTERN.exec(sessionId);
240
- if (!match) return null;
241
- const [, pid, startTicks, nonce] = match;
242
- return pid && startTicks && nonce ? { pid, startTicks, nonce } : null;
243
- }
244
- var DaytonaSandboxHandle = class _DaytonaSandboxHandle {
245
- constructor(sandbox, paths, failure) {
246
- this.sandbox = sandbox;
247
- this.paths = paths;
248
- this.failure = failure;
249
- this.detachedProcesses = createDaytonaDetachedProcessController(this.sandbox, {
250
- homeDir: this.paths.homeDir,
251
- readLegacyLogs: (command) => this.readLegacySessionLogs(command),
252
- stopLegacy: (command) => this.stopLegacySession(command),
253
- failure
254
- });
255
- }
256
- provider = "daytona";
257
- detachedProcesses;
258
- static async create(sandbox, failure) {
259
- const { homeDir, workDir } = await discoverDaytonaSandboxDirectories(
260
- sandbox,
261
- { failure }
262
- );
263
- return new _DaytonaSandboxHandle(
264
- sandbox,
265
- createProviderSandboxPaths("daytona", homeDir, workDir),
266
- failure
267
- );
268
- }
269
- get id() {
270
- return this.sandbox.id;
271
- }
272
- async makeDir(path) {
273
- const result = await makeDaytonaDirectory(this.sandbox, path, {
274
- timeoutMs: QUICK_COMMAND_TIMEOUT_MS
275
- });
276
- if (result.exitCode !== 0) {
277
- throw this.failure(result.result || `Failed to create directory ${path}`);
278
- }
279
- }
280
- writeFile(path, content) {
281
- return uploadDaytonaFile(this.sandbox, path, content, {
282
- timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
283
- });
284
- }
285
- async readFile(path) {
286
- const content = await this.sandbox.fs.downloadFile(
287
- path,
288
- daytonaTimeoutSeconds(SANDBOX_COMMAND_TIMEOUT_MS)
289
- );
290
- return content.toString("utf8");
291
- }
292
- async readFileBytes(path) {
293
- const content = await this.sandbox.fs.downloadFile(
294
- path,
295
- daytonaTimeoutSeconds(SANDBOX_COMMAND_TIMEOUT_MS)
296
- );
297
- return new Uint8Array(content);
298
- }
299
- async runCommand(cmd, options) {
300
- const result = await executeDaytonaCommand(this.sandbox, cmd, {
301
- timeoutMs: options.timeoutMs,
302
- ...options.cwd === void 0 ? {} : { cwd: options.cwd },
303
- ...options.envs === void 0 ? {} : { envs: options.envs }
304
- });
305
- if (result.stdout) options.onStdout?.(result.stdout);
306
- return result;
307
- }
308
- async startDetachedCommand(command, options = {}) {
309
- return this.detachedProcesses.start(command, options);
310
- }
311
- async readSessionLogs(command) {
312
- return this.detachedProcesses.readLogs(command);
313
- }
314
- async readLegacySessionLogs(command) {
315
- const { sessionId, commandId } = command;
316
- const legacy = parseLegacyDaytonaProcessHandle(sessionId);
317
- if (legacy) {
318
- try {
319
- const result = await executeDaytonaCommand(
320
- this.sandbox,
321
- buildReadLegacyDetachedLogsCommand(legacy.nonce),
322
- { timeoutMs: QUICK_COMMAND_TIMEOUT_MS }
323
- );
324
- return result.exitCode === 0 ? parseDetachedProcessLogs(result.stdout) ?? { stdout: "", stderr: "" } : { stdout: "", stderr: "" };
325
- } catch {
326
- return { stdout: "", stderr: "" };
327
- }
328
- }
329
- if (commandId === void 0) return { stdout: "", stderr: "" };
330
- try {
331
- const logs = await this.sandbox.process.getSessionCommandLogs(sessionId, commandId);
332
- return {
333
- stdout: boundDetachedProcessLog(logs.stdout ?? logs.output ?? ""),
334
- stderr: boundDetachedProcessLog(logs.stderr ?? "")
335
- };
336
- } catch {
337
- return { stdout: "", stderr: "" };
338
- }
339
- }
340
- async stopSession(command) {
341
- await this.detachedProcesses.stop(command);
342
- }
343
- async disposeSessionArtifacts(command) {
344
- await this.detachedProcesses.dispose(command);
345
- }
346
- async stopLegacySession(command) {
347
- const { sessionId } = command;
348
- const detached = parseLegacyDaytonaProcessHandle(sessionId);
349
- if (!detached) {
350
- await this.sandbox.process.deleteSession(sessionId);
351
- return;
352
- }
353
- const result = await executeRawDaytonaCommand(
354
- this.sandbox,
355
- buildLegacyDetachedStopCommand(detached.pid, detached.startTicks, "Daytona"),
356
- { timeoutMs: QUICK_COMMAND_TIMEOUT_MS }
357
- );
358
- if (result.exitCode !== 0) {
359
- throw this.failure(
360
- result.result || `Failed to stop detached Daytona process ${detached.pid}.`
361
- );
362
- }
363
- }
364
- async getServerEndpoint(port) {
365
- const preview = await this.sandbox.getPreviewLink(port);
366
- return { url: preview.url, trafficToken: preview.token };
367
- }
368
- destroy() {
369
- return this.sandbox.delete(
370
- daytonaTimeoutSeconds(SANDBOX_COMMAND_TIMEOUT_MS),
371
- true
372
- );
373
- }
374
- };
375
-
376
- // src/timeout.ts
377
- function settleOperation(operation, options = {}) {
378
- const { abort, timeout } = options;
379
- if (abort?.signal.aborted) throw abort.createError();
380
- if (!abort && !timeout) {
381
- try {
382
- return Promise.resolve(operation());
383
- } catch (error) {
384
- return Promise.reject(error);
385
- }
386
- }
387
- return new Promise((resolve2, reject) => {
388
- let settled = false;
389
- let timer;
390
- const cleanup = () => {
391
- if (timer !== void 0) {
392
- clearTimeout(timer);
393
- timer = void 0;
394
- }
395
- abort?.signal.removeEventListener("abort", onAbort);
396
- };
397
- const settle = (callback) => {
398
- if (settled) return;
399
- settled = true;
400
- cleanup();
401
- callback();
402
- };
403
- const onAbort = () => settle(() => reject(abort.createError()));
404
- abort?.signal.addEventListener("abort", onAbort, { once: true });
405
- if (timeout) {
406
- timer = setTimeout(
407
- () => settle(() => reject(timeout.createError())),
408
- timeout.timeoutMs
409
- );
410
- }
411
- let task;
412
- try {
413
- task = operation();
414
- } catch (error) {
415
- settle(() => reject(error));
416
- return;
417
- }
418
- void Promise.resolve(task).then(
419
- (value) => settle(() => resolve2(value)),
420
- (error) => settle(() => reject(error))
421
- );
422
- });
423
- }
424
- function withTimeout(task, timeoutMs, message) {
425
- return settleOperation(() => task, {
426
- timeout: {
427
- timeoutMs,
428
- createError: () => new Error(message)
429
- }
430
- });
431
- }
432
-
433
- // src/providers/e2b.ts
434
- var E2B_SANDBOX_HOME = "/home/user";
435
- var LEGACY_E2B_PROCESS_HANDLE_PATTERN = /^e2b:([1-9][0-9]*)$/u;
436
- var LEGACY_E2B_EXIT_POLL_INTERVAL_MS = 100;
437
- function parseLegacyE2bProcessHandle(value) {
438
- const match = LEGACY_E2B_PROCESS_HANDLE_PATTERN.exec(value);
439
- if (!match) return null;
440
- const pid = Number(match[1]);
441
- return Number.isSafeInteger(pid) && pid > 0 ? pid : null;
442
- }
443
- function remainingTimeoutMs(deadline) {
444
- return Math.max(1, Math.ceil(deadline - performance.now()));
445
- }
446
- function delay(timeoutMs) {
447
- return new Promise((resolve2) => setTimeout(resolve2, timeoutMs));
448
- }
449
- async function withinDeadline(operation, deadline) {
450
- return withTimeout(
451
- operation,
452
- remainingTimeoutMs(deadline),
453
- "E2B process control request timed out."
454
- );
455
- }
456
- function numberProperty(value, property) {
457
- if (typeof value !== "object" || value === null) return void 0;
458
- const propertyValue = Reflect.get(value, property);
459
- return typeof propertyValue === "number" ? propertyValue : void 0;
460
- }
461
- function stringProperty(value, property) {
462
- if (typeof value !== "object" || value === null) return void 0;
463
- const propertyValue = Reflect.get(value, property);
464
- return typeof propertyValue === "string" ? propertyValue : void 0;
465
- }
466
- function messageFrom(error) {
467
- return error instanceof Error ? error.message : String(error);
468
- }
469
- function writeContent(content) {
470
- if (typeof content === "string") return content;
471
- if (content instanceof ArrayBuffer) return content;
472
- return Uint8Array.from(content).buffer;
473
- }
474
- async function runE2bCommand(sandbox, cmd, options) {
475
- let stdout = "";
476
- let stderr = "";
477
- const command = options.cwd ? `cd ${shellQuote(options.cwd)} && ${cmd}` : cmd;
478
- try {
479
- const result = await sandbox.commands.run(command, {
480
- timeoutMs: options.timeoutMs,
481
- envs: options.envs,
482
- background: false,
483
- onStdout: (data) => {
484
- stdout += data;
485
- options.onStdout?.(data);
486
- },
487
- onStderr: (data) => {
488
- stderr += data;
489
- options.onStderr?.(data);
490
- }
491
- });
492
- return {
493
- exitCode: result.exitCode,
494
- stdout: stdout || result.stdout,
495
- stderr: stderr || result.stderr
496
- };
497
- } catch (error) {
498
- return {
499
- exitCode: numberProperty(error, "exitCode") ?? 1,
500
- stdout: stdout || stringProperty(error, "stdout") || "",
501
- stderr: stderr || stringProperty(error, "stderr") || messageFrom(error)
502
- };
503
- }
504
- }
505
- var E2bSandboxHandle = class {
506
- constructor(sandbox, failure) {
507
- this.sandbox = sandbox;
508
- this.failure = failure;
509
- this.detachedProcesses = new DetachedProcessController({
510
- provider: "e2b",
511
- genericPayloadEnvironmentDefaults: { HOME: this.paths.homeDir },
512
- execute: async (command, options) => ({
513
- state: "completed",
514
- result: await runE2bCommand(this.sandbox, command, {
515
- cwd: options?.cwd,
516
- envs: options?.envs,
517
- timeoutMs: DETACHED_PROCESS_CONTROL_TIMEOUT_MS
518
- })
519
- }),
520
- readLegacyLogs: (command) => this.readLegacySessionLogs(command),
521
- stopLegacy: (command) => this.stopLegacySession(command),
522
- failure
523
- });
524
- }
525
- provider = "e2b";
526
- detachedProcesses;
527
- paths = createProviderSandboxPaths(
528
- "e2b",
529
- E2B_SANDBOX_HOME,
530
- E2B_SANDBOX_HOME
531
- );
532
- get id() {
533
- return this.sandbox.sandboxId;
534
- }
535
- async makeDir(path) {
536
- await this.sandbox.files.makeDir(path);
537
- }
538
- writeFile(path, content) {
539
- return this.sandbox.files.write(path, writeContent(content)).then(() => void 0);
540
- }
541
- readFile(path) {
542
- return this.sandbox.files.read(path, { format: "text" });
543
- }
544
- readFileBytes(path) {
545
- return this.sandbox.files.read(path, { format: "bytes" });
546
- }
547
- runCommand(cmd, options) {
548
- return runE2bCommand(this.sandbox, cmd, options);
549
- }
550
- setTimeout(timeoutMs) {
551
- return this.sandbox.setTimeout(timeoutMs);
552
- }
553
- async startDetachedCommand(command, options = {}) {
554
- return this.detachedProcesses.start(command, options);
555
- }
556
- async readSessionLogs(command) {
557
- return this.detachedProcesses.readLogs(command);
558
- }
559
- async readLegacySessionLogs(command) {
560
- const { commandId } = command;
561
- if (commandId === void 0) return { stdout: "", stderr: "" };
562
- try {
563
- const handle = await this.sandbox.commands.connect(Number(commandId));
564
- return {
565
- stdout: boundDetachedProcessLog(handle.stdout ?? ""),
566
- stderr: boundDetachedProcessLog(handle.stderr ?? "")
567
- };
568
- } catch {
569
- return { stdout: "", stderr: "" };
570
- }
571
- }
572
- async stopSession(command) {
573
- await this.detachedProcesses.stop(command);
574
- }
575
- async disposeSessionArtifacts(command) {
576
- await this.detachedProcesses.dispose(command);
577
- }
578
- async stopLegacySession(command) {
579
- const { sessionId } = command;
580
- const legacyPid = parseLegacyE2bProcessHandle(sessionId);
581
- if (legacyPid === null) {
582
- throw this.failure("Detached process handle is invalid for E2B.");
583
- }
584
- const deadline = performance.now() + DETACHED_PROCESS_CONTROL_TIMEOUT_MS;
585
- let signalled;
586
- try {
587
- signalled = await withinDeadline(
588
- this.sandbox.commands.kill(legacyPid, {
589
- requestTimeoutMs: remainingTimeoutMs(deadline)
590
- }),
591
- deadline
592
- );
593
- } catch (error) {
594
- throw this.failure(
595
- `Failed to stop legacy detached E2B process ${legacyPid}: ${messageFrom(error)}`
596
- );
597
- }
598
- if (!signalled) return;
599
- while (performance.now() < deadline) {
600
- let processes;
601
- try {
602
- processes = await withinDeadline(
603
- this.sandbox.commands.list({
604
- requestTimeoutMs: remainingTimeoutMs(deadline)
605
- }),
606
- deadline
607
- );
608
- } catch (error) {
609
- throw this.failure(
610
- `Failed to confirm legacy detached E2B process ${legacyPid} exit: ${messageFrom(error)}`
611
- );
612
- }
613
- if (!processes.some((process2) => process2.pid === legacyPid)) return;
614
- const remaining = deadline - performance.now();
615
- if (remaining <= 0) break;
616
- await delay(Math.min(LEGACY_E2B_EXIT_POLL_INTERVAL_MS, remaining));
617
- }
618
- throw this.failure(
619
- `Failed to stop legacy detached E2B process ${legacyPid}: provider still reports it as running.`
620
- );
621
- }
622
- async getServerEndpoint(port) {
623
- return {
624
- url: `https://${this.sandbox.getHost(port)}`,
625
- trafficToken: this.sandbox.trafficAccessToken
626
- };
627
- }
628
- async destroy() {
629
- await this.sandbox.kill();
630
- }
631
- };
632
-
633
- // src/providers/modal.ts
634
- import { createHash } from "crypto";
635
-
636
- // src/providers/modal-sdk.ts
637
- import { createRequire } from "module";
638
- function getModalSdk() {
639
- const require3 = createRequire(typeof __filename === "string" ? __filename : import.meta.url);
640
- return require3("modal");
641
- }
642
-
643
- // src/providers/modal.ts
644
- var MODAL_DEFAULT_TEMPLATE = "node:22-bookworm";
645
- var MODAL_DEFAULT_TIMEOUT_MS = 60 * 60 * 1e3;
646
- function validateModalOptions(options, mode, failure) {
647
- validateProviderOptions("Modal", options, ["environment", ...mode === "connect" ? ["sandboxId", "tokenId", "tokenSecret"] : [
648
- "template",
649
- "appName",
650
- "timeoutMs",
651
- "cpu",
652
- "memoryMiB",
653
- ...mode === "create" ? ["tokenId", "tokenSecret", "envs"] : []
654
- ]], failure);
655
- if (mode === "connect" && !("sandboxId" in options && options.sandboxId)) {
656
- throw failure("Modal sandboxId is required.");
657
- }
658
- const credentials = options;
659
- if (credentials.tokenId === void 0 !== (credentials.tokenSecret === void 0)) {
660
- throw failure("Modal tokenId and tokenSecret must be supplied together.");
661
- }
662
- }
663
- var modalClients = /* @__PURE__ */ new Map();
664
- var MAX_MODAL_CLIENTS = 16;
665
- async function sharedClient(credentials) {
666
- if (Number(process.versions.node.split(".")[0]) < 22) {
667
- throw new Error("The Modal provider requires Node.js 22 or later.");
668
- }
669
- const configuration = {
670
- tokenId: credentials.tokenId,
671
- tokenSecret: credentials.tokenSecret,
672
- environment: credentials.environment,
673
- logLevel: "error"
674
- };
675
- const key = createHash("sha256").update(JSON.stringify([
676
- configuration,
677
- Object.entries(process.env).filter(([name]) => name.startsWith("MODAL_")).sort(([left], [right]) => left.localeCompare(right))
678
- ])).digest("hex");
679
- const existing = modalClients.get(key);
680
- if (existing) return existing;
681
- if (modalClients.size >= MAX_MODAL_CLIENTS) {
682
- throw new Error("Modal client configuration limit reached (16 per module instance); use a separate worker for additional credentials or restart after credential rotation.");
683
- }
684
- let client;
685
- try {
686
- const { ModalClient } = getModalSdk();
687
- client = Promise.resolve(new ModalClient(configuration));
688
- } catch (error) {
689
- client = Promise.reject(error);
690
- }
691
- modalClients.set(key, client);
692
- return client;
693
- }
694
- var ModalSandboxHandle = class _ModalSandboxHandle {
695
- constructor(id, client, failure) {
696
- this.id = id;
697
- this.client = client;
698
- this.detachedProcesses = new DetachedProcessController({
699
- provider: "modal",
700
- genericPayloadEnvironmentDefaults: { HOME: this.paths.homeDir },
701
- execute: async (command, options) => {
702
- try {
703
- return { state: "completed", result: await this.runCommand(command, {
704
- ...options,
705
- timeoutMs: DETACHED_PROCESS_CONTROL_TIMEOUT_MS
706
- }) };
707
- } catch (error) {
708
- return { state: "failed", error };
709
- }
710
- },
711
- readLegacyLogs: async () => {
712
- throw failure("Modal requires a managed detached process handle.");
713
- },
714
- stopLegacy: async () => {
715
- throw failure("Modal requires a managed detached process handle.");
716
- },
717
- failure
718
- });
719
- }
720
- provider = "modal";
721
- paths = createProviderSandboxPaths("modal", "/root", "/root");
722
- detachedProcesses;
723
- static async create(options, failure) {
724
- const credentials = {
725
- tokenId: options.tokenId,
726
- tokenSecret: options.tokenSecret,
727
- environment: options.environment
728
- };
729
- const client = await sharedClient(credentials);
730
- let sandbox;
731
- try {
732
- const app = await client.apps.fromName(options.appName ?? "agent-neckbeard", { createIfMissing: true });
733
- const image = client.images.fromRegistry(options.template ?? MODAL_DEFAULT_TEMPLATE).dockerfileCommands([
734
- "USER root",
735
- "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/*",
736
- "WORKDIR /root"
737
- ]);
738
- sandbox = await client.sandboxes.create(app, image, {
739
- timeoutMs: options.timeoutMs ?? MODAL_DEFAULT_TIMEOUT_MS,
740
- cpu: options.cpu,
741
- memoryMiB: options.memoryMiB,
742
- workdir: "/root",
743
- env: Object.fromEntries(Object.entries(options.envs ?? {}).filter(
744
- (entry) => entry[1] !== void 0
745
- ))
746
- // No tunnels: all HTTP access requires a port-scoped Connect Token.
747
- });
748
- return new _ModalSandboxHandle(sandbox.sandboxId, client, failure);
749
- } finally {
750
- sandbox?.detach();
751
- }
752
- }
753
- static async connect(options, failure) {
754
- const client = await sharedClient({
755
- tokenId: options.tokenId,
756
- tokenSecret: options.tokenSecret,
757
- environment: options.environment
758
- });
759
- const handle = new _ModalSandboxHandle(options.sandboxId, client, failure);
760
- await handle.use(async (sandbox) => {
761
- if (await sandbox.poll() !== null) throw failure("Modal sandbox is no longer running.");
762
- });
763
- return handle;
764
- }
765
- async use(operation, timeoutMs) {
766
- const client = this.client;
767
- let sandbox;
768
- let active = true;
769
- try {
770
- const work = (async () => {
771
- const connected = await client.sandboxes.fromId(this.id);
772
- if (!active) {
773
- connected.detach();
774
- throw new Error("Modal command request already timed out.");
775
- }
776
- sandbox = connected;
777
- return operation(sandbox);
778
- })();
779
- return await (timeoutMs === void 0 ? work : withTimeout(
780
- work,
781
- timeoutMs,
782
- "Modal command request timed out; remote completion is unknown."
783
- ));
784
- } finally {
785
- active = false;
786
- sandbox?.detach();
787
- }
788
- }
789
- makeDir(path) {
790
- return this.use((sandbox) => sandbox.filesystem.makeDirectory(path));
791
- }
792
- writeFile(path, content) {
793
- return this.use((sandbox) => typeof content === "string" ? sandbox.filesystem.writeText(content, path) : sandbox.filesystem.writeBytes(content, path));
794
- }
795
- readFile(path) {
796
- return this.use((sandbox) => sandbox.filesystem.readText(path));
797
- }
798
- readFileBytes(path) {
799
- return this.use((sandbox) => sandbox.filesystem.readBytes(path));
800
- }
801
- runCommand(command, options) {
802
- try {
803
- validateProviderCommand("Modal", command, options);
804
- } catch (error) {
805
- return Promise.reject(error);
806
- }
807
- return this.use(async (sandbox) => {
808
- const process2 = await sandbox.exec(["/bin/bash", "--noprofile", "--norc", "-c", command], {
809
- workdir: options.cwd ?? this.paths.workDir,
810
- env: options.envs,
811
- timeoutMs: Math.ceil(options.timeoutMs / 1e3) * 1e3
812
- });
813
- const read = async (stream, callback) => {
814
- let output = "";
815
- for await (const chunk of stream) {
816
- output += chunk;
817
- callback?.(chunk);
818
- }
819
- return output;
820
- };
821
- const [stdout, stderr, exitCode] = await Promise.all([
822
- read(process2.stdout, options.onStdout),
823
- read(process2.stderr, options.onStderr),
824
- process2.wait()
825
- ]);
826
- return { stdout, stderr, exitCode };
827
- }, options.timeoutMs);
828
- }
829
- startDetachedCommand(command, options = {}) {
830
- return this.detachedProcesses.start(command, options);
831
- }
832
- readSessionLogs(command) {
833
- return this.detachedProcesses.readLogs(command);
834
- }
835
- stopSession(command) {
836
- return this.detachedProcesses.stop(command);
837
- }
838
- disposeSessionArtifacts(command) {
839
- return this.detachedProcesses.dispose(command);
840
- }
841
- getServerEndpoint(port) {
842
- if (!Number.isInteger(port) || port < 1 || port > 65535) {
843
- return Promise.reject(new Error("Modal endpoint port must be between 1 and 65535."));
844
- }
845
- return this.use(async (sandbox) => {
846
- const credentials = await sandbox.createConnectToken({ port });
847
- let url;
848
- try {
849
- url = new URL(credentials.url);
850
- } catch {
851
- throw new Error("Modal returned invalid private endpoint credentials.");
852
- }
853
- if (typeof credentials.token !== "string" || !credentials.token.trim() || /[\r\n]/u.test(credentials.token) || url.protocol !== "https:" || url.username || url.password) {
854
- throw new Error("Modal returned invalid private endpoint credentials.");
855
- }
856
- return { url: credentials.url, trafficToken: credentials.token };
857
- });
858
- }
859
- async destroy() {
860
- const { NotFoundError } = getModalSdk();
861
- try {
862
- await this.use(async (sandbox) => {
863
- await sandbox.terminate({ wait: true });
864
- });
865
- } catch (error) {
866
- const grpcNotFound = error instanceof Error && error.name === "ClientError" && Reflect.get(error, "code") === 5;
867
- if (!(error instanceof NotFoundError) && !grpcNotFound) throw error;
868
- }
869
- }
870
- };
871
-
872
- // src/providers/docker.ts
873
- import { spawn } from "child_process";
874
- import { createServer } from "net";
875
- import { StringDecoder } from "string_decoder";
876
- var DOCKER_DEFAULT_TEMPLATE = "node:22-bookworm";
877
- var DOCKER_DEFAULT_TIMEOUT_MS = 60 * 60 * 1e3;
878
- var DOCKER_MANAGED_LABEL = "agent-neckbeard.managed";
879
- var DOCKER_HOME = "/root";
880
- var DOCKER_ENV_FILE = `${DOCKER_HOME}/.neckbeard-env`;
881
- var DOCKER_CONTROL_TIMEOUT_MS = 3e4;
882
- var DOCKER_FILE_TIMEOUT_MS = 3e5;
883
- var DOCKER_CREATE_TIMEOUT_MS = 10 * 60 * 1e3;
884
- var DOCKER_BOOTSTRAP_TIMEOUT_MS = 5 * 60 * 1e3;
885
- var DOCKER_ORPHAN_GRACE_SECONDS = 2;
886
- var REQUIRED_TOOLS = ["bash", "python3", "flock", "setsid", "timeout", "curl"];
887
- function validateDockerOptions(options, mode, failure) {
888
- validateProviderOptions("Docker", options, mode === "connect" ? ["sandboxId"] : [
889
- "template",
890
- "network",
891
- "platform",
892
- "timeoutMs",
893
- "cpu",
894
- "memoryMiB",
895
- ...mode === "create" ? ["envs"] : []
896
- ], failure);
897
- if (mode === "connect" && !("sandboxId" in options && options.sandboxId)) {
898
- throw failure("Docker sandboxId is required.");
899
- }
900
- }
901
- function exportLines(envs) {
902
- return Object.entries(envs ?? {}).filter((entry) => entry[1] !== void 0).map(([name, value]) => `export ${name}=${shellQuote(value)}
903
- `).join("");
904
- }
905
- var runDockerCli = (args, options) => new Promise((resolve2, reject) => {
906
- const child = spawn("docker", args, { stdio: ["pipe", "pipe", "pipe"] });
907
- const stdout = [];
908
- const stdoutDecoder = new StringDecoder("utf8");
909
- const stderrDecoder = new StringDecoder("utf8");
910
- let stderr = "";
911
- let settled = false;
912
- const timer = setTimeout(() => {
913
- child.kill("SIGKILL");
914
- settle(() => reject(new Error("Docker command request timed out; remote completion is unknown.")));
915
- }, options.timeoutMs);
916
- const settle = (callback) => {
917
- if (settled) return;
918
- settled = true;
919
- clearTimeout(timer);
920
- callback();
921
- };
922
- child.stdout.on("data", (chunk) => {
923
- stdout.push(chunk);
924
- if (options.onStdout) {
925
- const text = stdoutDecoder.write(chunk);
926
- if (text) options.onStdout(text);
927
- }
928
- });
929
- child.stderr.on("data", (chunk) => {
930
- const text = stderrDecoder.write(chunk);
931
- stderr += text;
932
- if (text) options.onStderr?.(text);
933
- });
934
- child.on("error", (error) => settle(() => reject(
935
- Reflect.get(error, "code") === "ENOENT" ? new Error("The Docker provider requires the `docker` CLI on PATH.") : error
936
- )));
937
- child.on("close", (code) => settle(() => resolve2({
938
- exitCode: code ?? 1,
939
- stdout: Buffer.concat(stdout),
940
- stderr
941
- })));
942
- child.stdin.on("error", () => void 0);
943
- child.stdin.end(options.input);
944
- });
945
- var tunnels = /* @__PURE__ */ new Map();
946
- function relaySource(port) {
947
- return [
948
- "import os,socket,threading",
949
- `s=socket.create_connection(("127.0.0.1",${port}))`,
950
- "def up():",
951
- " while True:",
952
- " d=os.read(0,65536)",
953
- " if not d: break",
954
- " s.sendall(d)",
955
- " try: s.shutdown(socket.SHUT_WR)",
956
- " except OSError: pass",
957
- "threading.Thread(target=up,daemon=True).start()",
958
- "while True:",
959
- " d=s.recv(65536)",
960
- " if not d: break",
961
- " while d: d=d[os.write(1,d):]"
962
- ].join("\n");
963
- }
964
- function openTunnel(containerId, port) {
965
- const key = `${containerId}:${port}`;
966
- const existing = tunnels.get(key);
967
- if (existing) return existing;
968
- const tunnel = new Promise((resolve2, reject) => {
969
- const server = createServer((socket) => {
970
- const relay = spawn("docker", [
971
- "exec",
972
- "-i",
973
- "--user",
974
- "root",
975
- containerId,
976
- "python3",
977
- "-u",
978
- "-c",
979
- relaySource(port)
980
- ], { stdio: ["pipe", "pipe", "ignore"] });
981
- socket.pipe(relay.stdin);
982
- relay.stdout.pipe(socket);
983
- relay.stdin.on("error", () => void 0);
984
- relay.on("error", () => socket.destroy());
985
- relay.on("close", () => socket.destroy());
986
- socket.on("error", () => relay.kill("SIGKILL"));
987
- socket.on("close", () => relay.kill("SIGKILL"));
988
- });
989
- server.once("error", reject);
990
- server.listen(0, "127.0.0.1", () => {
991
- server.unref();
992
- resolve2(server);
993
- });
994
- });
995
- tunnels.set(key, tunnel);
996
- tunnel.catch(() => tunnels.delete(key));
997
- return tunnel;
998
- }
999
- async function closeTunnels(containerId) {
1000
- for (const [key, tunnel] of tunnels) {
1001
- if (!key.startsWith(`${containerId}:`)) continue;
1002
- tunnels.delete(key);
1003
- await tunnel.then((server) => server.close(), () => void 0);
1004
- }
1005
- }
1006
- var DockerSandboxHandle = class _DockerSandboxHandle {
1007
- constructor(id, managed, failure, cli = runDockerCli) {
1008
- this.id = id;
1009
- this.managed = managed;
1010
- this.failure = failure;
1011
- this.cli = cli;
1012
- this.detachedProcesses = new DetachedProcessController({
1013
- provider: "docker",
1014
- genericPayloadEnvironmentDefaults: { HOME: this.paths.homeDir },
1015
- execute: async (command, options) => {
1016
- try {
1017
- return { state: "completed", result: await this.runCommand(command, {
1018
- ...options,
1019
- timeoutMs: DETACHED_PROCESS_CONTROL_TIMEOUT_MS
1020
- }) };
1021
- } catch (error) {
1022
- return { state: "failed", error };
1023
- }
1024
- },
1025
- readLegacyLogs: async () => {
1026
- throw failure("Docker requires a managed detached process handle.");
1027
- },
1028
- stopLegacy: async () => {
1029
- throw failure("Docker requires a managed detached process handle.");
1030
- },
1031
- failure
1032
- });
1033
- }
1034
- provider = "docker";
1035
- paths = createProviderSandboxPaths("docker", DOCKER_HOME, DOCKER_HOME);
1036
- detachedProcesses;
1037
- static async create(options, failure, cli = runDockerCli) {
1038
- const lifetimeSeconds = (options.timeoutMs ?? DOCKER_DEFAULT_TIMEOUT_MS) / 1e3;
1039
- const created = await cli([
1040
- "run",
1041
- "--detach",
1042
- "--rm",
1043
- "--init",
1044
- "--label",
1045
- `${DOCKER_MANAGED_LABEL}=true`,
1046
- "--user",
1047
- "root",
1048
- "--workdir",
1049
- DOCKER_HOME,
1050
- ...options.network ? ["--network", options.network] : [],
1051
- ...options.platform ? ["--platform", options.platform] : [],
1052
- ...options.cpu === void 0 ? [] : ["--cpus", String(options.cpu)],
1053
- ...options.memoryMiB === void 0 ? [] : ["--memory", `${options.memoryMiB}m`],
1054
- // No published ports: HTTP access goes through a loopback exec tunnel.
1055
- "--entrypoint",
1056
- "sleep",
1057
- options.template ?? DOCKER_DEFAULT_TEMPLATE,
1058
- String(lifetimeSeconds)
1059
- ], { timeoutMs: DOCKER_CREATE_TIMEOUT_MS });
1060
- const id = created.stdout.toString("utf8").trim().split("\n").pop() ?? "";
1061
- if (created.exitCode !== 0 || !/^[a-f0-9]{12,64}$/u.test(id)) {
1062
- throw failure(`Failed to create Docker sandbox: ${created.stderr.trim() || "no container ID returned."}`);
1063
- }
1064
- const handle = new _DockerSandboxHandle(id, true, failure, cli);
1065
- try {
1066
- await handle.writeFile(DOCKER_ENV_FILE, exportLines(options.envs));
1067
- await handle.ensureTools();
1068
- await handle.control(
1069
- "Docker pip configuration",
1070
- '[ -e /etc/pip.conf ] || printf "[global]\\nbreak-system-packages = true\\n" > /etc/pip.conf'
1071
- );
1072
- return handle;
1073
- } catch (error) {
1074
- await handle.destroy().catch(() => void 0);
1075
- throw error;
1076
- }
1077
- }
1078
- static async connect(options, failure, cli = runDockerCli) {
1079
- const inspected = await cli([
1080
- "inspect",
1081
- "--type",
1082
- "container",
1083
- "--format",
1084
- `{{.State.Running}} {{index .Config.Labels "${DOCKER_MANAGED_LABEL}"}}`,
1085
- options.sandboxId
1086
- ], { timeoutMs: DOCKER_CONTROL_TIMEOUT_MS });
1087
- if (inspected.exitCode !== 0) throw failure("Docker sandbox was not found.");
1088
- const [running, managed] = inspected.stdout.toString("utf8").trim().split(" ");
1089
- if (running !== "true") throw failure("Docker sandbox is no longer running.");
1090
- const handle = new _DockerSandboxHandle(options.sandboxId, managed === "true", failure, cli);
1091
- await handle.ensureTools();
1092
- return handle;
1093
- }
1094
- /** Installs the detached-process and deploy prerequisites only when the image lacks them. */
1095
- async ensureTools() {
1096
- await this.control(
1097
- "Docker sandbox tool preparation",
1098
- `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/*; }`,
1099
- [],
1100
- void 0,
1101
- DOCKER_BOOTSTRAP_TIMEOUT_MS
1102
- );
1103
- }
1104
- async control(label, script, args = [], input, timeoutMs = DOCKER_CONTROL_TIMEOUT_MS) {
1105
- const result = await this.cli(
1106
- ["exec", "-i", "--user", "root", this.id, "/bin/sh", "-c", script, "sh", ...args],
1107
- { input, timeoutMs }
1108
- );
1109
- if (result.exitCode !== 0) {
1110
- throw this.failure(`${label} failed: ${result.stderr.trim() || `exit code ${result.exitCode}`}`);
1111
- }
1112
- return result;
1113
- }
1114
- async makeDir(path) {
1115
- await this.control("Docker directory creation", 'mkdir -p -- "$1"', [path]);
1116
- }
1117
- async writeFile(path, content) {
1118
- const input = typeof content === "string" ? content : content instanceof ArrayBuffer ? new Uint8Array(content) : content;
1119
- await this.control("Docker file write", 'mkdir -p -- "$(dirname -- "$1")" && cat > "$1"', [path], input, DOCKER_FILE_TIMEOUT_MS);
1120
- }
1121
- async readFile(path) {
1122
- return (await this.control("Docker file read", 'cat -- "$1"', [path], void 0, DOCKER_FILE_TIMEOUT_MS)).stdout.toString("utf8");
1123
- }
1124
- async readFileBytes(path) {
1125
- return new Uint8Array((await this.control("Docker file read", 'cat -- "$1"', [path], void 0, DOCKER_FILE_TIMEOUT_MS)).stdout);
1126
- }
1127
- async runCommand(command, options) {
1128
- validateProviderCommand("Docker", command, options);
1129
- const deadlineSeconds = Math.ceil(options.timeoutMs / 1e3) + DOCKER_ORPHAN_GRACE_SECONDS;
1130
- const script = `[ -f ${DOCKER_ENV_FILE} ] && . ${DOCKER_ENV_FILE}
1131
- ` + exportLines(options.envs) + `cd -- ${shellQuote(options.cwd ?? this.paths.workDir)} || exit 1
1132
- exec timeout --kill-after=1 ${deadlineSeconds} /bin/bash --noprofile --norc -c ${shellQuote(command)} </dev/null
1133
- `;
1134
- const result = await this.cli(["exec", "-i", "--user", "root", this.id, "/bin/bash", "--noprofile", "--norc", "-s"], {
1135
- input: script,
1136
- timeoutMs: options.timeoutMs,
1137
- onStdout: options.onStdout,
1138
- onStderr: options.onStderr
1139
- });
1140
- return { stdout: result.stdout.toString("utf8"), stderr: result.stderr, exitCode: result.exitCode };
1141
- }
1142
- startDetachedCommand(command, options = {}) {
1143
- return this.detachedProcesses.start(command, options);
1144
- }
1145
- readSessionLogs(command) {
1146
- return this.detachedProcesses.readLogs(command);
1147
- }
1148
- stopSession(command) {
1149
- return this.detachedProcesses.stop(command);
1150
- }
1151
- disposeSessionArtifacts(command) {
1152
- return this.detachedProcesses.dispose(command);
1153
- }
1154
- async getServerEndpoint(port) {
1155
- if (!Number.isInteger(port) || port < 1 || port > 65535) {
1156
- throw new Error("Docker endpoint port must be between 1 and 65535.");
1157
- }
1158
- const address = (await openTunnel(this.id, port)).address();
1159
- if (!address || typeof address === "string") throw new Error("Docker tunnel has no loopback address.");
1160
- return { url: `http://127.0.0.1:${address.port}` };
1161
- }
1162
- /** Removes containers this provider created; containers it attached to are left to their owner. */
1163
- async destroy() {
1164
- if (!this.managed) return;
1165
- await closeTunnels(this.id);
1166
- const result = await this.cli(["rm", "--force", "--volumes", this.id], { timeoutMs: DOCKER_CONTROL_TIMEOUT_MS });
1167
- if (result.exitCode !== 0 && !/no such container|is already in progress/iu.test(result.stderr)) {
1168
- throw this.failure(`Failed to remove Docker sandbox: ${result.stderr.trim()}`);
1169
- }
1170
- }
1171
- };
1172
-
1173
- // src/index.ts
1174
- function readPackageJson(path) {
1175
- return JSON.parse(readFileSync(path, "utf8"));
1176
- }
1177
- var getEsbuild = () => import("esbuild");
1178
- var getE2b = () => import("e2b");
1179
- var getDaytona = () => import("@daytona/sdk");
1180
- var DEFAULT_MAX_DURATION = 300;
1181
- var SANDBOX_COMMAND_TIMEOUT_MS2 = 3e5;
1182
- var QUICK_COMMAND_TIMEOUT_MS2 = 3e4;
1183
- var DAYTONA_CREATE_TIMEOUT_SEC = 120;
1184
- var NODE_TARGET = "node20";
1185
- var DEFAULT_EXTERNALS = ["@anthropic-ai/claude-agent-sdk"];
1186
- var NECKBEARD_PACKAGE_NAME = "agent-neckbeard";
1187
- var NECKBEARD_SANDBOX_RUNTIME_ENV = "AGENT_NECKBEARD_SANDBOX_RUNTIME";
1188
- var SANDBOX_PLATFORM = process.env.NECKBEARD_SANDBOX_PLATFORM ?? "linux";
1189
- var SANDBOX_ARCH = process.env.NECKBEARD_SANDBOX_ARCH ?? "x64";
1190
- var DEFAULT_SERVER_PORT = 3e3;
1191
- var SERVER_HEALTH_TIMEOUT_MS = 12e4;
1192
- var SERVER_RECONNECT_HEALTH_TIMEOUT_MS = 3e3;
1193
- var SERVER_HEALTH_POLL_INTERVAL_MS = 1e3;
1194
- var DEFAULT_IDLE_TIMEOUT_MS = RUNTIME_ABORT_GRACE_MS + 3e4;
1195
- var SERVER_FAILURE_DIAGNOSTIC_TIMEOUT_MS = 1e3;
1196
- var NATIVE_EXT_RE = /\.(node|wasm|gyp|c|cc|cpp|cxx|h|hpp|hxx)$/i;
1197
- var TRACEABLE_SOURCE_EXT_RE = /\.(cjs|cts|js|jsx|mjs|mts|ts|tsx)$/i;
1198
- var NeckbeardError = class extends Error {
1199
- constructor(message) {
1200
- super(message);
1201
- this.name = "NeckbeardError";
1202
- }
1203
- };
1204
- var DeploymentError = class extends NeckbeardError {
1205
- constructor(message, cause) {
1206
- super(message);
1207
- this.cause = cause;
1208
- this.name = "DeploymentError";
1209
- }
1210
- };
1211
- var ValidationError = class extends NeckbeardError {
1212
- constructor(message, cause) {
1213
- super(message);
1214
- this.cause = cause;
1215
- this.name = "ValidationError";
1216
- }
1217
- };
1218
- var ExecutionError = class extends NeckbeardError {
1219
- constructor(message, cause) {
1220
- super(message);
1221
- this.cause = cause;
1222
- this.name = "ExecutionError";
1223
- }
1224
- };
1225
- var RuntimeBusyError = class extends ExecutionError {
1226
- constructor(message) {
1227
- super(message);
1228
- this.name = "RuntimeBusyError";
1229
- }
1230
- };
1231
- var ConfigurationError = class extends NeckbeardError {
1232
- constructor(message) {
1233
- super(message);
1234
- this.name = "ConfigurationError";
1235
- }
1236
- };
1237
- function resolveAgentSourceFile(candidates, options = {}) {
1238
- const normalizedCandidates = normalizeNonEmptyStrings("candidates", candidates);
1239
- const sourceFile = normalizedCandidates.find((candidate) => existsSync(candidate));
1240
- if (sourceFile) {
1241
- return sourceFile;
1242
- }
1243
- if (process.env[NECKBEARD_SANDBOX_RUNTIME_ENV] === "1") {
1244
- const sandboxSourceFile = options.sandboxSourceFile ?? resolve(process.cwd(), "agent.mjs");
1245
- if (existsSync(sandboxSourceFile)) {
1246
- return sandboxSourceFile;
1247
- }
1248
- }
1249
- throw new ConfigurationError(
1250
- options.errorMessage ?? `Could not resolve agent source file. Checked: ${candidates.join(", ")}`
1251
- );
1252
- }
1253
- function withNeckbeardNextConfig(nextConfig, options) {
1254
- const sourceFiles = normalizeNonEmptyStrings("sourceFiles", options.sourceFiles);
1255
- const routeGlobs = normalizeNonEmptyStrings("routeGlob", options.routeGlob ?? "/*");
1256
- const traceSourceDependencies = options.traceSourceDependencies ?? true;
1257
- const traceIncludeFiles = traceIncludeFilesForConfig(
1258
- process.cwd(),
1259
- sourceFiles,
1260
- traceSourceDependencies
1261
- );
1262
- const result = {
1263
- ...nextConfig,
1264
- serverExternalPackages: mergeStringArray(nextConfig.serverExternalPackages, [
1265
- NECKBEARD_PACKAGE_NAME,
1266
- "modal"
1267
- ]),
1268
- outputFileTracingIncludes: mergeTracingIncludes(
1269
- nextConfig.outputFileTracingIncludes,
1270
- routeGlobs,
1271
- traceIncludeFiles
1272
- )
1273
- };
1274
- if (nextConfig.webpack) {
1275
- result.webpack = withNextTraceIncludeWebpack(
1276
- nextConfig.webpack,
1277
- sourceFiles,
1278
- routeGlobs,
1279
- traceSourceDependencies
1280
- );
1281
- }
1282
- if (options.outputFileTracingRoot !== void 0) {
1283
- result.outputFileTracingRoot = options.outputFileTracingRoot;
1284
- }
1285
- return result;
1286
- }
1287
- var NextTraceIncludePlugin = class {
1288
- constructor(appDir, sourceFiles, routeGlobs, traceSourceDependencies) {
1289
- this.appDir = appDir;
1290
- this.sourceFiles = sourceFiles;
1291
- this.routeGlobs = routeGlobs;
1292
- this.traceSourceDependencies = traceSourceDependencies;
1293
- }
1294
- apply(compiler) {
1295
- const compilationHook = compiler.hooks?.compilation;
1296
- if (typeof compilationHook?.tap === "function") {
1297
- compilationHook.tap("NeckbeardNextTraceIncludePlugin", (compilation) => {
1298
- const processAssets = compilation.hooks?.processAssets;
1299
- if (typeof processAssets?.tap !== "function") {
1300
- return;
1301
- }
1302
- processAssets.tap({
1303
- name: "NeckbeardNextTraceIncludePlugin",
1304
- stage: compiler.webpack?.Compilation?.PROCESS_ASSETS_STAGE_REPORT ?? 5e3
1305
- }, (assets) => {
1306
- appendIncludesToTraceAssets({
1307
- appDir: this.appDir,
1308
- assets,
1309
- outputPath: compilation.outputOptions?.path ?? compiler.outputPath ?? "",
1310
- rawSource: compiler.webpack?.sources?.RawSource,
1311
- routeGlobs: this.routeGlobs,
1312
- sourceFiles: this.sourceFiles,
1313
- traceSourceDependencies: this.traceSourceDependencies,
1314
- updateAsset: compilation.updateAsset?.bind(compilation)
1315
- });
1316
- });
1317
- });
1318
- }
1319
- const afterEmit = compiler.hooks?.afterEmit;
1320
- const done = compiler.hooks?.done;
1321
- if (typeof afterEmit?.tap !== "function" && typeof done?.tap !== "function") {
1322
- return;
1323
- }
1324
- if (!compiler.outputPath) {
1325
- return;
1326
- }
1327
- const appendIncludes = () => {
1328
- appendIncludesToTraceFiles(
1329
- compiler.outputPath ?? "",
1330
- this.appDir,
1331
- this.sourceFiles,
1332
- this.routeGlobs,
1333
- this.traceSourceDependencies
1334
- );
1335
- };
1336
- if (typeof afterEmit?.tap === "function") {
1337
- afterEmit.tap("NeckbeardNextTraceIncludePlugin", appendIncludes);
1338
- }
1339
- if (typeof done?.tap === "function") {
1340
- done.tap("NeckbeardNextTraceIncludePlugin", appendIncludes);
1341
- }
1342
- }
1343
- };
1344
- function appendIncludesToTraceAssets({
1345
- appDir,
1346
- assets,
1347
- outputPath,
1348
- rawSource,
1349
- routeGlobs,
1350
- sourceFiles,
1351
- traceSourceDependencies,
1352
- updateAsset
1353
- }) {
1354
- const includedFiles = expandTraceIncludeFiles(appDir, sourceFiles, traceSourceDependencies);
1355
- if (includedFiles.length === 0) {
1356
- return;
1357
- }
1358
- for (const [assetName, asset] of Object.entries(assets)) {
1359
- if (!assetName.endsWith(".nft.json")) {
1360
- continue;
1361
- }
1362
- const routePath = routePathFromTraceAsset(outputPath, assetName);
1363
- if (!routePath || !routeGlobs.some((routeGlob) => routeGlobMatches(routeGlob, routePath))) {
1364
- continue;
1365
- }
1366
- const traceDir = dirname(join(outputPath, assetName));
1367
- const nextSource = traceWithIncludedFiles(String(asset.source()), traceDir, includedFiles);
1368
- if (rawSource && updateAsset) {
1369
- updateAsset(assetName, new rawSource(nextSource));
1370
- } else {
1371
- assets[assetName] = {
1372
- source: () => nextSource,
1373
- size: () => Buffer.byteLength(nextSource)
1374
- };
1375
- }
1376
- }
1377
- }
1378
- function withNextTraceIncludeWebpack(originalWebpack, sourceFiles, routeGlobs, traceSourceDependencies) {
1379
- return (config, context) => {
1380
- const nextConfig = originalWebpack ? originalWebpack(config, context) : config;
1381
- if (!context.isServer || context.dev) {
1382
- return nextConfig;
1383
- }
1384
- nextConfig.externals = withNeckbeardExternal(nextConfig.externals);
1385
- nextConfig.plugins = [
1386
- ...Array.isArray(nextConfig.plugins) ? nextConfig.plugins : [],
1387
- new NextTraceIncludePlugin(
1388
- context.dir ?? process.cwd(),
1389
- sourceFiles,
1390
- routeGlobs,
1391
- traceSourceDependencies
1392
- )
1393
- ];
1394
- return nextConfig;
1395
- };
1396
- }
1397
- function withNeckbeardExternal(externals) {
1398
- return [
1399
- neckbeardExternal,
1400
- ...Array.isArray(externals) ? externals : externals ? [externals] : []
1401
- ];
1402
- }
1403
- function neckbeardExternal(contextOrRequest, requestOrCallback) {
1404
- const legacyCallback = arguments[2];
1405
- const request = typeof requestOrCallback === "string" ? requestOrCallback : typeof contextOrRequest === "string" ? contextOrRequest : contextOrRequest.request;
1406
- const callback = typeof requestOrCallback === "function" ? requestOrCallback : legacyCallback;
1407
- if (request === NECKBEARD_PACKAGE_NAME || request === "modal") {
1408
- const result = `commonjs ${request}`;
1409
- if (callback) {
1410
- callback(null, result);
1411
- return;
1412
- }
1413
- return result;
1414
- }
1415
- if (callback) {
1416
- callback();
1417
- }
1418
- }
1419
- function appendIncludesToTraceFiles(outputPath, appDir, sourceFiles, routeGlobs, traceSourceDependencies) {
1420
- if (!outputPath || !existsSync(outputPath)) {
1421
- return;
1422
- }
1423
- const includedFiles = expandTraceIncludeFiles(appDir, sourceFiles, traceSourceDependencies);
1424
- if (includedFiles.length === 0) {
1425
- return;
1426
- }
1427
- for (const traceFile of findTraceFiles(outputPath)) {
1428
- const routePath = routePathFromTraceFile(outputPath, traceFile);
1429
- if (!routePath || !routeGlobs.some((routeGlob) => routeGlobMatches(routeGlob, routePath))) {
1430
- continue;
1431
- }
1432
- appendFilesToTrace(traceFile, includedFiles);
1433
- }
1434
- }
1435
- function appendFilesToTrace(traceFile, includedFiles) {
1436
- const nextSource = traceWithIncludedFiles(
1437
- readFileSync(traceFile, "utf8"),
1438
- dirname(traceFile),
1439
- includedFiles
1440
- );
1441
- writeFileSync(traceFile, nextSource);
1442
- }
1443
- function traceWithIncludedFiles(traceSource, traceDir, includedFiles) {
1444
- const trace = JSON.parse(traceSource);
1445
- const files = Array.isArray(trace.files) ? trace.files.filter((file) => typeof file === "string") : [];
1446
- const nextFiles = new Set(files);
1447
- for (const includedFile of includedFiles) {
1448
- nextFiles.add(relative(traceDir, includedFile).replace(/\\/g, "/"));
1449
- }
1450
- return JSON.stringify({
1451
- version: trace.version ?? 1,
1452
- files: [...nextFiles]
1453
- });
1454
- }
1455
- function expandTraceIncludeFiles(appDir, sourceFiles, traceSourceDependencies = true) {
1456
- const files = /* @__PURE__ */ new Set();
1457
- for (const sourceFile of sourceFiles) {
1458
- for (const file of expandTraceIncludePattern(appDir, sourceFile)) {
1459
- files.add(file);
1460
- }
1461
- }
1462
- if (traceSourceDependencies) {
1463
- for (const file of traceSourceDependencyFiles(appDir, [...files])) {
1464
- files.add(file);
1465
- }
1466
- }
1467
- return [...files];
1468
- }
1469
- function traceIncludeFilesForConfig(appDir, sourceFiles, traceSourceDependencies) {
1470
- const tracedFiles = expandTraceIncludeFiles(appDir, sourceFiles, traceSourceDependencies).map((file) => toNextTraceIncludePath(appDir, file));
1471
- return mergeStringArray(sourceFiles, tracedFiles);
1472
- }
1473
- function toNextTraceIncludePath(appDir, file) {
1474
- const relativePath = relative(appDir, file).replace(/\\/g, "/");
1475
- if (relativePath.startsWith("..")) {
1476
- return relativePath;
1477
- }
1478
- return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
1479
- }
1480
- function expandTraceIncludePattern(appDir, sourceFile) {
1481
- const normalized = sourceFile.replace(/\\/g, "/").replace(/^\.\//, "");
1482
- if (normalized.endsWith("/**/*")) {
1483
- const dir = resolve(appDir, normalized.slice(0, -5));
1484
- return findFiles(dir);
1485
- }
1486
- if (normalized.endsWith("/*")) {
1487
- const dir = resolve(appDir, normalized.slice(0, -2));
1488
- return directFiles(dir);
1489
- }
1490
- const file = resolve(appDir, normalized);
1491
- return existsSync(file) && statSync(file).isFile() ? [file] : [];
1492
- }
1493
- function traceSourceDependencyFiles(appDir, sourceFiles) {
1494
- const entryPoints = sourceFiles.filter((file) => TRACEABLE_SOURCE_EXT_RE.test(file));
1495
- if (entryPoints.length === 0) {
1496
- return [];
1497
- }
1498
- try {
1499
- const esbuild = getEsbuildSync();
1500
- const result = esbuild.buildSync({
1501
- absWorkingDir: appDir,
1502
- bundle: true,
1503
- entryPoints,
1504
- external: [...DEFAULT_EXTERNALS, NECKBEARD_PACKAGE_NAME],
1505
- format: "esm",
1506
- logLevel: "silent",
1507
- metafile: true,
1508
- platform: "node",
1509
- preserveSymlinks: true,
1510
- target: NODE_TARGET,
1511
- treeShaking: false,
1512
- write: false
1513
- });
1514
- const metafile = result.metafile;
1515
- if (!metafile) {
1516
- return [];
1517
- }
1518
- const files = /* @__PURE__ */ new Set();
1519
- const addFile = (file) => {
1520
- if (file && existsSync(file) && statSync(file).isFile()) {
1521
- files.add(file);
1522
- }
1523
- };
1524
- for (const [inputPath, input] of Object.entries(metafile.inputs)) {
1525
- const absoluteInput = resolveMetafileInput(appDir, inputPath);
1526
- addFile(absoluteInput);
1527
- for (const importRecord of input.imports ?? []) {
1528
- const importPath = importRecord.original ?? importRecord.path;
1529
- if (!isBareModuleImport(importPath) || isBuiltinModule(importPath)) {
1530
- continue;
1531
- }
1532
- if (importPath === NECKBEARD_PACKAGE_NAME) {
1533
- continue;
1534
- }
1535
- const resolvedImportPath = importRecord.external ? void 0 : resolveMetafileInput(appDir, importRecord.path);
1536
- const packageInfo = resolvedImportPath ? resolvePackageInfoFromResolvedPath(importPath, resolvedImportPath) : resolvePackageInfoSync(importPath, dirname(absoluteInput));
1537
- if (!packageInfo) {
1538
- continue;
1539
- }
1540
- addFile(packageInfo.resolvedPath);
1541
- addFile(join(packageInfo.root, "package.json"));
1542
- }
1543
- }
1544
- return [...files];
1545
- } catch (error) {
1546
- throw new ConfigurationError(
1547
- `Failed to trace Neckbeard source dependencies for Next.js output tracing: ${errorMessage(error)}`
1548
- );
1549
- }
1550
- }
1551
- function getEsbuildSync() {
1552
- return packageRequire("esbuild");
1553
- }
1554
- function resolveMetafileInput(absWorkingDir, inputPath) {
1555
- return resolve(absWorkingDir, inputPath);
1556
- }
1557
- function findTraceFiles(root) {
1558
- return findFiles(root).filter((file) => file.endsWith(".nft.json"));
1559
- }
1560
- function findFiles(root) {
1561
- if (!existsSync(root)) {
1562
- return [];
1563
- }
1564
- const stat = statSync(root);
1565
- if (stat.isFile()) {
1566
- return [root];
1567
- }
1568
- if (!stat.isDirectory()) {
1569
- return [];
1570
- }
1571
- const files = [];
1572
- for (const entry of readdirSync(root)) {
1573
- files.push(...findFiles(join(root, entry)));
1574
- }
1575
- return files;
1576
- }
1577
- function directFiles(root) {
1578
- if (!existsSync(root) || !statSync(root).isDirectory()) {
1579
- return [];
1580
- }
1581
- return readdirSync(root).map((entry) => join(root, entry)).filter((file) => statSync(file).isFile());
1582
- }
1583
- function routePathFromTraceFile(outputPath, traceFile) {
1584
- const relativeTrace = relative(outputPath, traceFile).replace(/\\/g, "/");
1585
- return routePathFromRelativeTrace(outputPath, relativeTrace);
1586
- }
1587
- function routePathFromTraceAsset(outputPath, assetName) {
1588
- return routePathFromRelativeTrace(outputPath, assetName.replace(/\\/g, "/"));
1589
- }
1590
- function routePathFromRelativeTrace(outputPath, relativeTrace) {
1591
- const normalizedTrace = relativeTrace.replace(/^(\.\.\/)+/, "");
1592
- if (relativeTrace.startsWith("app/")) {
1593
- return normalizeTraceRoute(relativeTrace.slice("app/".length));
1594
- }
1595
- if (relativeTrace.startsWith("pages/")) {
1596
- return normalizeTraceRoute(relativeTrace.slice("pages/".length));
1597
- }
1598
- if (normalizedTrace.startsWith("app/")) {
1599
- return normalizeTraceRoute(normalizedTrace.slice("app/".length));
1600
- }
1601
- if (normalizedTrace.startsWith("pages/")) {
1602
- return normalizeTraceRoute(normalizedTrace.slice("pages/".length));
1603
- }
1604
- if (basename(outputPath) === "app" || basename(outputPath) === "pages") {
1605
- return normalizeTraceRoute(relativeTrace);
1606
- }
1607
- return void 0;
1608
- }
1609
- function normalizeTraceRoute(relativeTrace) {
1610
- const withoutTraceSuffix = relativeTrace.replace(/\.js\.nft\.json$/, "");
1611
- const route = withoutTraceSuffix.replace(/\/route$/, "").replace(/\/page$/, "").replace(/\/index$/, "");
1612
- return `/${route}`;
1613
- }
1614
- function routeGlobMatches(routeGlob, routePath) {
1615
- if (routeGlob === "/*") {
1616
- return true;
1617
- }
1618
- return routeGlobToRegExp(routeGlob).test(routePath);
1619
- }
1620
- function routeGlobToRegExp(glob) {
1621
- let pattern = "";
1622
- for (let index = 0; index < glob.length; index += 1) {
1623
- const char = glob[index];
1624
- const nextChar = glob[index + 1];
1625
- if (char === "*" && nextChar === "*") {
1626
- pattern += ".*";
1627
- index += 1;
1628
- } else if (char === "*") {
1629
- pattern += "[^/]*";
1630
- } else {
1631
- pattern += escapeRegExp(char);
1632
- }
1633
- }
1634
- return new RegExp(`^${pattern}$`);
1635
- }
1636
- function escapeRegExp(value) {
1637
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1638
- }
1639
- function asRecord(value) {
1640
- return value && typeof value === "object" && !Array.isArray(value) ? value : {};
1641
- }
1642
- function normalizeNonEmptyStrings(name, value) {
1643
- const values = Array.isArray(value) ? value : [value];
1644
- if (values.length === 0) {
1645
- throw new ConfigurationError(`${name} must contain at least one entry.`);
1646
- }
1647
- for (const entry of values) {
1648
- if (typeof entry !== "string" || entry.trim() === "") {
1649
- throw new ConfigurationError(`${name} entries must be non-empty strings.`);
1650
- }
1651
- }
1652
- return values;
1653
- }
1654
- function mergeStringArray(existing, values) {
1655
- const current = Array.isArray(existing) ? existing.filter((value) => typeof value === "string") : [];
1656
- return [.../* @__PURE__ */ new Set([...current, ...values])];
1657
- }
1658
- function mergeTracingIncludes(existing, routeGlobs, sourceFiles) {
1659
- const includes = { ...asRecord(existing) };
1660
- for (const routeGlob of routeGlobs) {
1661
- includes[routeGlob] = mergeStringArray(includes[routeGlob], sourceFiles);
1662
- }
1663
- return includes;
1664
- }
1665
- var DEFAULT_DEPENDENCIES = {};
1666
- function isSessionAgentConfig(config) {
1667
- return "session" in config && config.session !== void 0 || "server" in config && config.server !== void 0;
1668
- }
1669
- function getSessionHandler(config) {
1670
- const session = "session" in config ? config.session : void 0;
1671
- const server = "server" in config ? config.server : void 0;
1672
- if (session && server) {
1673
- throw new ConfigurationError("Agent config must use session or deprecated server, not both.");
1674
- }
1675
- const handler = session ?? server;
1676
- if (!handler || typeof handler !== "object") {
1677
- throw new ConfigurationError("session must be an object.");
1678
- }
1679
- return handler;
1680
- }
1681
- function isSchemaLike(value) {
1682
- return Boolean(
1683
- value && typeof value === "object" && typeof value.parse === "function"
1684
- );
1685
- }
1686
- function requireSchemaLike(name, value) {
1687
- if (!isSchemaLike(value)) {
1688
- throw new ConfigurationError(`${name} must be an object with a parse(value) function.`);
1689
- }
1690
- return value;
1691
- }
1692
- function isAbortSignal(value) {
1693
- if (!value || typeof value !== "object") return false;
1694
- try {
1695
- const abortedGetter = Object.getOwnPropertyDescriptor(
1696
- AbortSignal.prototype,
1697
- "aborted"
1698
- )?.get;
1699
- if (!abortedGetter || typeof abortedGetter.call(value) !== "boolean") return false;
1700
- const candidate = value;
1701
- return typeof candidate.aborted === "boolean" && typeof candidate.addEventListener === "function" && typeof candidate.removeEventListener === "function";
1702
- } catch {
1703
- return false;
1704
- }
1705
- }
1706
- function normalizeLocalDirectoryDestination(destination, name) {
1707
- if (destination.trim() === "") {
1708
- throw new ConfigurationError(`${name}.destination must be a non-empty relative path.`);
1709
- }
1710
- if (destination.includes("\0")) {
1711
- throw new ConfigurationError(`${name}.destination must not contain null bytes.`);
1712
- }
1713
- const sandboxPath = destination.replace(/\\/g, "/");
1714
- if (isAbsolute(destination) || posix.isAbsolute(sandboxPath) || win32.isAbsolute(destination)) {
1715
- throw new ConfigurationError(
1716
- `${name}.destination must be relative to the sandbox agent directory.`
1717
- );
1718
- }
1719
- if (sandboxPath.split("/").includes("..")) {
1720
- throw new ConfigurationError(
1721
- `${name}.destination must not traverse outside the sandbox agent directory.`
1722
- );
1723
- }
1724
- const normalized = posix.normalize(sandboxPath);
1725
- if (normalized === ".") {
1726
- throw new ConfigurationError(`${name}.destination must not be ".".`);
1727
- }
1728
- return normalized;
1729
- }
1730
- function validateLocalDirectoriesConfig(value) {
1731
- if (value === void 0) return;
1732
- if (!Array.isArray(value)) {
1733
- throw new ConfigurationError("localDirectories must be an array when provided.");
1734
- }
1735
- for (const [index, entry] of value.entries()) {
1736
- const name = `localDirectories[${index}]`;
1737
- if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
1738
- throw new ConfigurationError(`${name} must be an object.`);
1739
- }
1740
- const candidate = entry;
1741
- if (typeof candidate.source !== "string" || candidate.source.trim() === "") {
1742
- throw new ConfigurationError(`${name}.source must be a non-empty string.`);
1743
- }
1744
- if (candidate.source.includes("\0")) {
1745
- throw new ConfigurationError(`${name}.source must not contain null bytes.`);
1746
- }
1747
- if (typeof candidate.destination !== "string") {
1748
- throw new ConfigurationError(`${name}.destination must be a string.`);
1749
- }
1750
- normalizeLocalDirectoryDestination(candidate.destination, name);
1751
- }
1752
- }
1753
- function validateAgentConfig(config) {
1754
- if (!config || typeof config !== "object") {
1755
- throw new ConfigurationError("Agent config must be an object.");
1756
- }
1757
- if (!config.sandbox || typeof config.sandbox !== "object") {
1758
- throw new ConfigurationError("Agent config requires sandbox settings.");
1759
- }
1760
- if (config.sandbox.provider !== "e2b" && config.sandbox.provider !== "daytona" && config.sandbox.provider !== "modal" && config.sandbox.provider !== "docker") {
1761
- throw new ConfigurationError('sandbox.provider must be "e2b", "daytona", "modal", or "docker".');
1762
- }
1763
- if (config.sandbox.provider === "modal") {
1764
- validateModalOptions(config.sandbox, "agent", (message) => new ConfigurationError(message));
1765
- } else if (config.sandbox.provider === "docker") {
1766
- validateDockerOptions(config.sandbox, "agent", (message) => new ConfigurationError(message));
1767
- } else if (typeof config.sandbox.template !== "string" || config.sandbox.template.trim() === "") {
1768
- throw new ConfigurationError("sandbox.template must be a non-empty string.");
1769
- }
1770
- if (config.sandbox.provider === "daytona") {
1771
- const { autoStopInterval, autoDeleteInterval } = config.sandbox;
1772
- if (autoStopInterval !== void 0 && (!Number.isInteger(autoStopInterval) || autoStopInterval < 0)) {
1773
- throw new ConfigurationError("sandbox.autoStopInterval must be a non-negative integer number of minutes.");
1774
- }
1775
- if (autoDeleteInterval !== void 0 && !Number.isInteger(autoDeleteInterval)) {
1776
- throw new ConfigurationError("sandbox.autoDeleteInterval must be an integer number of minutes.");
1777
- }
1778
- }
1779
- requireSchemaLike("inputSchema", config.inputSchema);
1780
- if (config.maxDuration !== void 0 && (!Number.isFinite(config.maxDuration) || config.maxDuration <= 0)) {
1781
- throw new ConfigurationError("maxDuration must be a positive finite number of seconds.");
1782
- }
1783
- if (config.sourceFile !== void 0 && (typeof config.sourceFile !== "string" || config.sourceFile.trim() === "")) {
1784
- throw new ConfigurationError("sourceFile must be a non-empty string when provided.");
1785
- }
1786
- validateLocalDirectoriesConfig(config.localDirectories);
1787
- if (isSessionAgentConfig(config)) {
1788
- if ("run" in config && typeof config.run === "function") {
1789
- throw new ConfigurationError("Agent config must use either run or session.handler, not both.");
1790
- }
1791
- const session = getSessionHandler(config);
1792
- if (session.port !== void 0) {
1793
- if (!Number.isInteger(session.port) || session.port < 1 || session.port > 65535) {
1794
- throw new ConfigurationError("session.port must be an integer between 1 and 65535.");
1795
- }
1796
- }
1797
- requireSchemaLike("session.frameSchema", session.frameSchema);
1798
- if (typeof session.handler !== "function") {
1799
- throw new ConfigurationError("session.handler must be a function.");
1800
- }
1801
- return;
1802
- }
1803
- if (typeof config.run !== "function") {
1804
- throw new ConfigurationError("run must be a function for run-output agents.");
1805
- }
1806
- requireSchemaLike("outputSchema", config.outputSchema);
1807
- }
1808
- function getTrafficToken(descriptor) {
1809
- return descriptor.trafficToken;
1810
- }
1811
- function appendTrafficTokenToUrl(url, descriptor) {
1812
- const token = getTrafficToken(descriptor);
1813
- if (descriptor.provider !== "daytona" || !token) return url;
1814
- const separator = url.includes("?") ? "&" : "?";
1815
- return `${url}${separator}DAYTONA_SANDBOX_AUTH_KEY=${encodeURIComponent(token)}`;
1816
- }
1817
- function trafficTokenHeaders(descriptor) {
1818
- const token = getTrafficToken(descriptor);
1819
- if (descriptor.provider === "modal") {
1820
- if (!token) throw new ConfigurationError("Modal HTTP requests require a Connect Token.");
1821
- return { authorization: `Bearer ${token}` };
1822
- }
1823
- if (descriptor.provider === "e2b" && token) {
1824
- return { "e2b-traffic-access-token": token };
1825
- }
1826
- return {};
1827
- }
1828
- function abortSignalError(signal) {
1829
- if (signal.reason instanceof Error) return signal.reason;
1830
- const error = new Error(
1831
- signal.reason === void 0 ? "Operation aborted." : String(signal.reason)
1832
- );
1833
- error.name = "AbortError";
1834
- return error;
1835
- }
1836
- function throwIfAborted(signal) {
1837
- if (signal?.aborted) throw abortSignalError(signal);
1838
- }
1839
- function awaitWithAbort(operation, signal) {
1840
- return settleOperation(operation, {
1841
- ...signal ? {
1842
- abort: {
1843
- signal,
1844
- createError: () => abortSignalError(signal)
1845
- }
1846
- } : {}
1847
- });
1848
- }
1849
- function awaitDiagnosticRead(operation, signal) {
1850
- return settleOperation(operation, {
1851
- ...signal ? {
1852
- abort: {
1853
- signal,
1854
- createError: () => abortSignalError(signal)
1855
- }
1856
- } : {},
1857
- timeout: {
1858
- timeoutMs: SERVER_FAILURE_DIAGNOSTIC_TIMEOUT_MS,
1859
- createError: () => new Error("Server diagnostic read timed out.")
1860
- }
1861
- });
1862
- }
1863
- function delayWithAbort(delayMs, signal) {
1864
- if (!signal) {
1865
- return new Promise((resolve2) => setTimeout(resolve2, delayMs));
1866
- }
1867
- throwIfAborted(signal);
1868
- return new Promise((resolve2, reject) => {
1869
- const onAbort = () => {
1870
- clearTimeout(timer);
1871
- reject(abortSignalError(signal));
1872
- };
1873
- const timer = setTimeout(() => {
1874
- signal.removeEventListener("abort", onAbort);
1875
- resolve2();
1876
- }, delayMs);
1877
- signal.addEventListener("abort", onAbort, { once: true });
1878
- });
1879
- }
1880
- async function waitForServerHealthy(healthUrl, descriptor, timeoutMs = SERVER_HEALTH_TIMEOUT_MS, signal) {
1881
- const deadline = Date.now() + timeoutMs;
1882
- let lastError;
1883
- const urlWithToken = appendTrafficTokenToUrl(healthUrl, descriptor);
1884
- while (Date.now() < deadline) {
1885
- throwIfAborted(signal);
1886
- try {
1887
- const response = await awaitWithAbort(
1888
- () => fetch(urlWithToken, {
1889
- headers: trafficTokenHeaders(descriptor),
1890
- ...signal === void 0 ? {} : { signal }
1891
- }),
1892
- signal
1893
- );
1894
- if (response.ok) {
1895
- try {
1896
- await awaitWithAbort(() => response.text(), signal);
1897
- } catch {
1898
- throwIfAborted(signal);
1899
- }
1900
- return;
1901
- }
1902
- lastError = new Error(`health check returned ${response.status}`);
1903
- } catch (error) {
1904
- throwIfAborted(signal);
1905
- lastError = error;
1906
- }
1907
- await delayWithAbort(SERVER_HEALTH_POLL_INTERVAL_MS, signal);
1908
- }
1909
- const message = lastError instanceof Error ? lastError.message : String(lastError);
1910
- throw new DeploymentError(
1911
- `Server did not become healthy at ${healthUrl} within ${timeoutMs}ms: ${message}`
1912
- );
1913
- }
1914
- function requireEnv(name) {
1915
- const value = process.env[name];
1916
- if (!value) {
1917
- throw new ConfigurationError(
1918
- `${name} environment variable is required. Please set it before calling deploy() or run().`
1919
- );
1920
- }
1921
- return value;
1922
- }
1923
- var require2 = createRequire2(join(process.cwd(), "__agent_neckbeard__.cjs"));
1924
- var packageRequire = createPackageRequire();
1925
- function createPackageRequire() {
1926
- const cwdPackageJsonPath = join(process.cwd(), "package.json");
1927
- try {
1928
- if (existsSync(cwdPackageJsonPath) && readPackageJson(cwdPackageJsonPath).name === NECKBEARD_PACKAGE_NAME) {
1929
- return createRequire2(cwdPackageJsonPath);
1930
- }
1931
- } catch {
1932
- }
1933
- try {
1934
- return createRequire2(require2.resolve(NECKBEARD_PACKAGE_NAME));
1935
- } catch {
1936
- return require2;
1937
- }
1938
- }
1939
- function isBareModuleImport(path) {
1940
- const excludes = [".", "/", "~", "file:", "data:"];
1941
- return !excludes.some((exclude) => path.startsWith(exclude));
1942
- }
1943
- function isBuiltinModule(path) {
1944
- return builtinModules.includes(path.replace("node:", ""));
1945
- }
1946
- function packageNameForImportPath(importPath) {
1947
- if (importPath.startsWith("@")) {
1948
- return importPath.split("/").slice(0, 2).join("/");
1949
- }
1950
- return importPath.split("/")[0];
1951
- }
1952
- function globToRegExp(pattern) {
1953
- const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
1954
- return new RegExp(`^${escaped}$`);
1955
- }
1956
- function matchesExternal(matchers, pkgName) {
1957
- return matchers.some((re) => re.test(pkgName));
1958
- }
1959
- async function resolvePackageInfo(importPath, resolveDir) {
1960
- return resolvePackageInfoSync(importPath, resolveDir);
1961
- }
1962
- function resolvePackageInfoSync(importPath, resolveDir) {
1963
- try {
1964
- const resolvedPath = require2.resolve(importPath, { paths: [resolveDir] });
1965
- const packageName = packageNameForImportPath(importPath);
1966
- let root = dirname(resolvedPath);
1967
- let packageJsonPath = null;
1968
- while (true) {
1969
- const candidate = join(root, "package.json");
1970
- if (existsSync(candidate)) {
1971
- const candidatePackageJson = readPackageJson(candidate);
1972
- if (candidatePackageJson.name === packageName) {
1973
- packageJsonPath = candidate;
1974
- break;
1975
- }
1976
- }
1977
- const parent = dirname(root);
1978
- if (parent === root) break;
1979
- root = parent;
1980
- }
1981
- if (!packageJsonPath) return null;
1982
- const packageJson = readPackageJson(packageJsonPath);
1983
- if (!packageJson.name || !packageJson.version) return null;
1984
- root = dirname(packageJsonPath);
1985
- return {
1986
- name: packageJson.name,
1987
- version: packageJson.version,
1988
- root,
1989
- resolvedPath,
1990
- packageJson
1991
- };
1992
- } catch {
1993
- return null;
1994
- }
1995
- }
1996
- function resolvePackageInfoFromResolvedPath(importPath, resolvedPath) {
1997
- const packageName = packageNameForImportPath(importPath);
1998
- let root = dirname(resolvedPath);
1999
- while (true) {
2000
- const packageJsonPath = join(root, "package.json");
2001
- if (existsSync(packageJsonPath)) {
2002
- const packageJson = readPackageJson(packageJsonPath);
2003
- if (packageJson.name === packageName) {
2004
- if (!packageJson.version) return null;
2005
- return {
2006
- name: packageJson.name,
2007
- version: packageJson.version,
2008
- root,
2009
- resolvedPath,
2010
- packageJson
2011
- };
2012
- }
2013
- }
2014
- const parent = dirname(root);
2015
- if (parent === root) return null;
2016
- root = parent;
2017
- }
2018
- }
2019
- function hasNativeHints(info) {
2020
- const files = Array.isArray(info.packageJson.files) ? info.packageJson.files : [];
2021
- const fields = [info.packageJson.main, info.packageJson.module, info.packageJson.browser].filter(
2022
- (f) => typeof f === "string"
2023
- );
2024
- return files.concat(fields).some((file) => NATIVE_EXT_RE.test(file));
2025
- }
2026
- function shouldAutoExternalize(info) {
2027
- if (info.resolvedPath.endsWith(".node") || info.resolvedPath.endsWith(".wasm")) return true;
2028
- if (hasNativeHints(info)) return true;
2029
- if (existsSync(join(info.root, "binding.gyp"))) return true;
2030
- return false;
2031
- }
2032
- function normalizeList(value) {
2033
- if (Array.isArray(value)) return value.filter((v) => typeof v === "string");
2034
- if (typeof value === "string") return [value];
2035
- return null;
2036
- }
2037
- function listAllowsTarget(list, target) {
2038
- if (!list || list.length === 0) return true;
2039
- const negated = list.filter((v) => v.startsWith("!")).map((v) => v.slice(1));
2040
- if (negated.includes(target)) return false;
2041
- const positives = list.filter((v) => !v.startsWith("!"));
2042
- if (positives.length === 0) return true;
2043
- return positives.includes(target);
2044
- }
2045
- function isPackageCompatible(info) {
2046
- const osList = normalizeList(info.packageJson.os);
2047
- const cpuList = normalizeList(info.packageJson.cpu);
2048
- return listAllowsTarget(osList, SANDBOX_PLATFORM) && listAllowsTarget(cpuList, SANDBOX_ARCH);
2049
- }
2050
- var INVALID_DETACHED_COMMAND_HANDLE_MESSAGE = "Detached process handle must contain a non-empty sessionId string and an optional commandId string.";
2051
- function normalizeDetachedCommandHandle(value) {
2052
- if (!value || typeof value !== "object") {
2053
- throw new ConfigurationError(INVALID_DETACHED_COMMAND_HANDLE_MESSAGE);
2054
- }
2055
- let sessionId;
2056
- let commandId;
2057
- try {
2058
- if (Array.isArray(value)) {
2059
- throw new Error("invalid detached command handle");
2060
- }
2061
- sessionId = Reflect.get(value, "sessionId");
2062
- commandId = Reflect.get(value, "commandId");
2063
- } catch {
2064
- throw new ConfigurationError(INVALID_DETACHED_COMMAND_HANDLE_MESSAGE);
2065
- }
2066
- if (typeof sessionId !== "string" || sessionId.length === 0 || commandId !== void 0 && typeof commandId !== "string") {
2067
- throw new ConfigurationError(INVALID_DETACHED_COMMAND_HANDLE_MESSAGE);
2068
- }
2069
- return commandId === void 0 ? { sessionId } : { sessionId, commandId };
2070
- }
2071
- function filterDefinedEnvs(envs) {
2072
- const filtered = {};
2073
- for (const [key, value] of Object.entries(envs)) {
2074
- if (value !== void 0) {
2075
- filtered[key] = value;
2076
- }
2077
- }
2078
- return filtered;
2079
- }
2080
- function asError(error) {
2081
- return error instanceof Error ? error : new Error(String(error));
2082
- }
2083
- function errorMessage(error) {
2084
- return error instanceof Error ? error.message : String(error);
2085
- }
2086
- var MINIMUM_BULK_DIAGNOSTIC_REDACTION_LENGTH = 8;
2087
- var CREDENTIAL_ENV_NAME_PATTERN = /(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)/iu;
2088
- function isConfiguredDiagnosticSecret(name, value) {
2089
- return CREDENTIAL_ENV_NAME_PATTERN.test(name) || value.length >= MINIMUM_BULK_DIAGNOSTIC_REDACTION_LENGTH;
2090
- }
2091
- function redactServerFailureDiagnosticStream(value, secrets) {
2092
- const mayStartAtTailBoundary = Buffer.byteLength(value, "utf8") >= DETACHED_PROCESS_LOG_MAX_BYTES - 3;
2093
- let redacted = boundDetachedProcessLog(value);
2094
- for (const secret of secrets) {
2095
- const replacement = secret.length < "[REDACTED]".length ? "*" : "[REDACTED]";
2096
- redacted = redacted.split(secret).join(replacement);
2097
- }
2098
- let maximumSecretLength = 0;
2099
- for (const secret of secrets) {
2100
- maximumSecretLength = Math.max(maximumSecretLength, secret.length);
2101
- }
2102
- if (mayStartAtTailBoundary && maximumSecretLength > 0 && redacted.length > 0) {
2103
- redacted = redacted.slice(maximumSecretLength);
2104
- }
2105
- return boundDetachedProcessLog(redacted);
2106
- }
2107
- async function readServerFailureDiagnostics(sandbox, command, environment, signal) {
2108
- if (!sandbox.readSessionLogs) return "";
2109
- try {
2110
- const captured = await awaitDiagnosticRead(
2111
- () => sandbox.readSessionLogs(command),
2112
- signal
2113
- );
2114
- const secrets = Object.entries(environment).filter(
2115
- (entry) => Boolean(entry[1]) && isConfiguredDiagnosticSecret(entry[0], entry[1])
2116
- ).map(([, value]) => value);
2117
- secrets.sort((left, right) => right.length - left.length);
2118
- const stdout = redactServerFailureDiagnosticStream(captured.stdout, secrets);
2119
- const stderr = redactServerFailureDiagnosticStream(captured.stderr, secrets);
2120
- const parts = [];
2121
- if (stdout.trim()) parts.push(`stdout:
2122
- ${stdout}`);
2123
- if (stderr.trim()) parts.push(`stderr:
2124
- ${stderr}`);
2125
- if (parts.length === 0) return "";
2126
- return boundDetachedProcessLog(`
2127
- --- server logs ---
2128
- ${parts.join("\n\n")}`);
2129
- } catch {
2130
- throwIfAborted(signal);
2131
- return "";
2132
- }
2133
- }
2134
- function providerApiKey(provider, explicitApiKey) {
2135
- if (explicitApiKey) return explicitApiKey;
2136
- return requireEnv(provider === "e2b" ? "E2B_API_KEY" : "DAYTONA_API_KEY");
2137
- }
2138
- async function createProviderSandboxHandle(options) {
2139
- if (options.provider === "modal") {
2140
- validateModalOptions(options, "create", (message) => new ConfigurationError(message));
2141
- return ModalSandboxHandle.create(options, (message) => new DeploymentError(message));
2142
- }
2143
- if (options.provider === "docker") {
2144
- validateDockerOptions(options, "create", (message) => new ConfigurationError(message));
2145
- return DockerSandboxHandle.create(options, (message) => new DeploymentError(message));
2146
- }
2147
- if (options.provider === "daytona") {
2148
- const apiKey2 = providerApiKey("daytona", options.apiKey);
2149
- const { Daytona } = await getDaytona();
2150
- const daytona = new Daytona({ apiKey: apiKey2 });
2151
- const sandbox2 = await daytona.create(
2152
- {
2153
- ...options.template ? { snapshot: options.template } : {},
2154
- ...options.networkBlockAll === void 0 ? {} : { networkBlockAll: options.networkBlockAll },
2155
- ...options.networkAllowList === void 0 ? {} : { networkAllowList: options.networkAllowList },
2156
- ...options.domainAllowList === void 0 ? {} : { domainAllowList: options.domainAllowList },
2157
- envVars: filterDefinedEnvs(options.envs ?? {}),
2158
- autoStopInterval: options.autoStopInterval,
2159
- autoDeleteInterval: options.autoDeleteInterval ?? -1
2160
- },
2161
- { timeout: options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC }
2162
- );
2163
- try {
2164
- return await DaytonaSandboxHandle.create(
2165
- sandbox2,
2166
- (message) => new DeploymentError(message)
2167
- );
2168
- } catch (error) {
2169
- await sandbox2.delete(
2170
- options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC,
2171
- true
2172
- ).catch(() => void 0);
2173
- throw error;
2174
- }
2175
- }
2176
- const apiKey = providerApiKey("e2b", options.apiKey);
2177
- const { Sandbox } = await getE2b();
2178
- const sandboxOptions = {
2179
- apiKey,
2180
- envs: filterDefinedEnvs(options.envs ?? {}),
2181
- timeoutMs: options.timeoutMs,
2182
- requestTimeoutMs: options.requestTimeoutMs,
2183
- network: options.allowPublicTraffic === void 0 ? void 0 : { allowPublicTraffic: options.allowPublicTraffic }
2184
- };
2185
- const sandbox = options.template ? await Sandbox.create(options.template, sandboxOptions) : await Sandbox.create(sandboxOptions);
2186
- return new E2bSandboxHandle(sandbox, (message) => new DeploymentError(message));
2187
- }
2188
- async function connectProviderSandboxHandle(options) {
2189
- if (options.provider === "modal") {
2190
- validateModalOptions(options, "connect", (message) => new ConfigurationError(message));
2191
- return ModalSandboxHandle.connect(options, (message) => new DeploymentError(message));
2192
- }
2193
- if (options.provider === "docker") {
2194
- validateDockerOptions(options, "connect", (message) => new ConfigurationError(message));
2195
- return DockerSandboxHandle.connect(options, (message) => new DeploymentError(message));
2196
- }
2197
- if (options.provider === "daytona") {
2198
- const apiKey2 = providerApiKey("daytona", options.apiKey);
2199
- const { Daytona } = await getDaytona();
2200
- const daytona = new Daytona({ apiKey: apiKey2 });
2201
- const sandbox2 = await daytona.get(options.sandboxId);
2202
- if (sandbox2.state !== "started") {
2203
- if (sandbox2.state === "starting" || sandbox2.state === "creating" || sandbox2.state === "restoring") {
2204
- await sandbox2.waitUntilStarted(options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC);
2205
- } else {
2206
- await sandbox2.start(options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC);
2207
- }
2208
- }
2209
- return DaytonaSandboxHandle.create(sandbox2, (message) => new DeploymentError(message));
2210
- }
2211
- const apiKey = providerApiKey("e2b", options.apiKey);
2212
- const { Sandbox } = await getE2b();
2213
- const sandbox = await Sandbox.connect(options.sandboxId, {
2214
- apiKey,
2215
- timeoutMs: options.timeoutMs,
2216
- requestTimeoutMs: options.requestTimeoutMs
2217
- });
2218
- return new E2bSandboxHandle(sandbox, (message) => new DeploymentError(message));
2219
- }
2220
- var SandboxClient = class _SandboxClient {
2221
- constructor(handle) {
2222
- this.handle = handle;
2223
- }
2224
- static async create(options) {
2225
- return new _SandboxClient(await createProviderSandboxHandle(options));
2226
- }
2227
- static async connect(options) {
2228
- return new _SandboxClient(await connectProviderSandboxHandle(options));
2229
- }
2230
- get id() {
2231
- return this.handle.id;
2232
- }
2233
- get provider() {
2234
- return this.handle.provider;
2235
- }
2236
- get paths() {
2237
- return {
2238
- provider: this.handle.paths.provider,
2239
- homeDir: this.handle.paths.homeDir,
2240
- workDir: this.handle.paths.workDir,
2241
- agentDir: this.handle.paths.agentDir,
2242
- ioDir: this.handle.paths.ioDir,
2243
- inputJson: this.handle.paths.inputJson,
2244
- outputJson: this.handle.paths.outputJson
2245
- };
2246
- }
2247
- async makeDir(path) {
2248
- await this.handle.makeDir(path);
2249
- }
2250
- async writeFile(path, content) {
2251
- await this.handle.writeFile(path, content);
2252
- }
2253
- async readFile(path) {
2254
- return this.handle.readFile(path);
2255
- }
2256
- async readFileBytes(path) {
2257
- return this.handle.readFileBytes(path);
2258
- }
2259
- async runCommand(command, options) {
2260
- return this.handle.runCommand(command, options);
2261
- }
2262
- async startDetachedCommand(command, options = {}) {
2263
- if (!this.handle.startDetachedCommand) {
2264
- throw new ConfigurationError(
2265
- `Sandbox provider "${this.provider}" does not support startDetachedCommand().`
2266
- );
2267
- }
2268
- if (typeof command !== "string") {
2269
- throw new ConfigurationError("Detached command must be a string.");
2270
- }
2271
- const normalized = normalizeProviderSandboxDetachedCommandOptions(
2272
- options,
2273
- (message) => new ConfigurationError(message),
2274
- { requireObject: true }
2275
- );
2276
- return this.handle.startDetachedCommand(command, normalized.options);
2277
- }
2278
- async readSessionLogs(commandOrSessionId, legacyCommandId) {
2279
- if (!this.handle.readSessionLogs) {
2280
- throw new ConfigurationError(
2281
- `Sandbox provider "${this.provider}" does not support readSessionLogs().`
2282
- );
2283
- }
2284
- if (typeof commandOrSessionId === "string" && legacyCommandId === void 0) {
2285
- throw new ConfigurationError(
2286
- "Legacy detached session log reads require a command ID."
2287
- );
2288
- }
2289
- const command = typeof commandOrSessionId === "string" ? { sessionId: commandOrSessionId, commandId: legacyCommandId } : normalizeDetachedCommandHandle(commandOrSessionId);
2290
- return this.handle.readSessionLogs(command);
2291
- }
2292
- async stopSession(commandOrSessionId) {
2293
- if (!this.handle.stopSession) {
2294
- throw new ConfigurationError(
2295
- `Sandbox provider "${this.provider}" does not support stopSession().`
2296
- );
2297
- }
2298
- const command = typeof commandOrSessionId === "string" ? { sessionId: commandOrSessionId } : normalizeDetachedCommandHandle(commandOrSessionId);
2299
- await this.handle.stopSession(command);
2300
- }
2301
- /**
2302
- * Irreversibly removes private lifecycle state and captured diagnostics for
2303
- * one managed detached command. Call `stopSession()` first, then perform any
2304
- * final `readSessionLogs()` before disposal. Disposal is idempotent after a
2305
- * confirmed stop but is not itself evidence that the process stopped.
2306
- */
2307
- async disposeSessionArtifacts(command) {
2308
- if (!this.handle.disposeSessionArtifacts) {
2309
- throw new ConfigurationError(
2310
- `Sandbox provider "${this.provider}" does not support disposeSessionArtifacts().`
2311
- );
2312
- }
2313
- await this.handle.disposeSessionArtifacts(
2314
- normalizeDetachedCommandHandle(command)
2315
- );
2316
- }
2317
- async setTimeout(timeoutMs) {
2318
- if (!this.handle.setTimeout) {
2319
- throw new ConfigurationError(`Sandbox provider "${this.provider}" does not support setTimeout().`);
2320
- }
2321
- await this.handle.setTimeout(timeoutMs);
2322
- }
2323
- async kill() {
2324
- await this.handle.destroy();
2325
- }
2326
- async destroy() {
2327
- await this.kill();
2328
- }
2329
- };
2330
- function normalizeStackFramePath(rawPath, cwd = process.cwd()) {
2331
- if (rawPath.startsWith("file://")) {
2332
- return fileURLToPath(rawPath);
2333
- }
2334
- if (rawPath.startsWith("webpack-internal:")) {
2335
- const afterScheme = rawPath.replace(/^webpack-internal:\/+/, "");
2336
- const afterLayer = afterScheme.replace(/^\([^)]+\)\//, "");
2337
- const resolved = resolve(cwd, afterLayer);
2338
- return existsSync(resolved) ? resolved : null;
2339
- }
2340
- return rawPath;
2341
- }
2342
- function getCallerFile() {
2343
- const stack = new Error().stack?.split("\n") ?? [];
2344
- let moduleFile;
2345
- let bundledFallback;
2346
- for (const line of stack.slice(1)) {
2347
- const match = line.match(/\((.+?):\d+:\d+\)/) || line.match(/at (.+?):\d+:\d+/);
2348
- if (!match) continue;
2349
- const file = normalizeStackFramePath(match[1]);
2350
- if (!file) continue;
2351
- if (!moduleFile) {
2352
- moduleFile = file;
2353
- continue;
2354
- }
2355
- if (file.includes("node:")) continue;
2356
- if (file.includes("node_modules/agent-neckbeard")) continue;
2357
- if (file === moduleFile) {
2358
- bundledFallback ??= file;
2359
- continue;
2360
- }
2361
- return file;
2362
- }
2363
- if (bundledFallback) return bundledFallback;
2364
- throw new Error("Could not determine source file");
2365
- }
2366
- function isFrameworkBuildOutputPath(file) {
2367
- const normalized = file.replace(/\\/g, "/");
2368
- return normalized.includes("/.next/server/chunks/") || normalized.includes("/.next/server/app/") || normalized.includes("/.next/server/pages/");
2369
- }
2370
- function frameworkBuildOutputError(file) {
2371
- return new ConfigurationError(
2372
- `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.`
2373
- );
2374
- }
2375
- function resolveSourceFile(sourceFile) {
2376
- if (!sourceFile) {
2377
- const inferred = getCallerFile();
2378
- if (isFrameworkBuildOutputPath(inferred)) {
2379
- throw frameworkBuildOutputError(inferred);
2380
- }
2381
- return inferred;
2382
- }
2383
- const normalized = normalizeStackFramePath(sourceFile);
2384
- if (!normalized) {
2385
- throw new ConfigurationError(`sourceFile could not be resolved: ${sourceFile}`);
2386
- }
2387
- const resolved = resolve(normalized);
2388
- if (isFrameworkBuildOutputPath(resolved)) {
2389
- throw frameworkBuildOutputError(resolved);
2390
- }
2391
- if (!existsSync(resolved)) {
2392
- throw new ConfigurationError(`sourceFile does not exist: ${resolved}`);
2393
- }
2394
- return resolved;
2395
- }
2396
- function localPathStats(localPath, upload, isSourceRoot = false) {
2397
- let stats;
2398
- try {
2399
- stats = lstatSync(localPath);
2400
- } catch (error) {
2401
- const code = error.code;
2402
- const detail = isSourceRoot && code === "ENOENT" ? "source does not exist" : "could not read local path";
2403
- throw new ConfigurationError(
2404
- `${upload.name} ${detail}: ${localPath} (${errorMessage(error)})`
2405
- );
2406
- }
2407
- if (!stats.isSymbolicLink()) return stats;
2408
- if (upload.rejectSymlinks) {
2409
- throw new ConfigurationError(
2410
- `${upload.name} source tree contains a symbolic link: ${localPath}`
2411
- );
2412
- }
2413
- try {
2414
- return statSync(localPath);
2415
- } catch (error) {
2416
- throw new ConfigurationError(
2417
- `${upload.name} could not follow legacy symbolic link: ${localPath} (${errorMessage(error)})`
2418
- );
2419
- }
2420
- }
2421
- function readConfiguredLocalDirectory(upload) {
2422
- const rootPath = resolve(process.cwd(), upload.source);
2423
- const rootStats = localPathStats(rootPath, upload, true);
2424
- if (!rootStats.isDirectory()) {
2425
- throw new ConfigurationError(`${upload.name}.source must be a directory: ${rootPath}`);
2426
- }
2427
- const destination = normalizeLocalDirectoryDestination(upload.destination, upload.name);
2428
- const files = [];
2429
- function walk(currentPath) {
2430
- let entries;
2431
- try {
2432
- entries = readdirSync(currentPath).sort((left, right) => left.localeCompare(right));
2433
- } catch (error) {
2434
- throw new ConfigurationError(
2435
- `${upload.name} could not read local directory: ${currentPath} (${errorMessage(error)})`
2436
- );
2437
- }
2438
- for (const entry of entries) {
2439
- const localPath = join(currentPath, entry);
2440
- const stats = localPathStats(localPath, upload);
2441
- if (stats.isDirectory()) {
2442
- walk(localPath);
2443
- continue;
2444
- }
2445
- if (!stats.isFile()) {
2446
- throw new ConfigurationError(
2447
- `${upload.name} source tree contains an unsupported filesystem entry: ${localPath}`
2448
- );
2449
- }
2450
- const relativePath = relative(rootPath, localPath).split(sep).join("/");
2451
- const targetPath = posix.join(destination, relativePath);
2452
- let content;
2453
- try {
2454
- content = readFileSync(localPath);
2455
- } catch (error) {
2456
- throw new ConfigurationError(
2457
- `${upload.name} could not read local file: ${localPath} (${errorMessage(error)})`
2458
- );
2459
- }
2460
- files.push({ localPath, targetPath, content });
2461
- }
2462
- }
2463
- walk(rootPath);
2464
- return { rootPath, files };
2465
- }
2466
- function prepareLocalDirectoryUploads(localDirectories, claudeDir) {
2467
- const uploads = localDirectories.map((entry, index) => ({
2468
- ...entry,
2469
- name: `localDirectories[${index}]`,
2470
- rejectSymlinks: true,
2471
- preserveRootDirectory: false
2472
- }));
2473
- if (claudeDir) {
2474
- uploads.push({
2475
- source: claudeDir,
2476
- destination: ".claude",
2477
- name: "claudeDir",
2478
- rejectSymlinks: false,
2479
- preserveRootDirectory: true
2480
- });
2481
- }
2482
- const filesByTarget = /* @__PURE__ */ new Map();
2483
- const requiredDirectories = /* @__PURE__ */ new Set();
2484
- for (const upload of uploads) {
2485
- const prepared = readConfiguredLocalDirectory(upload);
2486
- const destination = normalizeLocalDirectoryDestination(upload.destination, upload.name);
2487
- if (upload.preserveRootDirectory) {
2488
- requiredDirectories.add(destination);
2489
- }
2490
- for (const file of prepared.files) {
2491
- const existing = filesByTarget.get(file.targetPath);
2492
- if (existing) {
2493
- throw new ConfigurationError(
2494
- `Duplicate sandbox target "${file.targetPath}" from local files "${existing.localPath}" and "${file.localPath}".`
2495
- );
2496
- }
2497
- filesByTarget.set(file.targetPath, file);
2498
- }
2499
- }
2500
- for (const file of filesByTarget.values()) {
2501
- let parent = posix.dirname(file.targetPath);
2502
- while (parent !== ".") {
2503
- const parentFile = filesByTarget.get(parent);
2504
- if (parentFile) {
2505
- throw new ConfigurationError(
2506
- `Sandbox target collision: local file "${parentFile.localPath}" maps to "${parent}", which must be a directory for "${file.localPath}".`
2507
- );
2508
- }
2509
- requiredDirectories.add(parent);
2510
- parent = posix.dirname(parent);
2511
- }
2512
- }
2513
- const directories = [...requiredDirectories].sort((left, right) => {
2514
- const depthDifference = left.split("/").length - right.split("/").length;
2515
- return depthDifference || left.localeCompare(right);
2516
- });
2517
- const files = [...filesByTarget.values()].sort(
2518
- (left, right) => left.targetPath.localeCompare(right.targetPath)
2519
- );
2520
- return { directories, files };
2521
- }
2522
- var Agent = class {
2523
- sandbox;
2524
- provider;
2525
- template;
2526
- inputSchema;
2527
- /** Only populated for structured-task agents; undefined for session agents. */
2528
- outputSchema;
2529
- /** Only populated for attached-session agents; undefined for run-output agents. */
2530
- frameSchema;
2531
- /** User-facing execution shape. */
2532
- kind;
2533
- /** @deprecated Use `kind`; retained for compatibility with `run | stream` checks. */
2534
- mode;
2535
- maxDuration;
2536
- dependencies;
2537
- files;
2538
- localDirectories;
2539
- /** @deprecated Use `localDirectories` with destination `.claude` instead. */
2540
- claudeDir;
2541
- envs;
2542
- build;
2543
- /** @internal Used by the in-sandbox server for run-output agents. */
2544
- _run;
2545
- /** @internal Used by the in-sandbox server for attached-session agents. */
2546
- _server;
2547
- /** @internal Runtime state populated by deploy(). */
2548
- _serverRuntime;
2549
- _sandboxId;
2550
- _sourceFile;
2551
- constructor(config) {
2552
- validateAgentConfig(config);
2553
- this.sandbox = config.sandbox;
2554
- this.provider = config.sandbox.provider;
2555
- this.template = config.sandbox.template ?? (config.sandbox.provider === "docker" ? DOCKER_DEFAULT_TEMPLATE : MODAL_DEFAULT_TEMPLATE);
2556
- this.inputSchema = config.inputSchema;
2557
- this.maxDuration = config.maxDuration ?? DEFAULT_MAX_DURATION;
2558
- this._sourceFile = resolveSourceFile(config.sourceFile);
2559
- this.dependencies = config.dependencies ?? DEFAULT_DEPENDENCIES;
2560
- this.files = config.files ?? [];
2561
- this.localDirectories = (config.localDirectories ?? []).map((entry) => ({ ...entry }));
2562
- this.claudeDir = config.claudeDir;
2563
- this.envs = config.envs ?? {};
2564
- this.build = config.build ?? {};
2565
- if (isSessionAgentConfig(config)) {
2566
- const session = getSessionHandler(config);
2567
- this.kind = "session";
2568
- this.mode = "stream";
2569
- this._server = session;
2570
- this.frameSchema = session.frameSchema;
2571
- } else {
2572
- this.kind = "task";
2573
- this.mode = "run";
2574
- this._run = config.run;
2575
- this.outputSchema = config.outputSchema;
2576
- }
2577
- }
2578
- get sandboxId() {
2579
- return this._serverRuntime?.connection.sandboxId ?? this._sandboxId;
2580
- }
2581
- get sandboxEnv() {
2582
- return {
2583
- ...filterDefinedEnvs(this.envs),
2584
- [NECKBEARD_SANDBOX_RUNTIME_ENV]: "1"
2585
- };
2586
- }
2587
- async createSandboxHandle() {
2588
- if (this.sandbox.provider === "modal" || this.sandbox.provider === "docker") {
2589
- return createProviderSandboxHandle({ ...this.sandbox, envs: this.sandboxEnv });
2590
- }
2591
- if (this.provider === "e2b") {
2592
- return createProviderSandboxHandle({
2593
- provider: "e2b",
2594
- template: this.template,
2595
- envs: this.sandboxEnv,
2596
- allowPublicTraffic: false
2597
- });
2598
- }
2599
- const sandbox = this.sandbox;
2600
- return createProviderSandboxHandle({
2601
- provider: "daytona",
2602
- template: this.template,
2603
- envs: this.sandboxEnv,
2604
- networkBlockAll: sandbox.networkBlockAll,
2605
- networkAllowList: sandbox.networkAllowList,
2606
- domainAllowList: sandbox.domainAllowList,
2607
- autoStopInterval: sandbox.autoStopInterval,
2608
- autoDeleteInterval: sandbox.autoDeleteInterval
2609
- });
2610
- }
2611
- async connectSandboxHandle(sandboxId) {
2612
- if (this.sandbox.provider === "modal") {
2613
- return connectProviderSandboxHandle({
2614
- provider: "modal",
2615
- sandboxId,
2616
- environment: this.sandbox.environment
2617
- });
2618
- }
2619
- if (this.sandbox.provider === "docker") {
2620
- return connectProviderSandboxHandle({ provider: "docker", sandboxId });
2621
- }
2622
- if (this.provider === "e2b") {
2623
- return connectProviderSandboxHandle({
2624
- provider: "e2b",
2625
- sandboxId
2626
- });
2627
- }
2628
- return connectProviderSandboxHandle({
2629
- provider: "daytona",
2630
- sandboxId
2631
- });
2632
- }
2633
- async readRuntimeServerConfig(sandbox) {
2634
- try {
2635
- return JSON.parse(await sandbox.readFile(sandbox.paths.serverConfig));
2636
- } catch {
2637
- return void 0;
2638
- }
2639
- }
2640
- async createRuntimeConnection(sandbox, port) {
2641
- if (!sandbox.getServerEndpoint) {
2642
- throw new DeploymentError(
2643
- "Persistent agents require a sandbox provider that supports public port endpoints."
2644
- );
2645
- }
2646
- const endpoint = await sandbox.getServerEndpoint(port);
2647
- const baseServerUrl = endpoint.url.replace(/\/$/, "");
2648
- return {
2649
- provider: this.provider,
2650
- sandboxId: sandbox.id,
2651
- serverUrl: `${baseServerUrl}/invoke`,
2652
- trafficToken: endpoint.trafficToken
2653
- };
2654
- }
2655
- healthUrlFor(connection) {
2656
- const url = new URL(connection.serverUrl);
2657
- url.pathname = url.pathname.replace(/\/invoke$/, "/health");
2658
- url.search = "";
2659
- return url.toString();
2660
- }
2661
- async startRuntimeServer(sandbox) {
2662
- if (!sandbox.startDetachedCommand) {
2663
- throw new DeploymentError(
2664
- "Persistent agents require a sandbox provider that supports background commands."
2665
- );
2666
- }
2667
- return sandbox.startDetachedCommand("node server.mjs", {
2668
- cwd: sandbox.paths.agentDir,
2669
- envs: this.sandboxEnv
2670
- });
2671
- }
2672
- async resolveRuntimeConnection(sandboxId, options = {}) {
2673
- const { signal } = options;
2674
- throwIfAborted(signal);
2675
- const targetId = sandboxId ?? this._serverRuntime?.connection.sandboxId ?? this._sandboxId;
2676
- if (!targetId) {
2677
- throw new ConfigurationError("Agent not deployed. Call agent.deploy() first or pass sandboxId.");
2678
- }
2679
- if ((!sandboxId || options.reuseMatchingCachedConnection) && this._serverRuntime?.connection.sandboxId === targetId) {
2680
- return this._serverRuntime.connection;
2681
- }
2682
- const sandbox = await awaitWithAbort(() => this.connectSandboxHandle(targetId), signal);
2683
- if (sandbox.id !== targetId) {
2684
- throw new DeploymentError("Sandbox provider returned an unexpected runtime identity.");
2685
- }
2686
- const serverConfig = await awaitWithAbort(
2687
- () => this.readRuntimeServerConfig(sandbox),
2688
- signal
2689
- );
2690
- const port = serverConfig?.port ?? this._server?.port ?? DEFAULT_SERVER_PORT;
2691
- const connection = await awaitWithAbort(
2692
- () => this.createRuntimeConnection(sandbox, port),
2693
- signal
2694
- );
2695
- const healthUrl = this.healthUrlFor(connection);
2696
- try {
2697
- await waitForServerHealthy(
2698
- healthUrl,
2699
- connection,
2700
- SERVER_RECONNECT_HEALTH_TIMEOUT_MS,
2701
- signal
2702
- );
2703
- throwIfAborted(signal);
2704
- const cachedRuntime = this._serverRuntime;
2705
- this._serverRuntime = cachedRuntime?.connection.sandboxId === targetId ? { ...cachedRuntime, connection } : { connection };
2706
- this._sandboxId = targetId;
2707
- return connection;
2708
- } catch {
2709
- throwIfAborted(signal);
2710
- const detachedCommand = await awaitWithAbort(
2711
- () => this.startRuntimeServer(sandbox),
2712
- signal
2713
- );
2714
- try {
2715
- await waitForServerHealthy(
2716
- healthUrl,
2717
- connection,
2718
- SERVER_HEALTH_TIMEOUT_MS,
2719
- signal
2720
- );
2721
- } catch (error) {
2722
- throwIfAborted(signal);
2723
- const baseMessage = error instanceof Error ? error.message : String(error);
2724
- const logs = await readServerFailureDiagnostics(
2725
- sandbox,
2726
- detachedCommand,
2727
- this.envs,
2728
- signal
2729
- );
2730
- throw new DeploymentError(`${baseMessage}${logs}`);
2731
- }
2732
- throwIfAborted(signal);
2733
- this._serverRuntime = { detachedCommand, connection };
2734
- this._sandboxId = targetId;
2735
- return connection;
2736
- }
2737
- }
2738
- /**
2739
- * Kills the current sandbox and resets the cached runtime.
2740
- *
2741
- * Use this to clean up sandbox resources after a run, especially when
2742
- * running multiple evaluations that each need their own sandbox.
2743
- *
2744
- * @param target - Optional sandbox ID to kill. Defaults to the cached sandbox.
2745
- *
2746
- * @example
2747
- * ```typescript
2748
- * const sandboxId = await agent.deploy();
2749
- * const result = await agent.run(input, { sandboxId });
2750
- * await agent.kill(sandboxId);
2751
- * ```
2752
- */
2753
- async kill(target) {
2754
- const targetId = target ?? this._serverRuntime?.connection.sandboxId ?? this._sandboxId;
2755
- if (!targetId) return;
2756
- try {
2757
- const sandbox = await this.connectSandboxHandle(targetId);
2758
- if (this._serverRuntime && this._serverRuntime.connection.sandboxId === targetId && this._serverRuntime.detachedCommand && sandbox.stopSession) {
2759
- await sandbox.stopSession(this._serverRuntime.detachedCommand).catch(() => void 0);
2760
- }
2761
- await sandbox.destroy();
2762
- } catch {
2763
- }
2764
- if (targetId === this._sandboxId) {
2765
- this._sandboxId = void 0;
2766
- }
2767
- if (targetId === this._serverRuntime?.connection.sandboxId) {
2768
- this._serverRuntime = void 0;
2769
- }
2770
- }
2771
- /**
2772
- * Deploys the agent to a sandbox provider.
2773
- *
2774
- * This method bundles the agent code using esbuild, creates a new sandbox,
2775
- * installs any specified OS dependencies, downloads configured files, and
2776
- * uploads the agent and runtime server code, then starts a long-running HTTP
2777
- * server inside the sandbox.
2778
- *
2779
- * @param options.fresh - When true, always creates a new sandbox without caching.
2780
- * Useful for concurrent evaluations where each run needs its own sandbox.
2781
- * The returned sandbox ID won't be stored on the instance.
2782
- * @returns The sandbox ID. Persist this ID when another host process should reuse the sandbox.
2783
- * @throws {ConfigurationError} If the selected provider credentials are not set
2784
- * @throws {DeploymentError} If sandbox creation, dependency installation, or file upload fails
2785
- *
2786
- * @example
2787
- * ```typescript
2788
- * const agent = new Agent({ ... });
2789
- * const sandboxId = await agent.deploy();
2790
- * console.log(`Deployed to sandbox: ${sandboxId}`);
2791
- *
2792
- * // For concurrent evals: each call gets its own sandbox
2793
- * const sandboxId = await agent.deploy({ fresh: true });
2794
- * const result = await agent.run(input, { sandboxId });
2795
- * await agent.kill(sandboxId);
2796
- * ```
2797
- */
2798
- async deploy(options) {
2799
- return this._deploy(options);
2800
- }
2801
- async _deploy(options) {
2802
- if (!options?.fresh && this._serverRuntime) return this._serverRuntime.connection.sandboxId;
2803
- const localDirectoryUploads = prepareLocalDirectoryUploads(
2804
- this.localDirectories,
2805
- this.claudeDir
2806
- );
2807
- const esbuild = await getEsbuild();
2808
- const externalPatterns = Array.from(
2809
- /* @__PURE__ */ new Set([...DEFAULT_EXTERNALS, ...this.build.external ?? []])
2810
- );
2811
- const externalMatchers = externalPatterns.map(globToRegExp);
2812
- const autoDetectExternal = this.build.autoDetectExternal ?? true;
2813
- const collectedExternals = /* @__PURE__ */ new Map();
2814
- const result = await esbuild.build({
2815
- entryPoints: [this._sourceFile],
2816
- bundle: true,
2817
- platform: "node",
2818
- target: NODE_TARGET,
2819
- format: "esm",
2820
- write: false,
2821
- minify: true,
2822
- keepNames: true,
2823
- treeShaking: false,
2824
- // Preserve exports for the runtime server to import
2825
- banner: {
2826
- js: `import { fileURLToPath as __neckbeard_fileURLToPath } from 'node:url';
2827
- import { dirname as __neckbeard_dirname } from 'node:path';
2828
- import { createRequire as __neckbeard_createRequire } from 'node:module';
2829
- var __filename = __neckbeard_fileURLToPath(import.meta.url);
2830
- var __dirname = __neckbeard_dirname(__filename);
2831
- var require = __neckbeard_createRequire(import.meta.url);
2832
- `
2833
- },
2834
- plugins: [{
2835
- name: "agent-neckbeard-externals",
2836
- setup(build) {
2837
- build.onResolve({ filter: /^agent-neckbeard$/ }, () => ({
2838
- path: "agent-neckbeard",
2839
- namespace: "agent-shim"
2840
- }));
2841
- build.onLoad({ filter: /.*/, namespace: "agent-shim" }, () => ({
2842
- contents: `
2843
- export class Agent {
2844
- constructor(config) {
2845
- this.inputSchema = config.inputSchema;
2846
- this.outputSchema = config.outputSchema;
2847
- this.maxDuration = config.maxDuration ?? 300;
2848
- this._run = config.run;
2849
- const session = config.session ?? config.server;
2850
- if (session) {
2851
- this.kind = 'session';
2852
- this.mode = 'stream';
2853
- this._server = session;
2854
- this.frameSchema = session.frameSchema;
2855
- } else {
2856
- this.kind = 'task';
2857
- this.mode = 'run';
2858
- }
2859
- }
2860
- }
2861
- export function resolveAgentSourceFile(_candidates, options = {}) {
2862
- return options.sandboxSourceFile ?? process.cwd() + '/agent.mjs';
2863
- }
2864
- `,
2865
- loader: "js"
2866
- }));
2867
- build.onResolve({ filter: /^[^.\/]|^\.[^.\/]|^\.\.[^\/]/ }, async (args) => {
2868
- if (args.path.startsWith("node:")) return null;
2869
- if (builtinModules.includes(args.path.replace("node:", ""))) return null;
2870
- if (!isBareModuleImport(args.path)) return null;
2871
- const pkgName = packageNameForImportPath(args.path);
2872
- if (externalMatchers.length && matchesExternal(externalMatchers, pkgName)) {
2873
- const info2 = await resolvePackageInfo(args.path, args.resolveDir);
2874
- if (!info2) return null;
2875
- collectedExternals.set(info2.name, info2);
2876
- return { external: true };
2877
- }
2878
- if (!autoDetectExternal) return null;
2879
- const info = await resolvePackageInfo(args.path, args.resolveDir);
2880
- if (!info) return null;
2881
- if (!shouldAutoExternalize(info)) return null;
2882
- collectedExternals.set(info.name, info);
2883
- return { external: true };
2884
- });
2885
- }
2886
- }]
2887
- });
2888
- const sandbox = await this.createSandboxHandle();
2889
- let deploymentCompleted = false;
2890
- let detachedCommand;
2891
- try {
2892
- const { paths } = sandbox;
2893
- await sandbox.runCommand(`mkdir -p ${shellQuote(paths.agentDir)}`, {
2894
- timeoutMs: QUICK_COMMAND_TIMEOUT_MS2
2895
- });
2896
- const { apt, commands } = this.dependencies;
2897
- if (apt && apt.length > 0) {
2898
- const aptCmd = `sudo apt-get update && sudo apt-get install -y ${apt.join(" ")}`;
2899
- const aptResult = await sandbox.runCommand(aptCmd, {
2900
- timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS2
2901
- });
2902
- if (aptResult.exitCode !== 0) {
2903
- const details = [
2904
- `Failed to install apt packages: ${apt.join(", ")}`,
2905
- aptResult.stderr ? `stderr: ${aptResult.stderr}` : "",
2906
- aptResult.stdout ? `stdout: ${aptResult.stdout}` : ""
2907
- ].filter(Boolean).join("\n");
2908
- throw new DeploymentError(details);
2909
- }
2910
- }
2911
- if (commands && commands.length > 0) {
2912
- for (const cmd of commands) {
2913
- const cmdResult = await sandbox.runCommand(cmd, {
2914
- timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS2
2915
- });
2916
- if (cmdResult.exitCode !== 0) {
2917
- const details = [
2918
- `Failed to run command: ${cmd}`,
2919
- cmdResult.stderr ? `stderr: ${cmdResult.stderr}` : "",
2920
- cmdResult.stdout ? `stdout: ${cmdResult.stdout}` : ""
2921
- ].filter(Boolean).join("\n");
2922
- throw new DeploymentError(details);
2923
- }
2924
- }
2925
- }
2926
- if (this.files.length > 0) {
2927
- for (const file of this.files) {
2928
- const destPath = file.path.startsWith("/") ? file.path : `${paths.homeDir}/${file.path}`;
2929
- const parentDir = destPath.substring(0, destPath.lastIndexOf("/"));
2930
- if (parentDir) {
2931
- await sandbox.runCommand(`mkdir -p ${shellQuote(parentDir)}`, {
2932
- timeoutMs: QUICK_COMMAND_TIMEOUT_MS2
2933
- });
2934
- }
2935
- const curlCmd = `curl -fsSL -o ${shellQuote(destPath)} ${shellQuote(file.url)}`;
2936
- const downloadResult = await sandbox.runCommand(curlCmd, {
2937
- timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS2
2938
- });
2939
- if (downloadResult.exitCode !== 0) {
2940
- const details = [
2941
- `Failed to download file from ${file.url} to ${destPath}`,
2942
- downloadResult.stderr ? `stderr: ${downloadResult.stderr}` : "",
2943
- downloadResult.stdout ? `stdout: ${downloadResult.stdout}` : ""
2944
- ].filter(Boolean).join("\n");
2945
- throw new DeploymentError(details);
2946
- }
2947
- }
2948
- }
2949
- for (const directory of localDirectoryUploads.directories) {
2950
- await sandbox.makeDir(posix.join(paths.agentDir, directory));
2951
- }
2952
- for (const file of localDirectoryUploads.files) {
2953
- await sandbox.writeFile(
2954
- posix.join(paths.agentDir, file.targetPath),
2955
- file.content
2956
- );
2957
- }
2958
- await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
2959
- await sandbox.writeFile(paths.serverModule, RUNTIME_SERVER_SOURCE);
2960
- const serverConfig = {
2961
- protocolVersion: RUNTIME_PROTOCOL_VERSION,
2962
- port: this._server?.port ?? DEFAULT_SERVER_PORT,
2963
- maxDurationMs: this.maxDuration * 1e3,
2964
- sandboxContext: {
2965
- provider: paths.provider,
2966
- homeDir: paths.homeDir,
2967
- workDir: paths.workDir,
2968
- agentDir: paths.agentDir,
2969
- ioDir: paths.ioDir,
2970
- inputJson: paths.inputJson,
2971
- outputJson: paths.outputJson
2972
- }
2973
- };
2974
- await sandbox.writeFile(paths.serverConfig, JSON.stringify(serverConfig));
2975
- if (collectedExternals.size > 0) {
2976
- const installable = Array.from(collectedExternals.values()).filter(isPackageCompatible);
2977
- const dependencies = Object.fromEntries(installable.map((info) => [info.name, info.version]));
2978
- if (Object.keys(dependencies).length > 0) {
2979
- const pkgJson = JSON.stringify({
2980
- name: "agent-sandbox",
2981
- type: "module",
2982
- dependencies
2983
- });
2984
- await sandbox.writeFile(paths.packageJson, pkgJson);
2985
- const installResult = await sandbox.runCommand("npm install --legacy-peer-deps", {
2986
- cwd: paths.agentDir,
2987
- timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS2
2988
- });
2989
- if (installResult.exitCode !== 0) {
2990
- const details = [
2991
- `Failed to install npm packages: ${Object.keys(dependencies).join(", ")}`,
2992
- installResult.stderr ? `stderr: ${installResult.stderr}` : "",
2993
- installResult.stdout ? `stdout: ${installResult.stdout}` : ""
2994
- ].filter(Boolean).join("\n");
2995
- throw new DeploymentError(details);
2996
- }
2997
- }
2998
- }
2999
- const port = serverConfig.port;
3000
- detachedCommand = await this.startRuntimeServer(sandbox);
3001
- const connection = await this.createRuntimeConnection(sandbox, port);
3002
- const healthUrl = this.healthUrlFor(connection);
3003
- try {
3004
- await waitForServerHealthy(healthUrl, connection);
3005
- } catch (err) {
3006
- const baseMessage = err instanceof Error ? err.message : String(err);
3007
- const logs = await readServerFailureDiagnostics(
3008
- sandbox,
3009
- detachedCommand,
3010
- this.envs
3011
- );
3012
- throw new DeploymentError(`${baseMessage}${logs}`);
3013
- }
3014
- if (!options?.fresh) {
3015
- this._sandboxId = sandbox.id;
3016
- this._serverRuntime = { detachedCommand, connection };
3017
- }
3018
- deploymentCompleted = true;
3019
- return sandbox.id;
3020
- } finally {
3021
- if (!deploymentCompleted) {
3022
- if (detachedCommand && sandbox.stopSession) {
3023
- await sandbox.stopSession(detachedCommand).catch(() => void 0);
3024
- }
3025
- await sandbox.destroy().catch(() => void 0);
3026
- }
3027
- }
3028
- }
3029
- /**
3030
- * Executes the agent with the given input.
3031
- *
3032
- * The agent must be deployed before calling this method, or a sandbox ID
3033
- * must be provided in the options. Input is validated against the input
3034
- * schema, then POSTed to the in-sandbox server. Output is validated against
3035
- * the output schema before being returned.
3036
- *
3037
- * @param input - The input data for the agent, must conform to inputSchema
3038
- * @param options - Optional configuration for this run
3039
- * @param options.sandboxId - Sandbox ID to use, overrides the cached sandbox
3040
- * @returns A result object indicating success or failure with output or error
3041
- *
3042
- * @example
3043
- * ```typescript
3044
- * // Using deployed sandbox
3045
- * const result = await agent.run({ prompt: 'Hello, world!' });
3046
- *
3047
- * // Reconnecting from another process
3048
- * const result = await agent.run({ prompt: 'Hello!' }, { sandboxId });
3049
- * ```
3050
- */
3051
- async run(input, options) {
3052
- const executionId = `exec_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
3053
- if (this.mode !== "run") {
3054
- return {
3055
- ok: false,
3056
- executionId,
3057
- error: new ExecutionError(
3058
- "run() is only available on agents configured with a run handler. Use agent.createSession() for streaming session agents."
3059
- )
3060
- };
3061
- }
3062
- try {
3063
- const connection = await this.resolveRuntimeConnection(options?.sandboxId);
3064
- let validatedInput;
3065
- try {
3066
- validatedInput = this.inputSchema.parse(input);
3067
- } catch (error) {
3068
- throw new ValidationError("Input validation failed.", asError(error));
3069
- }
3070
- const { invokeServer } = await import("./invoke-client-YKWOTQWG.js");
3071
- let output;
3072
- let sawOutput = false;
3073
- for await (const event of invokeServer(validatedInput, {
3074
- serverUrl: connection.serverUrl,
3075
- provider: connection.provider,
3076
- trafficToken: getTrafficToken(connection),
3077
- invocationId: executionId,
3078
- signal: AbortSignal.timeout(this.maxDuration * 1e3 + RUNTIME_ABORT_GRACE_MS + 5e3)
3079
- })) {
3080
- if (event.kind === "error") {
3081
- const err = new ExecutionError(event.error.message);
3082
- err.stack = event.error.stack;
3083
- return { ok: false, executionId, error: err };
3084
- }
3085
- if (event.kind === "output") {
3086
- output = event.output;
3087
- sawOutput = true;
3088
- }
3089
- }
3090
- if (!sawOutput) {
3091
- return {
3092
- ok: false,
3093
- executionId,
3094
- error: new ExecutionError("Agent server completed without returning output.")
3095
- };
3096
- }
3097
- let validated;
3098
- try {
3099
- validated = this.outputSchema ? this.outputSchema.parse(output) : output;
3100
- } catch (error) {
3101
- throw new ValidationError("Output validation failed.", asError(error));
3102
- }
3103
- return { ok: true, executionId, output: validated };
3104
- } catch (err) {
3105
- const { InvokeHttpError } = await import("./invoke-client-YKWOTQWG.js");
3106
- if (err instanceof InvokeHttpError && err.status === 409) {
3107
- return { ok: false, executionId, error: new RuntimeBusyError(err.message) };
3108
- }
3109
- return { ok: false, executionId, error: err instanceof Error ? err : new Error(String(err)) };
3110
- }
3111
- }
3112
- /**
3113
- * Creates a caller-owned session against the persistent sandbox runtime.
3114
- * The returned handle supports sequential prompts, active-turn cancellation,
3115
- * and explicit close without destroying the reusable sandbox.
3116
- */
3117
- async createSession(options = {}) {
3118
- if (this.mode !== "stream") {
3119
- throw new ConfigurationError(
3120
- "createSession() is only available on agents configured with session.handler (or deprecated server.handler). Use agent.run() for run-output agents."
3121
- );
3122
- }
3123
- if (!options || typeof options !== "object") {
3124
- throw new ConfigurationError("Agent.createSession() options must be an object.");
3125
- }
3126
- let optionsAreArray;
3127
- try {
3128
- optionsAreArray = Array.isArray(options);
3129
- } catch {
3130
- throw new ConfigurationError(
3131
- "Agent.createSession() options must have readable values."
3132
- );
3133
- }
3134
- if (optionsAreArray) {
3135
- throw new ConfigurationError("Agent.createSession() options must be an object.");
3136
- }
3137
- let durability;
3138
- let requestedSandboxId;
3139
- let signal;
3140
- try {
3141
- durability = options.durability;
3142
- requestedSandboxId = options.sandboxId;
3143
- signal = options.signal;
3144
- } catch {
3145
- throw new ConfigurationError(
3146
- "Agent.createSession() options must have readable values."
3147
- );
3148
- }
3149
- if (durability !== void 0 && durability !== "attached") {
3150
- throw new ConfigurationError(
3151
- "Agent.createSession() creates caller-owned attached sessions. Gateway-owned durable sessions use the deprecated agent-neckbeard/supervisor APIs."
3152
- );
3153
- }
3154
- if (requestedSandboxId !== void 0 && (typeof requestedSandboxId !== "string" || requestedSandboxId.trim() === "")) {
3155
- throw new ConfigurationError(
3156
- "Agent.createSession() sandboxId must be a non-empty string when provided."
3157
- );
3158
- }
3159
- if (signal !== void 0 && !isAbortSignal(signal)) {
3160
- throw new ConfigurationError(
3161
- "Agent.createSession() signal must be an AbortSignal when provided."
3162
- );
3163
- }
3164
- const sandboxId = requestedSandboxId ?? this._serverRuntime?.connection.sandboxId ?? this._sandboxId;
3165
- if (!sandboxId) {
3166
- throw new ConfigurationError("Agent not deployed. Call agent.deploy() first or pass sandboxId.");
3167
- }
3168
- return createAttachedAgentSession({
3169
- sandboxId,
3170
- runPrompt: (input, signal2) => this.streamSessionPrompt(input, sandboxId, signal2),
3171
- ...signal === void 0 ? {} : { externalSignal: signal },
3172
- configurationError: (message) => new ConfigurationError(message),
3173
- abortError: abortSignalError
3174
- });
3175
- }
3176
- async *streamSessionPrompt(input, sandboxId, signal) {
3177
- const connection = await this.resolveRuntimeConnection(sandboxId, {
3178
- signal,
3179
- reuseMatchingCachedConnection: true
3180
- });
3181
- const { invokeServer, InvokeHttpError } = await import("./invoke-client-YKWOTQWG.js");
3182
- let validated;
3183
- try {
3184
- validated = this.inputSchema.parse(input);
3185
- } catch (error) {
3186
- throw new ValidationError("Input validation failed.", asError(error));
3187
- }
3188
- try {
3189
- let finished = false;
3190
- for await (const frame of invokeServer(validated, {
3191
- serverUrl: connection.serverUrl,
3192
- provider: connection.provider,
3193
- trafficToken: getTrafficToken(connection),
3194
- frameSchema: this.frameSchema,
3195
- signal
3196
- })) {
3197
- if (frame.kind === "frame") {
3198
- yield frame.data;
3199
- } else if (frame.kind === "error") {
3200
- const err = new ExecutionError(frame.error.message);
3201
- err.stack = frame.error.stack;
3202
- throw err;
3203
- } else if (frame.kind === "done") {
3204
- finished = true;
3205
- }
3206
- }
3207
- if (!finished) {
3208
- throwIfAborted(signal);
3209
- throw new ExecutionError("Runtime stream ended before the turn finished.");
3210
- }
3211
- } catch (error) {
3212
- if (error instanceof ExecutionError) throw error;
3213
- if (error instanceof InvokeHttpError && error.status === 409) {
3214
- throw new RuntimeBusyError(error.message);
3215
- }
3216
- throw error instanceof Error ? error : new Error(String(error));
3217
- }
3218
- }
3219
- /**
3220
- * Waits until the sandbox runtime has no handler running. An aborted turn rejects on the host
3221
- * at once, while its handler can keep running in the sandbox until it notices the abort, so call
3222
- * this before reading state the handler writes, such as a transcript. Throws `RuntimeBusyError`
3223
- * if a handler is still running, or the runtime doesn't answer, after `timeoutMs`.
3224
- */
3225
- async waitForIdle(options = {}) {
3226
- const { signal, timeoutMs = DEFAULT_IDLE_TIMEOUT_MS } = options;
3227
- const connection = await this.resolveRuntimeConnection(options.sandboxId, {
3228
- signal,
3229
- reuseMatchingCachedConnection: true
3230
- });
3231
- const healthUrl = appendTrafficTokenToUrl(this.healthUrlFor(connection), connection);
3232
- const deadline = Date.now() + timeoutMs;
3233
- while (true) {
3234
- let busy = true;
3235
- try {
3236
- const response = await awaitWithAbort(
3237
- () => fetch(healthUrl, {
3238
- headers: trafficTokenHeaders(connection),
3239
- signal: signal === void 0 ? AbortSignal.timeout(SERVER_HEALTH_POLL_INTERVAL_MS * 5) : AbortSignal.any([signal, AbortSignal.timeout(SERVER_HEALTH_POLL_INTERVAL_MS * 5)])
3240
- }),
3241
- signal
3242
- );
3243
- if (response.ok) {
3244
- const body = await awaitWithAbort(() => response.json(), signal);
3245
- busy = body.ok !== true || body.busy === true;
3246
- } else {
3247
- await response.body?.cancel().catch(() => void 0);
3248
- }
3249
- } catch {
3250
- throwIfAborted(signal);
3251
- }
3252
- if (!busy) return;
3253
- if (Date.now() >= deadline) {
3254
- throw new RuntimeBusyError(`Sandbox runtime still busy after ${timeoutMs}ms.`);
3255
- }
3256
- await delayWithAbort(SERVER_HEALTH_POLL_INTERVAL_MS, signal);
3257
- }
3258
- }
3259
- /**
3260
- * @deprecated Use `createSession()` and call `session.prompt(input)` instead.
3261
- * This compatibility wrapper creates one attached session, streams one turn,
3262
- * and closes the local handle afterward.
3263
- */
3264
- async *invoke(input, options) {
3265
- const session = await this.createSession({
3266
- ...options?.sandboxId === void 0 ? {} : { sandboxId: options.sandboxId },
3267
- ...options?.signal === void 0 ? {} : { signal: options.signal }
3268
- });
3269
- try {
3270
- yield* session.prompt(input);
3271
- } finally {
3272
- await session.close();
3273
- }
3274
- }
3275
- };
3276
30
  export {
3277
31
  Agent,
3278
32
  ConfigurationError,
3279
33
  DEFAULT_DEPENDENCIES,
34
+ DefinedAgent,
3280
35
  DeploymentError,
3281
36
  ExecutionError,
37
+ LegacyBundledAgent,
3282
38
  NeckbeardError,
3283
39
  RuntimeBusyError,
40
+ SKILLS_DIR,
3284
41
  SandboxClient,
42
+ TURN_PROTOCOL_VERSION,
43
+ TurnLostError,
3285
44
  ValidationError,
45
+ defineAgent,
46
+ destroyProviderSandbox,
47
+ getPiTurnResult,
48
+ isDefinedAgent,
3286
49
  normalizeStackFramePath,
3287
50
  resolveAgentSourceFile,
51
+ resolveImageTag,
3288
52
  withNeckbeardNextConfig
3289
53
  };