agent-neckbeard 1.1.25 → 1.1.26

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 CHANGED
@@ -1,6 +1,11 @@
1
1
  # Changelog
2
2
 
3
- ## Unreleased
3
+ ## 1.1.26 - 2026-11-03
4
+
5
+ - 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.
6
+ - 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.
7
+ - 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.
8
+ - 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
9
 
5
10
  ## 1.1.25 - 2026-11-03
6
11
 
package/README.md CHANGED
@@ -226,7 +226,7 @@ try {
226
226
  }
227
227
  ```
228
228
 
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.
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. 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
230
 
231
231
  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
232
 
@@ -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 Error(
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,
@@ -252,7 +264,7 @@ var import_node_module2 = require("module");
252
264
  init_protocol();
253
265
 
254
266
  // 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';
267
+ 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
268
 
257
269
  // src/sandbox-capabilities.ts
258
270
  var SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV = "NECKBEARD_SUPERVISOR_ENVIRONMENT_V1";
@@ -3899,6 +3911,7 @@ var DEFAULT_SERVER_PORT = 3e3;
3899
3911
  var SERVER_HEALTH_TIMEOUT_MS = 12e4;
3900
3912
  var SERVER_RECONNECT_HEALTH_TIMEOUT_MS = 3e3;
3901
3913
  var SERVER_HEALTH_POLL_INTERVAL_MS = 1e3;
3914
+ var DEFAULT_IDLE_TIMEOUT_MS = RUNTIME_ABORT_GRACE_MS + 3e4;
3902
3915
  var SERVER_FAILURE_DIAGNOSTIC_TIMEOUT_MS = 1e3;
3903
3916
  var NATIVE_EXT_RE = /\.(node|wasm|gyp|c|cc|cpp|cxx|h|hpp|hxx)$/i;
3904
3917
  var TRACEABLE_SOURCE_EXT_RE = /\.(cjs|cts|js|jsx|mjs|mts|ts|tsx)$/i;
@@ -3929,6 +3942,12 @@ var ExecutionError = class extends NeckbeardError {
3929
3942
  this.name = "ExecutionError";
3930
3943
  }
3931
3944
  };
3945
+ var RuntimeBusyError = class extends ExecutionError {
3946
+ constructor(message) {
3947
+ super(message);
3948
+ this.name = "RuntimeBusyError";
3949
+ }
3950
+ };
3932
3951
  var ConfigurationError = class extends NeckbeardError {
3933
3952
  constructor(message) {
3934
3953
  super(message);
@@ -5776,7 +5795,7 @@ var require = __neckbeard_createRequire(import.meta.url);
5776
5795
  provider: connection.provider,
5777
5796
  trafficToken: getTrafficToken(connection),
5778
5797
  invocationId: executionId,
5779
- signal: AbortSignal.timeout(this.maxDuration * 1e3 + 5e3)
5798
+ signal: AbortSignal.timeout(this.maxDuration * 1e3 + RUNTIME_ABORT_GRACE_MS + 5e3)
5780
5799
  })) {
5781
5800
  if (event.kind === "error") {
5782
5801
  const err = new ExecutionError(event.error.message);
@@ -5803,6 +5822,10 @@ var require = __neckbeard_createRequire(import.meta.url);
5803
5822
  }
5804
5823
  return { ok: true, executionId, output: validated };
5805
5824
  } catch (err) {
5825
+ const { InvokeHttpError: InvokeHttpError2 } = await Promise.resolve().then(() => (init_invoke_client(), invoke_client_exports));
5826
+ if (err instanceof InvokeHttpError2 && err.status === 409) {
5827
+ return { ok: false, executionId, error: new RuntimeBusyError(err.message) };
5828
+ }
5806
5829
  return { ok: false, executionId, error: err instanceof Error ? err : new Error(String(err)) };
5807
5830
  }
5808
5831
  }
@@ -5875,7 +5898,7 @@ var require = __neckbeard_createRequire(import.meta.url);
5875
5898
  signal,
5876
5899
  reuseMatchingCachedConnection: true
5877
5900
  });
5878
- const { invokeServer: invokeServer2 } = await Promise.resolve().then(() => (init_invoke_client(), invoke_client_exports));
5901
+ const { invokeServer: invokeServer2, InvokeHttpError: InvokeHttpError2 } = await Promise.resolve().then(() => (init_invoke_client(), invoke_client_exports));
5879
5902
  let validated;
5880
5903
  try {
5881
5904
  validated = this.inputSchema.parse(input);
@@ -5907,9 +5930,52 @@ var require = __neckbeard_createRequire(import.meta.url);
5907
5930
  }
5908
5931
  } catch (error) {
5909
5932
  if (error instanceof ExecutionError) throw error;
5933
+ if (error instanceof InvokeHttpError2 && error.status === 409) {
5934
+ throw new RuntimeBusyError(error.message);
5935
+ }
5910
5936
  throw error instanceof Error ? error : new Error(String(error));
5911
5937
  }
5912
5938
  }
5939
+ /**
5940
+ * Waits until the sandbox runtime has no handler running. An aborted turn rejects on the host
5941
+ * at once, while its handler can keep running in the sandbox until it notices the abort, so call
5942
+ * this before reading state the handler writes, such as a transcript. Throws `RuntimeBusyError`
5943
+ * if a handler is still running, or the runtime doesn't answer, after `timeoutMs`.
5944
+ */
5945
+ async waitForIdle(options = {}) {
5946
+ const { signal, timeoutMs = DEFAULT_IDLE_TIMEOUT_MS } = options;
5947
+ const connection = await this.resolveRuntimeConnection(options.sandboxId, {
5948
+ signal,
5949
+ reuseMatchingCachedConnection: true
5950
+ });
5951
+ const healthUrl = appendTrafficTokenToUrl(this.healthUrlFor(connection), connection);
5952
+ const deadline = Date.now() + timeoutMs;
5953
+ while (true) {
5954
+ let busy = true;
5955
+ try {
5956
+ const response = await awaitWithAbort(
5957
+ () => fetch(healthUrl, {
5958
+ headers: trafficTokenHeaders(connection),
5959
+ signal: signal === void 0 ? AbortSignal.timeout(SERVER_HEALTH_POLL_INTERVAL_MS * 5) : AbortSignal.any([signal, AbortSignal.timeout(SERVER_HEALTH_POLL_INTERVAL_MS * 5)])
5960
+ }),
5961
+ signal
5962
+ );
5963
+ if (response.ok) {
5964
+ const body = await awaitWithAbort(() => response.json(), signal);
5965
+ busy = body.ok !== true || body.busy === true;
5966
+ } else {
5967
+ await response.body?.cancel().catch(() => void 0);
5968
+ }
5969
+ } catch {
5970
+ throwIfAborted(signal);
5971
+ }
5972
+ if (!busy) return;
5973
+ if (Date.now() >= deadline) {
5974
+ throw new RuntimeBusyError(`Sandbox runtime still busy after ${timeoutMs}ms.`);
5975
+ }
5976
+ await delayWithAbort(SERVER_HEALTH_POLL_INTERVAL_MS, signal);
5977
+ }
5978
+ }
5913
5979
  /**
5914
5980
  * @deprecated Use `createSession()` and call `session.prompt(input)` instead.
5915
5981
  * This compatibility wrapper creates one attached session, streams one turn,
@@ -5935,6 +6001,7 @@ var require = __neckbeard_createRequire(import.meta.url);
5935
6001
  DeploymentError,
5936
6002
  ExecutionError,
5937
6003
  NeckbeardError,
6004
+ RuntimeBusyError,
5938
6005
  SandboxClient,
5939
6006
  ValidationError,
5940
6007
  normalizeStackFramePath,
package/dist/index.d.cts CHANGED
@@ -127,6 +127,13 @@ declare class ExecutionError extends NeckbeardError {
127
127
  readonly cause?: Error | undefined;
128
128
  constructor(message: string, cause?: Error | undefined);
129
129
  }
130
+ /**
131
+ * Error thrown when the sandbox runtime is still running an earlier handler, either because a
132
+ * turn was started while another was active or because `waitForIdle()` timed out.
133
+ */
134
+ declare class RuntimeBusyError extends ExecutionError {
135
+ constructor(message: string);
136
+ }
130
137
  /**
131
138
  * Error thrown when required environment variables are missing.
132
139
  */
@@ -674,6 +681,17 @@ declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
674
681
  */
675
682
  createSession(options?: CreateAttachedSessionOptions): Promise<AttachedAgentSession<TInput, TFrame>>;
676
683
  private streamSessionPrompt;
684
+ /**
685
+ * Waits until the sandbox runtime has no handler running. An aborted turn rejects on the host
686
+ * at once, while its handler can keep running in the sandbox until it notices the abort, so call
687
+ * this before reading state the handler writes, such as a transcript. Throws `RuntimeBusyError`
688
+ * if a handler is still running, or the runtime doesn't answer, after `timeoutMs`.
689
+ */
690
+ waitForIdle(options?: {
691
+ sandboxId?: string;
692
+ timeoutMs?: number;
693
+ signal?: AbortSignal;
694
+ }): Promise<void>;
677
695
  /**
678
696
  * @deprecated Use `createSession()` and call `session.prompt(input)` instead.
679
697
  * This compatibility wrapper creates one attached session, streams one turn,
@@ -685,4 +703,4 @@ declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
685
703
  }): AsyncGenerator<TFrame>;
686
704
  }
687
705
 
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 };
706
+ 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
@@ -127,6 +127,13 @@ declare class ExecutionError extends NeckbeardError {
127
127
  readonly cause?: Error | undefined;
128
128
  constructor(message: string, cause?: Error | undefined);
129
129
  }
130
+ /**
131
+ * Error thrown when the sandbox runtime is still running an earlier handler, either because a
132
+ * turn was started while another was active or because `waitForIdle()` timed out.
133
+ */
134
+ declare class RuntimeBusyError extends ExecutionError {
135
+ constructor(message: string);
136
+ }
130
137
  /**
131
138
  * Error thrown when required environment variables are missing.
132
139
  */
@@ -674,6 +681,17 @@ declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
674
681
  */
675
682
  createSession(options?: CreateAttachedSessionOptions): Promise<AttachedAgentSession<TInput, TFrame>>;
676
683
  private streamSessionPrompt;
684
+ /**
685
+ * Waits until the sandbox runtime has no handler running. An aborted turn rejects on the host
686
+ * at once, while its handler can keep running in the sandbox until it notices the abort, so call
687
+ * this before reading state the handler writes, such as a transcript. Throws `RuntimeBusyError`
688
+ * if a handler is still running, or the runtime doesn't answer, after `timeoutMs`.
689
+ */
690
+ waitForIdle(options?: {
691
+ sandboxId?: string;
692
+ timeoutMs?: number;
693
+ signal?: AbortSignal;
694
+ }): Promise<void>;
677
695
  /**
678
696
  * @deprecated Use `createSession()` and call `session.prompt(input)` instead.
679
697
  * This compatibility wrapper creates one attached session, streams one turn,
@@ -685,4 +703,4 @@ declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
685
703
  }): AsyncGenerator<TFrame>;
686
704
  }
687
705
 
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 };
706
+ 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-DHFC3O44.js";
22
+ } from "./chunk-6GCQOKYI.js";
22
23
  import "./chunk-33IXN6MM.js";
23
24
 
24
25
  // src/index.ts
@@ -45,7 +46,7 @@ import {
45
46
  import { builtinModules, createRequire as createRequire2 } from "module";
46
47
 
47
48
  // 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';
49
+ var RUNTIME_SERVER_SOURCE = '// src/runtime/server.ts\nimport { createServer } from "node:http";\nimport { readFileSync } from "node:fs";\nimport { fileURLToPath } from "node:url";\nimport { dirname, join } from "node:path";\nimport { once } from "node:events";\n\n// src/serialized-error.ts\nfunction serializeError(error) {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n ...error.stack === void 0 ? {} : { stack: error.stack }\n };\n }\n return { message: String(error) };\n}\n\n// src/runtime/protocol.ts\nvar RUNTIME_PROTOCOL_VERSION = 1;\nvar RUNTIME_ABORT_GRACE_MS = 1e4;\n\n// src/runtime/server.ts\nvar CONFIG_PATH = join(dirname(fileURLToPath(import.meta.url)), "server-config.json");\nvar CONFIG = JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));\nvar MAX_REQUEST_BODY_BYTES = 4 * 1024 * 1024;\nvar DEFAULT_SSE_HEARTBEAT_INTERVAL_MS = 15e3;\nvar RequestBodyTooLargeError = class extends Error {\n constructor(limitBytes) {\n super(`request body exceeds ${limitBytes} bytes`);\n this.name = "RequestBodyTooLargeError";\n }\n};\nfunction createLogger() {\n return {\n debug: (message, ...args) => console.log("[DEBUG]", message, ...args),\n info: (message, ...args) => console.log("[INFO]", message, ...args),\n warn: (message, ...args) => console.warn("[WARN]", message, ...args),\n error: (message, ...args) => console.error("[ERROR]", message, ...args)\n };\n}\nfunction sendJson(res, status, body) {\n res.writeHead(status, { "content-type": "application/json" });\n res.end(JSON.stringify(body));\n}\nfunction getSseHeartbeatIntervalMs() {\n const raw = process.env.NECKBEARD_RUNTIME_SSE_HEARTBEAT_MS;\n if (!raw) return DEFAULT_SSE_HEARTBEAT_INTERVAL_MS;\n const parsed = Number(raw);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_SSE_HEARTBEAT_INTERVAL_MS;\n}\nfunction getAbortGraceMs() {\n const raw = process.env.NECKBEARD_RUNTIME_ABORT_GRACE_MS;\n if (!raw) return RUNTIME_ABORT_GRACE_MS;\n const parsed = Number(raw);\n return Number.isFinite(parsed) && parsed >= 0 ? parsed : RUNTIME_ABORT_GRACE_MS;\n}\nfunction sendSseComment(res, comment) {\n if (res.writableEnded || res.destroyed) return;\n res.write(`: ${comment}\n\n`);\n}\nasync function sendSseFrame(res, event, signal) {\n if (res.destroyed) return;\n const canContinue = res.write(`data: ${JSON.stringify(event)}\n\n`);\n if (!canContinue && !signal.aborted) {\n await once(res, "drain", { signal }).catch(() => void 0);\n }\n}\nasync function readRequestBody(req, maxBytes = MAX_REQUEST_BODY_BYTES) {\n const chunks = [];\n let totalBytes = 0;\n for await (const chunk of req) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n totalBytes += buffer.byteLength;\n if (totalBytes > maxBytes) {\n throw new RequestBodyTooLargeError(maxBytes);\n }\n chunks.push(buffer);\n }\n return Buffer.concat(chunks).toString("utf-8");\n}\nfunction createTimeoutError(maxDurationMs) {\n const error = new Error(`Agent invocation exceeded maxDuration (${maxDurationMs}ms)`);\n error.name = "TimeoutError";\n return error;\n}\nfunction settleAfterAbort(task, signal, maxDurationMs) {\n return new Promise((resolve, reject) => {\n let aborted = false;\n const rejectAborted = () => reject(createTimeoutError(maxDurationMs));\n const onAbort = () => {\n aborted = true;\n const grace = setTimeout(rejectAborted, getAbortGraceMs());\n const stopped = () => {\n clearTimeout(grace);\n rejectAborted();\n };\n task.then(stopped, stopped);\n };\n if (signal.aborted) onAbort();\n else signal.addEventListener("abort", onAbort, { once: true });\n task.then(\n (value) => {\n if (aborted) return;\n signal.removeEventListener("abort", onAbort);\n resolve(value);\n },\n (error) => {\n if (aborted) return;\n signal.removeEventListener("abort", onAbort);\n reject(error);\n }\n );\n });\n}\nasync function loadAgent() {\n const mod = await import(new URL("./agent.mjs", import.meta.url).href);\n const agent = (mod.default && (mod.default._run || mod.default._server) ? mod.default : null) || Object.values(mod).find(\n (value) => value && typeof value === "object" && ("_run" in value || "_server" in value)\n );\n if (!agent || typeof agent !== "object") {\n throw new Error(\n `No agent found in agent.mjs. Exports: ${Object.keys(mod).join(", ")}`\n );\n }\n return agent;\n}\nasync function main() {\n const agent = await loadAgent();\n let activeInvocationId = null;\n const server = createServer(async (req, res) => {\n try {\n const url = new URL(req.url ?? "/", "http://localhost");\n if (url.pathname === "/health" && req.method === "GET") {\n return sendJson(res, 200, {\n ok: true,\n protocolVersion: RUNTIME_PROTOCOL_VERSION,\n busy: activeInvocationId !== null\n });\n }\n if (url.pathname === "/shutdown" && req.method === "POST") {\n sendJson(res, 200, { ok: true });\n setTimeout(() => shutdown(), 10).unref();\n return;\n }\n if (url.pathname === "/invoke" && req.method === "POST") {\n let rawBody;\n try {\n rawBody = await readRequestBody(req);\n } catch (error) {\n if (error instanceof RequestBodyTooLargeError) {\n return sendJson(res, 413, { error: error.message });\n }\n throw error;\n }\n let requestBody;\n try {\n requestBody = JSON.parse(rawBody);\n } catch {\n return sendJson(res, 400, { error: "invalid JSON body" });\n }\n if (!requestBody || typeof requestBody !== "object" || typeof requestBody.invocationId !== "string") {\n return sendJson(res, 400, { error: "invalid invoke request" });\n }\n let validatedInput;\n try {\n validatedInput = agent.inputSchema.parse(requestBody.input);\n } catch (error) {\n return sendJson(res, 400, {\n error: `input validation failed: ${serializeError(error).message}`\n });\n }\n if (activeInvocationId !== null) {\n return sendJson(res, 409, {\n error: `invocation ${activeInvocationId} is still running`\n });\n }\n const invocationId = requestBody.invocationId;\n activeInvocationId = invocationId;\n res.writeHead(200, {\n "content-type": "text/event-stream",\n "cache-control": "no-cache, no-transform",\n connection: "keep-alive",\n "x-accel-buffering": "no"\n });\n const controller = new AbortController();\n req.on("aborted", () => controller.abort());\n res.on("close", () => {\n if (!res.writableEnded) {\n controller.abort();\n }\n });\n const startedAt = Date.now();\n let sequence = 0;\n const timeout = setTimeout(() => controller.abort(), CONFIG.maxDurationMs);\n const heartbeat = setInterval(() => {\n try {\n sendSseComment(res, `heartbeat ${Date.now()}`);\n } catch {\n controller.abort();\n }\n }, getSseHeartbeatIntervalMs());\n heartbeat.unref();\n const emitHarnessEvent = async (event) => {\n if (!res.writableEnded) {\n await sendSseFrame(res, {\n protocolVersion: RUNTIME_PROTOCOL_VERSION,\n sequence: sequence++,\n timestamp: (/* @__PURE__ */ new Date()).toISOString(),\n elapsedMs: Date.now() - startedAt,\n ...event\n }, controller.signal);\n }\n };\n const ctx = {\n executionId: invocationId,\n signal: controller.signal,\n env: process.env,\n sandbox: CONFIG.sandboxContext,\n logger: createLogger()\n };\n let running;\n try {\n await emitHarnessEvent({ kind: "started", invocationId });\n const handler = agent._server ? () => agent._server.handler({\n input: validatedInput,\n ctx,\n signal: controller.signal,\n emit: async (data) => {\n const validatedFrame = agent._server?.frameSchema ? agent._server.frameSchema.parse(data) : data;\n await emitHarnessEvent({ kind: "frame", invocationId, data: validatedFrame });\n }\n }) : agent._run ? () => agent._run(validatedInput, ctx) : () => {\n throw new Error("Agent has neither a run handler nor a server handler.");\n };\n if (controller.signal.aborted) throw createTimeoutError(CONFIG.maxDurationMs);\n running = Promise.resolve().then(handler);\n void running.catch(() => void 0).finally(() => {\n if (activeInvocationId === invocationId) activeInvocationId = null;\n });\n const output = await settleAfterAbort(running, controller.signal, CONFIG.maxDurationMs);\n if (agent._run && !agent._server) {\n const validatedOutput = agent.outputSchema ? agent.outputSchema.parse(output) : output;\n await emitHarnessEvent({ kind: "output", invocationId, output: validatedOutput });\n }\n await emitHarnessEvent({ kind: "done", invocationId });\n } catch (error) {\n await emitHarnessEvent({ kind: "error", invocationId, error: serializeError(error) });\n } finally {\n clearInterval(heartbeat);\n clearTimeout(timeout);\n if (!running && activeInvocationId === invocationId) activeInvocationId = null;\n if (!res.writableEnded) {\n res.end();\n }\n }\n return;\n }\n return sendJson(res, 404, { error: "not found" });\n } catch (error) {\n console.error("[neckbeard-server] unexpected error", error);\n if (!res.headersSent) {\n sendJson(res, 500, { error: "internal error" });\n } else if (!res.writableEnded) {\n res.end();\n }\n }\n });\n function shutdown() {\n console.log("[neckbeard-server] shutting down");\n server.close(() => process.exit(0));\n setTimeout(() => process.exit(0), 5e3).unref();\n }\n server.listen(CONFIG.port, "0.0.0.0", () => {\n console.log(`[neckbeard-server] listening on port ${CONFIG.port}`);\n });\n process.on("SIGTERM", shutdown);\n process.on("SIGINT", shutdown);\n}\nmain().catch((error) => {\n console.error("[neckbeard-server] failed to start", error);\n process.exit(1);\n});\n';
49
50
 
50
51
  // src/attached-session.ts
51
52
  function linkAbortSignals(signals) {
@@ -1190,6 +1191,7 @@ var DEFAULT_SERVER_PORT = 3e3;
1190
1191
  var SERVER_HEALTH_TIMEOUT_MS = 12e4;
1191
1192
  var SERVER_RECONNECT_HEALTH_TIMEOUT_MS = 3e3;
1192
1193
  var SERVER_HEALTH_POLL_INTERVAL_MS = 1e3;
1194
+ var DEFAULT_IDLE_TIMEOUT_MS = RUNTIME_ABORT_GRACE_MS + 3e4;
1193
1195
  var SERVER_FAILURE_DIAGNOSTIC_TIMEOUT_MS = 1e3;
1194
1196
  var NATIVE_EXT_RE = /\.(node|wasm|gyp|c|cc|cpp|cxx|h|hpp|hxx)$/i;
1195
1197
  var TRACEABLE_SOURCE_EXT_RE = /\.(cjs|cts|js|jsx|mjs|mts|ts|tsx)$/i;
@@ -1220,6 +1222,12 @@ var ExecutionError = class extends NeckbeardError {
1220
1222
  this.name = "ExecutionError";
1221
1223
  }
1222
1224
  };
1225
+ var RuntimeBusyError = class extends ExecutionError {
1226
+ constructor(message) {
1227
+ super(message);
1228
+ this.name = "RuntimeBusyError";
1229
+ }
1230
+ };
1223
1231
  var ConfigurationError = class extends NeckbeardError {
1224
1232
  constructor(message) {
1225
1233
  super(message);
@@ -3059,7 +3067,7 @@ var require = __neckbeard_createRequire(import.meta.url);
3059
3067
  } catch (error) {
3060
3068
  throw new ValidationError("Input validation failed.", asError(error));
3061
3069
  }
3062
- const { invokeServer } = await import("./invoke-client-HIXYE2WN.js");
3070
+ const { invokeServer } = await import("./invoke-client-YKWOTQWG.js");
3063
3071
  let output;
3064
3072
  let sawOutput = false;
3065
3073
  for await (const event of invokeServer(validatedInput, {
@@ -3067,7 +3075,7 @@ var require = __neckbeard_createRequire(import.meta.url);
3067
3075
  provider: connection.provider,
3068
3076
  trafficToken: getTrafficToken(connection),
3069
3077
  invocationId: executionId,
3070
- signal: AbortSignal.timeout(this.maxDuration * 1e3 + 5e3)
3078
+ signal: AbortSignal.timeout(this.maxDuration * 1e3 + RUNTIME_ABORT_GRACE_MS + 5e3)
3071
3079
  })) {
3072
3080
  if (event.kind === "error") {
3073
3081
  const err = new ExecutionError(event.error.message);
@@ -3094,6 +3102,10 @@ var require = __neckbeard_createRequire(import.meta.url);
3094
3102
  }
3095
3103
  return { ok: true, executionId, output: validated };
3096
3104
  } catch (err) {
3105
+ const { InvokeHttpError } = await import("./invoke-client-YKWOTQWG.js");
3106
+ if (err instanceof InvokeHttpError && err.status === 409) {
3107
+ return { ok: false, executionId, error: new RuntimeBusyError(err.message) };
3108
+ }
3097
3109
  return { ok: false, executionId, error: err instanceof Error ? err : new Error(String(err)) };
3098
3110
  }
3099
3111
  }
@@ -3166,7 +3178,7 @@ var require = __neckbeard_createRequire(import.meta.url);
3166
3178
  signal,
3167
3179
  reuseMatchingCachedConnection: true
3168
3180
  });
3169
- const { invokeServer } = await import("./invoke-client-HIXYE2WN.js");
3181
+ const { invokeServer, InvokeHttpError } = await import("./invoke-client-YKWOTQWG.js");
3170
3182
  let validated;
3171
3183
  try {
3172
3184
  validated = this.inputSchema.parse(input);
@@ -3198,9 +3210,52 @@ var require = __neckbeard_createRequire(import.meta.url);
3198
3210
  }
3199
3211
  } catch (error) {
3200
3212
  if (error instanceof ExecutionError) throw error;
3213
+ if (error instanceof InvokeHttpError && error.status === 409) {
3214
+ throw new RuntimeBusyError(error.message);
3215
+ }
3201
3216
  throw error instanceof Error ? error : new Error(String(error));
3202
3217
  }
3203
3218
  }
3219
+ /**
3220
+ * Waits until the sandbox runtime has no handler running. An aborted turn rejects on the host
3221
+ * at once, while its handler can keep running in the sandbox until it notices the abort, so call
3222
+ * this before reading state the handler writes, such as a transcript. Throws `RuntimeBusyError`
3223
+ * if a handler is still running, or the runtime doesn't answer, after `timeoutMs`.
3224
+ */
3225
+ async waitForIdle(options = {}) {
3226
+ const { signal, timeoutMs = DEFAULT_IDLE_TIMEOUT_MS } = options;
3227
+ const connection = await this.resolveRuntimeConnection(options.sandboxId, {
3228
+ signal,
3229
+ reuseMatchingCachedConnection: true
3230
+ });
3231
+ const healthUrl = appendTrafficTokenToUrl(this.healthUrlFor(connection), connection);
3232
+ const deadline = Date.now() + timeoutMs;
3233
+ while (true) {
3234
+ let busy = true;
3235
+ try {
3236
+ const response = await awaitWithAbort(
3237
+ () => fetch(healthUrl, {
3238
+ headers: trafficTokenHeaders(connection),
3239
+ signal: signal === void 0 ? AbortSignal.timeout(SERVER_HEALTH_POLL_INTERVAL_MS * 5) : AbortSignal.any([signal, AbortSignal.timeout(SERVER_HEALTH_POLL_INTERVAL_MS * 5)])
3240
+ }),
3241
+ signal
3242
+ );
3243
+ if (response.ok) {
3244
+ const body = await awaitWithAbort(() => response.json(), signal);
3245
+ busy = body.ok !== true || body.busy === true;
3246
+ } else {
3247
+ await response.body?.cancel().catch(() => void 0);
3248
+ }
3249
+ } catch {
3250
+ throwIfAborted(signal);
3251
+ }
3252
+ if (!busy) return;
3253
+ if (Date.now() >= deadline) {
3254
+ throw new RuntimeBusyError(`Sandbox runtime still busy after ${timeoutMs}ms.`);
3255
+ }
3256
+ await delayWithAbort(SERVER_HEALTH_POLL_INTERVAL_MS, signal);
3257
+ }
3258
+ }
3204
3259
  /**
3205
3260
  * @deprecated Use `createSession()` and call `session.prompt(input)` instead.
3206
3261
  * This compatibility wrapper creates one attached session, streams one turn,
@@ -3225,6 +3280,7 @@ export {
3225
3280
  DeploymentError,
3226
3281
  ExecutionError,
3227
3282
  NeckbeardError,
3283
+ RuntimeBusyError,
3228
3284
  SandboxClient,
3229
3285
  ValidationError,
3230
3286
  normalizeStackFramePath,
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  isHarnessEvent
3
- } from "./chunk-DHFC3O44.js";
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 Error(
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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-neckbeard",
3
- "version": "1.1.25",
3
+ "version": "1.1.26",
4
4
  "description": "Deploy AI agents to E2B, Daytona, and Modal sandboxes, or local Docker containers",
5
5
  "type": "module",
6
6
  "exports": {