agent-neckbeard 1.1.24 → 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,16 @@
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.
9
+
10
+ ## 1.1.25 - 2026-11-03
11
+
12
+ - Accept `autoStopInterval` and `autoDeleteInterval` in an `Agent`'s Daytona sandbox config and pass them to sandbox creation, as `SandboxClient.create()` already did. `new Agent()` rejects values that are not whole minutes. Omitting `autoDeleteInterval` still never auto-deletes the sandbox.
13
+ - Deprecate the durable-session supervisor (`agent-neckbeard/supervisor`) and mark its launch and lifecycle functions `@deprecated`. It is no longer maintained and will be removed in a future major release.
4
14
 
5
15
  ## 1.1.24 - 2026-10-22
6
16
 
package/README.md CHANGED
@@ -21,7 +21,7 @@ The four primary usage patterns:
21
21
  - Structured tasks: an agent runs once per background task and returns one validated output (Structured Tasks below).
22
22
  - Attached sessions: a caller-owned session emits typed progress frames while work runs (Attached Sessions below).
23
23
  - Direct sandbox access: `SandboxClient` wraps E2B, Daytona, and Modal behind one filesystem/command API, no agent required (Direct Sandbox Access below).
24
- - Durable sessions: an opt-in generated supervisor owns Pi inside Daytona and reconnects outward to a long-lived gateway (Durable Sessions below).
24
+ - Durable sessions (deprecated): an opt-in generated supervisor owns Pi inside Daytona and reconnects outward to a long-lived gateway (Durable Sessions below).
25
25
 
26
26
  `Agent.kind` reports `"task"` or `"session"`. The older `mode: "run" | "stream"` property remains as a deprecated compatibility surface.
27
27
 
@@ -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
+ `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
+
139
141
  ## Structured Tasks
140
142
 
141
143
  Use `run` when each invocation should produce one validated output:
@@ -224,7 +226,7 @@ try {
224
226
  }
225
227
  ```
226
228
 
227
- 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.
228
230
 
229
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.
230
232
 
@@ -297,6 +299,8 @@ An application that reuses a sandbox can bound retained lifecycle state and diag
297
299
 
298
300
  ## Durable Sessions
299
301
 
302
+ > **Deprecated.** The durable-session supervisor is no longer maintained and will be removed in a future major release. Attached sessions (`Agent.createSession()`) remain supported, but they are not durable: a turn stops when its caller disconnects, and nothing is replayed.
303
+
300
304
  Use `agent-neckbeard/supervisor` when a persistent sandbox process should own Pi while a separate gateway and lifecycle worker may restart independently:
301
305
 
