agent-neckbeard 1.1.25 → 1.1.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -1
- package/README.md +4 -2
- package/dist/{chunk-DHFC3O44.js → chunk-6GCQOKYI.js} +2 -0
- package/dist/index.cjs +214 -22
- package/dist/index.d.cts +45 -1
- package/dist/index.d.ts +45 -1
- package/dist/index.js +194 -13
- package/dist/{invoke-client-HIXYE2WN.js → invoke-client-YKWOTQWG.js} +11 -2
- package/docs/MODAL.md +16 -2
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,6 +1,18 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
-
##
|
|
3
|
+
## 1.1.27 - 2026-11-09
|
|
4
|
+
|
|
5
|
+
- Upload `localDirectories` (and `claudeDir`) as one gzipped tar archive extracted with the sandbox's `tar`, instead of one provider call per file and directory. A 138-file skills directory took about two minutes to upload to a distant Modal sandbox. Images now need `tar` and `gzip`, and uploaded files have mode 0644.
|
|
6
|
+
- Accept `regions` in Modal sandbox config and pass it to sandbox creation. Modal otherwise places a sandbox in any region worldwide.
|
|
7
|
+
- Accept Daytona's `networkBlockAll`, `networkAllowList`, and `domainAllowList` in Modal sandbox config, in the same shape, mapped to Modal's outbound network policy. Modal's domain allow list only passes HTTPS, so with one set the image's apt sources are switched to HTTPS. See `docs/MODAL.md#network-policy`.
|
|
8
|
+
- Link a Modal image's `node`, `npm`, and `npx` into `/usr/local/bin` when they resolve elsewhere, such as an nvm install, so the runtime's fixed `PATH` finds them. Images like `daytonaio/sandbox:*-slim` failed their health check before.
|
|
9
|
+
|
|
10
|
+
## 1.1.26 - 2026-11-03
|
|
11
|
+
|
|
12
|
+
- Make the runtime wait up to 10 seconds for an aborted handler to stop before emitting the terminal `error` event, so the event marks the end of the handler's work. The host's `run()` timeout allows for that grace period.
|
|
13
|
+
- Run one handler at a time in the runtime: an invocation while another handler is still running is rejected with HTTP 409, raised by attached sessions and returned by `run()` as the new `RuntimeBusyError`. This changes behavior for callers that ran overlapping invocations in one sandbox, which now have to take turns.
|
|
14
|
+
- Report `busy` from the runtime's `/health`, and add `Agent.waitForIdle()`, which waits until no handler runs, for example before snapshotting a sandbox after a cancelled turn. A runtime that doesn't answer counts as busy; one from an older release, which doesn't report `busy`, counts as idle.
|
|
15
|
+
- Stop a handler's `emit()` from hanging once its invocation is aborted. The runtime used to wait for a stream whose caller had disconnected to drain, so a handler that emitted after its turn was cancelled never finished. A handler whose caller disconnects before it starts no longer runs.
|
|
4
16
|
|
|
5
17
|
## 1.1.25 - 2026-11-03
|
|
6
18
|
|
package/README.md
CHANGED
|
@@ -136,6 +136,8 @@ new Agent({
|
|
|
136
136
|
|
|
137
137
|
Set `networkBlockAll: true` only when you want to block all outbound network access. Daytona rejects `networkBlockAll: true` combined with non-empty allow lists.
|
|
138
138
|
|
|
139
|
+
Modal sandboxes accept the same three options in the same shape. Modal's domain allow list only passes HTTPS, so see [Modal network policy](docs/MODAL.md#network-policy).
|
|
140
|
+
|
|
139
141
|
`autoStopInterval` and `autoDeleteInterval` set the sandbox's Daytona lifecycle, in whole minutes, when the sandbox is created; reconnecting to an existing sandbox does not change them. Daytona stops a sandbox after `autoStopInterval` minutes without activity (`0` disables auto-stop; omitting it keeps Daytona's default, 15 minutes for standard sandbox classes) and deletes it `autoDeleteInterval` minutes after it stops (`0` deletes it immediately; `-1`, the default, never auto-deletes it).
|
|
140
142
|
|
|
141
143
|
## Structured Tasks
|
|
@@ -226,7 +228,7 @@ try {
|
|
|
226
228
|
}
|
|
227
229
|
```
|
|
228
230
|
|
|
229
|
-
An attached session is a local handle over the sandbox HTTP/SSE runtime. It supports sequential `prompt()` calls, one active turn at a time, `stop()` for the active turn, and `close()` for the local handle. Closing it does not destroy the reusable sandbox. Pass `{ signal }` to `createSession()` to bind the complete local session lifetime to an external abort signal. A turn's iterator completes only after the runtime reports that the handler finished; a stream that ends early throws `ExecutionError`, and a turn cancelled by `stop()`, `close()`, or the session signal rejects with that cancellation reason.
|
|
231
|
+
An attached session is a local handle over the sandbox HTTP/SSE runtime. It supports sequential `prompt()` calls, one active turn at a time, `stop()` for the active turn, and `close()` for the local handle. Closing it does not destroy the reusable sandbox. Pass `{ signal }` to `createSession()` to bind the complete local session lifetime to an external abort signal. A turn's iterator completes only after the runtime reports that the handler finished; a stream that ends early throws `ExecutionError`, and a turn cancelled by `stop()`, `close()`, or the session signal rejects with that cancellation reason. The runtime runs one handler at a time, so starting a turn while an earlier handler is still running throws `RuntimeBusyError`. A cancelled turn rejects at once while its handler may keep running in the sandbox until it notices the cancellation; call `agent.waitForIdle({ sandboxId })` before reading what the handler writes, such as a transcript, or starting the next turn.
|
|
230
232
|
|
|
231
233
|
The previous `server: { frameSchema, handler }` configuration remains as a deprecated alias for `session`. Likewise, `invoke(input, options)` remains as a deprecated compatibility wrapper: it creates one attached session, streams one prompt, and closes the local handle afterward.
|
|
232
234
|
|
|
@@ -419,7 +421,7 @@ interface LocalDirectoryUpload {
|
|
|
419
421
|
}
|
|
420
422
|
```
|
|
421
423
|
|
|
422
|
-
`localDirectories` recursively copies consumer-selected local directories beneath `ctx.sandbox.agentDir` during `deploy()`. Relative sources resolve from the deploying process's current working directory; absolute sources are also supported. Nested paths and dotfiles are included, text and binary files retain their exact bytes, and parent directories are created as needed. Empty directories are not preserved.
|
|
424
|
+
`localDirectories` recursively copies consumer-selected local directories beneath `ctx.sandbox.agentDir` during `deploy()`. Relative sources resolve from the deploying process's current working directory; absolute sources are also supported. Nested paths and dotfiles are included, text and binary files retain their exact bytes, and parent directories are created as needed. Empty directories are not preserved. The files go up as one gzipped tar archive that the sandbox extracts with `tar`, so the image needs `tar` and `gzip`; files land with mode 0644.
|
|
423
425
|
|
|
424
426
|
Each `destination` is relative to the sandbox agent directory. For example, this Pi-oriented configuration produces `<sandbox agentDir>/.agents/skills/...` on both E2B and Daytona:
|
|
425
427
|
|
|
@@ -4,6 +4,7 @@ import {
|
|
|
4
4
|
|
|
5
5
|
// src/runtime/protocol.ts
|
|
6
6
|
var RUNTIME_PROTOCOL_VERSION = 1;
|
|
7
|
+
var RUNTIME_ABORT_GRACE_MS = 1e4;
|
|
7
8
|
function isHarnessEvent(value) {
|
|
8
9
|
if (!value || typeof value !== "object") return false;
|
|
9
10
|
const candidate = value;
|
|
@@ -42,5 +43,6 @@ function hasValidMetadata(candidate) {
|
|
|
42
43
|
|
|
43
44
|
export {
|
|
44
45
|
RUNTIME_PROTOCOL_VERSION,
|
|
46
|
+
RUNTIME_ABORT_GRACE_MS,
|
|
45
47
|
isHarnessEvent
|
|
46
48
|
};
|
package/dist/index.cjs
CHANGED
|
@@ -78,12 +78,13 @@ function hasValidMetadata(candidate) {
|
|
|
78
78
|
}
|
|
79
79
|
return true;
|
|
80
80
|
}
|
|
81
|
-
var RUNTIME_PROTOCOL_VERSION;
|
|
81
|
+
var RUNTIME_PROTOCOL_VERSION, RUNTIME_ABORT_GRACE_MS;
|
|
82
82
|
var init_protocol = __esm({
|
|
83
83
|
"src/runtime/protocol.ts"() {
|
|
84
84
|
"use strict";
|
|
85
85
|
init_serialized_error();
|
|
86
86
|
RUNTIME_PROTOCOL_VERSION = 1;
|
|
87
|
+
RUNTIME_ABORT_GRACE_MS = 1e4;
|
|
87
88
|
}
|
|
88
89
|
});
|
|
89
90
|
|
|
@@ -135,6 +136,7 @@ var init_sse_framing = __esm({
|
|
|
135
136
|
// src/invoke-client.ts
|
|
136
137
|
var invoke_client_exports = {};
|
|
137
138
|
__export(invoke_client_exports, {
|
|
139
|
+
InvokeHttpError: () => InvokeHttpError,
|
|
138
140
|
invokeServer: () => invokeServer
|
|
139
141
|
});
|
|
140
142
|
function createInvocationId() {
|
|
@@ -186,7 +188,8 @@ async function* invokeServer(input, options) {
|
|
|
186
188
|
});
|
|
187
189
|
if (!response.ok) {
|
|
188
190
|
const text = await response.text().catch(() => "");
|
|
189
|
-
throw new
|
|
191
|
+
throw new InvokeHttpError(
|
|
192
|
+
response.status,
|
|
190
193
|
`Server returned ${response.status}${text ? `: ${text}` : ""}`
|
|
191
194
|
);
|
|
192
195
|
}
|
|
@@ -221,11 +224,19 @@ async function* invokeServer(input, options) {
|
|
|
221
224
|
}
|
|
222
225
|
}
|
|
223
226
|
}
|
|
227
|
+
var InvokeHttpError;
|
|
224
228
|
var init_invoke_client = __esm({
|
|
225
229
|
"src/invoke-client.ts"() {
|
|
226
230
|
"use strict";
|
|
227
231
|
init_sse_framing();
|
|
228
232
|
init_protocol();
|
|
233
|
+
InvokeHttpError = class extends Error {
|
|
234
|
+
constructor(status, message) {
|
|
235
|
+
super(message);
|
|
236
|
+
this.status = status;
|
|
237
|
+
this.name = "InvokeHttpError";
|
|
238
|
+
}
|
|
239
|
+
};
|
|
229
240
|
}
|
|
230
241
|
});
|
|
231
242
|
|
|
@@ -238,6 +249,7 @@ __export(src_exports, {
|
|
|
238
249
|
DeploymentError: () => DeploymentError,
|
|
239
250
|
ExecutionError: () => ExecutionError,
|
|
240
251
|
NeckbeardError: () => NeckbeardError,
|
|
252
|
+
RuntimeBusyError: () => RuntimeBusyError,
|
|
241
253
|
SandboxClient: () => SandboxClient,
|
|
242
254
|
ValidationError: () => ValidationError,
|
|
243
255
|
normalizeStackFramePath: () => normalizeStackFramePath,
|
|
@@ -248,11 +260,12 @@ module.exports = __toCommonJS(src_exports);
|
|
|
248
260
|
var import_node_url = require("url");
|
|
249
261
|
var import_node_fs = require("fs");
|
|
250
262
|
var import_node_path = require("path");
|
|
263
|
+
var import_node_crypto3 = require("crypto");
|
|
251
264
|
var import_node_module2 = require("module");
|
|
252
265
|
init_protocol();
|
|
253
266
|
|
|
254
267
|
// src/runtime/server-source.generated.ts
|
|
255
|
-
var RUNTIME_SERVER_SOURCE = '// src/runtime/server.ts\nimport { createServer } from "node:http";\nimport { readFileSync } from "node:fs";\nimport { fileURLToPath } from "node:url";\nimport { dirname, join } from "node:path";\nimport { once } from "node:events";\n\n// src/serialized-error.ts\nfunction serializeError(error) {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n ...error.stack === void 0 ? {} : { stack: error.stack }\n };\n }\n return { message: String(error) };\n}\n\n// src/runtime/protocol.ts\nvar RUNTIME_PROTOCOL_VERSION = 1;\n\n// src/timeout.ts\nfunction settleOperation(operation, options = {}) {\n const { abort, timeout } = options;\n if (abort?.signal.aborted) throw abort.createError();\n if (!abort && !timeout) {\n try {\n return Promise.resolve(operation());\n } catch (error) {\n return Promise.reject(error);\n }\n }\n return new Promise((resolve, reject) => {\n let settled = false;\n let timer;\n const cleanup = () => {\n if (timer !== void 0) {\n clearTimeout(timer);\n timer = void 0;\n }\n abort?.signal.removeEventListener("abort", onAbort);\n };\n const settle = (callback) => {\n if (settled) return;\n settled = true;\n cleanup();\n callback();\n };\n const onAbort = () => settle(() => reject(abort.createError()));\n abort?.signal.addEventListener("abort", onAbort, { once: true });\n if (timeout) {\n timer = setTimeout(\n () => settle(() => reject(timeout.createError())),\n timeout.timeoutMs\n );\n }\n let task;\n try {\n task = operation();\n } catch (error) {\n settle(() => reject(error));\n return;\n }\n void Promise.resolve(task).then(\n (value) => settle(() => resolve(value)),\n (error) => settle(() => reject(error))\n );\n });\n}\n\n// src/runtime/server.ts\nvar CONFIG_PATH = join(dirname(fileURLToPath(import.meta.url)), "server-config.json");\nvar CONFIG = JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));\nvar MAX_REQUEST_BODY_BYTES = 4 * 1024 * 1024;\nvar DEFAULT_SSE_HEARTBEAT_INTERVAL_MS = 15e3;\nvar RequestBodyTooLargeError = class extends Error {\n constructor(limitBytes) {\n super(`request body exceeds ${limitBytes} bytes`);\n this.name = "RequestBodyTooLargeError";\n }\n};\nfunction createLogger() {\n return {\n debug: (message, ...args) => console.log("[DEBUG]", message, ...args),\n info: (message, ...args) => console.log("[INFO]", message, ...args),\n warn: (message, ...args) => console.warn("[WARN]", message, ...args),\n error: (message, ...args) => console.error("[ERROR]", message, ...args)\n };\n}\nfunction sendJson(res, status, body) {\n res.writeHead(status, { "content-type": "application/json" });\n res.end(JSON.stringify(body));\n}\nfunction getSseHeartbeatIntervalMs() {\n const raw = process.env.NECKBEARD_RUNTIME_SSE_HEARTBEAT_MS;\n if (!raw) return DEFAULT_SSE_HEARTBEAT_INTERVAL_MS;\n const parsed = Number(raw);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_SSE_HEARTBEAT_INTERVAL_MS;\n}\nfunction sendSseComment(res, comment) {\n if (res.writableEnded || res.destroyed) return;\n res.write(`: ${comment}\n\n`);\n}\nasync function sendSseFrame(res, event) {\n const canContinue = res.write(`data: ${JSON.stringify(event)}\n\n`);\n if (!canContinue) {\n await once(res, "drain");\n }\n}\nasync function readRequestBody(req, maxBytes = MAX_REQUEST_BODY_BYTES) {\n const chunks = [];\n let totalBytes = 0;\n for await (const chunk of req) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n totalBytes += buffer.byteLength;\n if (totalBytes > maxBytes) {\n throw new RequestBodyTooLargeError(maxBytes);\n }\n chunks.push(buffer);\n }\n return Buffer.concat(chunks).toString("utf-8");\n}\nfunction createTimeoutError(maxDurationMs) {\n const error = new Error(`Agent invocation exceeded maxDuration (${maxDurationMs}ms)`);\n error.name = "TimeoutError";\n return error;\n}\nasync function rejectOnAbort(operation, signal, maxDurationMs) {\n return settleOperation(operation, {\n abort: {\n signal,\n createError: () => createTimeoutError(maxDurationMs)\n }\n });\n}\nasync function loadAgent() {\n const mod = await import(new URL("./agent.mjs", import.meta.url).href);\n const agent = (mod.default && (mod.default._run || mod.default._server) ? mod.default : null) || Object.values(mod).find(\n (value) => value && typeof value === "object" && ("_run" in value || "_server" in value)\n );\n if (!agent || typeof agent !== "object") {\n throw new Error(\n `No agent found in agent.mjs. Exports: ${Object.keys(mod).join(", ")}`\n );\n }\n return agent;\n}\nasync function main() {\n const agent = await loadAgent();\n const server = createServer(async (req, res) => {\n try {\n const url = new URL(req.url ?? "/", "http://localhost");\n if (url.pathname === "/health" && req.method === "GET") {\n return sendJson(res, 200, {\n ok: true,\n protocolVersion: RUNTIME_PROTOCOL_VERSION\n });\n }\n if (url.pathname === "/shutdown" && req.method === "POST") {\n sendJson(res, 200, { ok: true });\n setTimeout(() => shutdown(), 10).unref();\n return;\n }\n if (url.pathname === "/invoke" && req.method === "POST") {\n let rawBody;\n try {\n rawBody = await readRequestBody(req);\n } catch (error) {\n if (error instanceof RequestBodyTooLargeError) {\n return sendJson(res, 413, { error: error.message });\n }\n throw error;\n }\n let requestBody;\n try {\n requestBody = JSON.parse(rawBody);\n } catch {\n return sendJson(res, 400, { error: "invalid JSON body" });\n }\n if (!requestBody || typeof requestBody !== "object" || typeof requestBody.invocationId !== "string") {\n return sendJson(res, 400, { error: "invalid invoke request" });\n }\n let validatedInput;\n try {\n validatedInput = agent.inputSchema.parse(requestBody.input);\n } catch (error) {\n return sendJson(res, 400, {\n error: `input validation failed: ${serializeError(error).message}`\n });\n }\n res.writeHead(200, {\n "content-type": "text/event-stream",\n "cache-control": "no-cache, no-transform",\n connection: "keep-alive",\n "x-accel-buffering": "no"\n });\n const controller = new AbortController();\n req.on("aborted", () => controller.abort());\n res.on("close", () => {\n if (!res.writableEnded) {\n controller.abort();\n }\n });\n const startedAt = Date.now();\n let sequence = 0;\n const timeout = setTimeout(() => controller.abort(), CONFIG.maxDurationMs);\n const invocationId = requestBody.invocationId;\n const heartbeat = setInterval(() => {\n try {\n sendSseComment(res, `heartbeat ${Date.now()}`);\n } catch {\n controller.abort();\n }\n }, getSseHeartbeatIntervalMs());\n heartbeat.unref();\n const emitHarnessEvent = async (event) => {\n if (!res.writableEnded) {\n await sendSseFrame(res, {\n protocolVersion: RUNTIME_PROTOCOL_VERSION,\n sequence: sequence++,\n timestamp: (/* @__PURE__ */ new Date()).toISOString(),\n elapsedMs: Date.now() - startedAt,\n ...event\n });\n }\n };\n const ctx = {\n executionId: invocationId,\n signal: controller.signal,\n env: process.env,\n sandbox: CONFIG.sandboxContext,\n logger: createLogger()\n };\n try {\n await emitHarnessEvent({ kind: "started", invocationId });\n if (agent._server) {\n await rejectOnAbort(\n () => agent._server.handler({\n input: validatedInput,\n ctx,\n signal: controller.signal,\n emit: async (data) => {\n const validatedFrame = agent._server?.frameSchema ? agent._server.frameSchema.parse(data) : data;\n await emitHarnessEvent({ kind: "frame", invocationId, data: validatedFrame });\n }\n }),\n controller.signal,\n CONFIG.maxDurationMs\n );\n } else if (agent._run) {\n const output = await rejectOnAbort(\n () => agent._run(validatedInput, ctx),\n controller.signal,\n CONFIG.maxDurationMs\n );\n const validatedOutput = agent.outputSchema ? agent.outputSchema.parse(output) : output;\n await emitHarnessEvent({ kind: "output", invocationId, output: validatedOutput });\n } else {\n throw new Error("Agent has neither a run handler nor a server handler.");\n }\n await emitHarnessEvent({ kind: "done", invocationId });\n } catch (error) {\n await emitHarnessEvent({ kind: "error", invocationId, error: serializeError(error) });\n } finally {\n clearInterval(heartbeat);\n clearTimeout(timeout);\n if (!res.writableEnded) {\n res.end();\n }\n }\n return;\n }\n return sendJson(res, 404, { error: "not found" });\n } catch (error) {\n console.error("[neckbeard-server] unexpected error", error);\n if (!res.headersSent) {\n sendJson(res, 500, { error: "internal error" });\n } else if (!res.writableEnded) {\n res.end();\n }\n }\n });\n function shutdown() {\n console.log("[neckbeard-server] shutting down");\n server.close(() => process.exit(0));\n setTimeout(() => process.exit(0), 5e3).unref();\n }\n server.listen(CONFIG.port, "0.0.0.0", () => {\n console.log(`[neckbeard-server] listening on port ${CONFIG.port}`);\n });\n process.on("SIGTERM", shutdown);\n process.on("SIGINT", shutdown);\n}\nmain().catch((error) => {\n console.error("[neckbeard-server] failed to start", error);\n process.exit(1);\n});\n';
|
|
268
|
+
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';
|
|
256
269
|
|
|
257
270
|
// src/sandbox-capabilities.ts
|
|
258
271
|
var SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV = "NECKBEARD_SUPERVISOR_ENVIRONMENT_V1";
|
|
@@ -529,8 +542,91 @@ function shellQuote(value) {
|
|
|
529
542
|
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
530
543
|
}
|
|
531
544
|
|
|
532
|
-
// src/
|
|
545
|
+
// src/tar.ts
|
|
533
546
|
var import_node_buffer = require("buffer");
|
|
547
|
+
var import_node_util = require("util");
|
|
548
|
+
var import_node_zlib = require("zlib");
|
|
549
|
+
var gzipAsync = (0, import_node_util.promisify)(import_node_zlib.gzip);
|
|
550
|
+
var BLOCK_SIZE = 512;
|
|
551
|
+
var MAX_OCTAL_SIZE = 8589934591;
|
|
552
|
+
function writeString(header2, value, offset, length) {
|
|
553
|
+
header2.write(value, offset, length, "utf8");
|
|
554
|
+
}
|
|
555
|
+
function writeOctal(header2, value, offset, length) {
|
|
556
|
+
header2.write(`${value.toString(8).padStart(length - 1, "0")}\0`, offset, length, "ascii");
|
|
557
|
+
}
|
|
558
|
+
function splitUstarPath(path) {
|
|
559
|
+
if (import_node_buffer.Buffer.byteLength(path) <= 100) return { name: path, prefix: "" };
|
|
560
|
+
for (let index = path.indexOf("/"); index !== -1; index = path.indexOf("/", index + 1)) {
|
|
561
|
+
const prefix = path.slice(0, index);
|
|
562
|
+
const name = path.slice(index + 1);
|
|
563
|
+
if (import_node_buffer.Buffer.byteLength(prefix) <= 155 && import_node_buffer.Buffer.byteLength(name) <= 100 && name) {
|
|
564
|
+
return { name, prefix };
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
return void 0;
|
|
568
|
+
}
|
|
569
|
+
function header(options) {
|
|
570
|
+
if (options.size > MAX_OCTAL_SIZE) {
|
|
571
|
+
throw new Error(`Archive entry ${options.name} is too large.`);
|
|
572
|
+
}
|
|
573
|
+
const block = import_node_buffer.Buffer.alloc(BLOCK_SIZE);
|
|
574
|
+
writeString(block, options.name, 0, 100);
|
|
575
|
+
writeOctal(block, options.mode, 100, 8);
|
|
576
|
+
writeOctal(block, 0, 108, 8);
|
|
577
|
+
writeOctal(block, 0, 116, 8);
|
|
578
|
+
writeOctal(block, options.size, 124, 12);
|
|
579
|
+
writeOctal(block, options.mtime, 136, 12);
|
|
580
|
+
block.fill(" ", 148, 156);
|
|
581
|
+
writeString(block, options.type, 156, 1);
|
|
582
|
+
writeString(block, "ustar\0", 257, 6);
|
|
583
|
+
writeString(block, "00", 263, 2);
|
|
584
|
+
writeString(block, options.prefix ?? "", 345, 155);
|
|
585
|
+
let checksum = 0;
|
|
586
|
+
for (const byte of block) checksum += byte;
|
|
587
|
+
block.write(`${checksum.toString(8).padStart(6, "0")}\0 `, 148, 8, "ascii");
|
|
588
|
+
return block;
|
|
589
|
+
}
|
|
590
|
+
function padding(size) {
|
|
591
|
+
return import_node_buffer.Buffer.alloc((BLOCK_SIZE - size % BLOCK_SIZE) % BLOCK_SIZE);
|
|
592
|
+
}
|
|
593
|
+
function paxPathRecord(path) {
|
|
594
|
+
const body = ` path=${path}
|
|
595
|
+
`;
|
|
596
|
+
let length = import_node_buffer.Buffer.byteLength(body);
|
|
597
|
+
while (String(length).length + import_node_buffer.Buffer.byteLength(body) !== length) {
|
|
598
|
+
length = String(length).length + import_node_buffer.Buffer.byteLength(body);
|
|
599
|
+
}
|
|
600
|
+
return import_node_buffer.Buffer.from(`${length}${body}`);
|
|
601
|
+
}
|
|
602
|
+
async function createTarGz(entries, mtime = Math.floor(Date.now() / 1e3)) {
|
|
603
|
+
const chunks = [];
|
|
604
|
+
for (const entry of entries) {
|
|
605
|
+
const isDirectory = entry.content === void 0;
|
|
606
|
+
const path = isDirectory ? `${entry.path.replace(/\/+$/u, "")}/` : entry.path;
|
|
607
|
+
const size = entry.content?.byteLength ?? 0;
|
|
608
|
+
const type = isDirectory ? "5" : "0";
|
|
609
|
+
const mode = isDirectory ? 493 : 420;
|
|
610
|
+
const split = splitUstarPath(path);
|
|
611
|
+
if (split) {
|
|
612
|
+
chunks.push(header({ ...split, mode, size, mtime, type }));
|
|
613
|
+
} else {
|
|
614
|
+
const record = paxPathRecord(path);
|
|
615
|
+
chunks.push(header({ name: "PaxHeader", mode: 420, size: record.byteLength, mtime, type: "x" }));
|
|
616
|
+
chunks.push(record, padding(record.byteLength));
|
|
617
|
+
chunks.push(header({ name: path.slice(-100).replace(/^\/+/u, ""), mode, size, mtime, type }));
|
|
618
|
+
}
|
|
619
|
+
if (entry.content) {
|
|
620
|
+
chunks.push(import_node_buffer.Buffer.from(entry.content.buffer, entry.content.byteOffset, entry.content.byteLength));
|
|
621
|
+
chunks.push(padding(size));
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
chunks.push(import_node_buffer.Buffer.alloc(BLOCK_SIZE * 2));
|
|
625
|
+
return gzipAsync(import_node_buffer.Buffer.concat(chunks));
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
// src/providers/detached-process.ts
|
|
629
|
+
var import_node_buffer2 = require("buffer");
|
|
534
630
|
var import_node_crypto = require("crypto");
|
|
535
631
|
var DETACHED_PROCESS_ROOT = "/tmp/agent-neckbeard-detached";
|
|
536
632
|
var DETACHED_PROCESS_CONTROL_TIMEOUT_MS = 3e4;
|
|
@@ -2752,9 +2848,9 @@ function readLogFiles(stdout, stderr, previous, beforePrint = []) {
|
|
|
2752
2848
|
function parseDetachedProcessLogs(output) {
|
|
2753
2849
|
const lineEnd = output.indexOf("\n");
|
|
2754
2850
|
if (lineEnd < 0) return null;
|
|
2755
|
-
const
|
|
2851
|
+
const header2 = output.slice(0, lineEnd);
|
|
2756
2852
|
const match = new RegExp(`^${LOGS_PREFIX} (0|[1-9][0-9]*) (0|[1-9][0-9]*)$`, "u").exec(
|
|
2757
|
-
|
|
2853
|
+
header2
|
|
2758
2854
|
);
|
|
2759
2855
|
if (!match?.[1] || !match[2]) return null;
|
|
2760
2856
|
const stdoutBytes = Number(match[1]);
|
|
@@ -2775,7 +2871,7 @@ function parseDetachedProcessLogs(output) {
|
|
|
2775
2871
|
};
|
|
2776
2872
|
const stdout = decodeCanonicalBase64(stdoutBase64);
|
|
2777
2873
|
const stderr = decodeCanonicalBase64(stderrBase64);
|
|
2778
|
-
if (!stdout || !stderr || stdout.byteLength !== stdoutBytes || stderr.byteLength !== stderrBytes || !(0,
|
|
2874
|
+
if (!stdout || !stderr || stdout.byteLength !== stdoutBytes || stderr.byteLength !== stderrBytes || !(0, import_node_buffer2.isUtf8)(stdout) || !(0, import_node_buffer2.isUtf8)(stderr)) {
|
|
2779
2875
|
return null;
|
|
2780
2876
|
}
|
|
2781
2877
|
return {
|
|
@@ -2788,7 +2884,7 @@ function isStopConfirmation(output) {
|
|
|
2788
2884
|
}
|
|
2789
2885
|
|
|
2790
2886
|
// src/providers/daytona-transport.ts
|
|
2791
|
-
var
|
|
2887
|
+
var import_node_buffer3 = require("buffer");
|
|
2792
2888
|
function daytonaTimeoutSeconds(timeoutMs) {
|
|
2793
2889
|
return Math.max(1, Math.ceil(timeoutMs / 1e3));
|
|
2794
2890
|
}
|
|
@@ -2834,10 +2930,10 @@ async function makeDaytonaDirectory(sandbox, path, options) {
|
|
|
2834
2930
|
);
|
|
2835
2931
|
}
|
|
2836
2932
|
function daytonaUploadContent(content) {
|
|
2837
|
-
if (
|
|
2838
|
-
if (typeof content === "string") return
|
|
2839
|
-
if (content instanceof Uint8Array) return
|
|
2840
|
-
return
|
|
2933
|
+
if (import_node_buffer3.Buffer.isBuffer(content)) return content;
|
|
2934
|
+
if (typeof content === "string") return import_node_buffer3.Buffer.from(content);
|
|
2935
|
+
if (content instanceof Uint8Array) return import_node_buffer3.Buffer.from(content);
|
|
2936
|
+
return import_node_buffer3.Buffer.from(content);
|
|
2841
2937
|
}
|
|
2842
2938
|
async function uploadDaytonaFile(sandbox, path, content, options) {
|
|
2843
2939
|
await options.beforeIo?.();
|
|
@@ -3351,8 +3447,21 @@ function getModalSdk() {
|
|
|
3351
3447
|
// src/providers/modal.ts
|
|
3352
3448
|
var MODAL_DEFAULT_TEMPLATE = "node:22-bookworm";
|
|
3353
3449
|
var MODAL_DEFAULT_TIMEOUT_MS = 60 * 60 * 1e3;
|
|
3450
|
+
function parseModalAllowList(value) {
|
|
3451
|
+
return (value ?? "").split(",").map((entry) => entry.trim()).filter(Boolean);
|
|
3452
|
+
}
|
|
3453
|
+
function modalNetworkOptions(options) {
|
|
3454
|
+
if (options.networkBlockAll) return { blockNetwork: true };
|
|
3455
|
+
const cidrs = parseModalAllowList(options.networkAllowList);
|
|
3456
|
+
const domains = parseModalAllowList(options.domainAllowList);
|
|
3457
|
+
return {
|
|
3458
|
+
...cidrs.length > 0 ? { outboundCidrAllowlist: cidrs } : {},
|
|
3459
|
+
...domains.length > 0 ? { outboundDomainAllowlist: domains } : {}
|
|
3460
|
+
};
|
|
3461
|
+
}
|
|
3354
3462
|
function validateModalOptions(options, mode, failure) {
|
|
3355
|
-
|
|
3463
|
+
const { networkBlockAll, networkAllowList, domainAllowList, regions, ...rest } = options;
|
|
3464
|
+
validateProviderOptions("Modal", mode === "connect" ? options : rest, ["environment", ...mode === "connect" ? ["sandboxId", "tokenId", "tokenSecret"] : [
|
|
3356
3465
|
"template",
|
|
3357
3466
|
"appName",
|
|
3358
3467
|
"timeoutMs",
|
|
@@ -3360,6 +3469,20 @@ function validateModalOptions(options, mode, failure) {
|
|
|
3360
3469
|
"memoryMiB",
|
|
3361
3470
|
...mode === "create" ? ["tokenId", "tokenSecret", "envs"] : []
|
|
3362
3471
|
]], failure);
|
|
3472
|
+
if (regions !== void 0 && (!Array.isArray(regions) || regions.length === 0 || regions.some((region) => typeof region !== "string" || !/^[a-z0-9-]+$/u.test(region)))) {
|
|
3473
|
+
throw failure('Modal regions must be a non-empty array of region names such as "us" or "us-east".');
|
|
3474
|
+
}
|
|
3475
|
+
if (networkBlockAll !== void 0 && typeof networkBlockAll !== "boolean") {
|
|
3476
|
+
throw failure("Modal networkBlockAll must be a boolean.");
|
|
3477
|
+
}
|
|
3478
|
+
for (const [key, value] of [["networkAllowList", networkAllowList], ["domainAllowList", domainAllowList]]) {
|
|
3479
|
+
if (value !== void 0 && (typeof value !== "string" || parseModalAllowList(value).some((entry) => /[\s\0]/u.test(entry)))) {
|
|
3480
|
+
throw failure(`Modal ${key} must be a comma-separated string without whitespace or null bytes in entries.`);
|
|
3481
|
+
}
|
|
3482
|
+
}
|
|
3483
|
+
if (networkBlockAll && (parseModalAllowList(networkAllowList).length > 0 || parseModalAllowList(domainAllowList).length > 0)) {
|
|
3484
|
+
throw failure("Modal networkBlockAll cannot be combined with non-empty allow lists.");
|
|
3485
|
+
}
|
|
3363
3486
|
if (mode === "connect" && !("sandboxId" in options && options.sandboxId)) {
|
|
3364
3487
|
throw failure("Modal sandboxId is required.");
|
|
3365
3488
|
}
|
|
@@ -3438,12 +3561,19 @@ var ModalSandboxHandle = class _ModalSandboxHandle {
|
|
|
3438
3561
|
let sandbox;
|
|
3439
3562
|
try {
|
|
3440
3563
|
const app = await client.apps.fromName(options.appName ?? "agent-neckbeard", { createIfMissing: true });
|
|
3564
|
+
const network = modalNetworkOptions(options);
|
|
3441
3565
|
const image = client.images.fromRegistry(options.template ?? MODAL_DEFAULT_TEMPLATE).dockerfileCommands([
|
|
3442
3566
|
"USER root",
|
|
3443
3567
|
"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/*",
|
|
3568
|
+
// The runtime starts with a fixed PATH, so images with Node elsewhere (say nvm) need links.
|
|
3569
|
+
'RUN for bin in node npm npx; do target="$(command -v "$bin" || true)"; if [ -n "$target" ] && [ ! -e "/usr/local/bin/$bin" ]; then ln -s "$target" "/usr/local/bin/$bin"; fi; done',
|
|
3570
|
+
// The domain allow list only passes TLS, so apt installs in the sandbox need HTTPS sources.
|
|
3571
|
+
...network.outboundDomainAllowlist ? ["RUN find /etc/apt -name '*.list' -o -name '*.sources' | xargs -r sed -i 's|http://|https://|g'"] : [],
|
|
3444
3572
|
"WORKDIR /root"
|
|
3445
3573
|
]);
|
|
3446
3574
|
sandbox = await client.sandboxes.create(app, image, {
|
|
3575
|
+
...network,
|
|
3576
|
+
...options.regions ? { regions: options.regions } : {},
|
|
3447
3577
|
timeoutMs: options.timeoutMs ?? MODAL_DEFAULT_TIMEOUT_MS,
|
|
3448
3578
|
cpu: options.cpu,
|
|
3449
3579
|
memoryMiB: options.memoryMiB,
|
|
@@ -3899,6 +4029,7 @@ var DEFAULT_SERVER_PORT = 3e3;
|
|
|
3899
4029
|
var SERVER_HEALTH_TIMEOUT_MS = 12e4;
|
|
3900
4030
|
var SERVER_RECONNECT_HEALTH_TIMEOUT_MS = 3e3;
|
|
3901
4031
|
var SERVER_HEALTH_POLL_INTERVAL_MS = 1e3;
|
|
4032
|
+
var DEFAULT_IDLE_TIMEOUT_MS = RUNTIME_ABORT_GRACE_MS + 3e4;
|
|
3902
4033
|
var SERVER_FAILURE_DIAGNOSTIC_TIMEOUT_MS = 1e3;
|
|
3903
4034
|
var NATIVE_EXT_RE = /\.(node|wasm|gyp|c|cc|cpp|cxx|h|hpp|hxx)$/i;
|
|
3904
4035
|
var TRACEABLE_SOURCE_EXT_RE = /\.(cjs|cts|js|jsx|mjs|mts|ts|tsx)$/i;
|
|
@@ -3929,6 +4060,12 @@ var ExecutionError = class extends NeckbeardError {
|
|
|
3929
4060
|
this.name = "ExecutionError";
|
|
3930
4061
|
}
|
|
3931
4062
|
};
|
|
4063
|
+
var RuntimeBusyError = class extends ExecutionError {
|
|
4064
|
+
constructor(message) {
|
|
4065
|
+
super(message);
|
|
4066
|
+
this.name = "RuntimeBusyError";
|
|
4067
|
+
}
|
|
4068
|
+
};
|
|
3932
4069
|
var ConfigurationError = class extends NeckbeardError {
|
|
3933
4070
|
constructor(message) {
|
|
3934
4071
|
super(message);
|
|
@@ -5647,14 +5784,21 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
5647
5784
|
}
|
|
5648
5785
|
}
|
|
5649
5786
|
}
|
|
5650
|
-
|
|
5651
|
-
|
|
5652
|
-
|
|
5653
|
-
|
|
5654
|
-
|
|
5655
|
-
|
|
5656
|
-
|
|
5787
|
+
if (localDirectoryUploads.directories.length > 0 || localDirectoryUploads.files.length > 0) {
|
|
5788
|
+
const archivePath = import_node_path.posix.join(paths.agentDir, `.neckbeard-local-directories-${(0, import_node_crypto3.randomUUID)()}.tar.gz`);
|
|
5789
|
+
await sandbox.writeFile(archivePath, await createTarGz([
|
|
5790
|
+
...localDirectoryUploads.directories.map((directory) => ({ path: directory })),
|
|
5791
|
+
...localDirectoryUploads.files.map((file) => ({ path: file.targetPath, content: file.content }))
|
|
5792
|
+
]));
|
|
5793
|
+
const extractResult = await sandbox.runCommand(
|
|
5794
|
+
`tar -xzf ${shellQuote(archivePath)} --no-same-owner -C ${shellQuote(paths.agentDir)} && rm -f ${shellQuote(archivePath)}`,
|
|
5795
|
+
{ timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS2 }
|
|
5657
5796
|
);
|
|
5797
|
+
if (extractResult.exitCode !== 0) {
|
|
5798
|
+
throw new DeploymentError(
|
|
5799
|
+
`Failed to extract local directories: ${extractResult.stderr || extractResult.stdout}`
|
|
5800
|
+
);
|
|
5801
|
+
}
|
|
5658
5802
|
}
|
|
5659
5803
|
await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
|
|
5660
5804
|
await sandbox.writeFile(paths.serverModule, RUNTIME_SERVER_SOURCE);
|
|
@@ -5776,7 +5920,7 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
5776
5920
|
provider: connection.provider,
|
|
5777
5921
|
trafficToken: getTrafficToken(connection),
|
|
5778
5922
|
invocationId: executionId,
|
|
5779
|
-
signal: AbortSignal.timeout(this.maxDuration * 1e3 + 5e3)
|
|
5923
|
+
signal: AbortSignal.timeout(this.maxDuration * 1e3 + RUNTIME_ABORT_GRACE_MS + 5e3)
|
|
5780
5924
|
})) {
|
|
5781
5925
|
if (event.kind === "error") {
|
|
5782
5926
|
const err = new ExecutionError(event.error.message);
|
|
@@ -5803,6 +5947,10 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
5803
5947
|
}
|
|
5804
5948
|
return { ok: true, executionId, output: validated };
|
|
5805
5949
|
} catch (err) {
|
|
5950
|
+
const { InvokeHttpError: InvokeHttpError2 } = await Promise.resolve().then(() => (init_invoke_client(), invoke_client_exports));
|
|
5951
|
+
if (err instanceof InvokeHttpError2 && err.status === 409) {
|
|
5952
|
+
return { ok: false, executionId, error: new RuntimeBusyError(err.message) };
|
|
5953
|
+
}
|
|
5806
5954
|
return { ok: false, executionId, error: err instanceof Error ? err : new Error(String(err)) };
|
|
5807
5955
|
}
|
|
5808
5956
|
}
|
|
@@ -5875,7 +6023,7 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
5875
6023
|
signal,
|
|
5876
6024
|
reuseMatchingCachedConnection: true
|
|
5877
6025
|
});
|
|
5878
|
-
const { invokeServer: invokeServer2 } = await Promise.resolve().then(() => (init_invoke_client(), invoke_client_exports));
|
|
6026
|
+
const { invokeServer: invokeServer2, InvokeHttpError: InvokeHttpError2 } = await Promise.resolve().then(() => (init_invoke_client(), invoke_client_exports));
|
|
5879
6027
|
let validated;
|
|
5880
6028
|
try {
|
|
5881
6029
|
validated = this.inputSchema.parse(input);
|
|
@@ -5907,9 +6055,52 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
5907
6055
|
}
|
|
5908
6056
|
} catch (error) {
|
|
5909
6057
|
if (error instanceof ExecutionError) throw error;
|
|
6058
|
+
if (error instanceof InvokeHttpError2 && error.status === 409) {
|
|
6059
|
+
throw new RuntimeBusyError(error.message);
|
|
6060
|
+
}
|
|
5910
6061
|
throw error instanceof Error ? error : new Error(String(error));
|
|
5911
6062
|
}
|
|
5912
6063
|
}
|
|
6064
|
+
/**
|
|
6065
|
+
* Waits until the sandbox runtime has no handler running. An aborted turn rejects on the host
|
|
6066
|
+
* at once, while its handler can keep running in the sandbox until it notices the abort, so call
|
|
6067
|
+
* this before reading state the handler writes, such as a transcript. Throws `RuntimeBusyError`
|
|
6068
|
+
* if a handler is still running, or the runtime doesn't answer, after `timeoutMs`.
|
|
6069
|
+
*/
|
|
6070
|
+
async waitForIdle(options = {}) {
|
|
6071
|
+
const { signal, timeoutMs = DEFAULT_IDLE_TIMEOUT_MS } = options;
|
|
6072
|
+
const connection = await this.resolveRuntimeConnection(options.sandboxId, {
|
|
6073
|
+
signal,
|
|
6074
|
+
reuseMatchingCachedConnection: true
|
|
6075
|
+
});
|
|
6076
|
+
const healthUrl = appendTrafficTokenToUrl(this.healthUrlFor(connection), connection);
|
|
6077
|
+
const deadline = Date.now() + timeoutMs;
|
|
6078
|
+
while (true) {
|
|
6079
|
+
let busy = true;
|
|
6080
|
+
try {
|
|
6081
|
+
const response = await awaitWithAbort(
|
|
6082
|
+
() => fetch(healthUrl, {
|
|
6083
|
+
headers: trafficTokenHeaders(connection),
|
|
6084
|
+
signal: signal === void 0 ? AbortSignal.timeout(SERVER_HEALTH_POLL_INTERVAL_MS * 5) : AbortSignal.any([signal, AbortSignal.timeout(SERVER_HEALTH_POLL_INTERVAL_MS * 5)])
|
|
6085
|
+
}),
|
|
6086
|
+
signal
|
|
6087
|
+
);
|
|
6088
|
+
if (response.ok) {
|
|
6089
|
+
const body = await awaitWithAbort(() => response.json(), signal);
|
|
6090
|
+
busy = body.ok !== true || body.busy === true;
|
|
6091
|
+
} else {
|
|
6092
|
+
await response.body?.cancel().catch(() => void 0);
|
|
6093
|
+
}
|
|
6094
|
+
} catch {
|
|
6095
|
+
throwIfAborted(signal);
|
|
6096
|
+
}
|
|
6097
|
+
if (!busy) return;
|
|
6098
|
+
if (Date.now() >= deadline) {
|
|
6099
|
+
throw new RuntimeBusyError(`Sandbox runtime still busy after ${timeoutMs}ms.`);
|
|
6100
|
+
}
|
|
6101
|
+
await delayWithAbort(SERVER_HEALTH_POLL_INTERVAL_MS, signal);
|
|
6102
|
+
}
|
|
6103
|
+
}
|
|
5913
6104
|
/**
|
|
5914
6105
|
* @deprecated Use `createSession()` and call `session.prompt(input)` instead.
|
|
5915
6106
|
* This compatibility wrapper creates one attached session, streams one turn,
|
|
@@ -5935,6 +6126,7 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
5935
6126
|
DeploymentError,
|
|
5936
6127
|
ExecutionError,
|
|
5937
6128
|
NeckbeardError,
|
|
6129
|
+
RuntimeBusyError,
|
|
5938
6130
|
SandboxClient,
|
|
5939
6131
|
ValidationError,
|
|
5940
6132
|
normalizeStackFramePath,
|
package/dist/index.d.cts
CHANGED
|
@@ -55,6 +55,32 @@ interface ModalSandboxConfig {
|
|
|
55
55
|
timeoutMs?: number;
|
|
56
56
|
cpu?: number;
|
|
57
57
|
memoryMiB?: number;
|
|
58
|
+
/**
|
|
59
|
+
* Regions the sandbox may run in, such as `['us']` or `['us-east']`. Modal
|
|
60
|
+
* otherwise places it in any region worldwide, and every file and command
|
|
61
|
+
* call pays the round trip. Pinned regions cost more; see docs/MODAL.md.
|
|
62
|
+
*/
|
|
63
|
+
regions?: string[];
|
|
64
|
+
/**
|
|
65
|
+
* Whether to block all sandbox network egress. Cannot be combined with
|
|
66
|
+
* non-empty allow lists.
|
|
67
|
+
*/
|
|
68
|
+
networkBlockAll?: boolean;
|
|
69
|
+
/**
|
|
70
|
+
* Comma-separated CIDR allow list for sandbox egress, any protocol.
|
|
71
|
+
*
|
|
72
|
+
* Example: '203.0.113.0/24,198.51.100.10/32'
|
|
73
|
+
*/
|
|
74
|
+
networkAllowList?: string;
|
|
75
|
+
/**
|
|
76
|
+
* Comma-separated domain allow list for sandbox egress. Modal matches the
|
|
77
|
+
* TLS SNI, so it only allows HTTPS (port 443) to these domains; when set, the
|
|
78
|
+
* image's apt sources are switched to HTTPS. Wildcards are supported with a
|
|
79
|
+
* leading `*.`. Traffic matching either allow list is allowed.
|
|
80
|
+
*
|
|
81
|
+
* Example: '*.example.com,api.openai.com'
|
|
82
|
+
*/
|
|
83
|
+
domainAllowList?: string;
|
|
58
84
|
}
|
|
59
85
|
interface ModalClientCredentials {
|
|
60
86
|
tokenId?: string;
|
|
@@ -127,6 +153,13 @@ declare class ExecutionError extends NeckbeardError {
|
|
|
127
153
|
readonly cause?: Error | undefined;
|
|
128
154
|
constructor(message: string, cause?: Error | undefined);
|
|
129
155
|
}
|
|
156
|
+
/**
|
|
157
|
+
* Error thrown when the sandbox runtime is still running an earlier handler, either because a
|
|
158
|
+
* turn was started while another was active or because `waitForIdle()` timed out.
|
|
159
|
+
*/
|
|
160
|
+
declare class RuntimeBusyError extends ExecutionError {
|
|
161
|
+
constructor(message: string);
|
|
162
|
+
}
|
|
130
163
|
/**
|
|
131
164
|
* Error thrown when required environment variables are missing.
|
|
132
165
|
*/
|
|
@@ -674,6 +707,17 @@ declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
|
|
|
674
707
|
*/
|
|
675
708
|
createSession(options?: CreateAttachedSessionOptions): Promise<AttachedAgentSession<TInput, TFrame>>;
|
|
676
709
|
private streamSessionPrompt;
|
|
710
|
+
/**
|
|
711
|
+
* Waits until the sandbox runtime has no handler running. An aborted turn rejects on the host
|
|
712
|
+
* at once, while its handler can keep running in the sandbox until it notices the abort, so call
|
|
713
|
+
* this before reading state the handler writes, such as a transcript. Throws `RuntimeBusyError`
|
|
714
|
+
* if a handler is still running, or the runtime doesn't answer, after `timeoutMs`.
|
|
715
|
+
*/
|
|
716
|
+
waitForIdle(options?: {
|
|
717
|
+
sandboxId?: string;
|
|
718
|
+
timeoutMs?: number;
|
|
719
|
+
signal?: AbortSignal;
|
|
720
|
+
}): Promise<void>;
|
|
677
721
|
/**
|
|
678
722
|
* @deprecated Use `createSession()` and call `session.prompt(input)` instead.
|
|
679
723
|
* This compatibility wrapper creates one attached session, streams one turn,
|
|
@@ -685,4 +729,4 @@ declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
|
|
|
685
729
|
}): AsyncGenerator<TFrame>;
|
|
686
730
|
}
|
|
687
731
|
|
|
688
|
-
export { Agent, type AgentConfig, type AgentKind, type AgentMode, type AgentRunContext, type AgentRunResult, type AgentSandboxContext, type AgentSessionHandler, type AttachedAgentSession, type BuildOptions, ConfigurationError, type CreateAttachedSessionOptions, DEFAULT_DEPENDENCIES, type DaytonaSandboxConfig, DeploymentError, type DockerSandboxConfig, type E2BSandboxConfig, ExecutionError, type FileDownload, type LocalDirectoryUpload, type ModalSandboxConfig, NeckbeardError, type NeckbeardNextConfigOptions, type OsDependencies, type ResolveAgentSourceFileOptions, type RunAgentConfig, SandboxClient, type SandboxClientConnectOptions, type SandboxClientCreateOptions, SandboxCommandOptions, SandboxCommandResult, type SandboxConfig, SandboxDetachedCommand, SandboxDetachedCommandOptions, type SandboxFileContent, type SandboxProvider, type ServerAgentConfig, type SessionAgentConfig, type SessionDurability, ValidationError, resolveAgentSourceFile, withNeckbeardNextConfig };
|
|
732
|
+
export { Agent, type AgentConfig, type AgentKind, type AgentMode, type AgentRunContext, type AgentRunResult, type AgentSandboxContext, type AgentSessionHandler, type AttachedAgentSession, type BuildOptions, ConfigurationError, type CreateAttachedSessionOptions, DEFAULT_DEPENDENCIES, type DaytonaSandboxConfig, DeploymentError, type DockerSandboxConfig, type E2BSandboxConfig, ExecutionError, type FileDownload, type LocalDirectoryUpload, type ModalSandboxConfig, NeckbeardError, type NeckbeardNextConfigOptions, type OsDependencies, type ResolveAgentSourceFileOptions, type RunAgentConfig, RuntimeBusyError, SandboxClient, type SandboxClientConnectOptions, type SandboxClientCreateOptions, SandboxCommandOptions, SandboxCommandResult, type SandboxConfig, SandboxDetachedCommand, SandboxDetachedCommandOptions, type SandboxFileContent, type SandboxProvider, type ServerAgentConfig, type SessionAgentConfig, type SessionDurability, ValidationError, resolveAgentSourceFile, withNeckbeardNextConfig };
|
package/dist/index.d.ts
CHANGED
|
@@ -55,6 +55,32 @@ interface ModalSandboxConfig {
|
|
|
55
55
|
timeoutMs?: number;
|
|
56
56
|
cpu?: number;
|
|
57
57
|
memoryMiB?: number;
|
|
58
|
+
/**
|
|
59
|
+
* Regions the sandbox may run in, such as `['us']` or `['us-east']`. Modal
|
|
60
|
+
* otherwise places it in any region worldwide, and every file and command
|
|
61
|
+
* call pays the round trip. Pinned regions cost more; see docs/MODAL.md.
|
|
62
|
+
*/
|
|
63
|
+
regions?: string[];
|
|
64
|
+
/**
|
|
65
|
+
* Whether to block all sandbox network egress. Cannot be combined with
|
|
66
|
+
* non-empty allow lists.
|
|
67
|
+
*/
|
|
68
|
+
networkBlockAll?: boolean;
|
|
69
|
+
/**
|
|
70
|
+
* Comma-separated CIDR allow list for sandbox egress, any protocol.
|
|
71
|
+
*
|
|
72
|
+
* Example: '203.0.113.0/24,198.51.100.10/32'
|
|
73
|
+
*/
|
|
74
|
+
networkAllowList?: string;
|
|
75
|
+
/**
|
|
76
|
+
* Comma-separated domain allow list for sandbox egress. Modal matches the
|
|
77
|
+
* TLS SNI, so it only allows HTTPS (port 443) to these domains; when set, the
|
|
78
|
+
* image's apt sources are switched to HTTPS. Wildcards are supported with a
|
|
79
|
+
* leading `*.`. Traffic matching either allow list is allowed.
|
|
80
|
+
*
|
|
81
|
+
* Example: '*.example.com,api.openai.com'
|
|
82
|
+
*/
|
|
83
|
+
domainAllowList?: string;
|
|
58
84
|
}
|
|
59
85
|
interface ModalClientCredentials {
|
|
60
86
|
tokenId?: string;
|
|
@@ -127,6 +153,13 @@ declare class ExecutionError extends NeckbeardError {
|
|
|
127
153
|
readonly cause?: Error | undefined;
|
|
128
154
|
constructor(message: string, cause?: Error | undefined);
|
|
129
155
|
}
|
|
156
|
+
/**
|
|
157
|
+
* Error thrown when the sandbox runtime is still running an earlier handler, either because a
|
|
158
|
+
* turn was started while another was active or because `waitForIdle()` timed out.
|
|
159
|
+
*/
|
|
160
|
+
declare class RuntimeBusyError extends ExecutionError {
|
|
161
|
+
constructor(message: string);
|
|
162
|
+
}
|
|
130
163
|
/**
|
|
131
164
|
* Error thrown when required environment variables are missing.
|
|
132
165
|
*/
|
|
@@ -674,6 +707,17 @@ declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
|
|
|
674
707
|
*/
|
|
675
708
|
createSession(options?: CreateAttachedSessionOptions): Promise<AttachedAgentSession<TInput, TFrame>>;
|
|
676
709
|
private streamSessionPrompt;
|
|
710
|
+
/**
|
|
711
|
+
* Waits until the sandbox runtime has no handler running. An aborted turn rejects on the host
|
|
712
|
+
* at once, while its handler can keep running in the sandbox until it notices the abort, so call
|
|
713
|
+
* this before reading state the handler writes, such as a transcript. Throws `RuntimeBusyError`
|
|
714
|
+
* if a handler is still running, or the runtime doesn't answer, after `timeoutMs`.
|
|
715
|
+
*/
|
|
716
|
+
waitForIdle(options?: {
|
|
717
|
+
sandboxId?: string;
|
|
718
|
+
timeoutMs?: number;
|
|
719
|
+
signal?: AbortSignal;
|
|
720
|
+
}): Promise<void>;
|
|
677
721
|
/**
|
|
678
722
|
* @deprecated Use `createSession()` and call `session.prompt(input)` instead.
|
|
679
723
|
* This compatibility wrapper creates one attached session, streams one turn,
|
|
@@ -685,4 +729,4 @@ declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
|
|
|
685
729
|
}): AsyncGenerator<TFrame>;
|
|
686
730
|
}
|
|
687
731
|
|
|
688
|
-
export { Agent, type AgentConfig, type AgentKind, type AgentMode, type AgentRunContext, type AgentRunResult, type AgentSandboxContext, type AgentSessionHandler, type AttachedAgentSession, type BuildOptions, ConfigurationError, type CreateAttachedSessionOptions, DEFAULT_DEPENDENCIES, type DaytonaSandboxConfig, DeploymentError, type DockerSandboxConfig, type E2BSandboxConfig, ExecutionError, type FileDownload, type LocalDirectoryUpload, type ModalSandboxConfig, NeckbeardError, type NeckbeardNextConfigOptions, type OsDependencies, type ResolveAgentSourceFileOptions, type RunAgentConfig, SandboxClient, type SandboxClientConnectOptions, type SandboxClientCreateOptions, SandboxCommandOptions, SandboxCommandResult, type SandboxConfig, SandboxDetachedCommand, SandboxDetachedCommandOptions, type SandboxFileContent, type SandboxProvider, type ServerAgentConfig, type SessionAgentConfig, type SessionDurability, ValidationError, resolveAgentSourceFile, withNeckbeardNextConfig };
|
|
732
|
+
export { Agent, type AgentConfig, type AgentKind, type AgentMode, type AgentRunContext, type AgentRunResult, type AgentSandboxContext, type AgentSessionHandler, type AttachedAgentSession, type BuildOptions, ConfigurationError, type CreateAttachedSessionOptions, DEFAULT_DEPENDENCIES, type DaytonaSandboxConfig, DeploymentError, type DockerSandboxConfig, type E2BSandboxConfig, ExecutionError, type FileDownload, type LocalDirectoryUpload, type ModalSandboxConfig, NeckbeardError, type NeckbeardNextConfigOptions, type OsDependencies, type ResolveAgentSourceFileOptions, type RunAgentConfig, RuntimeBusyError, SandboxClient, type SandboxClientConnectOptions, type SandboxClientCreateOptions, SandboxCommandOptions, SandboxCommandResult, type SandboxConfig, SandboxDetachedCommand, SandboxDetachedCommandOptions, type SandboxFileContent, type SandboxProvider, type ServerAgentConfig, type SessionAgentConfig, type SessionDurability, ValidationError, resolveAgentSourceFile, withNeckbeardNextConfig };
|
package/dist/index.js
CHANGED
|
@@ -17,8 +17,9 @@ import {
|
|
|
17
17
|
uploadDaytonaFile
|
|
18
18
|
} from "./chunk-6P5I7ZCH.js";
|
|
19
19
|
import {
|
|
20
|
+
RUNTIME_ABORT_GRACE_MS,
|
|
20
21
|
RUNTIME_PROTOCOL_VERSION
|
|
21
|
-
} from "./chunk-
|
|
22
|
+
} from "./chunk-6GCQOKYI.js";
|
|
22
23
|
import "./chunk-33IXN6MM.js";
|
|
23
24
|
|
|
24
25
|
// src/index.ts
|
|
@@ -42,10 +43,11 @@ import {
|
|
|
42
43
|
sep,
|
|
43
44
|
win32
|
|
44
45
|
} from "path";
|
|
46
|
+
import { randomUUID } from "crypto";
|
|
45
47
|
import { builtinModules, createRequire as createRequire2 } from "module";
|
|
46
48
|
|
|
47
49
|
// src/runtime/server-source.generated.ts
|
|
48
|
-
var RUNTIME_SERVER_SOURCE = '// src/runtime/server.ts\nimport { createServer } from "node:http";\nimport { readFileSync } from "node:fs";\nimport { fileURLToPath } from "node:url";\nimport { dirname, join } from "node:path";\nimport { once } from "node:events";\n\n// src/serialized-error.ts\nfunction serializeError(error) {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n ...error.stack === void 0 ? {} : { stack: error.stack }\n };\n }\n return { message: String(error) };\n}\n\n// src/runtime/protocol.ts\nvar RUNTIME_PROTOCOL_VERSION = 1;\n\n// src/timeout.ts\nfunction settleOperation(operation, options = {}) {\n const { abort, timeout } = options;\n if (abort?.signal.aborted) throw abort.createError();\n if (!abort && !timeout) {\n try {\n return Promise.resolve(operation());\n } catch (error) {\n return Promise.reject(error);\n }\n }\n return new Promise((resolve, reject) => {\n let settled = false;\n let timer;\n const cleanup = () => {\n if (timer !== void 0) {\n clearTimeout(timer);\n timer = void 0;\n }\n abort?.signal.removeEventListener("abort", onAbort);\n };\n const settle = (callback) => {\n if (settled) return;\n settled = true;\n cleanup();\n callback();\n };\n const onAbort = () => settle(() => reject(abort.createError()));\n abort?.signal.addEventListener("abort", onAbort, { once: true });\n if (timeout) {\n timer = setTimeout(\n () => settle(() => reject(timeout.createError())),\n timeout.timeoutMs\n );\n }\n let task;\n try {\n task = operation();\n } catch (error) {\n settle(() => reject(error));\n return;\n }\n void Promise.resolve(task).then(\n (value) => settle(() => resolve(value)),\n (error) => settle(() => reject(error))\n );\n });\n}\n\n// src/runtime/server.ts\nvar CONFIG_PATH = join(dirname(fileURLToPath(import.meta.url)), "server-config.json");\nvar CONFIG = JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));\nvar MAX_REQUEST_BODY_BYTES = 4 * 1024 * 1024;\nvar DEFAULT_SSE_HEARTBEAT_INTERVAL_MS = 15e3;\nvar RequestBodyTooLargeError = class extends Error {\n constructor(limitBytes) {\n super(`request body exceeds ${limitBytes} bytes`);\n this.name = "RequestBodyTooLargeError";\n }\n};\nfunction createLogger() {\n return {\n debug: (message, ...args) => console.log("[DEBUG]", message, ...args),\n info: (message, ...args) => console.log("[INFO]", message, ...args),\n warn: (message, ...args) => console.warn("[WARN]", message, ...args),\n error: (message, ...args) => console.error("[ERROR]", message, ...args)\n };\n}\nfunction sendJson(res, status, body) {\n res.writeHead(status, { "content-type": "application/json" });\n res.end(JSON.stringify(body));\n}\nfunction getSseHeartbeatIntervalMs() {\n const raw = process.env.NECKBEARD_RUNTIME_SSE_HEARTBEAT_MS;\n if (!raw) return DEFAULT_SSE_HEARTBEAT_INTERVAL_MS;\n const parsed = Number(raw);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_SSE_HEARTBEAT_INTERVAL_MS;\n}\nfunction sendSseComment(res, comment) {\n if (res.writableEnded || res.destroyed) return;\n res.write(`: ${comment}\n\n`);\n}\nasync function sendSseFrame(res, event) {\n const canContinue = res.write(`data: ${JSON.stringify(event)}\n\n`);\n if (!canContinue) {\n await once(res, "drain");\n }\n}\nasync function readRequestBody(req, maxBytes = MAX_REQUEST_BODY_BYTES) {\n const chunks = [];\n let totalBytes = 0;\n for await (const chunk of req) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n totalBytes += buffer.byteLength;\n if (totalBytes > maxBytes) {\n throw new RequestBodyTooLargeError(maxBytes);\n }\n chunks.push(buffer);\n }\n return Buffer.concat(chunks).toString("utf-8");\n}\nfunction createTimeoutError(maxDurationMs) {\n const error = new Error(`Agent invocation exceeded maxDuration (${maxDurationMs}ms)`);\n error.name = "TimeoutError";\n return error;\n}\nasync function rejectOnAbort(operation, signal, maxDurationMs) {\n return settleOperation(operation, {\n abort: {\n signal,\n createError: () => createTimeoutError(maxDurationMs)\n }\n });\n}\nasync function loadAgent() {\n const mod = await import(new URL("./agent.mjs", import.meta.url).href);\n const agent = (mod.default && (mod.default._run || mod.default._server) ? mod.default : null) || Object.values(mod).find(\n (value) => value && typeof value === "object" && ("_run" in value || "_server" in value)\n );\n if (!agent || typeof agent !== "object") {\n throw new Error(\n `No agent found in agent.mjs. Exports: ${Object.keys(mod).join(", ")}`\n );\n }\n return agent;\n}\nasync function main() {\n const agent = await loadAgent();\n const server = createServer(async (req, res) => {\n try {\n const url = new URL(req.url ?? "/", "http://localhost");\n if (url.pathname === "/health" && req.method === "GET") {\n return sendJson(res, 200, {\n ok: true,\n protocolVersion: RUNTIME_PROTOCOL_VERSION\n });\n }\n if (url.pathname === "/shutdown" && req.method === "POST") {\n sendJson(res, 200, { ok: true });\n setTimeout(() => shutdown(), 10).unref();\n return;\n }\n if (url.pathname === "/invoke" && req.method === "POST") {\n let rawBody;\n try {\n rawBody = await readRequestBody(req);\n } catch (error) {\n if (error instanceof RequestBodyTooLargeError) {\n return sendJson(res, 413, { error: error.message });\n }\n throw error;\n }\n let requestBody;\n try {\n requestBody = JSON.parse(rawBody);\n } catch {\n return sendJson(res, 400, { error: "invalid JSON body" });\n }\n if (!requestBody || typeof requestBody !== "object" || typeof requestBody.invocationId !== "string") {\n return sendJson(res, 400, { error: "invalid invoke request" });\n }\n let validatedInput;\n try {\n validatedInput = agent.inputSchema.parse(requestBody.input);\n } catch (error) {\n return sendJson(res, 400, {\n error: `input validation failed: ${serializeError(error).message}`\n });\n }\n res.writeHead(200, {\n "content-type": "text/event-stream",\n "cache-control": "no-cache, no-transform",\n connection: "keep-alive",\n "x-accel-buffering": "no"\n });\n const controller = new AbortController();\n req.on("aborted", () => controller.abort());\n res.on("close", () => {\n if (!res.writableEnded) {\n controller.abort();\n }\n });\n const startedAt = Date.now();\n let sequence = 0;\n const timeout = setTimeout(() => controller.abort(), CONFIG.maxDurationMs);\n const invocationId = requestBody.invocationId;\n const heartbeat = setInterval(() => {\n try {\n sendSseComment(res, `heartbeat ${Date.now()}`);\n } catch {\n controller.abort();\n }\n }, getSseHeartbeatIntervalMs());\n heartbeat.unref();\n const emitHarnessEvent = async (event) => {\n if (!res.writableEnded) {\n await sendSseFrame(res, {\n protocolVersion: RUNTIME_PROTOCOL_VERSION,\n sequence: sequence++,\n timestamp: (/* @__PURE__ */ new Date()).toISOString(),\n elapsedMs: Date.now() - startedAt,\n ...event\n });\n }\n };\n const ctx = {\n executionId: invocationId,\n signal: controller.signal,\n env: process.env,\n sandbox: CONFIG.sandboxContext,\n logger: createLogger()\n };\n try {\n await emitHarnessEvent({ kind: "started", invocationId });\n if (agent._server) {\n await rejectOnAbort(\n () => agent._server.handler({\n input: validatedInput,\n ctx,\n signal: controller.signal,\n emit: async (data) => {\n const validatedFrame = agent._server?.frameSchema ? agent._server.frameSchema.parse(data) : data;\n await emitHarnessEvent({ kind: "frame", invocationId, data: validatedFrame });\n }\n }),\n controller.signal,\n CONFIG.maxDurationMs\n );\n } else if (agent._run) {\n const output = await rejectOnAbort(\n () => agent._run(validatedInput, ctx),\n controller.signal,\n CONFIG.maxDurationMs\n );\n const validatedOutput = agent.outputSchema ? agent.outputSchema.parse(output) : output;\n await emitHarnessEvent({ kind: "output", invocationId, output: validatedOutput });\n } else {\n throw new Error("Agent has neither a run handler nor a server handler.");\n }\n await emitHarnessEvent({ kind: "done", invocationId });\n } catch (error) {\n await emitHarnessEvent({ kind: "error", invocationId, error: serializeError(error) });\n } finally {\n clearInterval(heartbeat);\n clearTimeout(timeout);\n if (!res.writableEnded) {\n res.end();\n }\n }\n return;\n }\n return sendJson(res, 404, { error: "not found" });\n } catch (error) {\n console.error("[neckbeard-server] unexpected error", error);\n if (!res.headersSent) {\n sendJson(res, 500, { error: "internal error" });\n } else if (!res.writableEnded) {\n res.end();\n }\n }\n });\n function shutdown() {\n console.log("[neckbeard-server] shutting down");\n server.close(() => process.exit(0));\n setTimeout(() => process.exit(0), 5e3).unref();\n }\n server.listen(CONFIG.port, "0.0.0.0", () => {\n console.log(`[neckbeard-server] listening on port ${CONFIG.port}`);\n });\n process.on("SIGTERM", shutdown);\n process.on("SIGINT", shutdown);\n}\nmain().catch((error) => {\n console.error("[neckbeard-server] failed to start", error);\n process.exit(1);\n});\n';
|
|
50
|
+
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';
|
|
49
51
|
|
|
50
52
|
// src/attached-session.ts
|
|
51
53
|
function linkAbortSignals(signals) {
|
|
@@ -174,6 +176,89 @@ function createAttachedAgentSession(options) {
|
|
|
174
176
|
return new AttachedAgentSessionImpl(options);
|
|
175
177
|
}
|
|
176
178
|
|
|
179
|
+
// src/tar.ts
|
|
180
|
+
import { Buffer as Buffer2 } from "buffer";
|
|
181
|
+
import { promisify } from "util";
|
|
182
|
+
import { gzip } from "zlib";
|
|
183
|
+
var gzipAsync = promisify(gzip);
|
|
184
|
+
var BLOCK_SIZE = 512;
|
|
185
|
+
var MAX_OCTAL_SIZE = 8589934591;
|
|
186
|
+
function writeString(header2, value, offset, length) {
|
|
187
|
+
header2.write(value, offset, length, "utf8");
|
|
188
|
+
}
|
|
189
|
+
function writeOctal(header2, value, offset, length) {
|
|
190
|
+
header2.write(`${value.toString(8).padStart(length - 1, "0")}\0`, offset, length, "ascii");
|
|
191
|
+
}
|
|
192
|
+
function splitUstarPath(path) {
|
|
193
|
+
if (Buffer2.byteLength(path) <= 100) return { name: path, prefix: "" };
|
|
194
|
+
for (let index = path.indexOf("/"); index !== -1; index = path.indexOf("/", index + 1)) {
|
|
195
|
+
const prefix = path.slice(0, index);
|
|
196
|
+
const name = path.slice(index + 1);
|
|
197
|
+
if (Buffer2.byteLength(prefix) <= 155 && Buffer2.byteLength(name) <= 100 && name) {
|
|
198
|
+
return { name, prefix };
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
return void 0;
|
|
202
|
+
}
|
|
203
|
+
function header(options) {
|
|
204
|
+
if (options.size > MAX_OCTAL_SIZE) {
|
|
205
|
+
throw new Error(`Archive entry ${options.name} is too large.`);
|
|
206
|
+
}
|
|
207
|
+
const block = Buffer2.alloc(BLOCK_SIZE);
|
|
208
|
+
writeString(block, options.name, 0, 100);
|
|
209
|
+
writeOctal(block, options.mode, 100, 8);
|
|
210
|
+
writeOctal(block, 0, 108, 8);
|
|
211
|
+
writeOctal(block, 0, 116, 8);
|
|
212
|
+
writeOctal(block, options.size, 124, 12);
|
|
213
|
+
writeOctal(block, options.mtime, 136, 12);
|
|
214
|
+
block.fill(" ", 148, 156);
|
|
215
|
+
writeString(block, options.type, 156, 1);
|
|
216
|
+
writeString(block, "ustar\0", 257, 6);
|
|
217
|
+
writeString(block, "00", 263, 2);
|
|
218
|
+
writeString(block, options.prefix ?? "", 345, 155);
|
|
219
|
+
let checksum = 0;
|
|
220
|
+
for (const byte of block) checksum += byte;
|
|
221
|
+
block.write(`${checksum.toString(8).padStart(6, "0")}\0 `, 148, 8, "ascii");
|
|
222
|
+
return block;
|
|
223
|
+
}
|
|
224
|
+
function padding(size) {
|
|
225
|
+
return Buffer2.alloc((BLOCK_SIZE - size % BLOCK_SIZE) % BLOCK_SIZE);
|
|
226
|
+
}
|
|
227
|
+
function paxPathRecord(path) {
|
|
228
|
+
const body = ` path=${path}
|
|
229
|
+
`;
|
|
230
|
+
let length = Buffer2.byteLength(body);
|
|
231
|
+
while (String(length).length + Buffer2.byteLength(body) !== length) {
|
|
232
|
+
length = String(length).length + Buffer2.byteLength(body);
|
|
233
|
+
}
|
|
234
|
+
return Buffer2.from(`${length}${body}`);
|
|
235
|
+
}
|
|
236
|
+
async function createTarGz(entries, mtime = Math.floor(Date.now() / 1e3)) {
|
|
237
|
+
const chunks = [];
|
|
238
|
+
for (const entry of entries) {
|
|
239
|
+
const isDirectory = entry.content === void 0;
|
|
240
|
+
const path = isDirectory ? `${entry.path.replace(/\/+$/u, "")}/` : entry.path;
|
|
241
|
+
const size = entry.content?.byteLength ?? 0;
|
|
242
|
+
const type = isDirectory ? "5" : "0";
|
|
243
|
+
const mode = isDirectory ? 493 : 420;
|
|
244
|
+
const split = splitUstarPath(path);
|
|
245
|
+
if (split) {
|
|
246
|
+
chunks.push(header({ ...split, mode, size, mtime, type }));
|
|
247
|
+
} else {
|
|
248
|
+
const record = paxPathRecord(path);
|
|
249
|
+
chunks.push(header({ name: "PaxHeader", mode: 420, size: record.byteLength, mtime, type: "x" }));
|
|
250
|
+
chunks.push(record, padding(record.byteLength));
|
|
251
|
+
chunks.push(header({ name: path.slice(-100).replace(/^\/+/u, ""), mode, size, mtime, type }));
|
|
252
|
+
}
|
|
253
|
+
if (entry.content) {
|
|
254
|
+
chunks.push(Buffer2.from(entry.content.buffer, entry.content.byteOffset, entry.content.byteLength));
|
|
255
|
+
chunks.push(padding(size));
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
chunks.push(Buffer2.alloc(BLOCK_SIZE * 2));
|
|
259
|
+
return gzipAsync(Buffer2.concat(chunks));
|
|
260
|
+
}
|
|
261
|
+
|
|
177
262
|
// src/providers/types.ts
|
|
178
263
|
function createProviderSandboxPaths(provider, homeDir, workDir) {
|
|
179
264
|
const agentDir = `${homeDir}/agent`;
|
|
@@ -642,8 +727,21 @@ function getModalSdk() {
|
|
|
642
727
|
// src/providers/modal.ts
|
|
643
728
|
var MODAL_DEFAULT_TEMPLATE = "node:22-bookworm";
|
|
644
729
|
var MODAL_DEFAULT_TIMEOUT_MS = 60 * 60 * 1e3;
|
|
730
|
+
function parseModalAllowList(value) {
|
|
731
|
+
return (value ?? "").split(",").map((entry) => entry.trim()).filter(Boolean);
|
|
732
|
+
}
|
|
733
|
+
function modalNetworkOptions(options) {
|
|
734
|
+
if (options.networkBlockAll) return { blockNetwork: true };
|
|
735
|
+
const cidrs = parseModalAllowList(options.networkAllowList);
|
|
736
|
+
const domains = parseModalAllowList(options.domainAllowList);
|
|
737
|
+
return {
|
|
738
|
+
...cidrs.length > 0 ? { outboundCidrAllowlist: cidrs } : {},
|
|
739
|
+
...domains.length > 0 ? { outboundDomainAllowlist: domains } : {}
|
|
740
|
+
};
|
|
741
|
+
}
|
|
645
742
|
function validateModalOptions(options, mode, failure) {
|
|
646
|
-
|
|
743
|
+
const { networkBlockAll, networkAllowList, domainAllowList, regions, ...rest } = options;
|
|
744
|
+
validateProviderOptions("Modal", mode === "connect" ? options : rest, ["environment", ...mode === "connect" ? ["sandboxId", "tokenId", "tokenSecret"] : [
|
|
647
745
|
"template",
|
|
648
746
|
"appName",
|
|
649
747
|
"timeoutMs",
|
|
@@ -651,6 +749,20 @@ function validateModalOptions(options, mode, failure) {
|
|
|
651
749
|
"memoryMiB",
|
|
652
750
|
...mode === "create" ? ["tokenId", "tokenSecret", "envs"] : []
|
|
653
751
|
]], failure);
|
|
752
|
+
if (regions !== void 0 && (!Array.isArray(regions) || regions.length === 0 || regions.some((region) => typeof region !== "string" || !/^[a-z0-9-]+$/u.test(region)))) {
|
|
753
|
+
throw failure('Modal regions must be a non-empty array of region names such as "us" or "us-east".');
|
|
754
|
+
}
|
|
755
|
+
if (networkBlockAll !== void 0 && typeof networkBlockAll !== "boolean") {
|
|
756
|
+
throw failure("Modal networkBlockAll must be a boolean.");
|
|
757
|
+
}
|
|
758
|
+
for (const [key, value] of [["networkAllowList", networkAllowList], ["domainAllowList", domainAllowList]]) {
|
|
759
|
+
if (value !== void 0 && (typeof value !== "string" || parseModalAllowList(value).some((entry) => /[\s\0]/u.test(entry)))) {
|
|
760
|
+
throw failure(`Modal ${key} must be a comma-separated string without whitespace or null bytes in entries.`);
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
if (networkBlockAll && (parseModalAllowList(networkAllowList).length > 0 || parseModalAllowList(domainAllowList).length > 0)) {
|
|
764
|
+
throw failure("Modal networkBlockAll cannot be combined with non-empty allow lists.");
|
|
765
|
+
}
|
|
654
766
|
if (mode === "connect" && !("sandboxId" in options && options.sandboxId)) {
|
|
655
767
|
throw failure("Modal sandboxId is required.");
|
|
656
768
|
}
|
|
@@ -729,12 +841,19 @@ var ModalSandboxHandle = class _ModalSandboxHandle {
|
|
|
729
841
|
let sandbox;
|
|
730
842
|
try {
|
|
731
843
|
const app = await client.apps.fromName(options.appName ?? "agent-neckbeard", { createIfMissing: true });
|
|
844
|
+
const network = modalNetworkOptions(options);
|
|
732
845
|
const image = client.images.fromRegistry(options.template ?? MODAL_DEFAULT_TEMPLATE).dockerfileCommands([
|
|
733
846
|
"USER root",
|
|
734
847
|
"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/*",
|
|
848
|
+
// The runtime starts with a fixed PATH, so images with Node elsewhere (say nvm) need links.
|
|
849
|
+
'RUN for bin in node npm npx; do target="$(command -v "$bin" || true)"; if [ -n "$target" ] && [ ! -e "/usr/local/bin/$bin" ]; then ln -s "$target" "/usr/local/bin/$bin"; fi; done',
|
|
850
|
+
// The domain allow list only passes TLS, so apt installs in the sandbox need HTTPS sources.
|
|
851
|
+
...network.outboundDomainAllowlist ? ["RUN find /etc/apt -name '*.list' -o -name '*.sources' | xargs -r sed -i 's|http://|https://|g'"] : [],
|
|
735
852
|
"WORKDIR /root"
|
|
736
853
|
]);
|
|
737
854
|
sandbox = await client.sandboxes.create(app, image, {
|
|
855
|
+
...network,
|
|
856
|
+
...options.regions ? { regions: options.regions } : {},
|
|
738
857
|
timeoutMs: options.timeoutMs ?? MODAL_DEFAULT_TIMEOUT_MS,
|
|
739
858
|
cpu: options.cpu,
|
|
740
859
|
memoryMiB: options.memoryMiB,
|
|
@@ -1190,6 +1309,7 @@ var DEFAULT_SERVER_PORT = 3e3;
|
|
|
1190
1309
|
var SERVER_HEALTH_TIMEOUT_MS = 12e4;
|
|
1191
1310
|
var SERVER_RECONNECT_HEALTH_TIMEOUT_MS = 3e3;
|
|
1192
1311
|
var SERVER_HEALTH_POLL_INTERVAL_MS = 1e3;
|
|
1312
|
+
var DEFAULT_IDLE_TIMEOUT_MS = RUNTIME_ABORT_GRACE_MS + 3e4;
|
|
1193
1313
|
var SERVER_FAILURE_DIAGNOSTIC_TIMEOUT_MS = 1e3;
|
|
1194
1314
|
var NATIVE_EXT_RE = /\.(node|wasm|gyp|c|cc|cpp|cxx|h|hpp|hxx)$/i;
|
|
1195
1315
|
var TRACEABLE_SOURCE_EXT_RE = /\.(cjs|cts|js|jsx|mjs|mts|ts|tsx)$/i;
|
|
@@ -1220,6 +1340,12 @@ var ExecutionError = class extends NeckbeardError {
|
|
|
1220
1340
|
this.name = "ExecutionError";
|
|
1221
1341
|
}
|
|
1222
1342
|
};
|
|
1343
|
+
var RuntimeBusyError = class extends ExecutionError {
|
|
1344
|
+
constructor(message) {
|
|
1345
|
+
super(message);
|
|
1346
|
+
this.name = "RuntimeBusyError";
|
|
1347
|
+
}
|
|
1348
|
+
};
|
|
1223
1349
|
var ConfigurationError = class extends NeckbeardError {
|
|
1224
1350
|
constructor(message) {
|
|
1225
1351
|
super(message);
|
|
@@ -2938,14 +3064,21 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
2938
3064
|
}
|
|
2939
3065
|
}
|
|
2940
3066
|
}
|
|
2941
|
-
|
|
2942
|
-
|
|
2943
|
-
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
|
|
2947
|
-
|
|
3067
|
+
if (localDirectoryUploads.directories.length > 0 || localDirectoryUploads.files.length > 0) {
|
|
3068
|
+
const archivePath = posix.join(paths.agentDir, `.neckbeard-local-directories-${randomUUID()}.tar.gz`);
|
|
3069
|
+
await sandbox.writeFile(archivePath, await createTarGz([
|
|
3070
|
+
...localDirectoryUploads.directories.map((directory) => ({ path: directory })),
|
|
3071
|
+
...localDirectoryUploads.files.map((file) => ({ path: file.targetPath, content: file.content }))
|
|
3072
|
+
]));
|
|
3073
|
+
const extractResult = await sandbox.runCommand(
|
|
3074
|
+
`tar -xzf ${shellQuote(archivePath)} --no-same-owner -C ${shellQuote(paths.agentDir)} && rm -f ${shellQuote(archivePath)}`,
|
|
3075
|
+
{ timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS2 }
|
|
2948
3076
|
);
|
|
3077
|
+
if (extractResult.exitCode !== 0) {
|
|
3078
|
+
throw new DeploymentError(
|
|
3079
|
+
`Failed to extract local directories: ${extractResult.stderr || extractResult.stdout}`
|
|
3080
|
+
);
|
|
3081
|
+
}
|
|
2949
3082
|
}
|
|
2950
3083
|
await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
|
|
2951
3084
|
await sandbox.writeFile(paths.serverModule, RUNTIME_SERVER_SOURCE);
|
|
@@ -3059,7 +3192,7 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
3059
3192
|
} catch (error) {
|
|
3060
3193
|
throw new ValidationError("Input validation failed.", asError(error));
|
|
3061
3194
|
}
|
|
3062
|
-
const { invokeServer } = await import("./invoke-client-
|
|
3195
|
+
const { invokeServer } = await import("./invoke-client-YKWOTQWG.js");
|
|
3063
3196
|
let output;
|
|
3064
3197
|
let sawOutput = false;
|
|
3065
3198
|
for await (const event of invokeServer(validatedInput, {
|
|
@@ -3067,7 +3200,7 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
3067
3200
|
provider: connection.provider,
|
|
3068
3201
|
trafficToken: getTrafficToken(connection),
|
|
3069
3202
|
invocationId: executionId,
|
|
3070
|
-
signal: AbortSignal.timeout(this.maxDuration * 1e3 + 5e3)
|
|
3203
|
+
signal: AbortSignal.timeout(this.maxDuration * 1e3 + RUNTIME_ABORT_GRACE_MS + 5e3)
|
|
3071
3204
|
})) {
|
|
3072
3205
|
if (event.kind === "error") {
|
|
3073
3206
|
const err = new ExecutionError(event.error.message);
|
|
@@ -3094,6 +3227,10 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
3094
3227
|
}
|
|
3095
3228
|
return { ok: true, executionId, output: validated };
|
|
3096
3229
|
} catch (err) {
|
|
3230
|
+
const { InvokeHttpError } = await import("./invoke-client-YKWOTQWG.js");
|
|
3231
|
+
if (err instanceof InvokeHttpError && err.status === 409) {
|
|
3232
|
+
return { ok: false, executionId, error: new RuntimeBusyError(err.message) };
|
|
3233
|
+
}
|
|
3097
3234
|
return { ok: false, executionId, error: err instanceof Error ? err : new Error(String(err)) };
|
|
3098
3235
|
}
|
|
3099
3236
|
}
|
|
@@ -3166,7 +3303,7 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
3166
3303
|
signal,
|
|
3167
3304
|
reuseMatchingCachedConnection: true
|
|
3168
3305
|
});
|
|
3169
|
-
const { invokeServer } = await import("./invoke-client-
|
|
3306
|
+
const { invokeServer, InvokeHttpError } = await import("./invoke-client-YKWOTQWG.js");
|
|
3170
3307
|
let validated;
|
|
3171
3308
|
try {
|
|
3172
3309
|
validated = this.inputSchema.parse(input);
|
|
@@ -3198,9 +3335,52 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
3198
3335
|
}
|
|
3199
3336
|
} catch (error) {
|
|
3200
3337
|
if (error instanceof ExecutionError) throw error;
|
|
3338
|
+
if (error instanceof InvokeHttpError && error.status === 409) {
|
|
3339
|
+
throw new RuntimeBusyError(error.message);
|
|
3340
|
+
}
|
|
3201
3341
|
throw error instanceof Error ? error : new Error(String(error));
|
|
3202
3342
|
}
|
|
3203
3343
|
}
|
|
3344
|
+
/**
|
|
3345
|
+
* Waits until the sandbox runtime has no handler running. An aborted turn rejects on the host
|
|
3346
|
+
* at once, while its handler can keep running in the sandbox until it notices the abort, so call
|
|
3347
|
+
* this before reading state the handler writes, such as a transcript. Throws `RuntimeBusyError`
|
|
3348
|
+
* if a handler is still running, or the runtime doesn't answer, after `timeoutMs`.
|
|
3349
|
+
*/
|
|
3350
|
+
async waitForIdle(options = {}) {
|
|
3351
|
+
const { signal, timeoutMs = DEFAULT_IDLE_TIMEOUT_MS } = options;
|
|
3352
|
+
const connection = await this.resolveRuntimeConnection(options.sandboxId, {
|
|
3353
|
+
signal,
|
|
3354
|
+
reuseMatchingCachedConnection: true
|
|
3355
|
+
});
|
|
3356
|
+
const healthUrl = appendTrafficTokenToUrl(this.healthUrlFor(connection), connection);
|
|
3357
|
+
const deadline = Date.now() + timeoutMs;
|
|
3358
|
+
while (true) {
|
|
3359
|
+
let busy = true;
|
|
3360
|
+
try {
|
|
3361
|
+
const response = await awaitWithAbort(
|
|
3362
|
+
() => fetch(healthUrl, {
|
|
3363
|
+
headers: trafficTokenHeaders(connection),
|
|
3364
|
+
signal: signal === void 0 ? AbortSignal.timeout(SERVER_HEALTH_POLL_INTERVAL_MS * 5) : AbortSignal.any([signal, AbortSignal.timeout(SERVER_HEALTH_POLL_INTERVAL_MS * 5)])
|
|
3365
|
+
}),
|
|
3366
|
+
signal
|
|
3367
|
+
);
|
|
3368
|
+
if (response.ok) {
|
|
3369
|
+
const body = await awaitWithAbort(() => response.json(), signal);
|
|
3370
|
+
busy = body.ok !== true || body.busy === true;
|
|
3371
|
+
} else {
|
|
3372
|
+
await response.body?.cancel().catch(() => void 0);
|
|
3373
|
+
}
|
|
3374
|
+
} catch {
|
|
3375
|
+
throwIfAborted(signal);
|
|
3376
|
+
}
|
|
3377
|
+
if (!busy) return;
|
|
3378
|
+
if (Date.now() >= deadline) {
|
|
3379
|
+
throw new RuntimeBusyError(`Sandbox runtime still busy after ${timeoutMs}ms.`);
|
|
3380
|
+
}
|
|
3381
|
+
await delayWithAbort(SERVER_HEALTH_POLL_INTERVAL_MS, signal);
|
|
3382
|
+
}
|
|
3383
|
+
}
|
|
3204
3384
|
/**
|
|
3205
3385
|
* @deprecated Use `createSession()` and call `session.prompt(input)` instead.
|
|
3206
3386
|
* This compatibility wrapper creates one attached session, streams one turn,
|
|
@@ -3225,6 +3405,7 @@ export {
|
|
|
3225
3405
|
DeploymentError,
|
|
3226
3406
|
ExecutionError,
|
|
3227
3407
|
NeckbeardError,
|
|
3408
|
+
RuntimeBusyError,
|
|
3228
3409
|
SandboxClient,
|
|
3229
3410
|
ValidationError,
|
|
3230
3411
|
normalizeStackFramePath,
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
isHarnessEvent
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-6GCQOKYI.js";
|
|
4
4
|
import "./chunk-33IXN6MM.js";
|
|
5
5
|
|
|
6
6
|
// src/sse-framing.ts
|
|
@@ -44,6 +44,13 @@ function parseFrame(raw) {
|
|
|
44
44
|
}
|
|
45
45
|
|
|
46
46
|
// src/invoke-client.ts
|
|
47
|
+
var InvokeHttpError = class extends Error {
|
|
48
|
+
constructor(status, message) {
|
|
49
|
+
super(message);
|
|
50
|
+
this.status = status;
|
|
51
|
+
this.name = "InvokeHttpError";
|
|
52
|
+
}
|
|
53
|
+
};
|
|
47
54
|
function createInvocationId() {
|
|
48
55
|
return `invoke_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
|
49
56
|
}
|
|
@@ -93,7 +100,8 @@ async function* invokeServer(input, options) {
|
|
|
93
100
|
});
|
|
94
101
|
if (!response.ok) {
|
|
95
102
|
const text = await response.text().catch(() => "");
|
|
96
|
-
throw new
|
|
103
|
+
throw new InvokeHttpError(
|
|
104
|
+
response.status,
|
|
97
105
|
`Server returned ${response.status}${text ? `: ${text}` : ""}`
|
|
98
106
|
);
|
|
99
107
|
}
|
|
@@ -129,5 +137,6 @@ async function* invokeServer(input, options) {
|
|
|
129
137
|
}
|
|
130
138
|
}
|
|
131
139
|
export {
|
|
140
|
+
InvokeHttpError,
|
|
132
141
|
invokeServer
|
|
133
142
|
};
|
package/docs/MODAL.md
CHANGED
|
@@ -39,8 +39,12 @@ All settings except `provider` are optional:
|
|
|
39
39
|
| `timeoutMs` | `3600000` | Fixed sandbox lifetime, multiples of `1000` milliseconds from `1000` through `86400000` (24 hours); e.g. `1001` is rejected before SDK I/O |
|
|
40
40
|
| `cpu` | Modal default | Positive finite CPU reservation, fractional values accepted |
|
|
41
41
|
| `memoryMiB` | Modal default | Positive integer memory reservation |
|
|
42
|
+
| `regions` | any region | Regions the sandbox may run in, such as `['us']` or `['us-east']`; see [Region Selection](#region-selection) |
|
|
43
|
+
| `networkBlockAll` | `false` | Block all outbound traffic; cannot be combined with non-empty allow lists |
|
|
44
|
+
| `networkAllowList` | unset | Comma-separated CIDR ranges the sandbox may reach, any protocol |
|
|
45
|
+
| `domainAllowList` | unset | Comma-separated domains the sandbox may reach over HTTPS; `*.` wildcards match the domain and its subdomains |
|
|
42
46
|
|
|
43
|
-
The adapter extends the registry image with `USER root`, Bash, Python 3, util-linux (`flock`/`setsid`), coreutils, sudo, curl, and CA certificates. **It forces root for both setup and payload execution, even if your custom image declares a non-root user.** There is currently no user override. Custom images must support `apt-get` and provide a compatible Node.js/npm installation for `Agent`. Home and work directories are `/root`; runtime files live in `/root/agent`. The first image build can add latency; Modal caches image layers.
|
|
47
|
+
The adapter extends the registry image with `USER root`, Bash, Python 3, util-linux (`flock`/`setsid`), coreutils, sudo, curl, and CA certificates. **It forces root for both setup and payload execution, even if your custom image declares a non-root user.** There is currently no user override. Custom images must support `apt-get` and provide a compatible Node.js/npm installation for `Agent`. The runtime starts with a fixed `PATH`, so when the image's `node`, `npm`, or `npx` resolve elsewhere, such as an nvm install, the adapter links them into `/usr/local/bin`. Home and work directories are `/root`; runtime files live in `/root/agent`. The first image build can add latency; Modal caches image layers.
|
|
44
48
|
|
|
45
49
|
Use the same sandbox settings in an Agent:
|
|
46
50
|
|
|
@@ -123,9 +127,19 @@ No encrypted or unencrypted public tunnels are created. The adapter obtains a po
|
|
|
123
127
|
- Stop first, optionally read final diagnostics, then dispose artifacts. Disposal is irreversible and does not replace exact stop confirmation. Do not call stop after disposal; the proof required to stop has intentionally been removed.
|
|
124
128
|
- `destroy()` waits for Modal termination and tolerates a provider not-found response. Other provider failures still reject. Failed `Agent.deploy()` attempts retain the shared best-effort stop/destroy cleanup and preserve the original error.
|
|
125
129
|
|
|
130
|
+
## Region Selection
|
|
131
|
+
|
|
132
|
+
Without `regions`, Modal may place a sandbox in any region worldwide. Every file and command call from the host pays the round trip, so a sandbox far from the host slows deploys and turns: from a us-east host, measured per-call latency ranged from about 80 ms in us-east to about 1.5 s in ap-south. Pin `regions` near the host, preferring a broad region such as `us`, which Modal bills at 1.15x, over a narrow one such as `us-east`, at 1.75x and with a smaller pool of capacity. See [Region selection](https://modal.com/docs/guide/region-selection).
|
|
133
|
+
|
|
134
|
+
## Network Policy
|
|
135
|
+
|
|
136
|
+
`networkBlockAll`, `networkAllowList`, and `domainAllowList` take the same shape as the Daytona options, so a Daytona network policy carries over by changing the provider. They map to Modal's `blockNetwork`, `outboundCidrAllowlist`, and `outboundDomainAllowlist` (beta). Blank lists count as unset, traffic matching either list is allowed, and without any of them Modal's default open egress applies. They are creation-only; `connect()` rejects them.
|
|
137
|
+
|
|
138
|
+
Modal matches domains by the TLS SNI, so `domainAllowList` only allows HTTPS on port 443. Plain HTTP and other TCP or UDP traffic is blocked unless its IP is in `networkAllowList`. Debian images fetch apt packages over HTTP, so when `domainAllowList` is set the adapter rewrites the image's apt sources to HTTPS, and `dependencies.apt` installs work if the mirror's domain (for example `deb.debian.org`, covered by `*.debian.org`) is allowed. A custom image whose mirror has no HTTPS endpoint can't install apt packages under a domain allow list. DNS is always allowed unless all traffic is blocked. Modal does not decrypt TLS, so an allowed SNI paired with a different `Host` header on a shared endpoint is not caught. Blocked connections are logged to the sandbox's system output. See [Sandbox networking](https://modal.com/docs/guide/sandbox-networking).
|
|
139
|
+
|
|
126
140
|
## Unsupported Options
|
|
127
141
|
|
|
128
|
-
Modal config uses a strict allowlist. Unknown options are rejected rather than silently dropped, including `apiKey`, `allowPublicTraffic` (even `false`), public tunnel ports, `requestTimeoutMs`,
|
|
142
|
+
Modal config uses a strict allowlist. Unknown options are rejected rather than silently dropped, including `apiKey`, `allowPublicTraffic` (even `false`), public tunnel ports, `requestTimeoutMs`, auto-stop/auto-delete settings, idle timeout, GPUs, volumes, private registry credentials, custom working directories, snapshots, and experimental SDK features, including runtime network policy updates.
|
|
129
143
|
|
|
130
144
|
`setTimeout()` is unsupported: choose the lifetime at creation. Foreground command options support only `cwd`, `envs`, `timeoutMs`, `onStdout`, and `onStderr`; do not pass a provider-native `background` option. Use `startDetachedCommand()` instead.
|
|
131
145
|
|