302
306
  ```typescript
@@ -375,6 +379,8 @@ new Agent({
375
379
  networkBlockAll?: boolean,
376
380
  networkAllowList?: string,
377
381
  domainAllowList?: string,
382
+ autoStopInterval?: number,
383
+ autoDeleteInterval?: number,
378
384
  },
379
385
  inputSchema: ZodSchema,
380
386
  maxDuration?: number,
@@ -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);
@@ -4468,6 +4487,15 @@ function validateAgentConfig(config) {
4468
4487
  } else if (typeof config.sandbox.template !== "string" || config.sandbox.template.trim() === "") {
4469
4488
  throw new ConfigurationError("sandbox.template must be a non-empty string.");
4470
4489
  }
4490
+ if (config.sandbox.provider === "daytona") {
4491
+ const { autoStopInterval, autoDeleteInterval } = config.sandbox;
4492
+ if (autoStopInterval !== void 0 && (!Number.isInteger(autoStopInterval) || autoStopInterval < 0)) {
4493
+ throw new ConfigurationError("sandbox.autoStopInterval must be a non-negative integer number of minutes.");
4494
+ }
4495
+ if (autoDeleteInterval !== void 0 && !Number.isInteger(autoDeleteInterval)) {
4496
+ throw new ConfigurationError("sandbox.autoDeleteInterval must be an integer number of minutes.");
4497
+ }
4498
+ }
4471
4499
  requireSchemaLike("inputSchema", config.inputSchema);
4472
4500
  if (config.maxDuration !== void 0 && (!Number.isFinite(config.maxDuration) || config.maxDuration <= 0)) {
4473
4501
  throw new ConfigurationError("maxDuration must be a positive finite number of seconds.");
@@ -5295,7 +5323,9 @@ var Agent = class {
5295
5323
  envs: this.sandboxEnv,
5296
5324
  networkBlockAll: sandbox.networkBlockAll,
5297
5325
  networkAllowList: sandbox.networkAllowList,
5298
- domainAllowList: sandbox.domainAllowList
5326
+ domainAllowList: sandbox.domainAllowList,
5327
+ autoStopInterval: sandbox.autoStopInterval,
5328
+ autoDeleteInterval: sandbox.autoDeleteInterval
5299
5329
  });
5300
5330
  }
5301
5331
  async connectSandboxHandle(sandboxId) {
@@ -5765,7 +5795,7 @@ var require = __neckbeard_createRequire(import.meta.url);
5765
5795
  provider: connection.provider,
5766
5796
  trafficToken: getTrafficToken(connection),
5767
5797
  invocationId: executionId,
5768
- signal: AbortSignal.timeout(this.maxDuration * 1e3 + 5e3)
5798
+ signal: AbortSignal.timeout(this.maxDuration * 1e3 + RUNTIME_ABORT_GRACE_MS + 5e3)
5769
5799
  })) {
5770
5800
  if (event.kind === "error") {
5771
5801
  const err = new ExecutionError(event.error.message);
@@ -5792,6 +5822,10 @@ var require = __neckbeard_createRequire(import.meta.url);
5792
5822
  }
5793
5823
  return { ok: true, executionId, output: validated };
5794
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
+ }
5795
5829
  return { ok: false, executionId, error: err instanceof Error ? err : new Error(String(err)) };
5796
5830
  }
5797
5831
  }
@@ -5834,7 +5868,7 @@ var require = __neckbeard_createRequire(import.meta.url);
5834
5868
  }
5835
5869
  if (durability !== void 0 && durability !== "attached") {
5836
5870
  throw new ConfigurationError(
5837
- "Agent.createSession() creates caller-owned attached sessions. Use agent-neckbeard/supervisor durable-session APIs for gateway-owned sessions."
5871
+ "Agent.createSession() creates caller-owned attached sessions. Gateway-owned durable sessions use the deprecated agent-neckbeard/supervisor APIs."
5838
5872
  );
5839
5873
  }
5840
5874
  if (requestedSandboxId !== void 0 && (typeof requestedSandboxId !== "string" || requestedSandboxId.trim() === "")) {
@@ -5864,7 +5898,7 @@ var require = __neckbeard_createRequire(import.meta.url);
5864
5898
  signal,
5865
5899
  reuseMatchingCachedConnection: true
5866
5900
  });
5867
- 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));
5868
5902
  let validated;
5869
5903
  try {
5870
5904
  validated = this.inputSchema.parse(input);
@@ -5896,9 +5930,52 @@ var require = __neckbeard_createRequire(import.meta.url);
5896
5930
  }
5897
5931
  } catch (error) {
5898
5932
  if (error instanceof ExecutionError) throw error;
5933
+ if (error instanceof InvokeHttpError2 && error.status === 409) {
5934
+ throw new RuntimeBusyError(error.message);
5935
+ }
5899
5936
  throw error instanceof Error ? error : new Error(String(error));
5900
5937
  }
5901
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
+ }
5902
5979
  /**
5903
5980
  * @deprecated Use `createSession()` and call `session.prompt(input)` instead.
5904
5981
  * This compatibility wrapper creates one attached session, streams one turn,
@@ -5924,6 +6001,7 @@ var require = __neckbeard_createRequire(import.meta.url);
5924
6001
  DeploymentError,
5925
6002
  ExecutionError,
5926
6003
  NeckbeardError,
6004
+ RuntimeBusyError,
5927
6005
  SandboxClient,
5928
6006
  ValidationError,
5929
6007
  normalizeStackFramePath,
package/dist/index.d.cts CHANGED
@@ -18,8 +18,8 @@ interface CreateAttachedSessionOptions {
18
18
  /**
19
19
  * Attached sessions are owned by this client process and stop when their
20
20
  * active request is cancelled. Durable sessions are launched through the
21
- * `agent-neckbeard/supervisor` entrypoint because their control plane must
22
- * outlive this object.
21
+ * deprecated `agent-neckbeard/supervisor` entrypoint because their control
22
+ * plane must outlive this object.
23
23
  */
24
24
  durability?: 'attached';
25
25
  /** Existing sandbox runtime to reconnect to. Defaults to the deployed sandbox. */
@@ -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
  */
@@ -417,6 +424,18 @@ interface DaytonaSandboxConfig {
417
424
  * Example: '*.example.com,api.openai.com'
418
425
  */
419
426
  domainAllowList?: string;
427
+ /**
428
+ * Minutes without activity before Daytona stops the sandbox. `0` disables
429
+ * auto-stop. Omit it to keep Daytona's default (15 minutes for standard
430
+ * sandbox classes). Applied only when the sandbox is created.
431
+ */
432
+ autoStopInterval?: number;
433
+ /**
434
+ * Minutes after the sandbox stops before Daytona deletes it. `0` deletes it
435
+ * as soon as it stops; `-1`, the default, never auto-deletes it. Applied
436
+ * only when the sandbox is created.
437
+ */
438
+ autoDeleteInterval?: number;
420
439
  }
421
440
  type SandboxConfig = E2BSandboxConfig | DaytonaSandboxConfig | ModalSandboxConfig | DockerSandboxConfig;
422
441
  /**
@@ -545,7 +564,7 @@ declare class SandboxClient {
545
564
  /** @deprecated Use `AgentKind` for user-facing task/session terminology. */
546
565
  type AgentMode = 'run' | 'stream';
547
566
  type AgentKind = 'task' | 'session';
548
- /** @deprecated Durable sessions use the separate supervisor deployment API. */
567
+ /** @deprecated Durable sessions use the separate, deprecated supervisor deployment API. */
549
568
  type SessionDurability = 'attached' | 'durable';
550
569
  declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
551
570
  readonly sandbox: SandboxConfig;
@@ -662,6 +681,17 @@ declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
662
681
  */
663
682
  createSession(options?: CreateAttachedSessionOptions): Promise<AttachedAgentSession<TInput, TFrame>>;
664
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>;
665
695
  /**
666
696
  * @deprecated Use `createSession()` and call `session.prompt(input)` instead.
667
697
  * This compatibility wrapper creates one attached session, streams one turn,
@@ -673,4 +703,4 @@ declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
673
703
  }): AsyncGenerator<TFrame>;
674
704
  }
675
705
 
676
- 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
@@ -18,8 +18,8 @@ interface CreateAttachedSessionOptions {
18
18
  /**
19
19
  * Attached sessions are owned by this client process and stop when their
20
20
  * active request is cancelled. Durable sessions are launched through the
21
- * `agent-neckbeard/supervisor` entrypoint because their control plane must
22
- * outlive this object.
21
+ * deprecated `agent-neckbeard/supervisor` entrypoint because their control
22
+ * plane must outlive this object.
23
23
  */
24
24
  durability?: 'attached';
25
25
  /** Existing sandbox runtime to reconnect to. Defaults to the deployed sandbox. */
@@ -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
  */
@@ -417,6 +424,18 @@ interface DaytonaSandboxConfig {
417
424
  * Example: '*.example.com,api.openai.com'
418
425
  */
419
426
  domainAllowList?: string;
427
+ /**
428
+ * Minutes without activity before Daytona stops the sandbox. `0` disables
429
+ * auto-stop. Omit it to keep Daytona's default (15 minutes for standard
430
+ * sandbox classes). Applied only when the sandbox is created.
431
+ */
432
+ autoStopInterval?: number;
433
+ /**
434
+ * Minutes after the sandbox stops before Daytona deletes it. `0` deletes it
435
+ * as soon as it stops; `-1`, the default, never auto-deletes it. Applied
436
+ * only when the sandbox is created.
437
+ */
438
+ autoDeleteInterval?: number;
420
439
  }
421
440
  type SandboxConfig = E2BSandboxConfig | DaytonaSandboxConfig | ModalSandboxConfig | DockerSandboxConfig;
422
441
  /**
@@ -545,7 +564,7 @@ declare class SandboxClient {
545
564
  /** @deprecated Use `AgentKind` for user-facing task/session terminology. */
546
565
  type AgentMode = 'run' | 'stream';
547
566
  type AgentKind = 'task' | 'session';
548
- /** @deprecated Durable sessions use the separate supervisor deployment API. */
567
+ /** @deprecated Durable sessions use the separate, deprecated supervisor deployment API. */
549
568
  type SessionDurability = 'attached' | 'durable';
550
569
  declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
551
570
  readonly sandbox: SandboxConfig;
@@ -662,6 +681,17 @@ declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
662
681
  */
663
682
  createSession(options?: CreateAttachedSessionOptions): Promise<AttachedAgentSession<TInput, TFrame>>;
664
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>;
665
695
  /**
666
696
  * @deprecated Use `createSession()` and call `session.prompt(input)` instead.
667
697
  * This compatibility wrapper creates one attached session, streams one turn,
@@ -673,4 +703,4 @@ declare class Agent<TInput, TOutput = unknown, TFrame = unknown> {
673
703
  }): AsyncGenerator<TFrame>;
674
704
  }
675
705
 
676
- 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);
@@ -1759,6 +1767,15 @@ function validateAgentConfig(config) {
1759
1767
  } else if (typeof config.sandbox.template !== "string" || config.sandbox.template.trim() === "") {
1760
1768
  throw new ConfigurationError("sandbox.template must be a non-empty string.");
1761
1769
  }
1770
+ if (config.sandbox.provider === "daytona") {
1771
+ const { autoStopInterval, autoDeleteInterval } = config.sandbox;
1772
+ if (autoStopInterval !== void 0 && (!Number.isInteger(autoStopInterval) || autoStopInterval < 0)) {
1773
+ throw new ConfigurationError("sandbox.autoStopInterval must be a non-negative integer number of minutes.");
1774
+ }
1775
+ if (autoDeleteInterval !== void 0 && !Number.isInteger(autoDeleteInterval)) {
1776
+ throw new ConfigurationError("sandbox.autoDeleteInterval must be an integer number of minutes.");
1777
+ }
1778
+ }
1762
1779
  requireSchemaLike("inputSchema", config.inputSchema);
1763
1780
  if (config.maxDuration !== void 0 && (!Number.isFinite(config.maxDuration) || config.maxDuration <= 0)) {
1764
1781
  throw new ConfigurationError("maxDuration must be a positive finite number of seconds.");
@@ -2586,7 +2603,9 @@ var Agent = class {
2586
2603
  envs: this.sandboxEnv,
2587
2604
  networkBlockAll: sandbox.networkBlockAll,
2588
2605
  networkAllowList: sandbox.networkAllowList,
2589
- domainAllowList: sandbox.domainAllowList
2606
+ domainAllowList: sandbox.domainAllowList,
2607
+ autoStopInterval: sandbox.autoStopInterval,
2608
+ autoDeleteInterval: sandbox.autoDeleteInterval
2590
2609
  });
2591
2610
  }
2592
2611
  async connectSandboxHandle(sandboxId) {
@@ -3048,7 +3067,7 @@ var require = __neckbeard_createRequire(import.meta.url);
3048
3067
  } catch (error) {
3049
3068
  throw new ValidationError("Input validation failed.", asError(error));
3050
3069
  }
3051
- const { invokeServer } = await import("./invoke-client-HIXYE2WN.js");
3070
+ const { invokeServer } = await import("./invoke-client-YKWOTQWG.js");
3052
3071
  let output;
3053
3072
  let sawOutput = false;
3054
3073
  for await (const event of invokeServer(validatedInput, {
@@ -3056,7 +3075,7 @@ var require = __neckbeard_createRequire(import.meta.url);
3056
3075
  provider: connection.provider,
3057
3076
  trafficToken: getTrafficToken(connection),
3058
3077
  invocationId: executionId,
3059
- signal: AbortSignal.timeout(this.maxDuration * 1e3 + 5e3)
3078
+ signal: AbortSignal.timeout(this.maxDuration * 1e3 + RUNTIME_ABORT_GRACE_MS + 5e3)
3060
3079
  })) {
3061
3080
  if (event.kind === "error") {
3062
3081
  const err = new ExecutionError(event.error.message);
@@ -3083,6 +3102,10 @@ var require = __neckbeard_createRequire(import.meta.url);
3083
3102
  }
3084
3103
  return { ok: true, executionId, output: validated };
3085
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
+ }
3086
3109
  return { ok: false, executionId, error: err instanceof Error ? err : new Error(String(err)) };
3087
3110
  }
3088
3111
  }
@@ -3125,7 +3148,7 @@ var require = __neckbeard_createRequire(import.meta.url);
3125
3148
  }
3126
3149
  if (durability !== void 0 && durability !== "attached") {
3127
3150
  throw new ConfigurationError(
3128
- "Agent.createSession() creates caller-owned attached sessions. Use agent-neckbeard/supervisor durable-session APIs for gateway-owned sessions."
3151
+ "Agent.createSession() creates caller-owned attached sessions. Gateway-owned durable sessions use the deprecated agent-neckbeard/supervisor APIs."
3129
3152
  );
3130
3153
  }
3131
3154
  if (requestedSandboxId !== void 0 && (typeof requestedSandboxId !== "string" || requestedSandboxId.trim() === "")) {
@@ -3155,7 +3178,7 @@ var require = __neckbeard_createRequire(import.meta.url);
3155
3178
  signal,
3156
3179
  reuseMatchingCachedConnection: true
3157
3180
  });
3158
- const { invokeServer } = await import("./invoke-client-HIXYE2WN.js");
3181
+ const { invokeServer, InvokeHttpError } = await import("./invoke-client-YKWOTQWG.js");
3159
3182
  let validated;
3160
3183
  try {
3161
3184
  validated = this.inputSchema.parse(input);
@@ -3187,9 +3210,52 @@ var require = __neckbeard_createRequire(import.meta.url);
3187
3210
  }
3188
3211
  } catch (error) {
3189
3212
  if (error instanceof ExecutionError) throw error;
3213
+ if (error instanceof InvokeHttpError && error.status === 409) {
3214
+ throw new RuntimeBusyError(error.message);
3215
+ }
3190
3216
  throw error instanceof Error ? error : new Error(String(error));
3191
3217
  }
3192
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
+ }
3193
3259
  /**
3194
3260
  * @deprecated Use `createSession()` and call `session.prompt(input)` instead.
3195
3261
  * This compatibility wrapper creates one attached session, streams one turn,
@@ -3214,6 +3280,7 @@ export {
3214
3280
  DeploymentError,
3215
3281
  ExecutionError,
3216
3282
  NeckbeardError,
3283
+ RuntimeBusyError,
3217
3284
  SandboxClient,
3218
3285
  ValidationError,
3219
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
  };
@@ -345,20 +345,26 @@ interface DurableSessionArtifact {
345
345
  interface SupervisorSandboxTarget extends SupervisorSandboxCapabilities {
346
346
  readonly provider: "daytona";
347
347
  }
348
+ /** @deprecated The durable-session supervisor is no longer maintained and will be removed in a future major release. */
348
349
  declare function createDurableSessionArtifact(options: CreateDurableSessionArtifactOptions): DurableSessionArtifact;
350
+ /** @deprecated The durable-session supervisor is no longer maintained and will be removed in a future major release. */
349
351
  declare function deployDurableSessionArtifact(sandbox: SupervisorSandboxTarget, artifact: DurableSessionArtifact, options: {
350
352
  envs: Record<string, string | undefined>;
351
353
  beforeRelease?: (command: SandboxDetachedCommand) => void | Promise<void>;
352
354
  }): Promise<SandboxDetachedCommand>;
353
- /** Validates every launch secret before any sandbox I/O occurs. */
355
+ /**
356
+ * Validates every launch secret before any sandbox I/O occurs.
357
+ *
358
+ * @deprecated The durable-session supervisor is no longer maintained and will be removed in a future major release.
359
+ */
354
360
  declare function validateDurableSessionDeploymentEnvironment(artifact: DurableSessionArtifact, source: Record<string, string | undefined>): Record<string, string>;
355
- /** @deprecated Use `CreateDurableSessionArtifactOptions`. */
361
+ /** @deprecated The durable-session supervisor is no longer maintained and will be removed in a future major release. */
356
362
  type CreatePiSupervisorArtifactOptions = CreateDurableSessionArtifactOptions;
357
- /** @deprecated Use `DurableSessionArtifact`. */
363
+ /** @deprecated The durable-session supervisor is no longer maintained and will be removed in a future major release. */
358
364
  type PiSupervisorArtifact = DurableSessionArtifact;
359
- /** @deprecated Use `createDurableSessionArtifact()`. */
365
+ /** @deprecated The durable-session supervisor is no longer maintained and will be removed in a future major release. */
360
366
  declare const createPiSupervisorArtifact: typeof createDurableSessionArtifact;
361
- /** @deprecated Use `deployDurableSessionArtifact()`. */
367
+ /** @deprecated The durable-session supervisor is no longer maintained and will be removed in a future major release. */
362
368
  declare const deploySupervisorArtifact: typeof deployDurableSessionArtifact;
363
369
 
364
370
  interface DaytonaCommandResult {
@@ -398,18 +404,24 @@ interface DaytonaSupervisorSandboxTargetOptions {
398
404
  * Stops the exact managed Daytona supervisor process and resolves only after
399
405
  * the detached controller confirms exit. This does not remove lifecycle state
400
406
  * or captured diagnostics.
407
+ *
408
+ * @deprecated The durable-session supervisor is no longer maintained and will be removed in a future major release.
401
409
  */
402
410
  declare function stopDaytonaSupervisorSession(sandbox: DaytonaCommandTransport, command: SandboxDetachedCommand, targetOptions?: DaytonaSupervisorSandboxTargetOptions): Promise<void>;
403
411
  /**
404
412
  * Irreversibly removes lifecycle state and diagnostics for an exactly stopped
405
413
  * managed Daytona supervisor process. Call `stopDaytonaSupervisorSession()`
406
414
  * first; this operation is cleanup, not process-liveness proof.
415
+ *
416
+ * @deprecated The durable-session supervisor is no longer maintained and will be removed in a future major release.
407
417
  */
408
418
  declare function disposeDaytonaSupervisorSessionArtifacts(sandbox: DaytonaCommandTransport, command: SandboxDetachedCommand, targetOptions?: DaytonaSupervisorSandboxTargetOptions): Promise<void>;
409
419
  /**
410
420
  * Adapts an already-connected Daytona sandbox to the narrow deployment target
411
421
  * used by `deployDurableSessionArtifact()`. The returned target owns no client
412
422
  * connection and does not create, start, stop, or delete the sandbox.
423
+ *
424
+ * @deprecated The durable-session supervisor is no longer maintained and will be removed in a future major release.
413
425
  */
414
426
  declare function createDaytonaSupervisorSandboxTarget(sandbox: DaytonaSupervisorSandbox, targetOptions?: DaytonaSupervisorSandboxTargetOptions): Promise<SupervisorSandboxTarget>;
415
427
 
@@ -345,20 +345,26 @@ interface DurableSessionArtifact {
345
345
  interface SupervisorSandboxTarget extends SupervisorSandboxCapabilities {
346
346
  readonly provider: "daytona";
347
347
  }
348
+ /** @deprecated The durable-session supervisor is no longer maintained and will be removed in a future major release. */
348
349
  declare function createDurableSessionArtifact(options: CreateDurableSessionArtifactOptions): DurableSessionArtifact;
350
+ /** @deprecated The durable-session supervisor is no longer maintained and will be removed in a future major release. */
349
351
  declare function deployDurableSessionArtifact(sandbox: SupervisorSandboxTarget, artifact: DurableSessionArtifact, options: {
350
352
  envs: Record<string, string | undefined>;
351
353
  beforeRelease?: (command: SandboxDetachedCommand) => void | Promise<void>;
352
354
  }): Promise<SandboxDetachedCommand>;
353
- /** Validates every launch secret before any sandbox I/O occurs. */
355
+ /**
356
+ * Validates every launch secret before any sandbox I/O occurs.
357
+ *
358
+ * @deprecated The durable-session supervisor is no longer maintained and will be removed in a future major release.
359
+ */
354
360
  declare function validateDurableSessionDeploymentEnvironment(artifact: DurableSessionArtifact, source: Record<string, string | undefined>): Record<string, string>;
355
- /** @deprecated Use `CreateDurableSessionArtifactOptions`. */
361
+ /** @deprecated The durable-session supervisor is no longer maintained and will be removed in a future major release. */
356
362
  type CreatePiSupervisorArtifactOptions = CreateDurableSessionArtifactOptions;
357
- /** @deprecated Use `DurableSessionArtifact`. */
363
+ /** @deprecated The durable-session supervisor is no longer maintained and will be removed in a future major release. */
358
364
  type PiSupervisorArtifact = DurableSessionArtifact;
359
- /** @deprecated Use `createDurableSessionArtifact()`. */
365
+ /** @deprecated The durable-session supervisor is no longer maintained and will be removed in a future major release. */
360
366
  declare const createPiSupervisorArtifact: typeof createDurableSessionArtifact;
361
- /** @deprecated Use `deployDurableSessionArtifact()`. */
367
+ /** @deprecated The durable-session supervisor is no longer maintained and will be removed in a future major release. */
362
368
  declare const deploySupervisorArtifact: typeof deployDurableSessionArtifact;
363
369
 
364
370
  interface DaytonaCommandResult {
@@ -398,18 +404,24 @@ interface DaytonaSupervisorSandboxTargetOptions {
398
404
  * Stops the exact managed Daytona supervisor process and resolves only after
399
405
  * the detached controller confirms exit. This does not remove lifecycle state
400
406
  * or captured diagnostics.
407
+ *
408
+ * @deprecated The durable-session supervisor is no longer maintained and will be removed in a future major release.
401
409
  */
402
410
  declare function stopDaytonaSupervisorSession(sandbox: DaytonaCommandTransport, command: SandboxDetachedCommand, targetOptions?: DaytonaSupervisorSandboxTargetOptions): Promise<void>;
403
411
  /**
404
412
  * Irreversibly removes lifecycle state and diagnostics for an exactly stopped
405
413
  * managed Daytona supervisor process. Call `stopDaytonaSupervisorSession()`
406
414
  * first; this operation is cleanup, not process-liveness proof.
415
+ *
416
+ * @deprecated The durable-session supervisor is no longer maintained and will be removed in a future major release.
407
417
  */
408
418
  declare function disposeDaytonaSupervisorSessionArtifacts(sandbox: DaytonaCommandTransport, command: SandboxDetachedCommand, targetOptions?: DaytonaSupervisorSandboxTargetOptions): Promise<void>;
409
419
  /**
410
420
  * Adapts an already-connected Daytona sandbox to the narrow deployment target
411
421
  * used by `deployDurableSessionArtifact()`. The returned target owns no client
412
422
  * connection and does not create, start, stop, or delete the sandbox.
423
+ *
424
+ * @deprecated The durable-session supervisor is no longer maintained and will be removed in a future major release.
413
425
  */
414
426
  declare function createDaytonaSupervisorSandboxTarget(sandbox: DaytonaSupervisorSandbox, targetOptions?: DaytonaSupervisorSandboxTargetOptions): Promise<SupervisorSandboxTarget>;
415
427
 
@@ -1,5 +1,7 @@
1
1
  # Durable Sessions (Sandbox Supervisor)
2
2
 
3
+ > **Deprecated.** The durable-session supervisor is no longer maintained and will be removed in a future major release. Attached sessions (`Agent.createSession()`) remain supported, but they are not durable: a turn stops when its caller disconnects, and nothing is replayed.
4
+
3
5
  The sandbox supervisor is the implementation of Neckbeard's opt-in durable-session runtime. It is separate from the attached HTTP/SSE session transport: importing `agent-neckbeard/supervisor` does not change `Agent.deploy()`, `run()`, `createSession()`, the deprecated `invoke()` wrapper, or `kill()`.
4
6
 
5
7
  The v1 adapter embeds Pi through `@earendil-works/pi-coding-agent`'s structured SDK. The generated Node runtime connects outward from a Daytona sandbox to a WebSocket gateway, journals durable events before sending them, and lets an accepted Pi turn continue when the gateway or Hatchet worker disconnects.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-neckbeard",
3
- "version": "1.1.24",
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": {