agent-neckbeard 1.1.28 → 1.1.30

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.
Files changed (51) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +28 -30
  3. package/dist/archil.d.ts +73 -0
  4. package/dist/archil.js +673 -0
  5. package/dist/build.cjs +129 -5160
  6. package/dist/build.d.cts +9 -5
  7. package/dist/build.d.ts +9 -5
  8. package/dist/build.js +4 -6
  9. package/dist/{chunk-JF5YPOBY.js → chunk-FHNQ5DNA.js} +3235 -511
  10. package/dist/{chunk-M7XNBKG4.js → chunk-I5GIWADK.js} +29 -7
  11. package/dist/chunk-I5NULOJP.js +129 -0
  12. package/dist/chunk-PKUGXECR.js +13 -0
  13. package/dist/chunk-QA4L7ZI2.js +72 -0
  14. package/dist/{chunk-KG6SJM74.js → chunk-VHBDBB3N.js} +8 -5
  15. package/dist/cli.cjs +124 -5154
  16. package/dist/cli.js +7 -8
  17. package/dist/define-gdmBe9RA.d.ts +227 -0
  18. package/dist/durable.d.ts +53 -0
  19. package/dist/durable.js +92 -0
  20. package/dist/index.cjs +720 -833
  21. package/dist/index.d.cts +139 -78
  22. package/dist/index.d.ts +139 -78
  23. package/dist/index.js +12 -11
  24. package/dist/inside.d.ts +15 -0
  25. package/dist/inside.js +530 -0
  26. package/dist/{invoke-client-P2CPBYTF.js → invoke-client-QB2NTZ3L.js} +1 -2
  27. package/dist/pi-watch-legacy.d.ts +4503 -0
  28. package/dist/serve.cjs +9 -309
  29. package/dist/serve.d.cts +14 -1
  30. package/dist/serve.d.ts +14 -1
  31. package/dist/serve.js +3 -5
  32. package/docs/AGENT.md +95 -59
  33. package/docs/DAYTONA.md +2 -0
  34. package/docs/DOCKER.md +0 -1
  35. package/docs/E2B.md +1 -1
  36. package/docs/LEGACY.md +1 -8
  37. package/docs/MODAL.md +1 -1
  38. package/package.json +57 -23
  39. package/types/pi-watch.d.cts +68 -0
  40. package/dist/chunk-33IXN6MM.js +0 -21
  41. package/dist/chunk-6P5I7ZCH.js +0 -2552
  42. package/dist/chunk-M3FISP7J.js +0 -377
  43. package/dist/sandbox-capabilities-CFjnZ_kB.d.cts +0 -77
  44. package/dist/sandbox-capabilities-CFjnZ_kB.d.ts +0 -77
  45. package/dist/serve-Dan1HQKN.d.cts +0 -89
  46. package/dist/serve-Dan1HQKN.d.ts +0 -89
  47. package/dist/supervisor.cjs +0 -5731
  48. package/dist/supervisor.d.cts +0 -482
  49. package/dist/supervisor.d.ts +0 -482
  50. package/dist/supervisor.js +0 -3187
  51. package/docs/SUPERVISOR.md +0 -258
@@ -1,34 +1,11 @@
1
1
  import {
2
- DETACHED_PROCESS_CONTROL_TIMEOUT_MS,
3
- DETACHED_PROCESS_LOG_MAX_BYTES,
4
- DetachedProcessController,
5
- boundDetachedProcessLog,
6
- buildLegacyDetachedStopCommand,
7
- buildReadLegacyDetachedLogsCommand,
8
- createDaytonaDetachedProcessController,
9
- daytonaTimeoutSeconds,
10
- discoverDaytonaSandboxDirectories,
11
- executeDaytonaCommand,
12
- executeRawDaytonaCommand,
13
- makeDaytonaDirectory,
14
- normalizeProviderSandboxDetachedCommandOptions,
15
- parseDetachedProcessLogs,
16
- shellQuote,
17
- uploadDaytonaFile
18
- } from "./chunk-6P5I7ZCH.js";
19
- import {
20
- TURN_PROTOCOL_VERSION,
21
- getPiTurnResult,
22
- parseTurnHealth,
23
- parseTurnRecord,
24
2
  serve
25
- } from "./chunk-M3FISP7J.js";
3
+ } from "./chunk-PKUGXECR.js";
26
4
  import {
27
- IncompleteSseFrameError,
28
5
  RUNTIME_ABORT_GRACE_MS,
29
6
  RUNTIME_PROTOCOL_VERSION,
30
7
  decodeSseStream
31
- } from "./chunk-KG6SJM74.js";
8
+ } from "./chunk-VHBDBB3N.js";
32
9
 
33
10
  // src/index.ts
34
11
  import { fileURLToPath } from "url";
@@ -51,12 +28,155 @@ import {
51
28
  sep,
52
29
  win32
53
30
  } from "path";
54
- import { randomUUID } from "crypto";
31
+ import { randomUUID as randomUUID2 } from "crypto";
55
32
  import { builtinModules, createRequire as createRequire2 } from "module";
56
33
 
57
34
  // src/runtime/server-source.generated.ts
58
35
  var RUNTIME_SERVER_SOURCE = '// src/runtime/server.ts\nimport { createServer } from "node:http";\nimport { readFileSync } from "node:fs";\nimport { fileURLToPath } from "node:url";\nimport { dirname, join } from "node:path";\nimport { once } from "node:events";\n\n// src/serialized-error.ts\nfunction serializeError(error) {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n ...error.stack === void 0 ? {} : { stack: error.stack }\n };\n }\n return { message: String(error) };\n}\n\n// src/runtime/protocol.ts\nvar RUNTIME_PROTOCOL_VERSION = 1;\nvar RUNTIME_ABORT_GRACE_MS = 1e4;\n\n// src/runtime/server.ts\nvar CONFIG_PATH = join(dirname(fileURLToPath(import.meta.url)), "server-config.json");\nvar CONFIG = JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));\nvar MAX_REQUEST_BODY_BYTES = 4 * 1024 * 1024;\nvar DEFAULT_SSE_HEARTBEAT_INTERVAL_MS = 15e3;\nvar RequestBodyTooLargeError = class extends Error {\n constructor(limitBytes) {\n super(`request body exceeds ${limitBytes} bytes`);\n this.name = "RequestBodyTooLargeError";\n }\n};\nfunction createLogger() {\n return {\n debug: (message, ...args) => console.log("[DEBUG]", message, ...args),\n info: (message, ...args) => console.log("[INFO]", message, ...args),\n warn: (message, ...args) => console.warn("[WARN]", message, ...args),\n error: (message, ...args) => console.error("[ERROR]", message, ...args)\n };\n}\nfunction sendJson(res, status, body) {\n res.writeHead(status, { "content-type": "application/json" });\n res.end(JSON.stringify(body));\n}\nfunction getSseHeartbeatIntervalMs() {\n const raw = process.env.NECKBEARD_RUNTIME_SSE_HEARTBEAT_MS;\n if (!raw) return DEFAULT_SSE_HEARTBEAT_INTERVAL_MS;\n const parsed = Number(raw);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_SSE_HEARTBEAT_INTERVAL_MS;\n}\nfunction getAbortGraceMs() {\n const raw = process.env.NECKBEARD_RUNTIME_ABORT_GRACE_MS;\n if (!raw) return RUNTIME_ABORT_GRACE_MS;\n const parsed = Number(raw);\n return Number.isFinite(parsed) && parsed >= 0 ? parsed : RUNTIME_ABORT_GRACE_MS;\n}\nfunction sendSseComment(res, comment) {\n if (res.writableEnded || res.destroyed) return;\n res.write(`: ${comment}\n\n`);\n}\nasync function sendSseFrame(res, event, signal) {\n if (res.destroyed) return;\n const canContinue = res.write(`data: ${JSON.stringify(event)}\n\n`);\n if (!canContinue && !signal.aborted) {\n await once(res, "drain", { signal }).catch(() => void 0);\n }\n}\nasync function readRequestBody(req, maxBytes = MAX_REQUEST_BODY_BYTES) {\n const chunks = [];\n let totalBytes = 0;\n for await (const chunk of req) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n totalBytes += buffer.byteLength;\n if (totalBytes > maxBytes) {\n throw new RequestBodyTooLargeError(maxBytes);\n }\n chunks.push(buffer);\n }\n return Buffer.concat(chunks).toString("utf-8");\n}\nfunction createTimeoutError(maxDurationMs) {\n const error = new Error(`Agent invocation exceeded maxDuration (${maxDurationMs}ms)`);\n error.name = "TimeoutError";\n return error;\n}\nfunction settleAfterAbort(task, signal, maxDurationMs) {\n return new Promise((resolve, reject) => {\n let aborted = false;\n const rejectAborted = () => reject(createTimeoutError(maxDurationMs));\n const onAbort = () => {\n aborted = true;\n const grace = setTimeout(rejectAborted, getAbortGraceMs());\n const stopped = () => {\n clearTimeout(grace);\n rejectAborted();\n };\n task.then(stopped, stopped);\n };\n if (signal.aborted) onAbort();\n else signal.addEventListener("abort", onAbort, { once: true });\n task.then(\n (value) => {\n if (aborted) return;\n signal.removeEventListener("abort", onAbort);\n resolve(value);\n },\n (error) => {\n if (aborted) return;\n signal.removeEventListener("abort", onAbort);\n reject(error);\n }\n );\n });\n}\nasync function loadAgent() {\n const mod = await import(new URL("./agent.mjs", import.meta.url).href);\n const agent = (mod.default && (mod.default._run || mod.default._server) ? mod.default : null) || Object.values(mod).find(\n (value) => value && typeof value === "object" && ("_run" in value || "_server" in value)\n );\n if (!agent || typeof agent !== "object") {\n throw new Error(\n `No agent found in agent.mjs. Exports: ${Object.keys(mod).join(", ")}`\n );\n }\n return agent;\n}\nasync function main() {\n const agent = await loadAgent();\n let activeInvocationId = null;\n const server = createServer(async (req, res) => {\n try {\n const url = new URL(req.url ?? "/", "http://localhost");\n if (url.pathname === "/health" && req.method === "GET") {\n return sendJson(res, 200, {\n ok: true,\n protocolVersion: RUNTIME_PROTOCOL_VERSION,\n busy: activeInvocationId !== null\n });\n }\n if (url.pathname === "/shutdown" && req.method === "POST") {\n sendJson(res, 200, { ok: true });\n setTimeout(() => shutdown(), 10).unref();\n return;\n }\n if (url.pathname === "/invoke" && req.method === "POST") {\n let rawBody;\n try {\n rawBody = await readRequestBody(req);\n } catch (error) {\n if (error instanceof RequestBodyTooLargeError) {\n return sendJson(res, 413, { error: error.message });\n }\n throw error;\n }\n let requestBody;\n try {\n requestBody = JSON.parse(rawBody);\n } catch {\n return sendJson(res, 400, { error: "invalid JSON body" });\n }\n if (!requestBody || typeof requestBody !== "object" || typeof requestBody.invocationId !== "string") {\n return sendJson(res, 400, { error: "invalid invoke request" });\n }\n let validatedInput;\n try {\n validatedInput = agent.inputSchema.parse(requestBody.input);\n } catch (error) {\n return sendJson(res, 400, {\n error: `input validation failed: ${serializeError(error).message}`\n });\n }\n if (activeInvocationId !== null) {\n return sendJson(res, 409, {\n error: `invocation ${activeInvocationId} is still running`\n });\n }\n const invocationId = requestBody.invocationId;\n activeInvocationId = invocationId;\n res.writeHead(200, {\n "content-type": "text/event-stream",\n "cache-control": "no-cache, no-transform",\n connection: "keep-alive",\n "x-accel-buffering": "no"\n });\n const controller = new AbortController();\n req.on("aborted", () => controller.abort());\n res.on("close", () => {\n if (!res.writableEnded) {\n controller.abort();\n }\n });\n const startedAt = Date.now();\n let sequence = 0;\n const timeout = setTimeout(() => controller.abort(), CONFIG.maxDurationMs);\n const heartbeat = setInterval(() => {\n try {\n sendSseComment(res, `heartbeat ${Date.now()}`);\n } catch {\n controller.abort();\n }\n }, getSseHeartbeatIntervalMs());\n heartbeat.unref();\n const emitHarnessEvent = async (event) => {\n if (!res.writableEnded) {\n await sendSseFrame(res, {\n protocolVersion: RUNTIME_PROTOCOL_VERSION,\n sequence: sequence++,\n timestamp: (/* @__PURE__ */ new Date()).toISOString(),\n elapsedMs: Date.now() - startedAt,\n ...event\n }, controller.signal);\n }\n };\n const ctx = {\n executionId: invocationId,\n signal: controller.signal,\n env: process.env,\n sandbox: CONFIG.sandboxContext,\n logger: createLogger()\n };\n let running;\n try {\n await emitHarnessEvent({ kind: "started", invocationId });\n const handler = agent._server ? () => agent._server.handler({\n input: validatedInput,\n ctx,\n signal: controller.signal,\n emit: async (data) => {\n const validatedFrame = agent._server?.frameSchema ? agent._server.frameSchema.parse(data) : data;\n await emitHarnessEvent({ kind: "frame", invocationId, data: validatedFrame });\n }\n }) : agent._run ? () => agent._run(validatedInput, ctx) : () => {\n throw new Error("Agent has neither a run handler nor a server handler.");\n };\n if (controller.signal.aborted) throw createTimeoutError(CONFIG.maxDurationMs);\n running = Promise.resolve().then(handler);\n void running.catch(() => void 0).finally(() => {\n if (activeInvocationId === invocationId) activeInvocationId = null;\n });\n const output = await settleAfterAbort(running, controller.signal, CONFIG.maxDurationMs);\n if (agent._run && !agent._server) {\n const validatedOutput = agent.outputSchema ? agent.outputSchema.parse(output) : output;\n await emitHarnessEvent({ kind: "output", invocationId, output: validatedOutput });\n }\n await emitHarnessEvent({ kind: "done", invocationId });\n } catch (error) {\n await emitHarnessEvent({ kind: "error", invocationId, error: serializeError(error) });\n } finally {\n clearInterval(heartbeat);\n clearTimeout(timeout);\n if (!running && activeInvocationId === invocationId) activeInvocationId = null;\n if (!res.writableEnded) {\n res.end();\n }\n }\n return;\n }\n return sendJson(res, 404, { error: "not found" });\n } catch (error) {\n console.error("[neckbeard-server] unexpected error", error);\n if (!res.headersSent) {\n sendJson(res, 500, { error: "internal error" });\n } else if (!res.writableEnded) {\n res.end();\n }\n }\n });\n function shutdown() {\n console.log("[neckbeard-server] shutting down");\n server.close(() => process.exit(0));\n setTimeout(() => process.exit(0), 5e3).unref();\n }\n server.listen(CONFIG.port, "0.0.0.0", () => {\n console.log(`[neckbeard-server] listening on port ${CONFIG.port}`);\n });\n process.on("SIGTERM", shutdown);\n process.on("SIGINT", shutdown);\n}\nmain().catch((error) => {\n console.error("[neckbeard-server] failed to start", error);\n process.exit(1);\n});\n';
59
36
 
37
+ // src/sandbox-capabilities.ts
38
+ var SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV = "NECKBEARD_SUPERVISOR_ENVIRONMENT_V1";
39
+ var SUPERVISOR_ENVIRONMENT_FD_ENV = "NECKBEARD_SUPERVISOR_ENVIRONMENT_FD";
40
+ var SUPERVISOR_ENVIRONMENT_FD = 3;
41
+ var SUPERVISOR_ENVIRONMENT_MAX_BYTES = 64 * 1024;
42
+ var SUPERVISOR_ENVIRONMENT_MAX_ENTRIES = 256;
43
+ var SUPERVISOR_ENVIRONMENT_MAX_NAME_BYTES = 256;
44
+ var SUPERVISOR_ENVIRONMENT_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/u;
45
+ function supervisorEnvironmentByteLength(value) {
46
+ return new TextEncoder().encode(value).byteLength;
47
+ }
48
+ function isRecord(value) {
49
+ if (typeof value !== "object" || value === null) return false;
50
+ try {
51
+ return !Array.isArray(value);
52
+ } catch {
53
+ return false;
54
+ }
55
+ }
56
+ function normalizeSupervisorEnvironment(value) {
57
+ if (!isRecord(value)) return { ok: false, reason: "invalid_environment" };
58
+ let entries;
59
+ try {
60
+ entries = Object.entries(value).sort(
61
+ ([left], [right]) => left < right ? -1 : left > right ? 1 : 0
62
+ );
63
+ } catch {
64
+ return { ok: false, reason: "invalid_environment" };
65
+ }
66
+ if (entries.length > SUPERVISOR_ENVIRONMENT_MAX_ENTRIES) {
67
+ return { ok: false, reason: "entry_limit" };
68
+ }
69
+ const environment = /* @__PURE__ */ Object.create(null);
70
+ let environmentBytes = 0;
71
+ let exceedsByteLimit = false;
72
+ for (const [name, item] of entries) {
73
+ if (name.length > SUPERVISOR_ENVIRONMENT_MAX_NAME_BYTES || !SUPERVISOR_ENVIRONMENT_NAME_PATTERN.test(name) || name === SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV || name === SUPERVISOR_ENVIRONMENT_FD_ENV) {
74
+ return { ok: false, reason: "invalid_name" };
75
+ }
76
+ if (typeof item !== "string" || item.includes("\0")) {
77
+ return { ok: false, reason: "invalid_value" };
78
+ }
79
+ if (!exceedsByteLimit) {
80
+ if (item.length > SUPERVISOR_ENVIRONMENT_MAX_BYTES || environmentBytes + name.length + item.length > SUPERVISOR_ENVIRONMENT_MAX_BYTES) {
81
+ exceedsByteLimit = true;
82
+ } else {
83
+ environmentBytes += name.length + supervisorEnvironmentByteLength(item);
84
+ if (environmentBytes > SUPERVISOR_ENVIRONMENT_MAX_BYTES) {
85
+ exceedsByteLimit = true;
86
+ }
87
+ }
88
+ }
89
+ environment[name] = item;
90
+ }
91
+ if (exceedsByteLimit) return { ok: false, reason: "byte_limit" };
92
+ return {
93
+ ok: true,
94
+ environment,
95
+ environmentKeys: entries.map(([name]) => name)
96
+ };
97
+ }
98
+ function serializeSupervisorEnvironmentHandoff(value, defaults) {
99
+ let normalized = normalizeSupervisorEnvironment(value);
100
+ if (!normalized.ok) return normalized;
101
+ if (defaults !== void 0) {
102
+ const normalizedDefaults = normalizeSupervisorEnvironment(defaults);
103
+ if (!normalizedDefaults.ok) return normalizedDefaults;
104
+ const environment = Object.assign(
105
+ /* @__PURE__ */ Object.create(null),
106
+ normalizedDefaults.environment,
107
+ normalized.environment
108
+ );
109
+ normalized = normalizeSupervisorEnvironment(environment);
110
+ if (!normalized.ok) return normalized;
111
+ }
112
+ let payload;
113
+ try {
114
+ payload = JSON.stringify({ version: 1, environment: normalized.environment });
115
+ } catch {
116
+ return { ok: false, reason: "serialization_failed" };
117
+ }
118
+ if (payload.length > SUPERVISOR_ENVIRONMENT_MAX_BYTES || supervisorEnvironmentByteLength(payload) > SUPERVISOR_ENVIRONMENT_MAX_BYTES) {
119
+ return { ok: false, reason: "byte_limit" };
120
+ }
121
+ return { ...normalized, payload };
122
+ }
123
+ function normalizeProviderSandboxDetachedCommandOptions(value, failure, policy = {}) {
124
+ if (policy.requireObject) {
125
+ try {
126
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
127
+ throw new Error("invalid detached command options");
128
+ }
129
+ } catch {
130
+ throw failure("Detached command options could not be inspected.");
131
+ }
132
+ }
133
+ let cwd;
134
+ let rawEnvironment;
135
+ let launchId;
136
+ let beforeRelease;
137
+ let environmentMode;
138
+ let environmentRevision;
139
+ let restartReleasedWhenExited;
140
+ try {
141
+ cwd = Reflect.get(value, "cwd");
142
+ rawEnvironment = Reflect.get(value, "envs");
143
+ launchId = Reflect.get(value, "launchId");
144
+ beforeRelease = Reflect.get(value, "beforeRelease");
145
+ environmentMode = Reflect.get(value, "environmentMode");
146
+ environmentRevision = Reflect.get(value, "environmentRevision");
147
+ restartReleasedWhenExited = Reflect.get(
148
+ value,
149
+ "restartReleasedWhenExited"
150
+ );
151
+ } catch {
152
+ throw failure("Detached command options could not be inspected.");
153
+ }
154
+ if (cwd !== void 0 && typeof cwd !== "string") {
155
+ throw failure("Detached command cwd must be a string when provided.");
156
+ }
157
+ if (policy.validateBeforeRelease && beforeRelease !== void 0 && typeof beforeRelease !== "function") {
158
+ throw failure("Detached command beforeRelease must be a function.");
159
+ }
160
+ const options = {
161
+ cwd,
162
+ envs: rawEnvironment,
163
+ launchId,
164
+ beforeRelease,
165
+ environmentMode,
166
+ environmentRevision,
167
+ restartReleasedWhenExited
168
+ };
169
+ return {
170
+ options,
171
+ environment: {
172
+ environmentMode,
173
+ environmentRevision,
174
+ restartReleasedWhenExited,
175
+ rawEnvironment
176
+ }
177
+ };
178
+ }
179
+
60
180
  // src/attached-session.ts
61
181
  function linkAbortSignals(signals) {
62
182
  const controller = new AbortController();
@@ -115,8 +235,8 @@ var AttachedAgentSessionImpl = class {
115
235
  get closed() {
116
236
  return this.isClosed;
117
237
  }
118
- prompt(input) {
119
- return this.runTurn(input);
238
+ prompt(input2) {
239
+ return this.runTurn(input2);
120
240
  }
121
241
  async stop(reason = "attached_session_stopped") {
122
242
  await this.stopActiveTurn(reason);
@@ -124,7 +244,7 @@ var AttachedAgentSessionImpl = class {
124
244
  close() {
125
245
  return this.closeWithReason("attached_session_closed");
126
246
  }
127
- async *runTurn(input) {
247
+ async *runTurn(input2) {
128
248
  if (this.isClosed || this.lifetime.signal.aborted) {
129
249
  throw this.configurationError("Attached session is closed.");
130
250
  }
@@ -133,7 +253,7 @@ var AttachedAgentSessionImpl = class {
133
253
  }
134
254
  const controller = new AbortController();
135
255
  const linked = linkAbortSignals([this.lifetime.signal, controller.signal]);
136
- const iterator = this.runPrompt(input, linked.signal);
256
+ const iterator = this.runPrompt(input2, linked.signal);
137
257
  const turn = {
138
258
  controller,
139
259
  iterator,
@@ -184,6 +304,11 @@ function createAttachedAgentSession(options) {
184
304
  return new AttachedAgentSessionImpl(options);
185
305
  }
186
306
 
307
+ // src/shell.ts
308
+ function shellQuote(value) {
309
+ return `'${value.replace(/'/g, `'\\''`)}'`;
310
+ }
311
+
187
312
  // src/tar.ts
188
313
  import { Buffer as Buffer2 } from "buffer";
189
314
  import { promisify } from "util";
@@ -242,29 +367,2382 @@ function paxPathRecord(path2) {
242
367
  return Buffer2.from(`${length}${body}`);
243
368
  }
244
369
  async function createTarGz(entries, mtime = Math.floor(Date.now() / 1e3)) {
245
- const chunks = [];
246
- for (const entry of entries) {
247
- const isDirectory = entry.content === void 0;
248
- const path2 = isDirectory ? `${entry.path.replace(/\/+$/u, "")}/` : entry.path;
249
- const size = entry.content?.byteLength ?? 0;
370
+ const chunks2 = [];
371
+ for (const entry2 of entries) {
372
+ const isDirectory = entry2.content === void 0;
373
+ const path2 = isDirectory ? `${entry2.path.replace(/\/+$/u, "")}/` : entry2.path;
374
+ const size = entry2.content?.byteLength ?? 0;
250
375
  const type = isDirectory ? "5" : "0";
251
376
  const mode = isDirectory ? 493 : 420;
252
377
  const split = splitUstarPath(path2);
253
378
  if (split) {
254
- chunks.push(header({ ...split, mode, size, mtime, type }));
379
+ chunks2.push(header({ ...split, mode, size, mtime, type }));
255
380
  } else {
256
381
  const record = paxPathRecord(path2);
257
- chunks.push(header({ name: "PaxHeader", mode: 420, size: record.byteLength, mtime, type: "x" }));
258
- chunks.push(record, padding(record.byteLength));
259
- chunks.push(header({ name: path2.slice(-100).replace(/^\/+/u, ""), mode, size, mtime, type }));
382
+ chunks2.push(header({ name: "PaxHeader", mode: 420, size: record.byteLength, mtime, type: "x" }));
383
+ chunks2.push(record, padding(record.byteLength));
384
+ chunks2.push(header({ name: path2.slice(-100).replace(/^\/+/u, ""), mode, size, mtime, type }));
260
385
  }
261
- if (entry.content) {
262
- chunks.push(Buffer2.from(entry.content.buffer, entry.content.byteOffset, entry.content.byteLength));
263
- chunks.push(padding(size));
386
+ if (entry2.content) {
387
+ chunks2.push(Buffer2.from(entry2.content.buffer, entry2.content.byteOffset, entry2.content.byteLength));
388
+ chunks2.push(padding(size));
264
389
  }
265
390
  }
266
- chunks.push(Buffer2.alloc(BLOCK_SIZE * 2));
267
- return gzipAsync(Buffer2.concat(chunks));
391
+ chunks2.push(Buffer2.alloc(BLOCK_SIZE * 2));
392
+ return gzipAsync(Buffer2.concat(chunks2));
393
+ }
394
+
395
+ // src/providers/detached-process.ts
396
+ import { isUtf8 } from "buffer";
397
+ import { createHash, randomUUID } from "crypto";
398
+ var DETACHED_PROCESS_ROOT = "/tmp/agent-neckbeard-detached";
399
+ var DETACHED_PROCESS_CONTROL_TIMEOUT_MS = 3e4;
400
+ var DETACHED_PROCESS_LOG_MAX_BYTES = 8 * 1024 * 1024;
401
+ var DETACHED_PROCESS_CONTROL_OUTPUT_MAX_BYTES = 64 * 1024;
402
+ var DETACHED_PROCESS_LOG_ENVELOPE_MAX_BYTES = 256 + 8 * Math.ceil(DETACHED_PROCESS_LOG_MAX_BYTES / 3);
403
+ var DETACHED_PROCESS_TRUSTED_PATH = "/usr/local/share/nvm/current/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
404
+ var DETACHED_PROCESS_LIFECYCLE_ENVIRONMENT = {
405
+ PATH: DETACHED_PROCESS_TRUSTED_PATH,
406
+ HOME: "/tmp",
407
+ TMPDIR: "/tmp",
408
+ LANG: "C.UTF-8"
409
+ };
410
+ var DETACHED_PROCESS_PROVIDER_CONTROL_ENVIRONMENT = Object.freeze({
411
+ ...DETACHED_PROCESS_LIFECYCLE_ENVIRONMENT,
412
+ HOME: "/nonexistent",
413
+ BASH_ENV: "/dev/null",
414
+ ENV: "/dev/null",
415
+ SHELLOPTS: "",
416
+ BASHOPTS: "",
417
+ PS4: "+ ",
418
+ BASH_XTRACEFD: ""
419
+ });
420
+ var DETACHED_PROCESS_LOG_CHUNK_BYTES = 64 * 1024;
421
+ var DETACHED_PROCESS_LOG_SEGMENT_BYTES = DETACHED_PROCESS_LOG_MAX_BYTES / 2 - DETACHED_PROCESS_LOG_CHUNK_BYTES;
422
+ var DETACHED_PROCESS_LOG_SNAPSHOT_MAX_BYTES = 96;
423
+ var DETACHED_PROCESS_LEGACY_LOG_SNAPSHOT_ATTEMPTS = 100;
424
+ var IDENTITY_PREFIX = "NECKBEARD_PROCESS_V3";
425
+ var LEGACY_IDENTITY_PREFIX = "NECKBEARD_PROCESS_V2";
426
+ var DECISION_PREFIX = "NECKBEARD_DECISION_V1";
427
+ var STARTED_PREFIX = "NECKBEARD_STARTED_V1";
428
+ var QUIESCENT_PREFIX = "NECKBEARD_QUIESCENT_V1";
429
+ var PREPARED_SENTINEL = "NECKBEARD_DETACHED_PREPARED";
430
+ var RELEASED_SENTINEL = "NECKBEARD_DETACHED_RELEASED";
431
+ var RELEASED_GENERATION_UNAVAILABLE_SENTINEL = "NECKBEARD_DETACHED_RELEASED_GENERATION_UNAVAILABLE";
432
+ var CANCELLED_SENTINEL = "NECKBEARD_DETACHED_CANCELLED";
433
+ var STOPPED_SENTINEL = "NECKBEARD_DETACHED_STOPPED";
434
+ var DISPOSED_SENTINEL = "NECKBEARD_DETACHED_ARTIFACTS_DISPOSED";
435
+ var LOGS_PREFIX = "NECKBEARD_DETACHED_LOGS_V1";
436
+ var LEGACY_LOG_SNAPSHOT_PREFIX = "NECKBEARD_LOG_SNAPSHOT_V1";
437
+ var LOG_SNAPSHOT_PREFIX = "NECKBEARD_LOG_SNAPSHOT_V2";
438
+ var DESCRIPTOR_MISMATCH_SENTINEL = "NECKBEARD_DETACHED_DESCRIPTOR_MISMATCH";
439
+ var HASH_PATTERN = "[a-f0-9]{64}";
440
+ var PREPARED_PATTERN = new RegExp(
441
+ `^${PREPARED_SENTINEL} (\\d+) (\\d+) (\\d+) (${HASH_PATTERN})$`,
442
+ "u"
443
+ );
444
+ var RELEASED_PATTERN = new RegExp(
445
+ `^${RELEASED_SENTINEL} (\\d+) (\\d+) (\\d+) (${HASH_PATTERN})$`,
446
+ "u"
447
+ );
448
+ var HANDLE_PATTERN = new RegExp(
449
+ `^(daytona|e2b|modal|docker)-process-v2:(\\d+):(\\d+):(\\d+):(${HASH_PATTERN}):(${HASH_PATTERN})$`,
450
+ "u"
451
+ );
452
+ function boundDetachedProcessLog(value) {
453
+ const candidate = value.length > DETACHED_PROCESS_LOG_MAX_BYTES ? value.slice(-DETACHED_PROCESS_LOG_MAX_BYTES) : value;
454
+ const bytes = Buffer.from(candidate, "utf8");
455
+ if (bytes.byteLength <= DETACHED_PROCESS_LOG_MAX_BYTES) return candidate;
456
+ let offset = bytes.byteLength - DETACHED_PROCESS_LOG_MAX_BYTES;
457
+ while (offset < bytes.byteLength && ((bytes[offset] ?? 0) & 192) === 128) {
458
+ offset += 1;
459
+ }
460
+ return bytes.subarray(offset).toString("utf8");
461
+ }
462
+ var DETACHED_PROCESS_LAUNCH_CANCELLED_MARKER = /* @__PURE__ */ Symbol.for(
463
+ "agent-neckbeard.detached-process-launch-cancelled.v1"
464
+ );
465
+ var DETACHED_PROCESS_RELEASED_GENERATION_UNAVAILABLE_MARKER = /* @__PURE__ */ Symbol.for(
466
+ "agent-neckbeard.detached-process-released-generation-unavailable.v1"
467
+ );
468
+ var DetachedProcessLaunchCancelledError = class extends Error {
469
+ name = "DetachedProcessLaunchCancelledError";
470
+ [DETACHED_PROCESS_LAUNCH_CANCELLED_MARKER] = true;
471
+ constructor() {
472
+ super("Detached process launch was cancelled before release.");
473
+ }
474
+ };
475
+ var DetachedProcessReleasedGenerationUnavailableError = class extends Error {
476
+ name = "DetachedProcessReleasedGenerationUnavailableError";
477
+ [DETACHED_PROCESS_RELEASED_GENERATION_UNAVAILABLE_MARKER] = true;
478
+ constructor() {
479
+ super("Detached released process generation is unavailable.");
480
+ }
481
+ };
482
+ function markDetachedProcessLaunchCancelled(error) {
483
+ return markDetachedProcessError(error, DETACHED_PROCESS_LAUNCH_CANCELLED_MARKER);
484
+ }
485
+ function markDetachedProcessReleasedGenerationUnavailable(error) {
486
+ return markDetachedProcessError(
487
+ error,
488
+ DETACHED_PROCESS_RELEASED_GENERATION_UNAVAILABLE_MARKER
489
+ );
490
+ }
491
+ function markDetachedProcessError(error, marker) {
492
+ if (typeof error !== "object" && typeof error !== "function" || error === null) {
493
+ return error;
494
+ }
495
+ try {
496
+ Reflect.defineProperty(error, marker, {
497
+ configurable: false,
498
+ enumerable: false,
499
+ value: true,
500
+ writable: false
501
+ });
502
+ } catch {
503
+ }
504
+ return error;
505
+ }
506
+ function messageFrom(error) {
507
+ return error instanceof Error ? error.message : String(error);
508
+ }
509
+ function hash(parts) {
510
+ return createHash("sha256").update(JSON.stringify(parts), "utf8").digest("hex");
511
+ }
512
+ function detachedEnvironmentFailureMessage(boundary, reason) {
513
+ const subject = `${boundary} environment`;
514
+ if (reason === "entry_limit") return `${subject} exceeds the entry limit.`;
515
+ if (reason === "invalid_name") {
516
+ return `${subject} contains an invalid or reserved name.`;
517
+ }
518
+ if (reason === "invalid_value") return `${subject} contains an invalid value.`;
519
+ if (reason === "byte_limit") return `${subject} exceeds the byte limit.`;
520
+ if (reason === "invalid_environment" && boundary === "Detached command") {
521
+ return `${subject} could not be inspected.`;
522
+ }
523
+ return `${subject} could not be serialized.`;
524
+ }
525
+ function serializeDetachedEnvironment(value, boundary, defaults) {
526
+ const handoff = serializeSupervisorEnvironmentHandoff(
527
+ value === void 0 ? {} : value,
528
+ defaults
529
+ );
530
+ if (!handoff.ok) {
531
+ throw new Error(detachedEnvironmentFailureMessage(boundary, handoff.reason));
532
+ }
533
+ return handoff;
534
+ }
535
+ function createDetachedEnvironmentTransport(options, genericPayloadEnvironmentDefaults) {
536
+ const {
537
+ environmentMode: mode,
538
+ environmentRevision,
539
+ restartReleasedWhenExited,
540
+ rawEnvironment
541
+ } = options;
542
+ const hasSupervisorControl = mode !== void 0 || environmentRevision !== void 0 || restartReleasedWhenExited !== void 0;
543
+ if (!hasSupervisorControl) {
544
+ const handoff2 = serializeDetachedEnvironment(
545
+ rawEnvironment,
546
+ "Detached command",
547
+ genericPayloadEnvironmentDefaults
548
+ );
549
+ return {
550
+ mode: "exec",
551
+ providerEnvironment: {
552
+ ...DETACHED_PROCESS_PROVIDER_CONTROL_ENVIRONMENT,
553
+ [SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV]: handoff2.payload
554
+ },
555
+ environmentKeys: handoff2.environmentKeys
556
+ };
557
+ }
558
+ if (mode !== "supervisor-fd-v1" || typeof environmentRevision !== "string" || !/^[a-f0-9]{64}$/u.test(environmentRevision) || restartReleasedWhenExited !== true) {
559
+ throw new Error(
560
+ "Supervisor detached commands require FD mode, a lowercase SHA-256 environment revision, and exited-generation restart control."
561
+ );
562
+ }
563
+ const handoff = serializeDetachedEnvironment(rawEnvironment, "Supervisor");
564
+ return {
565
+ mode: "supervisor-fd-v1",
566
+ providerEnvironment: {
567
+ ...DETACHED_PROCESS_PROVIDER_CONTROL_ENVIRONMENT,
568
+ [SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV]: handoff.payload
569
+ },
570
+ environmentKeys: handoff.environmentKeys,
571
+ environmentRevision
572
+ };
573
+ }
574
+ function createDetachedLaunchDescriptor(command, cwd, environment, restartReleasedWhenExited = false) {
575
+ return hash([
576
+ "detached-command-v2",
577
+ command,
578
+ cwd ?? null,
579
+ environment?.mode ?? "exec",
580
+ ...environment?.environmentKeys ?? [],
581
+ ...environment?.environmentRevision === void 0 ? [] : ["environment-revision-v1", environment.environmentRevision],
582
+ ...restartReleasedWhenExited ? ["replacement-policy-v1"] : []
583
+ ]);
584
+ }
585
+ function createDetachedLaunchPaths(launchId) {
586
+ const semanticId = launchId === void 0 ? randomUUID() : launchId;
587
+ if (typeof semanticId !== "string" || !semanticId || semanticId.length > 512) {
588
+ throw new Error("Detached command launchId must contain between 1 and 512 characters.");
589
+ }
590
+ const launchKey = hash(["detached-launch-v1", semanticId]);
591
+ return pathsForLaunchKey(launchKey);
592
+ }
593
+ function pathsForLaunchKey(launchKey) {
594
+ const directory = `${DETACHED_PROCESS_ROOT}/${launchKey}`;
595
+ return detachedLaunchPathsForDirectory(
596
+ launchKey,
597
+ directory,
598
+ `${DETACHED_PROCESS_ROOT}/${launchKey}.lock`,
599
+ `${DETACHED_PROCESS_ROOT}/.${launchKey}.retired`
600
+ );
601
+ }
602
+ function detachedLaunchPathsForDirectory(launchKey, directory, controlLock, retiredDirectory) {
603
+ return {
604
+ launchKey,
605
+ directory,
606
+ record: `${directory}/identity`,
607
+ recordPartial: `${directory}/.identity.partial`,
608
+ decision: `${directory}/decision`,
609
+ releaseDecisionPartial: `${directory}/.release-decision.partial`,
610
+ cancelDecisionPartial: `${directory}/.cancel-decision.partial`,
611
+ started: `${directory}/started`,
612
+ startedPartial: `${directory}/.started.partial`,
613
+ quiescent: `${directory}/quiescent`,
614
+ controlLock,
615
+ retiredDirectory,
616
+ stdout: `${directory}/stdout.log`,
617
+ stderr: `${directory}/stderr.log`
618
+ };
619
+ }
620
+ function pathsForDetachedLaunchDirectory(paths, directory) {
621
+ return detachedLaunchPathsForDirectory(
622
+ paths.launchKey,
623
+ directory,
624
+ paths.controlLock,
625
+ paths.retiredDirectory
626
+ );
627
+ }
628
+ function parseIdentityOutput(pattern, provider, paths, descriptorKey, output) {
629
+ const match = pattern.exec(output.trim());
630
+ if (!match) return null;
631
+ const [, pid, startTicks, sessionId, returnedDescriptor] = match;
632
+ if (!pid || !startTicks || !sessionId || !returnedDescriptor || pid !== sessionId || returnedDescriptor !== descriptorKey) {
633
+ return null;
634
+ }
635
+ return { provider, pid, startTicks, sessionId, launchKey: paths.launchKey, descriptorKey };
636
+ }
637
+ function parsePreparedIdentity(provider, paths, descriptorKey, output) {
638
+ return parseIdentityOutput(PREPARED_PATTERN, provider, paths, descriptorKey, output);
639
+ }
640
+ function parseReleasedIdentity(provider, paths, descriptorKey, output) {
641
+ return parseIdentityOutput(RELEASED_PATTERN, provider, paths, descriptorKey, output);
642
+ }
643
+ function isDescriptorMismatch(output) {
644
+ return output.trim() === DESCRIPTOR_MISMATCH_SENTINEL;
645
+ }
646
+ function formatDetachedCommand(identity) {
647
+ return {
648
+ sessionId: `${identity.provider}-process-v2:${identity.pid}:${identity.startTicks}:${identity.sessionId}:${identity.launchKey}:${identity.descriptorKey}`,
649
+ commandId: identity.pid
650
+ };
651
+ }
652
+ function parseDetachedCommand(sessionId) {
653
+ const match = HANDLE_PATTERN.exec(sessionId);
654
+ if (!match) return null;
655
+ const [, provider, pid, startTicks, processSessionId, launchKey, descriptorKey] = match;
656
+ if (provider !== "daytona" && provider !== "e2b" && provider !== "modal" && provider !== "docker" || !pid || !startTicks || !processSessionId || !launchKey || !descriptorKey || pid !== processSessionId) {
657
+ return null;
658
+ }
659
+ return {
660
+ provider,
661
+ pid,
662
+ startTicks,
663
+ sessionId: processSessionId,
664
+ launchKey,
665
+ descriptorKey
666
+ };
667
+ }
668
+ function hasDetachedProcessV2Prefix(sessionId) {
669
+ return /^(?:daytona|e2b|modal|docker)-process-v2/u.test(sessionId);
670
+ }
671
+ var DETACHED_PROCESS_PROVIDER_NAMES = {
672
+ daytona: "Daytona",
673
+ e2b: "E2B",
674
+ modal: "Modal",
675
+ docker: "Docker"
676
+ };
677
+ function detachedProcessProviderName(provider) {
678
+ return DETACHED_PROCESS_PROVIDER_NAMES[provider];
679
+ }
680
+ function resolveDetachedCommandForProvider(sessionId, expectedProvider, failure, commandId) {
681
+ const identity = parseDetachedCommand(sessionId);
682
+ if (identity?.provider === expectedProvider) {
683
+ if (commandId !== void 0 && commandId !== identity.pid) {
684
+ throw failure(
685
+ `Detached process handle is invalid for ${detachedProcessProviderName(expectedProvider)}.`
686
+ );
687
+ }
688
+ return identity;
689
+ }
690
+ if (identity || hasDetachedProcessV2Prefix(sessionId)) {
691
+ throw failure(
692
+ `Detached process handle is invalid for ${detachedProcessProviderName(expectedProvider)}.`
693
+ );
694
+ }
695
+ return null;
696
+ }
697
+ function pathsForIdentity(identity) {
698
+ return pathsForLaunchKey(identity.launchKey);
699
+ }
700
+ function disposedDirectoryForIdentity(identity) {
701
+ const disposalKey = hash([
702
+ "detached-disposal-v1",
703
+ identity.provider,
704
+ identity.pid,
705
+ identity.startTicks,
706
+ identity.sessionId,
707
+ identity.launchKey,
708
+ identity.descriptorKey
709
+ ]);
710
+ return `${DETACHED_PROCESS_ROOT}/.${identity.launchKey}.${disposalKey}.disposed`;
711
+ }
712
+ var DetachedProcessController = class {
713
+ constructor(options) {
714
+ this.options = options;
715
+ }
716
+ get providerName() {
717
+ return detachedProcessProviderName(this.options.provider);
718
+ }
719
+ resolve(command) {
720
+ return resolveDetachedCommandForProvider(
721
+ command.sessionId,
722
+ this.options.provider,
723
+ this.options.failure,
724
+ command.commandId
725
+ );
726
+ }
727
+ async executeControl(command, options, stdoutMaxBytes = DETACHED_PROCESS_CONTROL_OUTPUT_MAX_BYTES) {
728
+ try {
729
+ const response = await this.options.execute(command, {
730
+ ...options,
731
+ envs: options?.envs ?? {
732
+ ...DETACHED_PROCESS_PROVIDER_CONTROL_ENVIRONMENT
733
+ }
734
+ });
735
+ if (!response || typeof response !== "object") {
736
+ throw new Error("invalid detached control response");
737
+ }
738
+ const state = Reflect.get(response, "state");
739
+ if (state === "failed") {
740
+ return {
741
+ state: "failed",
742
+ error: new Error(`${this.providerName} detached command control request failed.`)
743
+ };
744
+ }
745
+ if (state !== "completed") {
746
+ throw new Error("invalid detached control response");
747
+ }
748
+ const result = Reflect.get(response, "result");
749
+ if (!result || typeof result !== "object") {
750
+ throw new Error("invalid detached control result");
751
+ }
752
+ const exitCode = Reflect.get(result, "exitCode");
753
+ const stdout = Reflect.get(result, "stdout");
754
+ const stderr = Reflect.get(result, "stderr");
755
+ if (typeof exitCode !== "number" || !Number.isSafeInteger(exitCode) || typeof stdout !== "string" || typeof stderr !== "string" || stdout.length > stdoutMaxBytes || stderr.length > DETACHED_PROCESS_CONTROL_OUTPUT_MAX_BYTES || Buffer.byteLength(stdout, "utf8") > stdoutMaxBytes || Buffer.byteLength(stderr, "utf8") > DETACHED_PROCESS_CONTROL_OUTPUT_MAX_BYTES) {
756
+ throw new Error("invalid detached control result");
757
+ }
758
+ return {
759
+ state: "completed",
760
+ result: { exitCode, stdout, stderr }
761
+ };
762
+ } catch {
763
+ return {
764
+ state: "failed",
765
+ error: new Error(`${this.providerName} detached command control request failed.`)
766
+ };
767
+ }
768
+ }
769
+ async start(command, options = {}) {
770
+ if (typeof command !== "string") {
771
+ throw this.options.failure("Detached command must be a string.");
772
+ }
773
+ const normalized = normalizeProviderSandboxDetachedCommandOptions(
774
+ options,
775
+ this.options.failure,
776
+ { validateBeforeRelease: true }
777
+ );
778
+ const inspectedOptions = normalized.options;
779
+ const environment = createDetachedEnvironmentTransport(
780
+ normalized.environment,
781
+ this.options.genericPayloadEnvironmentDefaults
782
+ );
783
+ const protectProviderDiagnostics = environment.mode === "supervisor-fd-v1";
784
+ const restartReleasedWhenExited = protectProviderDiagnostics;
785
+ const paths = createDetachedLaunchPaths(inspectedOptions.launchId);
786
+ const descriptorKey = createDetachedLaunchDescriptor(
787
+ command,
788
+ inspectedOptions.cwd,
789
+ environment,
790
+ restartReleasedWhenExited
791
+ );
792
+ const identity = await this.prepareWithAdoption(
793
+ command,
794
+ paths,
795
+ descriptorKey,
796
+ inspectedOptions,
797
+ environment,
798
+ restartReleasedWhenExited
799
+ );
800
+ const detached = formatDetachedCommand(identity);
801
+ try {
802
+ await inspectedOptions.beforeRelease?.(detached);
803
+ } catch (error) {
804
+ const resolution2 = await this.cancelOrAdopt(
805
+ paths,
806
+ descriptorKey,
807
+ identity,
808
+ "Detached command preparation callback failed",
809
+ error,
810
+ protectProviderDiagnostics,
811
+ restartReleasedWhenExited
812
+ );
813
+ if (resolution2.state === "cancelled") {
814
+ throw markDetachedProcessLaunchCancelled(error);
815
+ }
816
+ if (resolution2.state === "released_generation_unavailable") {
817
+ throw markDetachedProcessReleasedGenerationUnavailable(error);
818
+ }
819
+ throw error;
820
+ }
821
+ let releaseFailure;
822
+ for (let attempt = 0; attempt < 2; attempt += 1) {
823
+ const release = await this.executeControl(
824
+ buildReleaseDetachedCommand(paths, identity, restartReleasedWhenExited)
825
+ );
826
+ if (release.state === "completed" && release.result.exitCode === 0 && isReleaseConfirmation(release.result.stdout, identity)) {
827
+ return detached;
828
+ }
829
+ if (restartReleasedWhenExited && release.state === "completed" && release.result.exitCode === 0 && release.result.stdout.trim() === RELEASED_GENERATION_UNAVAILABLE_SENTINEL) {
830
+ throw new DetachedProcessReleasedGenerationUnavailableError();
831
+ }
832
+ if (release.state === "failed") {
833
+ releaseFailure = protectProviderDiagnostics ? new Error(`${this.providerName} supervisor detached command release failed.`) : new Error(`${this.providerName} detached command release failed.`);
834
+ } else if (protectProviderDiagnostics) {
835
+ releaseFailure = new Error(
836
+ `${this.providerName} did not confirm supervisor detached command release.`
837
+ );
838
+ } else {
839
+ releaseFailure = new Error(`${this.providerName} did not confirm detached command release.`);
840
+ }
841
+ }
842
+ const resolution = await this.cancelOrAdopt(
843
+ paths,
844
+ descriptorKey,
845
+ identity,
846
+ `${this.providerName} detached command release was uncertain`,
847
+ releaseFailure,
848
+ protectProviderDiagnostics,
849
+ restartReleasedWhenExited
850
+ );
851
+ if (resolution.state === "released") return formatDetachedCommand(resolution.identity);
852
+ const failedRelease = this.options.failure(
853
+ protectProviderDiagnostics ? `${this.providerName} detached command release failed: ${messageFrom(releaseFailure)}` : `${this.providerName} detached command release failed.`
854
+ );
855
+ throw resolution.state === "released_generation_unavailable" ? markDetachedProcessReleasedGenerationUnavailable(failedRelease) : markDetachedProcessLaunchCancelled(failedRelease);
856
+ }
857
+ async prepareWithAdoption(command, paths, descriptorKey, options, environment, restartReleasedWhenExited) {
858
+ let failure;
859
+ for (let attempt = 0; attempt < 2; attempt += 1) {
860
+ await this.options.beforePrepareMutation?.();
861
+ const prepared = await this.executeControl(
862
+ buildPrepareDetachedCommand(
863
+ paths,
864
+ descriptorKey,
865
+ command,
866
+ environment.mode,
867
+ restartReleasedWhenExited
868
+ ),
869
+ { cwd: options.cwd, envs: environment.providerEnvironment }
870
+ );
871
+ if (prepared.state === "failed") {
872
+ failure = environment.mode === "supervisor-fd-v1" ? new Error(`${this.providerName} supervisor environment handoff failed.`) : new Error(`${this.providerName} detached command preparation failed.`);
873
+ continue;
874
+ }
875
+ const { result } = prepared;
876
+ const identity = result.exitCode === 0 ? parsePreparedIdentity(this.options.provider, paths, descriptorKey, result.stdout) : null;
877
+ if (identity) return identity;
878
+ if (isDescriptorMismatch(result.stdout)) {
879
+ throw this.options.failure(
880
+ "Detached command launchId is already bound to a different launch descriptor."
881
+ );
882
+ }
883
+ if (environment.mode === "supervisor-fd-v1") {
884
+ failure = new Error(
885
+ `${this.providerName} did not confirm the supervisor environment handoff.`
886
+ );
887
+ } else {
888
+ failure = new Error(`${this.providerName} did not confirm detached command preparation.`);
889
+ }
890
+ }
891
+ const resolution = await this.cancelOrAdopt(
892
+ paths,
893
+ descriptorKey,
894
+ void 0,
895
+ `${this.providerName} detached command preparation was uncertain`,
896
+ failure,
897
+ environment.mode === "supervisor-fd-v1",
898
+ restartReleasedWhenExited
899
+ );
900
+ if (resolution.state === "released") return resolution.identity;
901
+ const failedPreparation = this.options.failure(
902
+ environment.mode === "supervisor-fd-v1" ? `Failed to prepare detached ${this.providerName} process: ${messageFrom(failure)}` : `Failed to prepare detached ${this.providerName} process.`
903
+ );
904
+ throw resolution.state === "released_generation_unavailable" ? markDetachedProcessReleasedGenerationUnavailable(failedPreparation) : markDetachedProcessLaunchCancelled(failedPreparation);
905
+ }
906
+ async cancelOrAdopt(paths, descriptorKey, identity, context, cause, protectProviderDiagnostics = false, serializeGenerationChanges = false) {
907
+ let cleanupFailure;
908
+ for (let attempt = 0; attempt < 2; attempt += 1) {
909
+ if (identity === void 0) {
910
+ await this.options.beforePrepareMutation?.();
911
+ }
912
+ const stopped = await this.executeControl(
913
+ buildCancelDetachedCommand(
914
+ paths,
915
+ descriptorKey,
916
+ identity,
917
+ serializeGenerationChanges
918
+ )
919
+ );
920
+ if (stopped.state === "failed") {
921
+ cleanupFailure = protectProviderDiagnostics ? new Error(`${this.providerName} supervisor detached command cleanup failed.`) : new Error(`${this.providerName} detached command cleanup failed.`);
922
+ continue;
923
+ }
924
+ const { result } = stopped;
925
+ const parsedResolution = result.exitCode === 0 ? parseCancellationResult(
926
+ this.options.provider,
927
+ paths,
928
+ descriptorKey,
929
+ result.stdout
930
+ ) : null;
931
+ const resolution = parsedResolution?.state === "released_generation_unavailable" && !serializeGenerationChanges ? null : parsedResolution;
932
+ if (resolution) return resolution;
933
+ if (isDescriptorMismatch(result.stdout)) {
934
+ throw this.options.failure(
935
+ "Detached command launchId is already bound to a different launch descriptor."
936
+ );
937
+ }
938
+ cleanupFailure = protectProviderDiagnostics ? new Error(`${this.providerName} did not confirm supervisor detached command cleanup.`) : new Error(`${this.providerName} did not confirm detached command cleanup.`);
939
+ }
940
+ throw this.options.failure(
941
+ protectProviderDiagnostics ? `${context}: ${messageFrom(cause)}. Cleanup could not be confirmed: ${messageFrom(cleanupFailure)}` : `${context}. Cleanup could not be confirmed.`
942
+ );
943
+ }
944
+ async stop(command) {
945
+ const identity = this.resolve(command);
946
+ if (!identity) return this.options.stopLegacy(command);
947
+ for (let attempt = 0; attempt < 2; attempt += 1) {
948
+ await this.options.beforeStopOrDisposeMutation?.();
949
+ const stopped = await this.executeControl(
950
+ buildStopDetachedCommand(pathsForIdentity(identity), identity)
951
+ );
952
+ if (stopped.state === "failed") {
953
+ continue;
954
+ }
955
+ if (stopped.result.exitCode === 0 && isStopConfirmation(stopped.result.stdout)) return;
956
+ }
957
+ throw this.options.failure(`Failed to stop detached ${this.providerName} process.`);
958
+ }
959
+ /**
960
+ * Irreversibly removes the private lifecycle state and diagnostics for one
961
+ * exact managed generation. This is deliberately separate from `stop()`:
962
+ * callers must first obtain exact stop confirmation and perform any final
963
+ * diagnostic read they need.
964
+ */
965
+ async dispose(command) {
966
+ const identity = this.resolve(command);
967
+ if (!identity) {
968
+ throw this.options.failure(
969
+ `Detached ${this.providerName} artifact disposal requires a managed process handle.`
970
+ );
971
+ }
972
+ for (let attempt = 0; attempt < 2; attempt += 1) {
973
+ await this.options.beforeStopOrDisposeMutation?.();
974
+ const disposed = await this.executeControl(
975
+ buildDisposeDetachedArtifactsCommand(pathsForIdentity(identity), identity)
976
+ );
977
+ if (disposed.state === "failed") continue;
978
+ if (disposed.result.exitCode === 0 && isDisposeConfirmation(disposed.result.stdout)) {
979
+ return;
980
+ }
981
+ }
982
+ throw this.options.failure(
983
+ `Failed to dispose detached ${this.providerName} process artifacts.`
984
+ );
985
+ }
986
+ async readLogs(command) {
987
+ const identity = this.resolve(command);
988
+ if (!identity) return this.options.readLegacyLogs(command);
989
+ const read = await this.executeControl(
990
+ buildReadDetachedLogsCommand(identity),
991
+ void 0,
992
+ DETACHED_PROCESS_LOG_ENVELOPE_MAX_BYTES
993
+ );
994
+ if (read.state !== "completed" || read.result.exitCode !== 0) {
995
+ return { stdout: "", stderr: "" };
996
+ }
997
+ return parseDetachedProcessLogs(read.result.stdout) ?? { stdout: "", stderr: "" };
998
+ }
999
+ };
1000
+ function processStatParserFunctions() {
1001
+ return [
1002
+ "read_process_stat_file() {",
1003
+ " proc_stat_raw=",
1004
+ " proc_stat_separator=",
1005
+ " proc_stat_seen=no",
1006
+ " proc_stat_newline=$(printf '\\n_') || return 1",
1007
+ " proc_stat_newline=${proc_stat_newline%_}",
1008
+ " {",
1009
+ " while :; do",
1010
+ " proc_stat_line=",
1011
+ " IFS= read -r proc_stat_line",
1012
+ " proc_stat_read_status=$?",
1013
+ ' if [ "$proc_stat_read_status" -ne 0 ] && [ -z "$proc_stat_line" ]; then break; fi',
1014
+ ' proc_stat_raw="${proc_stat_raw}${proc_stat_separator}${proc_stat_line}"',
1015
+ " proc_stat_separator=$proc_stat_newline",
1016
+ " proc_stat_seen=yes",
1017
+ ' [ "$proc_stat_read_status" -eq 0 ] || break',
1018
+ ' done < "$1"',
1019
+ " } 2>/dev/null",
1020
+ ' [ "$proc_stat_seen" = yes ]',
1021
+ "}",
1022
+ "parse_process_stat() {",
1023
+ " proc_stat_fields=${1##*) }",
1024
+ " proc_stat_index=1",
1025
+ " proc_stat_state=",
1026
+ " proc_stat_pgrp=",
1027
+ " proc_stat_session=",
1028
+ " proc_stat_ticks=",
1029
+ ' while [ "$proc_stat_index" -le 20 ]; do',
1030
+ ' case "$proc_stat_fields" in',
1031
+ " *' '*) proc_stat_field=${proc_stat_fields%% *}; proc_stat_fields=${proc_stat_fields#* } ;;",
1032
+ " *) proc_stat_field=$proc_stat_fields; proc_stat_fields= ;;",
1033
+ " esac",
1034
+ ' [ -n "$proc_stat_field" ] || return 1',
1035
+ ' case "$proc_stat_index" in',
1036
+ " 1) proc_stat_state=$proc_stat_field ;;",
1037
+ " 3) proc_stat_pgrp=$proc_stat_field ;;",
1038
+ " 4) proc_stat_session=$proc_stat_field ;;",
1039
+ " 20) proc_stat_ticks=$proc_stat_field ;;",
1040
+ " esac",
1041
+ " proc_stat_index=$((proc_stat_index + 1))",
1042
+ " done",
1043
+ ' [ -n "$proc_stat_state" ] && [ -n "$proc_stat_pgrp" ] && [ -n "$proc_stat_session" ] && [ -n "$proc_stat_ticks" ]',
1044
+ "}"
1045
+ ];
1046
+ }
1047
+ function identityFunctions(paths) {
1048
+ return [
1049
+ ...processStatParserFunctions(),
1050
+ "read_launch_identity() {",
1051
+ ...assertSafeRegularFile(paths.record).map((line) => ` ${line}`),
1052
+ ` [ -s ${shellQuote(paths.record)} ] || return 1`,
1053
+ ` identity=$(cat ${shellQuote(paths.record)}) || return 1`,
1054
+ ` identity_prefix=$(printf '%s\\n' "$identity" | awk 'NF == 5 { print $1 }')`,
1055
+ ` target_pid=$(printf '%s\\n' "$identity" | awk 'NF == 5 && $2 ~ /^[0-9]+$/ { print $2 }')`,
1056
+ ` target_ticks=$(printf '%s\\n' "$identity" | awk 'NF == 5 && $3 ~ /^[0-9]+$/ { print $3 }')`,
1057
+ ` target_session=$(printf '%s\\n' "$identity" | awk 'NF == 5 && $4 ~ /^[0-9]+$/ { print $4 }')`,
1058
+ ` target_descriptor=$(printf '%s\\n' "$identity" | awk 'NF == 5 && $5 ~ /^[a-f0-9]+$/ { print $5 }')`,
1059
+ ' case "$identity_prefix" in',
1060
+ ` ${IDENTITY_PREFIX}) target_reaper_protocol=v3 ;;`,
1061
+ ` ${LEGACY_IDENTITY_PREFIX}) target_reaper_protocol=v2 ;;`,
1062
+ " *) return 1 ;;",
1063
+ " esac",
1064
+ ' [ -n "$target_pid" ] && [ -n "$target_ticks" ] && [ "$target_pid" = "$target_session" ] && [ ${#target_descriptor} -eq 64 ]',
1065
+ "}",
1066
+ "leader_identity_status() {",
1067
+ ' read_process_stat_file "/proc/$target_pid/stat" || return 1',
1068
+ ' parse_process_stat "$proc_stat_raw" || return 1',
1069
+ " state=$proc_stat_state",
1070
+ " pgrp=$proc_stat_pgrp",
1071
+ " current_session=$proc_stat_session",
1072
+ " current_ticks=$proc_stat_ticks",
1073
+ ' [ "$current_ticks" = "$target_ticks" ] && [ "$pgrp" = "$target_pid" ] && [ "$current_session" = "$target_session" ] || return 2',
1074
+ ' [ "$state" != "Z" ] || return 1',
1075
+ " return 0",
1076
+ "}"
1077
+ ];
1078
+ }
1079
+ function decisionFunctions(paths) {
1080
+ return [
1081
+ "read_launch_decision() {",
1082
+ ...assertSafeRegularFile(paths.decision).map((line) => ` ${line}`),
1083
+ ` [ -s ${shellQuote(paths.decision)} ] || return 1`,
1084
+ ` decision=$(cat ${shellQuote(paths.decision)}) || return 1`,
1085
+ ` decision_prefix=$(printf '%s\\n' "$decision" | awk 'NF == 6 { print $1 }')`,
1086
+ ` decision_action=$(printf '%s\\n' "$decision" | awk 'NF == 6 { print $2 }')`,
1087
+ ` decision_pid=$(printf '%s\\n' "$decision" | awk 'NF == 6 && $3 ~ /^[0-9]+$/ { print $3 }')`,
1088
+ ` decision_ticks=$(printf '%s\\n' "$decision" | awk 'NF == 6 && $4 ~ /^[0-9]+$/ { print $4 }')`,
1089
+ ` decision_session=$(printf '%s\\n' "$decision" | awk 'NF == 6 && $5 ~ /^[0-9]+$/ { print $5 }')`,
1090
+ ` decision_descriptor=$(printf '%s\\n' "$decision" | awk 'NF == 6 && $6 ~ /^[a-f0-9]+$/ { print $6 }')`,
1091
+ ` [ "$decision_prefix" = ${shellQuote(DECISION_PREFIX)} ] || return 1`,
1092
+ ' case "$decision_action" in RELEASE|CANCEL) ;; *) return 1 ;; esac',
1093
+ ' [ -n "$decision_pid" ] && [ -n "$decision_ticks" ] && [ -n "$decision_session" ] && [ ${#decision_descriptor} -eq 64 ]',
1094
+ "}",
1095
+ "read_started_identity() {",
1096
+ ...assertSafeRegularFile(paths.started).map((line) => ` ${line}`),
1097
+ ` [ -s ${shellQuote(paths.started)} ] || return 1`,
1098
+ ` started=$(cat ${shellQuote(paths.started)}) || return 1`,
1099
+ ` started_prefix=$(printf '%s\\n' "$started" | awk 'NF == 5 { print $1 }')`,
1100
+ ` started_pid=$(printf '%s\\n' "$started" | awk 'NF == 5 && $2 ~ /^[0-9]+$/ { print $2 }')`,
1101
+ ` started_ticks=$(printf '%s\\n' "$started" | awk 'NF == 5 && $3 ~ /^[0-9]+$/ { print $3 }')`,
1102
+ ` started_session=$(printf '%s\\n' "$started" | awk 'NF == 5 && $4 ~ /^[0-9]+$/ { print $4 }')`,
1103
+ ` started_descriptor=$(printf '%s\\n' "$started" | awk 'NF == 5 && $5 ~ /^[a-f0-9]+$/ { print $5 }')`,
1104
+ ` [ "$started_prefix" = ${shellQuote(STARTED_PREFIX)} ] || return 1`,
1105
+ ' [ "$started_pid:$started_ticks:$started_session:$started_descriptor" = "$decision_pid:$decision_ticks:$decision_session:$decision_descriptor" ]',
1106
+ "}"
1107
+ ];
1108
+ }
1109
+ function exactLifecycleMarkerFunction(functionName, variablePrefix, path2, expectation) {
1110
+ const quotedPath = shellQuote(path2);
1111
+ const missingMarker = expectation.kind === "populated" ? [
1112
+ ` if [ ! -e ${quotedPath} ] && [ ! -L ${quotedPath} ]; then return 1; fi`
1113
+ ] : [];
1114
+ const expectedMarker = expectation.kind === "populated" ? [
1115
+ ` ${variablePrefix}_expected="${expectation.markerPrefix} $target_pid $target_ticks $target_session $target_descriptor"`,
1116
+ ` ${variablePrefix}_expected_size=$((\${#${variablePrefix}_expected} + 1))`
1117
+ ] : [];
1118
+ const expectedSize = expectation.kind === "populated" ? `$${variablePrefix}_expected_size` : "0";
1119
+ const exactContentProof = expectation.kind === "populated" ? [
1120
+ ` printf '%s\\n' "$${variablePrefix}_expected" | cmp -s - /proc/self/fd/8 || { exec 8<&-; return 2; }`
1121
+ ] : [];
1122
+ return [
1123
+ `${functionName}() {`,
1124
+ ...missingMarker,
1125
+ ` [ -f ${quotedPath} ] && [ ! -L ${quotedPath} ] || return 2`,
1126
+ ...expectedMarker,
1127
+ ` ${variablePrefix}_path_metadata=$(stat -c %u:%a:%h:%s ${quotedPath} 2>/dev/null) || return 2`,
1128
+ ` [ "$${variablePrefix}_path_metadata" = "$(id -u):600:1:${expectedSize}" ] || return 2`,
1129
+ ` exec 8<${quotedPath} || return 2`,
1130
+ ` ${variablePrefix}_descriptor_metadata=$(stat -Lc %u:%a:%h:%s /proc/self/fd/8 2>/dev/null) || { exec 8<&-; return 2; }`,
1131
+ ` [ "$${variablePrefix}_descriptor_metadata" = "$${variablePrefix}_path_metadata" ] || { exec 8<&-; return 2; }`,
1132
+ ` ${variablePrefix}_path_inode=$(stat -c %d:%i ${quotedPath} 2>/dev/null) || { exec 8<&-; return 2; }`,
1133
+ ` ${variablePrefix}_descriptor_inode=$(stat -Lc %d:%i /proc/self/fd/8 2>/dev/null) || { exec 8<&-; return 2; }`,
1134
+ ` [ "$${variablePrefix}_descriptor_inode" = "$${variablePrefix}_path_inode" ] || { exec 8<&-; return 2; }`,
1135
+ ...exactContentProof,
1136
+ ` ${variablePrefix}_path_metadata_after=$(stat -c %u:%a:%h:%s ${quotedPath} 2>/dev/null) || { exec 8<&-; return 2; }`,
1137
+ ` ${variablePrefix}_path_inode_after=$(stat -c %d:%i ${quotedPath} 2>/dev/null) || { exec 8<&-; return 2; }`,
1138
+ ` ${variablePrefix}_descriptor_metadata_after=$(stat -Lc %u:%a:%h:%s /proc/self/fd/8 2>/dev/null) || { exec 8<&-; return 2; }`,
1139
+ ` ${variablePrefix}_descriptor_inode_after=$(stat -Lc %d:%i /proc/self/fd/8 2>/dev/null) || { exec 8<&-; return 2; }`,
1140
+ " exec 8<&-",
1141
+ ` [ "$${variablePrefix}_path_metadata_after:$${variablePrefix}_path_inode_after" = "$${variablePrefix}_descriptor_metadata_after:$${variablePrefix}_descriptor_inode_after" ] || return 2`,
1142
+ ` [ "$${variablePrefix}_path_metadata_after:$${variablePrefix}_path_inode_after" = "$${variablePrefix}_path_metadata:$${variablePrefix}_path_inode" ] || return 2`,
1143
+ " return 0",
1144
+ "}"
1145
+ ];
1146
+ }
1147
+ function processTreeFunctions(paths) {
1148
+ const liveness = paths === void 0 ? [
1149
+ // Pre-V2 provider handles have no durable reaper proof. Preserve
1150
+ // their documented best-effort session scan without using it for a
1151
+ // current V3 generation.
1152
+ "target_has_live_processes() {",
1153
+ " for stat_path in /proc/[0-9]*/stat; do",
1154
+ " assert_no_pid_reuse || return 2",
1155
+ ' read_process_stat_file "$stat_path" || continue',
1156
+ ' parse_process_stat "$proc_stat_raw" || continue',
1157
+ " state=$proc_stat_state",
1158
+ " process_session=$proc_stat_session",
1159
+ ' [ "$process_session" = "$target_session" ] && [ "$state" != "Z" ] && return 0',
1160
+ " done",
1161
+ " return 1",
1162
+ "}",
1163
+ "assert_no_pid_reuse() {",
1164
+ " leader_identity_status",
1165
+ " identity_status=$?",
1166
+ ' [ "$identity_status" -ne 2 ]',
1167
+ "}"
1168
+ ] : [
1169
+ ...exactLifecycleMarkerFunction(
1170
+ "read_exact_started_marker",
1171
+ "exact_started",
1172
+ paths.started,
1173
+ { kind: "populated", markerPrefix: STARTED_PREFIX }
1174
+ ),
1175
+ ...exactLifecycleMarkerFunction(
1176
+ "read_exact_quiescent_marker",
1177
+ "exact_quiescent",
1178
+ paths.quiescent,
1179
+ { kind: "populated", markerPrefix: QUIESCENT_PREFIX }
1180
+ ),
1181
+ "target_has_live_processes() {",
1182
+ " leader_identity_status",
1183
+ " target_leader_status=$?",
1184
+ ' [ "$target_leader_status" -ne 0 ] || return 0',
1185
+ " read_exact_started_marker",
1186
+ " target_started_status=$?",
1187
+ ' if [ "$target_leader_status" -eq 2 ]; then',
1188
+ ' if [ "$target_reaper_protocol" = v3 ] && [ "$target_started_status" -eq 1 ]; then',
1189
+ " return 1",
1190
+ " fi",
1191
+ ' if [ "$target_reaper_protocol" = v3 ] && [ "$target_started_status" -eq 0 ]; then',
1192
+ " read_exact_quiescent_marker",
1193
+ ' [ "$?" -eq 0 ] && return 1',
1194
+ " fi",
1195
+ " return 2",
1196
+ " fi",
1197
+ ' case "$target_started_status" in',
1198
+ " 1) return 1 ;;",
1199
+ " 2) return 2 ;;",
1200
+ " esac",
1201
+ ' [ "$target_reaper_protocol" = v3 ] || return 2',
1202
+ " read_exact_quiescent_marker",
1203
+ ' [ "$?" -eq 0 ] && return 1',
1204
+ " return 2",
1205
+ "}"
1206
+ ];
1207
+ return [
1208
+ ...liveness,
1209
+ "signal_target_session() {",
1210
+ " signal_name=$1",
1211
+ ` PATH=${shellQuote(DETACHED_PROCESS_TRUSTED_PATH)}`,
1212
+ " export PATH",
1213
+ " command -v python3 >/dev/null 2>&1 || return 1",
1214
+ " preserve_target_leader=no",
1215
+ ...paths === void 0 ? [] : [
1216
+ ' if [ "$target_reaper_protocol" = v3 ]; then',
1217
+ " read_exact_started_marker",
1218
+ " target_started_status=$?",
1219
+ ' [ "$target_started_status" -ne 2 ] || return 2',
1220
+ ' [ "$target_started_status" -ne 0 ] || preserve_target_leader=yes',
1221
+ " fi"
1222
+ ],
1223
+ " # pidfds bind every candidate before its session is checked and signaled.",
1224
+ // -I excludes the caller working directory and PYTHON* settings from
1225
+ // module lookup; -S prevents sitecustomize from running before fencing.
1226
+ ` python3 -I -S - "$target_pid" "$target_ticks" "$target_session" "$signal_name" "$preserve_target_leader" <<'PY'`,
1227
+ "import os",
1228
+ "import signal",
1229
+ "import sys",
1230
+ "",
1231
+ "target_pid = int(sys.argv[1])",
1232
+ "target_ticks = int(sys.argv[2])",
1233
+ "target_session = int(sys.argv[3])",
1234
+ 'signal_value = getattr(signal, "SIG" + sys.argv[4])',
1235
+ 'preserve_target_leader = sys.argv[5] == "yes"',
1236
+ 'if not hasattr(os, "pidfd_open") or not hasattr(signal, "pidfd_send_signal"):',
1237
+ " raise SystemExit(1)",
1238
+ "",
1239
+ "def read_identity(pid):",
1240
+ " try:",
1241
+ ' with open(f"/proc/{pid}/stat", "rb") as stat_file:',
1242
+ " raw = stat_file.read()",
1243
+ " except (FileNotFoundError, ProcessLookupError):",
1244
+ " return None",
1245
+ ' marker = raw.rfind(b") ")',
1246
+ " fields = raw[marker + 2:].split() if marker >= 0 else []",
1247
+ " if len(fields) <= 19:",
1248
+ " raise SystemExit(1)",
1249
+ " return fields[0], int(fields[2]), int(fields[3]), int(fields[19])",
1250
+ "",
1251
+ "def leader_was_reused():",
1252
+ " identity = read_identity(target_pid)",
1253
+ " if identity is None:",
1254
+ " return False",
1255
+ " _state, pgrp, session_id, ticks = identity",
1256
+ " return (pgrp, session_id, ticks) != (target_pid, target_session, target_ticks)",
1257
+ "",
1258
+ 'for entry in os.scandir("/proc"):',
1259
+ " if not entry.name.isdecimal():",
1260
+ " continue",
1261
+ " pid = int(entry.name)",
1262
+ " if pid == target_pid:",
1263
+ " if preserve_target_leader:",
1264
+ " continue",
1265
+ " try:",
1266
+ " pidfd = os.pidfd_open(pid)",
1267
+ " except (PermissionError, ProcessLookupError):",
1268
+ " continue",
1269
+ " try:",
1270
+ " identity = read_identity(pid)",
1271
+ " if identity is None:",
1272
+ " continue",
1273
+ " state, _pgrp, session_id, _ticks = identity",
1274
+ ' if session_id != target_session or state == b"Z":',
1275
+ " continue",
1276
+ " if leader_was_reused():",
1277
+ " raise SystemExit(2)",
1278
+ " try:",
1279
+ " signal.pidfd_send_signal(pidfd, signal_value)",
1280
+ " except ProcessLookupError:",
1281
+ " pass",
1282
+ " finally:",
1283
+ " os.close(pidfd)",
1284
+ "PY",
1285
+ "}"
1286
+ ];
1287
+ }
1288
+ function stopTargetCommands(options) {
1289
+ const stoppedAction = options?.exitAsSoonAsStopped ? "exit 0" : "break";
1290
+ return [
1291
+ "target_has_live_processes",
1292
+ "target_status=$?",
1293
+ '[ "$target_status" -ne 2 ] || exit 2',
1294
+ ...options?.exitAsSoonAsStopped ? ['[ "$target_status" -eq 0 ] || exit 0'] : [],
1295
+ 'if [ "$target_status" -eq 0 ]; then signal_target_session TERM || exit $?; fi',
1296
+ "attempt=0",
1297
+ 'while [ "$attempt" -lt 150 ]; do',
1298
+ " target_has_live_processes",
1299
+ " target_status=$?",
1300
+ ' [ "$target_status" -ne 2 ] || exit 2',
1301
+ ` [ "$target_status" -eq 0 ] || ${stoppedAction}`,
1302
+ " sleep 0.1",
1303
+ " attempt=$((attempt + 1))",
1304
+ "done",
1305
+ 'if [ "$target_status" -eq 0 ]; then signal_target_session KILL || exit $?; fi',
1306
+ "attempt=0",
1307
+ 'while [ "$attempt" -lt 50 ]; do',
1308
+ " target_has_live_processes",
1309
+ " target_status=$?",
1310
+ ' [ "$target_status" -ne 2 ] || exit 2',
1311
+ ` [ "$target_status" -eq 0 ] || ${stoppedAction}`,
1312
+ " sleep 0.1",
1313
+ " attempt=$((attempt + 1))",
1314
+ "done",
1315
+ ...options?.failureMessage === void 0 ? ['[ "$target_status" -ne 0 ] || exit 1'] : [
1316
+ 'if [ "$target_status" -eq 0 ]; then',
1317
+ ` printf '%s\\n' ${shellQuote(options.failureMessage)} >&2`,
1318
+ " exit 1",
1319
+ "fi"
1320
+ ]
1321
+ ];
1322
+ }
1323
+ function buildLegacyDetachedStopCommand(pid, startTicks, providerName) {
1324
+ return [
1325
+ "umask 077",
1326
+ ...secureDetachedRoot(),
1327
+ `target_pid=${shellQuote(pid)}`,
1328
+ `target_ticks=${shellQuote(startTicks)}`,
1329
+ "target_session=$target_pid",
1330
+ ...processStatParserFunctions(),
1331
+ "leader_identity_status() {",
1332
+ ' read_process_stat_file "/proc/$target_pid/stat" || return 1',
1333
+ ' parse_process_stat "$proc_stat_raw" || return 1',
1334
+ " current_ticks=$proc_stat_ticks",
1335
+ ' [ "$current_ticks" = "$target_ticks" ] || return 2',
1336
+ " return 0",
1337
+ "}",
1338
+ "target_reaper_protocol=legacy",
1339
+ ...processTreeFunctions(),
1340
+ "# Revalidate the leader birth immediately before every scan and every kill.",
1341
+ ...stopTargetCommands({
1342
+ exitAsSoonAsStopped: true,
1343
+ failureMessage: `Detached ${providerName} process ${pid} did not stop.`
1344
+ })
1345
+ ].join("\n");
1346
+ }
1347
+ function atomicFile(partialPath, path2, parentDirectory, write) {
1348
+ return [
1349
+ `${write} || exit 1`,
1350
+ `sync -f ${shellQuote(partialPath)} || exit 1`,
1351
+ `mv -f ${shellQuote(partialPath)} ${shellQuote(path2)} || exit 1`,
1352
+ `sync -f ${shellQuote(parentDirectory)} || exit 1`
1353
+ ];
1354
+ }
1355
+ function secureDirectory(path2, create) {
1356
+ return [
1357
+ ...create ? [
1358
+ `if [ ! -e ${shellQuote(path2)} ] && [ ! -L ${shellQuote(path2)} ]; then`,
1359
+ ` mkdir ${shellQuote(path2)} 2>/dev/null || true`,
1360
+ "fi"
1361
+ ] : [],
1362
+ `[ -d ${shellQuote(path2)} ] && [ ! -L ${shellQuote(path2)} ] || exit 1`,
1363
+ `directory_owner=$(stat -c %u ${shellQuote(path2)} 2>/dev/null) || exit 1`,
1364
+ '[ "$directory_owner" = "$(id -u)" ] || exit 1',
1365
+ `directory_mode=$(stat -c %a ${shellQuote(path2)} 2>/dev/null) || exit 1`,
1366
+ '[ "$directory_mode" = 700 ] || exit 1'
1367
+ ];
1368
+ }
1369
+ function secureDetachedRoot() {
1370
+ return secureDirectory(DETACHED_PROCESS_ROOT, true);
1371
+ }
1372
+ function secureLaunchDirectory(paths, create) {
1373
+ return secureDirectory(paths.directory, create);
1374
+ }
1375
+ function assertSafeRegularFile(path2) {
1376
+ return [
1377
+ `[ -e ${shellQuote(path2)} ] || return 1`,
1378
+ `[ -f ${shellQuote(path2)} ] && [ ! -L ${shellQuote(path2)} ] || exit 1`
1379
+ ];
1380
+ }
1381
+ function publishDecision(paths, action, partialPath) {
1382
+ return [
1383
+ `printf '${DECISION_PREFIX} ${action} %s %s %s %s\\n' "$publish_pid" "$publish_ticks" "$publish_session" "$publish_descriptor" > ${shellQuote(partialPath)} || exit 1`,
1384
+ `sync -f ${shellQuote(partialPath)} || exit 1`,
1385
+ `ln ${shellQuote(partialPath)} ${shellQuote(paths.decision)} 2>/dev/null || true`,
1386
+ `rm -f ${shellQuote(partialPath)} || exit 1`,
1387
+ `sync -f ${shellQuote(paths.directory)} || exit 1`,
1388
+ "read_launch_decision || exit 1"
1389
+ ];
1390
+ }
1391
+ function waitForStarted(paths) {
1392
+ return [
1393
+ "attempt=0",
1394
+ `while [ ! -s ${shellQuote(paths.started)} ] && [ "$attempt" -lt 400 ]; do`,
1395
+ " sleep 0.05",
1396
+ " attempt=$((attempt + 1))",
1397
+ "done",
1398
+ "read_started_identity || exit 1"
1399
+ ];
1400
+ }
1401
+ function releasedAdoptionOutcome(paths, descriptorKey, serializeGenerationChanges) {
1402
+ if (!serializeGenerationChanges) {
1403
+ return [
1404
+ ...waitForStarted(paths),
1405
+ `printf '${RELEASED_SENTINEL} %s %s %s %s\\n' "$decision_pid" "$decision_ticks" "$decision_session" "$decision_descriptor"`,
1406
+ "exit 0"
1407
+ ];
1408
+ }
1409
+ return [
1410
+ // Replacement-capable adoption runs under the generation lock. Rebind the
1411
+ // durable decision to the exact current record before returning any handle.
1412
+ "read_launch_identity || exit 1",
1413
+ `[ "$target_descriptor" = ${shellQuote(descriptorKey)} ] || { printf '${DESCRIPTOR_MISMATCH_SENTINEL}\\n'; exit 2; }`,
1414
+ '[ "$decision_pid:$decision_ticks:$decision_session:$decision_descriptor" = "$target_pid:$target_ticks:$target_session:$target_descriptor" ] || exit 1',
1415
+ '[ "$target_reaper_protocol" = v3 ] || exit 1',
1416
+ ...waitForStarted(paths),
1417
+ "read_exact_started_marker || exit 1",
1418
+ "leader_identity_status",
1419
+ "released_leader_status=$?",
1420
+ 'if [ "$released_leader_status" -eq 0 ]; then',
1421
+ ` printf '${RELEASED_SENTINEL} %s %s %s %s\\n' "$decision_pid" "$decision_ticks" "$decision_session" "$decision_descriptor"`,
1422
+ " exit 0",
1423
+ "fi",
1424
+ // Exact quiescence is recoverable by retrying the same deterministic
1425
+ // launch. Any absent or ambiguous proof after exact STARTED is a distinct
1426
+ // reset-required outcome, never a stale released-handle adoption.
1427
+ "read_exact_quiescent_marker",
1428
+ "released_quiescent_status=$?",
1429
+ '[ "$released_quiescent_status" -ne 0 ] || exit 1',
1430
+ `printf '${RELEASED_GENERATION_UNAVAILABLE_SENTINEL}\\n'`,
1431
+ "exit 0"
1432
+ ];
1433
+ }
1434
+ function renderShellLockAssertion(options) {
1435
+ const { functionName, variablePrefix, path: path2, descriptorFd } = options;
1436
+ const pathExpression = shellQuote(path2);
1437
+ const descriptorPathExpression = `/proc/self/fd/${descriptorFd}`;
1438
+ const descriptorChecks = [
1439
+ `[ -f ${descriptorPathExpression} ] || return 1`,
1440
+ `${variablePrefix}_descriptor_metadata=$(stat -Lc %u:%a:%h:%s ${descriptorPathExpression} 2>/dev/null) || return 1`,
1441
+ `[ "$${variablePrefix}_descriptor_metadata" = "$${variablePrefix}_path_metadata" ] || return 1`,
1442
+ `${variablePrefix}_path_inode=$(stat -c %d:%i ${pathExpression} 2>/dev/null) || return 1`,
1443
+ `${variablePrefix}_descriptor_inode=$(stat -Lc %d:%i ${descriptorPathExpression} 2>/dev/null) || return 1`,
1444
+ `[ "$${variablePrefix}_descriptor_inode" = "$${variablePrefix}_path_inode" ] || return 1`
1445
+ ];
1446
+ return [
1447
+ `${functionName}() {`,
1448
+ ` [ -f ${pathExpression} ] && [ ! -L ${pathExpression} ] || return 1`,
1449
+ ` ${variablePrefix}_path_metadata=$(stat -c %u:%a:%h:%s ${pathExpression} 2>/dev/null) || return 1`,
1450
+ ` [ "$${variablePrefix}_path_metadata" = "$(id -u):600:1:0" ] || return 1`,
1451
+ ...descriptorChecks.map((line) => ` ${line}`),
1452
+ " return 0",
1453
+ "}"
1454
+ ];
1455
+ }
1456
+ function generationLock(paths) {
1457
+ return [
1458
+ "command -v flock >/dev/null 2>&1 || exit 1",
1459
+ `if [ -e ${shellQuote(paths.controlLock)} ] || [ -L ${shellQuote(paths.controlLock)} ]; then [ -f ${shellQuote(paths.controlLock)} ] && [ ! -L ${shellQuote(paths.controlLock)} ] || exit 1; fi`,
1460
+ `exec 9>>${shellQuote(paths.controlLock)} || exit 1`,
1461
+ ...renderShellLockAssertion({
1462
+ functionName: "assert_generation_lock",
1463
+ variablePrefix: "generation_lock",
1464
+ path: paths.controlLock,
1465
+ descriptorFd: 9
1466
+ }),
1467
+ "assert_generation_lock || exit 1",
1468
+ "flock -w 8 9 || exit 1",
1469
+ "assert_generation_lock || exit 1"
1470
+ ];
1471
+ }
1472
+ function acquireGenerationLock(paths) {
1473
+ return [...secureDetachedRoot(), ...generationLock(paths)];
1474
+ }
1475
+ function retireExitedReleasedLaunch(paths, descriptorKey) {
1476
+ return [
1477
+ `if [ -e ${shellQuote(paths.retiredDirectory)} ] || [ -L ${shellQuote(paths.retiredDirectory)} ]; then`,
1478
+ ...secureDirectory(paths.retiredDirectory, false).map((line) => ` ${line}`),
1479
+ ` rm -rf -- ${shellQuote(paths.retiredDirectory)} || exit 1`,
1480
+ ` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
1481
+ "fi",
1482
+ `if [ -e ${shellQuote(paths.directory)} ] || [ -L ${shellQuote(paths.directory)} ]; then`,
1483
+ ...secureLaunchDirectory(paths, false).map((line) => ` ${line}`),
1484
+ ` if [ ! -e ${shellQuote(paths.record)} ] && [ ! -L ${shellQuote(paths.record)} ]; then`,
1485
+ ` [ ! -e ${shellQuote(paths.decision)} ] && [ ! -L ${shellQuote(paths.decision)} ] || exit 1`,
1486
+ ` mv -- ${shellQuote(paths.directory)} ${shellQuote(paths.retiredDirectory)} || exit 1`,
1487
+ ` [ -d ${shellQuote(paths.retiredDirectory)} ] && [ ! -L ${shellQuote(paths.retiredDirectory)} ] || exit 1`,
1488
+ ` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
1489
+ ` rm -rf -- ${shellQuote(paths.retiredDirectory)} || exit 1`,
1490
+ ` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
1491
+ " elif read_launch_identity; then",
1492
+ ` [ "$target_descriptor" = ${shellQuote(descriptorKey)} ] || { printf '${DESCRIPTOR_MISMATCH_SENTINEL}\\n'; exit 2; }`,
1493
+ " if read_launch_decision; then",
1494
+ ` [ "$decision_descriptor" = ${shellQuote(descriptorKey)} ] || { printf '${DESCRIPTOR_MISMATCH_SENTINEL}\\n'; exit 2; }`,
1495
+ ' [ "$decision_pid:$decision_ticks:$decision_session:$decision_descriptor" = "$target_pid:$target_ticks:$target_session:$target_descriptor" ] || exit 1',
1496
+ ' if [ "$decision_action" = RELEASE ]; then',
1497
+ ` if [ -e ${shellQuote(paths.started)} ] || [ -L ${shellQuote(paths.started)} ]; then`,
1498
+ " read_started_identity || exit 1",
1499
+ " fi",
1500
+ " target_has_live_processes",
1501
+ " target_status=$?",
1502
+ ' [ "$target_status" -ne 2 ] || exit 1',
1503
+ ' if [ "$target_status" -ne 0 ]; then',
1504
+ ` mv -- ${shellQuote(paths.directory)} ${shellQuote(paths.retiredDirectory)} || exit 1`,
1505
+ ` [ -d ${shellQuote(paths.retiredDirectory)} ] && [ ! -L ${shellQuote(paths.retiredDirectory)} ] || exit 1`,
1506
+ ` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
1507
+ ` rm -rf -- ${shellQuote(paths.retiredDirectory)} || exit 1`,
1508
+ ` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
1509
+ " fi",
1510
+ " fi",
1511
+ " fi",
1512
+ " fi",
1513
+ "fi"
1514
+ ];
1515
+ }
1516
+ function buildEnvironmentFdLaunch(paths, child, environmentMode) {
1517
+ const handoff = `${paths.directory}/.supervisor-environment-v1.empty`;
1518
+ const cleanLaunch = "nohup setsid env -i " + Object.entries(DETACHED_PROCESS_LIFECYCLE_ENVIRONMENT).map(([name, value]) => shellQuote(`${name}=${value}`)).join(" ") + (environmentMode === "supervisor-fd-v1" ? ` ${SUPERVISOR_ENVIRONMENT_FD_ENV}=${SUPERVISOR_ENVIRONMENT_FD}` : "") + ` sh -c ${shellQuote(child)} >/dev/null 2>/dev/null < /dev/null ${SUPERVISOR_ENVIRONMENT_FD}<&7 7<&- &`;
1519
+ return [
1520
+ `: > ${shellQuote(handoff)} || exit 1`,
1521
+ `chmod 600 ${shellQuote(handoff)} || exit 1`,
1522
+ // Keep the inherited reader writable so the selected payload boundary can
1523
+ // erase the anonymous inode before closing its copy. This also clears any
1524
+ // duplicate retained by a generic parent shell after it forks the command.
1525
+ `exec 7<>${shellQuote(handoff)} || exit 1`,
1526
+ `exec 8>${shellQuote(handoff)} || exit 1`,
1527
+ `rm -f -- ${shellQuote(handoff)} || exit 1`,
1528
+ `printf '%s' "$${SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV}" >&8 || exit 1`,
1529
+ "exec 8>&-",
1530
+ `unset ${SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV}`,
1531
+ cleanLaunch,
1532
+ "exec 7<&-"
1533
+ ];
1534
+ }
1535
+ var SANDBOX_NETWORK_ENVIRONMENT_KEYS = [
1536
+ "HTTP_PROXY",
1537
+ "HTTPS_PROXY",
1538
+ "ALL_PROXY",
1539
+ "NO_PROXY",
1540
+ "http_proxy",
1541
+ "https_proxy",
1542
+ "all_proxy",
1543
+ "no_proxy",
1544
+ "NODE_EXTRA_CA_CERTS",
1545
+ "SSL_CERT_FILE",
1546
+ "SSL_CERT_DIR",
1547
+ "REQUESTS_CA_BUNDLE",
1548
+ "CURL_CA_BUNDLE"
1549
+ ];
1550
+ function inheritSandboxNetworkEnvironment() {
1551
+ const script = [
1552
+ "import json, os",
1553
+ `payload = json.loads(os.environ[${JSON.stringify(SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV)}])`,
1554
+ `for name in ${JSON.stringify(SANDBOX_NETWORK_ENVIRONMENT_KEYS)}:`,
1555
+ " if name in os.environ:",
1556
+ ' payload["environment"].setdefault(name, os.environ[name])',
1557
+ 'encoded = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))',
1558
+ `if len(encoded.encode("utf-8")) > ${SUPERVISOR_ENVIRONMENT_MAX_BYTES} or len(payload["environment"]) > ${SUPERVISOR_ENVIRONMENT_MAX_ENTRIES}:`,
1559
+ " raise SystemExit(1)",
1560
+ "print(encoded)"
1561
+ ].join("\n");
1562
+ return `${SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV}=$(${SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV}="$${SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV}" python3 -I -S -c ${shellQuote(script)}) || exit 1`;
1563
+ }
1564
+ function cleanLifecycleShell(script, environmentMode) {
1565
+ let suffix = 0;
1566
+ let delimiter = "NECKBEARD_DETACHED_LIFECYCLE";
1567
+ const lines = new Set(script.split("\n"));
1568
+ while (lines.has(delimiter)) {
1569
+ suffix += 1;
1570
+ delimiter = `NECKBEARD_DETACHED_LIFECYCLE_${suffix}`;
1571
+ }
1572
+ const fixedEnvironment = Object.entries(
1573
+ DETACHED_PROCESS_LIFECYCLE_ENVIRONMENT
1574
+ ).map(([name, value]) => shellQuote(`${name}=${value}`)).join(" ");
1575
+ return [
1576
+ `export PATH=${shellQuote(DETACHED_PROCESS_TRUSTED_PATH)}`,
1577
+ ...environmentMode === "exec" ? [
1578
+ `if [ -z "\${${SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV}+present}" ]; then ${SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV}=${shellQuote('{"version":1,"environment":{}}')}; fi`,
1579
+ inheritSandboxNetworkEnvironment()
1580
+ ] : [],
1581
+ `exec env -i ${fixedEnvironment} ${SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV}="$${SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV}" sh -s <<'${delimiter}'`,
1582
+ script,
1583
+ delimiter
1584
+ ].join("\n");
1585
+ }
1586
+ function previousLogPath(path2) {
1587
+ return `${path2}.previous`;
1588
+ }
1589
+ function logPipePath(path2) {
1590
+ return `${path2}.pipe`;
1591
+ }
1592
+ function logSnapshotPath(path2) {
1593
+ return `${path2}.snapshot`;
1594
+ }
1595
+ function logSnapshotStagingPath(path2) {
1596
+ return `${logSnapshotPath(path2)}.partial`;
1597
+ }
1598
+ function legacyLogSnapshotLockPath(path2) {
1599
+ return `${logSnapshotPath(path2)}.lock`;
1600
+ }
1601
+ function logChunkPath(path2) {
1602
+ return `${path2}.chunk`;
1603
+ }
1604
+ function boundedLogProgram() {
1605
+ return [
1606
+ "const fs = require('node:fs');",
1607
+ "const [input, output, previous, snapshot, snapshotStaging] = process.argv.slice(1);",
1608
+ "let generation = 0;",
1609
+ "let captureEnabled = true;",
1610
+ "const waitArray = new Int32Array(new SharedArrayBuffer(4));",
1611
+ "function assertSafeLeaf(path, optional = false) {",
1612
+ " let stats;",
1613
+ " try { stats = fs.lstatSync(path); } catch (error) { if (optional && error?.code === 'ENOENT') return; throw error; }",
1614
+ " if (!stats.isFile() || stats.isSymbolicLink()) throw new Error('unsafe log leaf');",
1615
+ "}",
1616
+ "function publishSnapshot(state) {",
1617
+ ` fs.writeFileSync(snapshotStaging, \`${LOG_SNAPSHOT_PREFIX} \${state} \${generation}\\n\`, { encoding: 'utf8', mode: 0o600, flag: 'wx' });`,
1618
+ " fs.chmodSync(snapshotStaging, 0o600);",
1619
+ " fs.renameSync(snapshotStaging, snapshot);",
1620
+ "}",
1621
+ "void (async () => {",
1622
+ ` for await (const chunk of fs.createReadStream(input, { highWaterMark: ${DETACHED_PROCESS_LOG_CHUNK_BYTES} })) {`,
1623
+ " if (captureEnabled) {",
1624
+ " try {",
1625
+ " generation += 1;",
1626
+ " publishSnapshot('ROTATING');",
1627
+ " assertSafeLeaf(output);",
1628
+ " assertSafeLeaf(previous, true);",
1629
+ " fs.appendFileSync(output, chunk);",
1630
+ ` if (fs.statSync(output).size >= ${DETACHED_PROCESS_LOG_SEGMENT_BYTES}) {`,
1631
+ " fs.renameSync(output, previous);",
1632
+ " fs.writeFileSync(output, '', { mode: 0o600, flag: 'wx' });",
1633
+ " fs.chmodSync(output, 0o600);",
1634
+ " }",
1635
+ " publishSnapshot('STABLE');",
1636
+ " } catch {",
1637
+ " // Diagnostic capture failure must never close the target pipe.",
1638
+ " captureEnabled = false;",
1639
+ " }",
1640
+ " }",
1641
+ " // Avoid monopolizing the process while the pipe remains continuously readable.",
1642
+ " Atomics.wait(waitArray, 0, 0, 10);",
1643
+ " }",
1644
+ " fs.rmSync(input);",
1645
+ "})().catch(() => { process.exitCode = 1; });"
1646
+ ].join("\n");
1647
+ }
1648
+ function boundedLogShellFunctions() {
1649
+ return [
1650
+ "bounded_log_shell() {",
1651
+ " log_input=$1",
1652
+ " log_output=$2",
1653
+ " log_previous=$3",
1654
+ " log_snapshot=$4",
1655
+ " log_snapshot_staging=$5",
1656
+ " log_chunk=$6",
1657
+ " log_generation=0",
1658
+ " log_capture_enabled=yes",
1659
+ ' exec 6<"$log_input" || exit 1',
1660
+ " while :; do",
1661
+ ' if [ "$log_capture_enabled" != yes ]; then',
1662
+ " cat <&6 >/dev/null 2>&1 || true",
1663
+ " break",
1664
+ " fi",
1665
+ ` if ! dd bs=${DETACHED_PROCESS_LOG_CHUNK_BYTES} count=1 <&6 >"$log_chunk" 2>/dev/null; then`,
1666
+ " cat <&6 >/dev/null 2>&1 || true",
1667
+ " break",
1668
+ " fi",
1669
+ ' if ! log_chunk_size=$(stat -c %s "$log_chunk" 2>/dev/null); then',
1670
+ " log_capture_enabled=no",
1671
+ " continue",
1672
+ " fi",
1673
+ ' [ "$log_chunk_size" -gt 0 ] || break',
1674
+ " log_generation=$((log_generation + 1))",
1675
+ " if ! (",
1676
+ ' publish_log_snapshot ROTATING "$log_generation" "$log_snapshot" "$log_snapshot_staging" || exit 1',
1677
+ ' [ -f "$log_output" ] && [ ! -L "$log_output" ] || exit 1',
1678
+ ' if [ -e "$log_previous" ] || [ -L "$log_previous" ]; then [ -f "$log_previous" ] && [ ! -L "$log_previous" ] || exit 1; fi',
1679
+ ' cat "$log_chunk" >> "$log_output" || exit 1',
1680
+ ' log_after=$(stat -c %s "$log_output" 2>/dev/null) || exit 1',
1681
+ ` if [ "$log_after" -ge ${DETACHED_PROCESS_LOG_SEGMENT_BYTES} ]; then`,
1682
+ ' mv -f -- "$log_output" "$log_previous" || exit 1',
1683
+ ' ( set -C; : > "$log_output" ) 2>/dev/null || exit 1',
1684
+ ' chmod 600 "$log_output" || exit 1',
1685
+ " fi",
1686
+ ' publish_log_snapshot STABLE "$log_generation" "$log_snapshot" "$log_snapshot_staging" || exit 1',
1687
+ " ); then",
1688
+ " # Keep draining even when diagnostic capture becomes unavailable.",
1689
+ " log_capture_enabled=no",
1690
+ " fi",
1691
+ " # Avoid monopolizing the shell while the pipe remains continuously readable.",
1692
+ " sleep 0.01",
1693
+ " done",
1694
+ " exec 6<&-",
1695
+ ' rm -f -- "$log_input" 2>/dev/null || true',
1696
+ "}",
1697
+ "publish_log_snapshot() {",
1698
+ " log_snapshot_state=$1",
1699
+ " log_snapshot_generation=$2",
1700
+ " log_snapshot_path=$3",
1701
+ " log_snapshot_staging_path=$4",
1702
+ ' [ ! -e "$log_snapshot_staging_path" ] && [ ! -L "$log_snapshot_staging_path" ] || return 1',
1703
+ ` printf '${LOG_SNAPSHOT_PREFIX} %s %s\\n' "$log_snapshot_state" "$log_snapshot_generation" > "$log_snapshot_staging_path" || return 1`,
1704
+ ' chmod 600 "$log_snapshot_staging_path" || return 1',
1705
+ ' mv -f -- "$log_snapshot_staging_path" "$log_snapshot_path" || return 1',
1706
+ "}",
1707
+ "assert_legacy_log_lock_leaf() {",
1708
+ " legacy_log_lock_path=$1",
1709
+ ' [ -f "$legacy_log_lock_path" ] && [ ! -L "$legacy_log_lock_path" ] || return 1',
1710
+ ' legacy_log_lock_metadata=$(stat -c %u:%a:%h:%s "$legacy_log_lock_path" 2>/dev/null) || return 1',
1711
+ ' [ "$legacy_log_lock_metadata" = "$(id -u):600:1:0" ]',
1712
+ "}"
1713
+ ];
1714
+ }
1715
+ function boundedLogCaptureSetup(paths) {
1716
+ const stdoutPipe = logPipePath(paths.stdout);
1717
+ const stderrPipe = logPipePath(paths.stderr);
1718
+ return [
1719
+ ...boundedLogShellFunctions(),
1720
+ "if ! command -v node >/dev/null 2>&1; then",
1721
+ " command -v dd >/dev/null 2>&1 || exit 1",
1722
+ "fi",
1723
+ "command -v python3 >/dev/null 2>&1 || exit 1",
1724
+ `: > ${shellQuote(paths.stdout)} || exit 1`,
1725
+ `: > ${shellQuote(paths.stderr)} || exit 1`,
1726
+ `: > ${shellQuote(logChunkPath(paths.stdout))} || exit 1`,
1727
+ `: > ${shellQuote(logChunkPath(paths.stderr))} || exit 1`,
1728
+ `( set -C; : > ${shellQuote(legacyLogSnapshotLockPath(paths.stdout))} ) 2>/dev/null || exit 1`,
1729
+ `( set -C; : > ${shellQuote(legacyLogSnapshotLockPath(paths.stderr))} ) 2>/dev/null || exit 1`,
1730
+ `chmod 600 ${shellQuote(paths.stdout)} ${shellQuote(paths.stderr)} ${shellQuote(logChunkPath(paths.stdout))} ${shellQuote(logChunkPath(paths.stderr))} ${shellQuote(legacyLogSnapshotLockPath(paths.stdout))} ${shellQuote(legacyLogSnapshotLockPath(paths.stderr))} || exit 1`,
1731
+ `assert_legacy_log_lock_leaf ${shellQuote(legacyLogSnapshotLockPath(paths.stdout))} || exit 1`,
1732
+ `assert_legacy_log_lock_leaf ${shellQuote(legacyLogSnapshotLockPath(paths.stderr))} || exit 1`,
1733
+ `publish_log_snapshot STABLE 0 ${shellQuote(logSnapshotPath(paths.stdout))} ${shellQuote(logSnapshotStagingPath(paths.stdout))} || exit 1`,
1734
+ `publish_log_snapshot STABLE 0 ${shellQuote(logSnapshotPath(paths.stderr))} ${shellQuote(logSnapshotStagingPath(paths.stderr))} || exit 1`,
1735
+ `mkfifo -m 600 ${shellQuote(stdoutPipe)} ${shellQuote(stderrPipe)} || exit 1`,
1736
+ ...assertSafeRegularFile(paths.stdout).map((line) => line.replace("return 1", "exit 1")),
1737
+ ...assertSafeRegularFile(paths.stderr).map((line) => line.replace("return 1", "exit 1")),
1738
+ `[ -p ${shellQuote(stdoutPipe)} ] && [ ! -L ${shellQuote(stdoutPipe)} ] || exit 1`,
1739
+ `[ -p ${shellQuote(stderrPipe)} ] && [ ! -L ${shellQuote(stderrPipe)} ] || exit 1`,
1740
+ `( set -C; : > ${shellQuote(paths.quiescent)} ) 2>/dev/null || exit 1`,
1741
+ `chmod 600 ${shellQuote(paths.quiescent)} || exit 1`,
1742
+ `exec 6<>${shellQuote(paths.quiescent)} || exit 1`,
1743
+ ...renderShellLockAssertion({
1744
+ functionName: "assert_quiescent_descriptor",
1745
+ variablePrefix: "quiescent",
1746
+ path: paths.quiescent,
1747
+ descriptorFd: 6
1748
+ }),
1749
+ "assert_quiescent_descriptor || exit 1",
1750
+ "sync -f /proc/self/fd/6 || exit 1",
1751
+ `sync -f ${shellQuote(paths.directory)} || exit 1`
1752
+ ];
1753
+ }
1754
+ function detachedProcessReaperProgram() {
1755
+ return [
1756
+ "import ctypes",
1757
+ "import errno",
1758
+ "import fcntl",
1759
+ "import json",
1760
+ "import os",
1761
+ "import re",
1762
+ "import stat",
1763
+ "import subprocess",
1764
+ "import sys",
1765
+ "import time",
1766
+ "",
1767
+ "PR_SET_CHILD_SUBREAPER = 36",
1768
+ "command = sys.argv[1]",
1769
+ "logger_mode = sys.argv[2]",
1770
+ "node_program = sys.argv[3]",
1771
+ "shell_program = sys.argv[4]",
1772
+ "stdout_args = sys.argv[5:11]",
1773
+ "stderr_args = sys.argv[11:17]",
1774
+ "completion_path = sys.argv[17]",
1775
+ "started_partial_path = sys.argv[18]",
1776
+ "started_path = sys.argv[19]",
1777
+ "launch_directory = sys.argv[20]",
1778
+ "target_pid = int(sys.argv[21])",
1779
+ "target_ticks = sys.argv[22]",
1780
+ "target_session = int(sys.argv[23])",
1781
+ "target_descriptor = sys.argv[24]",
1782
+ "environment_mode = sys.argv[25]",
1783
+ "environment_fd = int(sys.argv[26])",
1784
+ "completion_fd = int(sys.argv[27])",
1785
+ "if len(stdout_args) != 6 or len(stderr_args) != 6:",
1786
+ " raise SystemExit(1)",
1787
+ 'if environment_mode not in ("exec", "supervisor-fd-v1"):',
1788
+ " raise SystemExit(1)",
1789
+ "if os.getpid() != target_pid or os.getpgrp() != target_pid or os.getsid(0) != target_session:",
1790
+ " raise SystemExit(1)",
1791
+ "",
1792
+ "def process_start_ticks(pid):",
1793
+ ' with open(f"/proc/{pid}/stat", "rb") as stat_file:',
1794
+ " raw = stat_file.read()",
1795
+ ' marker = raw.rfind(b") ")',
1796
+ " fields = raw[marker + 2:].split() if marker >= 0 else []",
1797
+ " if len(fields) <= 19:",
1798
+ " raise SystemExit(1)",
1799
+ ' return fields[19].decode("ascii")',
1800
+ "",
1801
+ "def consume_exec_environment():",
1802
+ " descriptor_stats = os.fstat(environment_fd)",
1803
+ " if (",
1804
+ " not stat.S_ISREG(descriptor_stats.st_mode)",
1805
+ " or stat.S_IMODE(descriptor_stats.st_mode) != 0o600",
1806
+ " or descriptor_stats.st_uid != os.geteuid()",
1807
+ " or descriptor_stats.st_nlink != 0",
1808
+ " or descriptor_stats.st_size <= 0",
1809
+ ` or descriptor_stats.st_size > ${SUPERVISOR_ENVIRONMENT_MAX_BYTES}`,
1810
+ " ):",
1811
+ " raise SystemExit(1)",
1812
+ ' source = b""',
1813
+ " try:",
1814
+ ` while len(source) <= ${SUPERVISOR_ENVIRONMENT_MAX_BYTES}:`,
1815
+ ` chunk = os.read(environment_fd, ${SUPERVISOR_ENVIRONMENT_MAX_BYTES + 1} - len(source))`,
1816
+ " if not chunk:",
1817
+ " break",
1818
+ " source += chunk",
1819
+ " finally:",
1820
+ " os.ftruncate(environment_fd, 0)",
1821
+ " os.close(environment_fd)",
1822
+ ` if not source or len(source) > ${SUPERVISOR_ENVIRONMENT_MAX_BYTES}:`,
1823
+ " raise SystemExit(1)",
1824
+ " try:",
1825
+ ' payload = json.loads(source.decode("utf-8", errors="strict"))',
1826
+ " except (UnicodeDecodeError, json.JSONDecodeError):",
1827
+ " raise SystemExit(1)",
1828
+ " if (",
1829
+ " type(payload) is not dict",
1830
+ ' or set(payload) != {"version", "environment"}',
1831
+ ' or type(payload.get("version")) is not int',
1832
+ ' or payload.get("version") != 1',
1833
+ ' or type(payload.get("environment")) is not dict',
1834
+ " ):",
1835
+ " raise SystemExit(1)",
1836
+ ' environment = payload["environment"]',
1837
+ ` if len(environment) > ${SUPERVISOR_ENVIRONMENT_MAX_ENTRIES} or any(`,
1838
+ " type(name) is not str",
1839
+ ` or len(name) > ${SUPERVISOR_ENVIRONMENT_MAX_NAME_BYTES}`,
1840
+ ' or re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name) is None',
1841
+ ` or name in (${JSON.stringify(SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV)}, ${JSON.stringify(SUPERVISOR_ENVIRONMENT_FD_ENV)})`,
1842
+ ' or "\\x00" in name',
1843
+ " or type(value) is not str",
1844
+ ' or "\\x00" in value',
1845
+ " for name, value in environment.items()",
1846
+ " ):",
1847
+ " raise SystemExit(1)",
1848
+ " payload_environment = {",
1849
+ ...Object.entries(DETACHED_PROCESS_LIFECYCLE_ENVIRONMENT).map(
1850
+ ([name, value]) => ` ${JSON.stringify(name)}: ${JSON.stringify(value)},`
1851
+ ),
1852
+ " }",
1853
+ " payload_environment.update(environment)",
1854
+ " return payload_environment",
1855
+ "",
1856
+ "def validate_completion_descriptor(expected_size=None):",
1857
+ " descriptor_stats = os.fstat(completion_fd)",
1858
+ " path_stats = os.lstat(completion_path)",
1859
+ " if (",
1860
+ " not stat.S_ISREG(descriptor_stats.st_mode)",
1861
+ " or not stat.S_ISREG(path_stats.st_mode)",
1862
+ " or stat.S_IMODE(descriptor_stats.st_mode) != 0o600",
1863
+ " or stat.S_IMODE(path_stats.st_mode) != 0o600",
1864
+ " or descriptor_stats.st_uid != os.geteuid()",
1865
+ " or path_stats.st_uid != os.geteuid()",
1866
+ " or descriptor_stats.st_nlink != 1",
1867
+ " or path_stats.st_nlink != 1",
1868
+ " or (descriptor_stats.st_dev, descriptor_stats.st_ino) != (path_stats.st_dev, path_stats.st_ino)",
1869
+ " or (expected_size is not None and descriptor_stats.st_size != expected_size)",
1870
+ " ):",
1871
+ " raise SystemExit(1)",
1872
+ " return descriptor_stats",
1873
+ "",
1874
+ "def validate_launch_directory(directory_fd):",
1875
+ " descriptor_stats = os.fstat(directory_fd)",
1876
+ " path_stats = os.lstat(launch_directory)",
1877
+ " if (",
1878
+ " not stat.S_ISDIR(descriptor_stats.st_mode)",
1879
+ " or not stat.S_ISDIR(path_stats.st_mode)",
1880
+ " or stat.S_IMODE(descriptor_stats.st_mode) != 0o700",
1881
+ " or stat.S_IMODE(path_stats.st_mode) != 0o700",
1882
+ " or descriptor_stats.st_uid != os.geteuid()",
1883
+ " or path_stats.st_uid != os.geteuid()",
1884
+ " or (descriptor_stats.st_dev, descriptor_stats.st_ino) != (path_stats.st_dev, path_stats.st_ino)",
1885
+ " ):",
1886
+ " raise SystemExit(1)",
1887
+ "",
1888
+ "def publish_started():",
1889
+ " if (",
1890
+ " os.path.dirname(started_partial_path) != launch_directory",
1891
+ " or os.path.dirname(started_path) != launch_directory",
1892
+ " ):",
1893
+ " raise SystemExit(1)",
1894
+ " partial_leaf = os.path.basename(started_partial_path)",
1895
+ " started_leaf = os.path.basename(started_path)",
1896
+ ` value = f"${STARTED_PREFIX} {target_pid} {target_ticks} {target_session} {target_descriptor}\\n".encode("ascii")`,
1897
+ " directory_fd = os.open(",
1898
+ " launch_directory,",
1899
+ " os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC | os.O_NOFOLLOW,",
1900
+ " )",
1901
+ " started_fd = -1",
1902
+ " try:",
1903
+ " validate_launch_directory(directory_fd)",
1904
+ " started_fd = os.open(",
1905
+ " partial_leaf,",
1906
+ " os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_CLOEXEC | os.O_NOFOLLOW,",
1907
+ " 0o600,",
1908
+ " dir_fd=directory_fd,",
1909
+ " )",
1910
+ " os.fchmod(started_fd, 0o600)",
1911
+ " offset = 0",
1912
+ " while offset < len(value):",
1913
+ " written = os.write(started_fd, value[offset:])",
1914
+ " if written <= 0:",
1915
+ " raise SystemExit(1)",
1916
+ " offset += written",
1917
+ " os.fsync(started_fd)",
1918
+ " partial_stats = os.fstat(started_fd)",
1919
+ " if (",
1920
+ " not stat.S_ISREG(partial_stats.st_mode)",
1921
+ " or stat.S_IMODE(partial_stats.st_mode) != 0o600",
1922
+ " or partial_stats.st_uid != os.geteuid()",
1923
+ " or partial_stats.st_nlink != 1",
1924
+ " or partial_stats.st_size != len(value)",
1925
+ " ):",
1926
+ " raise SystemExit(1)",
1927
+ " os.replace(",
1928
+ " partial_leaf,",
1929
+ " started_leaf,",
1930
+ " src_dir_fd=directory_fd,",
1931
+ " dst_dir_fd=directory_fd,",
1932
+ " )",
1933
+ " os.fsync(directory_fd)",
1934
+ " validate_launch_directory(directory_fd)",
1935
+ " published_stats = os.stat(started_leaf, dir_fd=directory_fd, follow_symlinks=False)",
1936
+ " full_path_stats = os.lstat(started_path)",
1937
+ " if (",
1938
+ " (published_stats.st_dev, published_stats.st_ino)",
1939
+ " != (partial_stats.st_dev, partial_stats.st_ino)",
1940
+ " or (full_path_stats.st_dev, full_path_stats.st_ino)",
1941
+ " != (partial_stats.st_dev, partial_stats.st_ino)",
1942
+ " or published_stats.st_nlink != 1",
1943
+ " or full_path_stats.st_nlink != 1",
1944
+ " or published_stats.st_size != len(value)",
1945
+ " or full_path_stats.st_size != len(value)",
1946
+ " ):",
1947
+ " raise SystemExit(1)",
1948
+ " finally:",
1949
+ " if started_fd >= 0:",
1950
+ " os.close(started_fd)",
1951
+ " os.close(directory_fd)",
1952
+ "",
1953
+ "if process_start_ticks(target_pid) != target_ticks:",
1954
+ " raise SystemExit(1)",
1955
+ "validate_completion_descriptor(0)",
1956
+ "os.set_inheritable(completion_fd, False)",
1957
+ "libc = ctypes.CDLL(None, use_errno=True)",
1958
+ "if libc.prctl(PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0) != 0:",
1959
+ " raise SystemExit(1)",
1960
+ "payload_environment = None",
1961
+ 'if environment_mode == "exec":',
1962
+ " payload_environment = consume_exec_environment()",
1963
+ " environment_fd = -1",
1964
+ "publish_started()",
1965
+ "",
1966
+ "def spawn_logger(arguments):",
1967
+ ' if logger_mode == "node":',
1968
+ ' argv = ["node", "-e", node_program, *arguments]',
1969
+ ' elif logger_mode == "shell":',
1970
+ ' argv = ["sh", "-c", shell_program, "bounded-log", *arguments]',
1971
+ " else:",
1972
+ " raise SystemExit(1)",
1973
+ " return subprocess.Popen(",
1974
+ " argv,",
1975
+ " stdin=subprocess.DEVNULL,",
1976
+ " stdout=subprocess.DEVNULL,",
1977
+ " stderr=subprocess.DEVNULL,",
1978
+ " close_fds=True,",
1979
+ " )",
1980
+ "",
1981
+ "def open_fifo_writer(path, logger):",
1982
+ " deadline = time.monotonic() + 5",
1983
+ " while True:",
1984
+ " try:",
1985
+ " descriptor = os.open(",
1986
+ " path,",
1987
+ " os.O_WRONLY | os.O_NONBLOCK | os.O_NOFOLLOW | os.O_CLOEXEC,",
1988
+ " )",
1989
+ " break",
1990
+ " except OSError as error:",
1991
+ " if error.errno != errno.ENXIO or logger.poll() is not None or time.monotonic() >= deadline:",
1992
+ " raise",
1993
+ " time.sleep(0.01)",
1994
+ " descriptor_stats = os.fstat(descriptor)",
1995
+ " path_stats = os.lstat(path)",
1996
+ " if (",
1997
+ " not stat.S_ISFIFO(descriptor_stats.st_mode)",
1998
+ " or not stat.S_ISFIFO(path_stats.st_mode)",
1999
+ " or stat.S_IMODE(descriptor_stats.st_mode) != 0o600",
2000
+ " or stat.S_IMODE(path_stats.st_mode) != 0o600",
2001
+ " or descriptor_stats.st_uid != os.geteuid()",
2002
+ " or path_stats.st_uid != os.geteuid()",
2003
+ " or (descriptor_stats.st_dev, descriptor_stats.st_ino) != (path_stats.st_dev, path_stats.st_ino)",
2004
+ " ):",
2005
+ " os.close(descriptor)",
2006
+ " raise SystemExit(1)",
2007
+ " flags = fcntl.fcntl(descriptor, fcntl.F_GETFL)",
2008
+ " fcntl.fcntl(descriptor, fcntl.F_SETFL, flags & ~os.O_NONBLOCK)",
2009
+ ' return os.fdopen(descriptor, "wb", buffering=0)',
2010
+ "",
2011
+ "if environment_fd < 0:",
2012
+ " try:",
2013
+ ` os.close(${SUPERVISOR_ENVIRONMENT_FD})`,
2014
+ " except OSError:",
2015
+ " pass",
2016
+ "children = []",
2017
+ "writers = []",
2018
+ "payload = None",
2019
+ "payload_returncode = 1",
2020
+ "initialization_failed = False",
2021
+ "try:",
2022
+ " stdout_logger = spawn_logger(stdout_args)",
2023
+ " children.append(stdout_logger)",
2024
+ " stderr_logger = spawn_logger(stderr_args)",
2025
+ " children.append(stderr_logger)",
2026
+ " stdout_writer = open_fifo_writer(stdout_args[0], stdout_logger)",
2027
+ " writers.append(stdout_writer)",
2028
+ " stderr_writer = open_fifo_writer(stderr_args[0], stderr_logger)",
2029
+ " writers.append(stderr_writer)",
2030
+ " payload = subprocess.Popen(",
2031
+ ' ["/bin/sh", "-c", command],',
2032
+ " stdin=subprocess.DEVNULL,",
2033
+ " stdout=stdout_writer,",
2034
+ " stderr=stderr_writer,",
2035
+ " env=payload_environment,",
2036
+ " close_fds=True,",
2037
+ " pass_fds=(() if environment_fd < 0 else (environment_fd,)),",
2038
+ " )",
2039
+ " children.append(payload)",
2040
+ "except BaseException:",
2041
+ " initialization_failed = True",
2042
+ "finally:",
2043
+ " for writer in writers:",
2044
+ " try:",
2045
+ " writer.close()",
2046
+ " except OSError:",
2047
+ " pass",
2048
+ " if environment_fd >= 0:",
2049
+ " try:",
2050
+ " os.close(environment_fd)",
2051
+ " except OSError:",
2052
+ " pass",
2053
+ "",
2054
+ "if initialization_failed:",
2055
+ " for child in children:",
2056
+ " if child.poll() is None:",
2057
+ " try:",
2058
+ " child.terminate()",
2059
+ " except ProcessLookupError:",
2060
+ " pass",
2061
+ " for child in children:",
2062
+ " try:",
2063
+ " child.wait(timeout=2)",
2064
+ " except subprocess.TimeoutExpired:",
2065
+ " try:",
2066
+ " child.kill()",
2067
+ " except ProcessLookupError:",
2068
+ " pass",
2069
+ " child.wait()",
2070
+ "else:",
2071
+ " payload_returncode = payload.wait()",
2072
+ " stdout_logger.wait()",
2073
+ " stderr_logger.wait()",
2074
+ "while True:",
2075
+ " try:",
2076
+ " os.wait()",
2077
+ " except InterruptedError:",
2078
+ " continue",
2079
+ " except ChildProcessError:",
2080
+ " break",
2081
+ "",
2082
+ `completion = f"${QUIESCENT_PREFIX} {target_pid} {target_ticks} {target_session} {target_descriptor}\\n".encode("ascii")`,
2083
+ "validate_completion_descriptor()",
2084
+ "os.ftruncate(completion_fd, 0)",
2085
+ "os.lseek(completion_fd, 0, os.SEEK_SET)",
2086
+ "offset = 0",
2087
+ "while offset < len(completion):",
2088
+ " written = os.write(completion_fd, completion[offset:])",
2089
+ " if written <= 0:",
2090
+ " raise SystemExit(1)",
2091
+ " offset += written",
2092
+ "os.fsync(completion_fd)",
2093
+ "validate_completion_descriptor(len(completion))",
2094
+ "raise SystemExit(payload_returncode if 0 <= payload_returncode <= 255 else 1)"
2095
+ ].join("\n");
2096
+ }
2097
+ function boundedLogCaptureLaunch(paths, descriptorKey, environmentMode) {
2098
+ const stdoutArgs = [
2099
+ logPipePath(paths.stdout),
2100
+ paths.stdout,
2101
+ previousLogPath(paths.stdout),
2102
+ logSnapshotPath(paths.stdout),
2103
+ logSnapshotStagingPath(paths.stdout),
2104
+ logChunkPath(paths.stdout)
2105
+ ];
2106
+ const stderrArgs = [
2107
+ logPipePath(paths.stderr),
2108
+ paths.stderr,
2109
+ previousLogPath(paths.stderr),
2110
+ logSnapshotPath(paths.stderr),
2111
+ logSnapshotStagingPath(paths.stderr),
2112
+ logChunkPath(paths.stderr)
2113
+ ];
2114
+ const shellLogger = [...boundedLogShellFunctions(), 'bounded_log_shell "$@"'].join("\n");
2115
+ const args = [
2116
+ '"$1"',
2117
+ '"$logger_mode"',
2118
+ shellQuote(boundedLogProgram()),
2119
+ shellQuote(shellLogger),
2120
+ ...stdoutArgs.map(shellQuote),
2121
+ ...stderrArgs.map(shellQuote),
2122
+ shellQuote(paths.quiescent),
2123
+ shellQuote(paths.startedPartial),
2124
+ shellQuote(paths.started),
2125
+ shellQuote(paths.directory),
2126
+ '"$pid"',
2127
+ '"$ticks"',
2128
+ '"$session"',
2129
+ shellQuote(descriptorKey),
2130
+ shellQuote(environmentMode),
2131
+ String(SUPERVISOR_ENVIRONMENT_FD),
2132
+ "6"
2133
+ ];
2134
+ return [
2135
+ "if command -v node >/dev/null 2>&1; then logger_mode=node; else logger_mode=shell; fi",
2136
+ // The provider-selected cwd is payload state, not trusted lifecycle code.
2137
+ // Isolated/no-site mode keeps it and sitecustomize out of reaper startup.
2138
+ `exec python3 -I -S -c ${shellQuote(detachedProcessReaperProgram())} ${args.join(" ")}`
2139
+ ];
2140
+ }
2141
+ function buildPrepareDetachedCommand(paths, descriptorKey, command, environmentMode = "exec", restartReleasedWhenExited = false) {
2142
+ const recordWrite = `printf '${IDENTITY_PREFIX} %s %s %s ${descriptorKey}\\n' "$pid" "$ticks" "$session" > ` + shellQuote(paths.recordPartial);
2143
+ const child = [
2144
+ "pid=$$",
2145
+ "stat=$(cat /proc/$$/stat 2>/dev/null) || exit 1",
2146
+ "rest=${stat##*) }",
2147
+ `pgrp=$(printf '%s\\n' "$rest" | awk '{print $3}')`,
2148
+ `session=$(printf '%s\\n' "$rest" | awk '{print $4}')`,
2149
+ `ticks=$(printf '%s\\n' "$rest" | awk '{print $20}')`,
2150
+ `case "$pid:$pgrp:$session:$ticks" in *[!0-9:]*) exit 1 ;; esac`,
2151
+ '[ "$pid" = "$pgrp" ] && [ "$pid" = "$session" ] && [ -n "$ticks" ] || exit 1',
2152
+ ...boundedLogCaptureSetup(paths),
2153
+ ...atomicFile(paths.recordPartial, paths.record, paths.directory, recordWrite),
2154
+ ...restartReleasedWhenExited ? ["exec 9>&-"] : [],
2155
+ "attempt=0",
2156
+ `while [ ! -s ${shellQuote(paths.decision)} ] && [ "$attempt" -lt 1200 ]; do`,
2157
+ " sleep 0.05",
2158
+ " attempt=$((attempt + 1))",
2159
+ "done",
2160
+ ...decisionFunctions(paths),
2161
+ "read_launch_decision || exit 1",
2162
+ `[ "$decision_descriptor" = ${shellQuote(descriptorKey)} ] || exit 1`,
2163
+ '[ "$decision_action" = RELEASE ] || exit 1',
2164
+ '[ "$decision_pid:$decision_ticks:$decision_session" = "$pid:$ticks:$session" ] || exit 1',
2165
+ ...boundedLogCaptureLaunch(paths, descriptorKey, environmentMode)
2166
+ ].join("\n");
2167
+ const childCommand = `set -- ${shellQuote(command)}
2168
+ ${child}`;
2169
+ const launch = buildEnvironmentFdLaunch(paths, childCommand, environmentMode);
2170
+ return cleanLifecycleShell(
2171
+ [
2172
+ "umask 077",
2173
+ ...secureDetachedRoot(),
2174
+ ...restartReleasedWhenExited ? generationLock(paths) : [],
2175
+ ...identityFunctions(paths),
2176
+ ...decisionFunctions(paths),
2177
+ ...processTreeFunctions(paths),
2178
+ ...restartReleasedWhenExited ? retireExitedReleasedLaunch(paths, descriptorKey) : [],
2179
+ `if [ ! -e ${shellQuote(paths.directory)} ] && [ ! -L ${shellQuote(paths.directory)} ] && mkdir ${shellQuote(paths.directory)} 2>/dev/null; then`,
2180
+ ...secureLaunchDirectory(paths, false).map((line) => ` ${line}`),
2181
+ ` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
2182
+ ...launch.map((line) => ` ${line}`),
2183
+ "fi",
2184
+ ...secureLaunchDirectory(paths, false),
2185
+ "attempt=0",
2186
+ `while [ ! -s ${shellQuote(paths.record)} ] && [ "$attempt" -lt 200 ]; do`,
2187
+ " sleep 0.05",
2188
+ " attempt=$((attempt + 1))",
2189
+ "done",
2190
+ "read_launch_identity || exit 1",
2191
+ `if [ "$target_descriptor" != ${shellQuote(descriptorKey)} ]; then`,
2192
+ ` printf '${DESCRIPTOR_MISMATCH_SENTINEL}\\n'`,
2193
+ " exit 2",
2194
+ "fi",
2195
+ "if read_launch_decision; then",
2196
+ ` [ "$decision_descriptor" = ${shellQuote(descriptorKey)} ] || { printf '${DESCRIPTOR_MISMATCH_SENTINEL}\\n'; exit 2; }`,
2197
+ ` [ "$decision_action" = RELEASE ] || { printf '${CANCELLED_SENTINEL}\\n'; exit 3; }`,
2198
+ ...waitForStarted(paths).map((line) => ` ${line}`),
2199
+ "else",
2200
+ " leader_identity_status || exit 1",
2201
+ "fi",
2202
+ ...restartReleasedWhenExited ? ["exec 9>&-"] : [],
2203
+ `printf '${PREPARED_SENTINEL} %s %s %s %s\\n' "$target_pid" "$target_ticks" "$target_session" "$target_descriptor"`
2204
+ ].join("\n"),
2205
+ environmentMode
2206
+ );
2207
+ }
2208
+ function buildReleaseDetachedCommand(paths, identity, serializeGenerationChanges = false) {
2209
+ return [
2210
+ "umask 077",
2211
+ ...serializeGenerationChanges ? acquireGenerationLock(paths) : [],
2212
+ ...serializeGenerationChanges ? [] : secureDetachedRoot(),
2213
+ ...secureLaunchDirectory(paths, false),
2214
+ ...identityFunctions(paths),
2215
+ ...decisionFunctions(paths),
2216
+ ...serializeGenerationChanges ? processTreeFunctions(paths) : [],
2217
+ "read_launch_identity || exit 1",
2218
+ `[ "$target_pid:$target_ticks:$target_session:$target_descriptor" = ${shellQuote(
2219
+ `${identity.pid}:${identity.startTicks}:${identity.sessionId}:${identity.descriptorKey}`
2220
+ )} ] || exit 1`,
2221
+ "publish_pid=$target_pid",
2222
+ "publish_ticks=$target_ticks",
2223
+ "publish_session=$target_session",
2224
+ "publish_descriptor=$target_descriptor",
2225
+ ...publishDecision(paths, "RELEASE", paths.releaseDecisionPartial),
2226
+ '[ "$decision_action" = RELEASE ] || exit 3',
2227
+ '[ "$decision_pid:$decision_ticks:$decision_session:$decision_descriptor" = "$target_pid:$target_ticks:$target_session:$target_descriptor" ] || exit 1',
2228
+ ...releasedAdoptionOutcome(
2229
+ paths,
2230
+ identity.descriptorKey,
2231
+ serializeGenerationChanges
2232
+ )
2233
+ ].join("\n");
2234
+ }
2235
+ function isReleaseConfirmation(output, identity) {
2236
+ return Boolean(
2237
+ parseIdentityOutput(
2238
+ RELEASED_PATTERN,
2239
+ identity.provider,
2240
+ pathsForIdentity(identity),
2241
+ identity.descriptorKey,
2242
+ output
2243
+ )
2244
+ );
2245
+ }
2246
+ function buildCancelDetachedCommand(paths, descriptorKey, expected, serializeGenerationChanges = false) {
2247
+ return [
2248
+ "umask 077",
2249
+ ...serializeGenerationChanges ? acquireGenerationLock(paths) : secureDetachedRoot(),
2250
+ ...secureLaunchDirectory(paths, true),
2251
+ `sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
2252
+ ...identityFunctions(paths),
2253
+ ...decisionFunctions(paths),
2254
+ ...processTreeFunctions(paths),
2255
+ "if read_launch_identity; then",
2256
+ ` [ "$target_descriptor" = ${shellQuote(descriptorKey)} ] || { printf '${DESCRIPTOR_MISMATCH_SENTINEL}\\n'; exit 2; }`,
2257
+ ...expected ? [
2258
+ ` [ "$target_pid:$target_ticks:$target_session:$target_descriptor" = ${shellQuote(
2259
+ `${expected.pid}:${expected.startTicks}:${expected.sessionId}:${expected.descriptorKey}`
2260
+ )} ] || exit 1`
2261
+ ] : [],
2262
+ " publish_pid=$target_pid",
2263
+ " publish_ticks=$target_ticks",
2264
+ " publish_session=$target_session",
2265
+ "else",
2266
+ " publish_pid=0",
2267
+ " publish_ticks=0",
2268
+ " publish_session=0",
2269
+ "fi",
2270
+ `publish_descriptor=${shellQuote(descriptorKey)}`,
2271
+ ...publishDecision(paths, "CANCEL", paths.cancelDecisionPartial),
2272
+ `[ "$decision_descriptor" = ${shellQuote(descriptorKey)} ] || { printf '${DESCRIPTOR_MISMATCH_SENTINEL}\\n'; exit 2; }`,
2273
+ 'if [ "$decision_action" = RELEASE ]; then',
2274
+ ...releasedAdoptionOutcome(paths, descriptorKey, serializeGenerationChanges).map(
2275
+ (line) => ` ${line}`
2276
+ ),
2277
+ "fi",
2278
+ "# CANCEL won the only durable decision. The child can never execute the requested command.",
2279
+ "if read_launch_identity; then",
2280
+ ...stopTargetCommands().map((line) => ` ${line}`),
2281
+ "fi",
2282
+ `printf '${CANCELLED_SENTINEL}\\n'`
2283
+ ].join("\n");
2284
+ }
2285
+ function parseCancellationResult(provider, paths, descriptorKey, output) {
2286
+ if (output.trim() === CANCELLED_SENTINEL) return { state: "cancelled" };
2287
+ if (output.trim() === RELEASED_GENERATION_UNAVAILABLE_SENTINEL) {
2288
+ return { state: "released_generation_unavailable" };
2289
+ }
2290
+ const identity = parseReleasedIdentity(
2291
+ provider,
2292
+ paths,
2293
+ descriptorKey,
2294
+ output
2295
+ );
2296
+ return identity ? { state: "released", identity } : null;
2297
+ }
2298
+ function buildStopDetachedCommand(paths, expected) {
2299
+ return [
2300
+ "umask 077",
2301
+ ...secureDetachedRoot(),
2302
+ ...secureLaunchDirectory(paths, false),
2303
+ ...identityFunctions(paths),
2304
+ ...processTreeFunctions(paths),
2305
+ "read_launch_identity || exit 1",
2306
+ `[ "$target_pid:$target_ticks:$target_session:$target_descriptor" = ${shellQuote(
2307
+ `${expected.pid}:${expected.startTicks}:${expected.sessionId}:${expected.descriptorKey}`
2308
+ )} ] || exit 1`,
2309
+ "# Revalidate the leader birth immediately before every scan and every kill.",
2310
+ ...stopTargetCommands(),
2311
+ `printf '${STOPPED_SENTINEL}\\n'`
2312
+ ].join("\n");
2313
+ }
2314
+ function disposableLaunchDirectoryProof(paths, expected, namespace) {
2315
+ const readIdentity = `read_exact_${namespace}_identity`;
2316
+ const readStarted = `read_exact_${namespace}_started`;
2317
+ const readQuiescent = `read_exact_${namespace}_quiescent`;
2318
+ const readEmptyQuiescent = `read_exact_${namespace}_empty_quiescent`;
2319
+ const expectedIdentity = `${expected.pid}:${expected.startTicks}:${expected.sessionId}:` + expected.descriptorKey;
2320
+ return [
2321
+ ...secureLaunchDirectory(paths, false),
2322
+ ...identityFunctions(paths),
2323
+ ...exactLifecycleMarkerFunction(
2324
+ readIdentity,
2325
+ `exact_${namespace}_identity`,
2326
+ paths.record,
2327
+ { kind: "populated", markerPrefix: IDENTITY_PREFIX }
2328
+ ),
2329
+ ...exactLifecycleMarkerFunction(
2330
+ readStarted,
2331
+ `exact_${namespace}_started`,
2332
+ paths.started,
2333
+ { kind: "populated", markerPrefix: STARTED_PREFIX }
2334
+ ),
2335
+ ...exactLifecycleMarkerFunction(
2336
+ readQuiescent,
2337
+ `exact_${namespace}_quiescent`,
2338
+ paths.quiescent,
2339
+ { kind: "populated", markerPrefix: QUIESCENT_PREFIX }
2340
+ ),
2341
+ ...exactLifecycleMarkerFunction(
2342
+ readEmptyQuiescent,
2343
+ `exact_${namespace}_empty_quiescent`,
2344
+ paths.quiescent,
2345
+ { kind: "empty" }
2346
+ ),
2347
+ "read_launch_identity || exit 1",
2348
+ `[ "$target_pid:$target_ticks:$target_session:$target_descriptor" = ${shellQuote(expectedIdentity)} ] || exit 1`,
2349
+ '[ "$target_reaper_protocol" = v3 ] || exit 1',
2350
+ `${readIdentity} || exit 1`,
2351
+ "leader_identity_status",
2352
+ `${namespace}_leader_status=$?`,
2353
+ `[ "$${namespace}_leader_status" -ne 0 ] || exit 1`,
2354
+ `${readStarted}`,
2355
+ `${namespace}_started_status=$?`,
2356
+ `case "$${namespace}_started_status" in`,
2357
+ ` 0) ${readQuiescent} || exit 1 ;;`,
2358
+ ` 1) ${readEmptyQuiescent} || exit 1 ;;`,
2359
+ " *) exit 1 ;;",
2360
+ "esac"
2361
+ ];
2362
+ }
2363
+ function buildDisposeDetachedArtifactsCommand(paths, expected) {
2364
+ const disposedDirectory = disposedDirectoryForIdentity(expected);
2365
+ const retiredPaths = pathsForDetachedLaunchDirectory(
2366
+ paths,
2367
+ paths.retiredDirectory
2368
+ );
2369
+ return [
2370
+ "umask 077",
2371
+ ...acquireGenerationLock(paths),
2372
+ `if [ -e ${shellQuote(disposedDirectory)} ] || [ -L ${shellQuote(disposedDirectory)} ]; then`,
2373
+ ...secureDirectory(disposedDirectory, false).map((line) => ` ${line}`),
2374
+ ` rm -rf -- ${shellQuote(disposedDirectory)} || exit 1`,
2375
+ ` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
2376
+ "fi",
2377
+ `if [ -e ${shellQuote(paths.retiredDirectory)} ] || [ -L ${shellQuote(paths.retiredDirectory)} ]; then`,
2378
+ ...disposableLaunchDirectoryProof(
2379
+ retiredPaths,
2380
+ expected,
2381
+ "retired_disposal"
2382
+ ).map((line) => ` ${line}`),
2383
+ ` mv -- ${shellQuote(paths.retiredDirectory)} ${shellQuote(disposedDirectory)} || exit 1`,
2384
+ ...secureDirectory(disposedDirectory, false).map((line) => ` ${line}`),
2385
+ ` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
2386
+ ` rm -rf -- ${shellQuote(disposedDirectory)} || exit 1`,
2387
+ ` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
2388
+ "fi",
2389
+ `if [ -e ${shellQuote(paths.directory)} ] || [ -L ${shellQuote(paths.directory)} ]; then`,
2390
+ ...disposableLaunchDirectoryProof(paths, expected, "live_disposal").map(
2391
+ (line) => ` ${line}`
2392
+ ),
2393
+ ` mv -- ${shellQuote(paths.directory)} ${shellQuote(disposedDirectory)} || exit 1`,
2394
+ ...secureDirectory(disposedDirectory, false).map((line) => ` ${line}`),
2395
+ ` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
2396
+ ` rm -rf -- ${shellQuote(disposedDirectory)} || exit 1`,
2397
+ ` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
2398
+ "fi",
2399
+ `if [ -e ${shellQuote(disposedDirectory)} ] || [ -L ${shellQuote(disposedDirectory)} ]; then exit 1; fi`,
2400
+ `if [ -e ${shellQuote(paths.retiredDirectory)} ] || [ -L ${shellQuote(paths.retiredDirectory)} ]; then exit 1; fi`,
2401
+ `if [ -e ${shellQuote(paths.directory)} ] || [ -L ${shellQuote(paths.directory)} ]; then exit 1; fi`,
2402
+ "assert_generation_lock || exit 1",
2403
+ `rm -f -- ${shellQuote(paths.controlLock)} || exit 1`,
2404
+ `if [ -e ${shellQuote(paths.controlLock)} ] || [ -L ${shellQuote(paths.controlLock)} ]; then exit 1; fi`,
2405
+ `sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
2406
+ `printf '${DISPOSED_SENTINEL}
2407
+ '`
2408
+ ].join("\n");
2409
+ }
2410
+ function isDisposeConfirmation(output) {
2411
+ return output.trim() === DISPOSED_SENTINEL;
2412
+ }
2413
+ function buildReadDetachedLogsCommand(expected) {
2414
+ const paths = pathsForIdentity(expected);
2415
+ const expectedIdentity = `${expected.pid}:${expected.startTicks}:${expected.sessionId}:${expected.descriptorKey}`;
2416
+ return [
2417
+ "umask 077",
2418
+ ...secureDetachedRoot(),
2419
+ ...secureLaunchDirectory(paths, false),
2420
+ ...identityFunctions(paths),
2421
+ ...processTreeFunctions(paths),
2422
+ "read_launch_identity || exit 1",
2423
+ `[ "$target_pid:$target_ticks:$target_session:$target_descriptor" = ${shellQuote(expectedIdentity)} ] || exit 3`,
2424
+ ...readLogFiles(
2425
+ paths.stdout,
2426
+ paths.stderr,
2427
+ {
2428
+ stdout: previousLogPath(paths.stdout),
2429
+ stderr: previousLogPath(paths.stderr)
2430
+ },
2431
+ [
2432
+ "read_launch_identity || exit 1",
2433
+ `[ "$target_pid:$target_ticks:$target_session:$target_descriptor" = ${shellQuote(expectedIdentity)} ] || exit 3`
2434
+ ]
2435
+ )
2436
+ ].join("\n");
2437
+ }
2438
+ function buildReadLegacyDetachedLogsCommand(nonce) {
2439
+ const stdout = `${DETACHED_PROCESS_ROOT}/${nonce}.stdout.log`;
2440
+ const stderr = `${DETACHED_PROCESS_ROOT}/${nonce}.stderr.log`;
2441
+ return [
2442
+ "umask 077",
2443
+ ...secureDetachedRoot(),
2444
+ ...readLogFiles(stdout, stderr)
2445
+ ].join("\n");
2446
+ }
2447
+ function readLogFiles(stdout, stderr, previous, beforePrint = []) {
2448
+ const optionalPrevious = (path2) => [
2449
+ `if [ -e ${shellQuote(path2)} ] || [ -L ${shellQuote(path2)} ]; then`,
2450
+ ...assertSafeRegularFile(path2).map((line) => line.replace("return 1", "exit 1")).map((line) => ` ${line}`),
2451
+ "fi"
2452
+ ];
2453
+ const boundedPayload = (current, prior) => prior === void 0 ? `read_bounded_log_file ${shellQuote(current)}` : `read_bounded_log_snapshot ${shellQuote(current)} ${shellQuote(prior)} ${shellQuote(logSnapshotPath(current))}`;
2454
+ return [
2455
+ ...previous === void 0 ? [] : [...optionalPrevious(previous.stdout), ...optionalPrevious(previous.stderr)],
2456
+ "command -v base64 >/dev/null 2>&1 || exit 1",
2457
+ ...previous === void 0 ? [] : ["command -v head >/dev/null 2>&1 || exit 1"],
2458
+ "command -v tail >/dev/null 2>&1 || exit 1",
2459
+ "command -v tr >/dev/null 2>&1 || exit 1",
2460
+ "close_log_segment_descriptors() {",
2461
+ " exec 6<&-",
2462
+ " exec 7<&-",
2463
+ "}",
2464
+ "assert_log_segment_descriptor() {",
2465
+ " snapshot_log_path=$1",
2466
+ " snapshot_log_fd=$2",
2467
+ ' [ -f "$snapshot_log_path" ] && [ ! -L "$snapshot_log_path" ] || return 1',
2468
+ ' [ -f "/proc/self/fd/$snapshot_log_fd" ] || return 1',
2469
+ ' snapshot_log_path_metadata=$(stat -c %u:%a:%h "$snapshot_log_path" 2>/dev/null) || return 1',
2470
+ ' snapshot_log_descriptor_metadata=$(stat -Lc %u:%a:%h "/proc/self/fd/$snapshot_log_fd" 2>/dev/null) || return 1',
2471
+ ' [ "$snapshot_log_path_metadata" = "$(id -u):600:1" ] || return 1',
2472
+ ' [ "$snapshot_log_descriptor_metadata" = "$snapshot_log_path_metadata" ] || return 1',
2473
+ ' snapshot_log_path_inode=$(stat -c %d:%i "$snapshot_log_path" 2>/dev/null) || return 1',
2474
+ ' snapshot_log_descriptor_inode=$(stat -Lc %d:%i "/proc/self/fd/$snapshot_log_fd" 2>/dev/null) || return 1',
2475
+ ' [ "$snapshot_log_descriptor_inode" = "$snapshot_log_path_inode" ]',
2476
+ "}",
2477
+ "read_bounded_log_file() {",
2478
+ " snapshot_current=$1",
2479
+ " close_log_segment_descriptors",
2480
+ ' [ -f "$snapshot_current" ] && [ ! -L "$snapshot_current" ] || return 1',
2481
+ ' exec 6<"$snapshot_current" || return 1',
2482
+ ' assert_log_segment_descriptor "$snapshot_current" 6 || { close_log_segment_descriptors; return 1; }',
2483
+ ` tail -c ${DETACHED_PROCESS_LOG_MAX_BYTES} -- /proc/self/fd/6 | base64 6<&- 7<&- | tr -d '\\n' 6<&- 7<&-`,
2484
+ " snapshot_segment_status=$?",
2485
+ " close_log_segment_descriptors",
2486
+ ' return "$snapshot_segment_status"',
2487
+ "}",
2488
+ ...previous === void 0 ? [] : [
2489
+ "read_log_snapshot_marker() {",
2490
+ " snapshot_marker_path=$1",
2491
+ ' [ -e "$snapshot_marker_path" ] || return 1',
2492
+ ' [ -f "$snapshot_marker_path" ] && [ ! -L "$snapshot_marker_path" ] || return 1',
2493
+ ` snapshot_marker=$(head -c ${DETACHED_PROCESS_LOG_SNAPSHOT_MAX_BYTES + 1} -- "$snapshot_marker_path") || return 1`,
2494
+ ` [ "\${#snapshot_marker}" -le ${DETACHED_PROCESS_LOG_SNAPSHOT_MAX_BYTES} ] || return 1`,
2495
+ ` snapshot_marker_valid=$(printf '%s\\n' "$snapshot_marker" | awk 'NR == 1 && ($1 == "${LEGACY_LOG_SNAPSHOT_PREFIX}" || $1 == "${LOG_SNAPSHOT_PREFIX}") && ($2 == "STABLE" || $2 == "ROTATING") && $3 ~ /^[0-9]+$/ && NF == 3 { valid = 1; next } { valid = 0 } END { if (NR == 1 && valid == 1) print "yes" }')`,
2496
+ ' [ "$snapshot_marker_valid" = yes ] || return 1',
2497
+ ` printf '%s\\n' "$snapshot_marker"`,
2498
+ "}",
2499
+ "read_legacy_log_snapshot() {",
2500
+ " snapshot_current=$1",
2501
+ " snapshot_previous=$2",
2502
+ " snapshot_marker_path=$3",
2503
+ " snapshot_attempt=0",
2504
+ ` while [ "$snapshot_attempt" -lt ${DETACHED_PROCESS_LEGACY_LOG_SNAPSHOT_ATTEMPTS} ]; do`,
2505
+ ' snapshot_before=$(read_log_snapshot_marker "$snapshot_marker_path") || return 1',
2506
+ ` case "$snapshot_before" in '${LEGACY_LOG_SNAPSHOT_PREFIX} STABLE '*) ;; '${LEGACY_LOG_SNAPSHOT_PREFIX} ROTATING '*) snapshot_attempt=$((snapshot_attempt + 1)); sleep 0.01; continue ;; *) return 1 ;; esac`,
2507
+ ' snapshot_payload=$(read_bounded_log_segments "$snapshot_current" "$snapshot_previous") || return 1',
2508
+ ' snapshot_after=$(read_log_snapshot_marker "$snapshot_marker_path") || return 1',
2509
+ ' if [ "$snapshot_before" = "$snapshot_after" ]; then',
2510
+ ` printf '%s' "$snapshot_payload"`,
2511
+ " return 0",
2512
+ " fi",
2513
+ " snapshot_attempt=$((snapshot_attempt + 1))",
2514
+ " sleep 0.01",
2515
+ " done",
2516
+ " return 1",
2517
+ "}",
2518
+ "target_is_quiescent() {",
2519
+ " target_has_live_processes",
2520
+ " snapshot_process_status=$?",
2521
+ ' [ "$snapshot_process_status" -eq 1 ]',
2522
+ "}",
2523
+ "open_log_segment_descriptors() {",
2524
+ " snapshot_current=$1",
2525
+ " snapshot_previous=$2",
2526
+ " close_log_segment_descriptors",
2527
+ ' [ -f "$snapshot_current" ] && [ ! -L "$snapshot_current" ] || return 1',
2528
+ ' exec 6<"$snapshot_current" || return 1',
2529
+ ' assert_log_segment_descriptor "$snapshot_current" 6 || { close_log_segment_descriptors; return 1; }',
2530
+ " snapshot_has_previous=no",
2531
+ ' if [ -e "$snapshot_previous" ] || [ -L "$snapshot_previous" ]; then',
2532
+ ' [ -f "$snapshot_previous" ] && [ ! -L "$snapshot_previous" ] || { close_log_segment_descriptors; return 1; }',
2533
+ ' exec 7<"$snapshot_previous" || { close_log_segment_descriptors; return 1; }',
2534
+ ' assert_log_segment_descriptor "$snapshot_previous" 7 || { close_log_segment_descriptors; return 1; }',
2535
+ " snapshot_has_previous=yes",
2536
+ " fi",
2537
+ ' assert_log_segment_descriptor "$snapshot_current" 6 || { close_log_segment_descriptors; return 1; }',
2538
+ ' if [ "$snapshot_has_previous" = yes ]; then',
2539
+ ' assert_log_segment_descriptor "$snapshot_previous" 7 || { close_log_segment_descriptors; return 1; }',
2540
+ " fi",
2541
+ "}",
2542
+ "read_bounded_log_segments() {",
2543
+ " snapshot_current=$1",
2544
+ " snapshot_previous=$2",
2545
+ ' open_log_segment_descriptors "$snapshot_current" "$snapshot_previous" || return 1',
2546
+ ` { if [ "$snapshot_has_previous" = yes ]; then tail -c ${DETACHED_PROCESS_LOG_MAX_BYTES} -- /proc/self/fd/7; fi; tail -c ${DETACHED_PROCESS_LOG_MAX_BYTES} -- /proc/self/fd/6; } | tail -c ${DETACHED_PROCESS_LOG_MAX_BYTES} 6<&- 7<&- | base64 6<&- 7<&- | tr -d '\\n' 6<&- 7<&-`,
2547
+ " snapshot_segment_status=$?",
2548
+ " close_log_segment_descriptors",
2549
+ ' return "$snapshot_segment_status"',
2550
+ "}",
2551
+ "read_v2_log_snapshot() {",
2552
+ " snapshot_current=$1",
2553
+ " snapshot_previous=$2",
2554
+ " snapshot_marker_path=$3",
2555
+ " snapshot_attempt=0",
2556
+ ` while [ "$snapshot_attempt" -lt ${DETACHED_PROCESS_LEGACY_LOG_SNAPSHOT_ATTEMPTS} ]; do`,
2557
+ " snapshot_before=",
2558
+ ' if [ ! -e "$snapshot_marker_path" ] && [ ! -L "$snapshot_marker_path" ]; then',
2559
+ " # Markerless V2 logs predate marker coordination and are safe",
2560
+ " # to inspect only after their exact process session is quiescent.",
2561
+ " target_is_quiescent || return 1",
2562
+ " else",
2563
+ ' snapshot_before=$(read_log_snapshot_marker "$snapshot_marker_path") || return 1',
2564
+ ` case "$snapshot_before" in '${LOG_SNAPSHOT_PREFIX} STABLE '*) ;; '${LOG_SNAPSHOT_PREFIX} ROTATING '*) if ! target_is_quiescent; then snapshot_attempt=$((snapshot_attempt + 1)); sleep 0.01; continue; fi ;; *) return 1 ;; esac`,
2565
+ " fi",
2566
+ ' if [ ! -e "$snapshot_current" ] && [ ! -L "$snapshot_current" ]; then',
2567
+ " # A crashed rotation may strand current absent after it became",
2568
+ " # previous. Recreate it only after the captured session is gone.",
2569
+ " target_is_quiescent || return 1",
2570
+ ' ( set -C; : > "$snapshot_current" ) 2>/dev/null || true',
2571
+ ' [ -e "$snapshot_current" ] || return 1',
2572
+ ' chmod 600 "$snapshot_current" || return 1',
2573
+ " fi",
2574
+ ' [ -f "$snapshot_current" ] && [ ! -L "$snapshot_current" ] || return 1',
2575
+ ' if [ -e "$snapshot_previous" ] || [ -L "$snapshot_previous" ]; then',
2576
+ ' [ -f "$snapshot_previous" ] && [ ! -L "$snapshot_previous" ] || return 1',
2577
+ " fi",
2578
+ ' snapshot_payload=$(read_bounded_log_segments "$snapshot_current" "$snapshot_previous") || return 1',
2579
+ ' if [ -z "$snapshot_before" ]; then',
2580
+ ` printf '%s' "$snapshot_payload"`,
2581
+ " return 0",
2582
+ " fi",
2583
+ ' snapshot_after=$(read_log_snapshot_marker "$snapshot_marker_path") || return 1',
2584
+ ' if [ "$snapshot_before" = "$snapshot_after" ]; then',
2585
+ ` printf '%s' "$snapshot_payload"`,
2586
+ " return 0",
2587
+ " fi",
2588
+ " snapshot_attempt=$((snapshot_attempt + 1))",
2589
+ " sleep 0.01",
2590
+ " done",
2591
+ " return 1",
2592
+ "}",
2593
+ "read_bounded_log_snapshot() {",
2594
+ " snapshot_current=$1",
2595
+ " snapshot_previous=$2",
2596
+ " snapshot_marker_path=$3",
2597
+ ' if [ -e "$snapshot_marker_path" ] && [ ! -L "$snapshot_marker_path" ]; then',
2598
+ ' snapshot_protocol=$(read_log_snapshot_marker "$snapshot_marker_path") || return 1',
2599
+ ` case "$snapshot_protocol" in '${LEGACY_LOG_SNAPSHOT_PREFIX} '*) read_legacy_log_snapshot "$snapshot_current" "$snapshot_previous" "$snapshot_marker_path"; return $? ;; esac`,
2600
+ " fi",
2601
+ ' read_v2_log_snapshot "$snapshot_current" "$snapshot_previous" "$snapshot_marker_path"',
2602
+ "}"
2603
+ ],
2604
+ `stdout_payload=$(${boundedPayload(stdout, previous?.stdout)}) || exit 1`,
2605
+ `stderr_payload=$(${boundedPayload(stderr, previous?.stderr)}) || exit 1`,
2606
+ ...beforePrint,
2607
+ 'stdout_padding=0; case "$stdout_payload" in *==) stdout_padding=2 ;; *=) stdout_padding=1 ;; esac',
2608
+ 'stderr_padding=0; case "$stderr_payload" in *==) stderr_padding=2 ;; *=) stderr_padding=1 ;; esac',
2609
+ "stdout_size=$((${#stdout_payload} / 4 * 3 - stdout_padding))",
2610
+ "stderr_size=$((${#stderr_payload} / 4 * 3 - stderr_padding))",
2611
+ `printf '${LOGS_PREFIX} %s %s\\n' "$stdout_size" "$stderr_size"`,
2612
+ `printf '%s\\n%s\\n' "$stdout_payload" "$stderr_payload"`
2613
+ ];
2614
+ }
2615
+ function parseDetachedProcessLogs(output) {
2616
+ const lineEnd = output.indexOf("\n");
2617
+ if (lineEnd < 0) return null;
2618
+ const header2 = output.slice(0, lineEnd);
2619
+ const match = new RegExp(`^${LOGS_PREFIX} (0|[1-9][0-9]*) (0|[1-9][0-9]*)$`, "u").exec(
2620
+ header2
2621
+ );
2622
+ if (!match?.[1] || !match[2]) return null;
2623
+ const stdoutBytes = Number(match[1]);
2624
+ const stderrBytes = Number(match[2]);
2625
+ if (!Number.isSafeInteger(stdoutBytes) || !Number.isSafeInteger(stderrBytes) || stdoutBytes > DETACHED_PROCESS_LOG_MAX_BYTES || stderrBytes > DETACHED_PROCESS_LOG_MAX_BYTES) {
2626
+ return null;
2627
+ }
2628
+ const payloadLines = output.slice(lineEnd + 1).split("\n");
2629
+ if (payloadLines.length !== 3 || payloadLines[2] !== "") return null;
2630
+ const [stdoutBase64, stderrBase64] = payloadLines;
2631
+ if (stdoutBase64 === void 0 || stderrBase64 === void 0) return null;
2632
+ if (stdoutBase64.length !== 4 * Math.ceil(stdoutBytes / 3) || stderrBase64.length !== 4 * Math.ceil(stderrBytes / 3)) {
2633
+ return null;
2634
+ }
2635
+ const decodeCanonicalBase64 = (value) => {
2636
+ const decoded = Buffer.from(value, "base64");
2637
+ return decoded.toString("base64") === value ? decoded : null;
2638
+ };
2639
+ const stdout = decodeCanonicalBase64(stdoutBase64);
2640
+ const stderr = decodeCanonicalBase64(stderrBase64);
2641
+ if (!stdout || !stderr || stdout.byteLength !== stdoutBytes || stderr.byteLength !== stderrBytes || !isUtf8(stdout) || !isUtf8(stderr)) {
2642
+ return null;
2643
+ }
2644
+ return {
2645
+ stdout: stdout.toString("utf8"),
2646
+ stderr: stderr.toString("utf8")
2647
+ };
2648
+ }
2649
+ function isStopConfirmation(output) {
2650
+ return output.trim() === STOPPED_SENTINEL;
2651
+ }
2652
+
2653
+ // src/providers/daytona-transport.ts
2654
+ import { Buffer as Buffer3 } from "buffer";
2655
+ function daytonaTimeoutSeconds(timeoutMs) {
2656
+ return Math.max(1, Math.ceil(timeoutMs / 1e3));
2657
+ }
2658
+ function daytonaCommandOutput(result) {
2659
+ return result.artifacts?.stdout || result.result || "";
2660
+ }
2661
+ async function discoverDaytonaSandboxDirectories(sandbox, options) {
2662
+ await options.beforeIo?.();
2663
+ const reportedWorkDir = await sandbox.getWorkDir();
2664
+ await options.beforeIo?.();
2665
+ const reportedHomeDir = await sandbox.getUserHomeDir();
2666
+ const workDir = reportedWorkDir ?? reportedHomeDir;
2667
+ const homeDir = reportedHomeDir ?? workDir;
2668
+ if (!homeDir || !workDir) {
2669
+ throw options.failure(
2670
+ "Daytona sandbox did not report a home or working directory."
2671
+ );
2672
+ }
2673
+ return { homeDir, workDir };
2674
+ }
2675
+ async function executeDaytonaCommand(sandbox, command, options) {
2676
+ const result = await executeRawDaytonaCommand(sandbox, command, options);
2677
+ return {
2678
+ exitCode: result.exitCode,
2679
+ stdout: daytonaCommandOutput(result),
2680
+ stderr: ""
2681
+ };
2682
+ }
2683
+ async function executeRawDaytonaCommand(sandbox, command, options) {
2684
+ await options.beforeIo?.();
2685
+ return sandbox.process.executeCommand(
2686
+ command,
2687
+ options.cwd,
2688
+ options.envs,
2689
+ daytonaTimeoutSeconds(options.timeoutMs)
2690
+ );
2691
+ }
2692
+ async function makeDaytonaDirectory(sandbox, path2, options) {
2693
+ return executeRawDaytonaCommand(
2694
+ sandbox,
2695
+ `mkdir -p -- ${shellQuote(path2)}`,
2696
+ options
2697
+ );
2698
+ }
2699
+ function daytonaUploadContent(content) {
2700
+ if (Buffer3.isBuffer(content)) return content;
2701
+ if (typeof content === "string") return Buffer3.from(content);
2702
+ if (content instanceof Uint8Array) return Buffer3.from(content);
2703
+ return Buffer3.from(content);
2704
+ }
2705
+ async function uploadDaytonaFile(sandbox, path2, content, options) {
2706
+ await options.beforeIo?.();
2707
+ await sandbox.fs.uploadFile(
2708
+ daytonaUploadContent(content),
2709
+ path2,
2710
+ daytonaTimeoutSeconds(options.timeoutMs)
2711
+ );
2712
+ }
2713
+ function createDaytonaProcessController(sandbox, options) {
2714
+ return new DetachedProcessController({
2715
+ provider: "daytona",
2716
+ ...options.homeDir === void 0 ? {} : { genericPayloadEnvironmentDefaults: { HOME: options.homeDir } },
2717
+ ...options.beforePrepareMutation === void 0 ? {} : { beforePrepareMutation: options.beforePrepareMutation },
2718
+ ...options.beforeStopOrDisposeMutation === void 0 ? {} : {
2719
+ beforeStopOrDisposeMutation: options.beforeStopOrDisposeMutation
2720
+ },
2721
+ execute: async (command, commandOptions) => {
2722
+ try {
2723
+ const result = await executeDaytonaCommand(sandbox, command, {
2724
+ timeoutMs: DETACHED_PROCESS_CONTROL_TIMEOUT_MS,
2725
+ ...commandOptions?.cwd === void 0 ? {} : { cwd: commandOptions.cwd },
2726
+ ...commandOptions?.envs === void 0 ? {} : { envs: commandOptions.envs }
2727
+ });
2728
+ return { state: "completed", result };
2729
+ } catch (error) {
2730
+ return { state: "failed", error };
2731
+ }
2732
+ },
2733
+ readLegacyLogs: options.readLegacyLogs,
2734
+ stopLegacy: options.stopLegacy,
2735
+ failure: options.failure
2736
+ });
2737
+ }
2738
+ function createDaytonaDetachedProcessController(sandbox, options) {
2739
+ const controller = createDaytonaProcessController(sandbox, options);
2740
+ return {
2741
+ start: (command, startOptions) => controller.start(command, startOptions),
2742
+ readLogs: (command) => controller.readLogs(command),
2743
+ stop: (command) => controller.stop(command),
2744
+ dispose: (command) => controller.dispose(command)
2745
+ };
268
2746
  }
269
2747
 
270
2748
  // src/providers/types.ts
@@ -320,7 +2798,7 @@ function validateProviderCommand(label, command, options) {
320
2798
  if (options.cwd !== void 0 && (typeof options.cwd !== "string" || !options.cwd.startsWith("/") || options.cwd.includes("\0")) || options.onStdout !== void 0 && typeof options.onStdout !== "function" || options.onStderr !== void 0 && typeof options.onStderr !== "function") {
321
2799
  throw new Error(`${label} command cwd must be absolute and output callbacks must be functions.`);
322
2800
  }
323
- if (options.envs !== void 0) validateProviderEnvs(label, options.envs, (message) => new Error(message));
2801
+ if (options.envs !== void 0) validateProviderEnvs(label, options.envs, (message2) => new Error(message2));
324
2802
  }
325
2803
 
326
2804
  // src/providers/daytona.ts
@@ -513,11 +2991,21 @@ function settleOperation(operation, options = {}) {
513
2991
  );
514
2992
  });
515
2993
  }
516
- function withTimeout(task, timeoutMs, message) {
2994
+ function untilAborted(operation, signal) {
2995
+ if (signal?.aborted) return Promise.reject(abortError(signal));
2996
+ return settleOperation(operation, signal ? { abort: { signal, createError: () => abortError(signal) } } : {});
2997
+ }
2998
+ function abortError(signal) {
2999
+ if (signal.reason instanceof Error) return signal.reason;
3000
+ const error = new Error("Operation aborted.");
3001
+ error.name = "AbortError";
3002
+ return error;
3003
+ }
3004
+ function withTimeout(task, timeoutMs, message2) {
517
3005
  return settleOperation(() => task, {
518
3006
  timeout: {
519
3007
  timeoutMs,
520
- createError: () => new Error(message)
3008
+ createError: () => new Error(message2)
521
3009
  }
522
3010
  });
523
3011
  }
@@ -555,7 +3043,7 @@ function stringProperty(value, property) {
555
3043
  const propertyValue = Reflect.get(value, property);
556
3044
  return typeof propertyValue === "string" ? propertyValue : void 0;
557
3045
  }
558
- function messageFrom(error) {
3046
+ function messageFrom2(error) {
559
3047
  return error instanceof Error ? error.message : String(error);
560
3048
  }
561
3049
  function writeContent(content) {
@@ -590,7 +3078,7 @@ async function runE2bCommand(sandbox, cmd, options) {
590
3078
  return {
591
3079
  exitCode: numberProperty(error, "exitCode") ?? 1,
592
3080
  stdout: stdout || stringProperty(error, "stdout") || "",
593
- stderr: stderr || stringProperty(error, "stderr") || messageFrom(error)
3081
+ stderr: stderr || stringProperty(error, "stderr") || messageFrom2(error)
594
3082
  };
595
3083
  }
596
3084
  }
@@ -684,7 +3172,7 @@ var E2bSandboxHandle = class {
684
3172
  );
685
3173
  } catch (error) {
686
3174
  throw this.failure(
687
- `Failed to stop legacy detached E2B process ${legacyPid}: ${messageFrom(error)}`
3175
+ `Failed to stop legacy detached E2B process ${legacyPid}: ${messageFrom2(error)}`
688
3176
  );
689
3177
  }
690
3178
  if (!signalled) return;
@@ -699,7 +3187,7 @@ var E2bSandboxHandle = class {
699
3187
  );
700
3188
  } catch (error) {
701
3189
  throw this.failure(
702
- `Failed to confirm legacy detached E2B process ${legacyPid} exit: ${messageFrom(error)}`
3190
+ `Failed to confirm legacy detached E2B process ${legacyPid} exit: ${messageFrom2(error)}`
703
3191
  );
704
3192
  }
705
3193
  if (!processes.some((process2) => process2.pid === legacyPid)) return;
@@ -723,7 +3211,7 @@ var E2bSandboxHandle = class {
723
3211
  };
724
3212
 
725
3213
  // src/providers/modal.ts
726
- import { createHash } from "crypto";
3214
+ import { createHash as createHash2 } from "crypto";
727
3215
 
728
3216
  // src/providers/modal-sdk.ts
729
3217
  import { createRequire } from "module";
@@ -736,7 +3224,7 @@ function getModalSdk() {
736
3224
  var MODAL_DEFAULT_TEMPLATE = "node:22-bookworm";
737
3225
  var MODAL_DEFAULT_TIMEOUT_MS = 60 * 60 * 1e3;
738
3226
  function parseModalAllowList(value) {
739
- return (value ?? "").split(",").map((entry) => entry.trim()).filter(Boolean);
3227
+ return (value ?? "").split(",").map((entry2) => entry2.trim()).filter(Boolean);
740
3228
  }
741
3229
  function modalNetworkOptions(options) {
742
3230
  if (options.networkBlockAll) return { blockNetwork: true };
@@ -767,7 +3255,7 @@ function validateModalOptions(options, mode, failure) {
767
3255
  throw failure("Modal networkBlockAll must be a boolean.");
768
3256
  }
769
3257
  for (const [key, value] of [["networkAllowList", networkAllowList], ["domainAllowList", domainAllowList]]) {
770
- if (value !== void 0 && (typeof value !== "string" || parseModalAllowList(value).some((entry) => /[\s\0]/u.test(entry)))) {
3258
+ if (value !== void 0 && (typeof value !== "string" || parseModalAllowList(value).some((entry2) => /[\s\0]/u.test(entry2)))) {
771
3259
  throw failure(`Modal ${key} must be a comma-separated string without whitespace or null bytes in entries.`);
772
3260
  }
773
3261
  }
@@ -794,7 +3282,7 @@ async function sharedClient(credentials) {
794
3282
  environment: credentials.environment,
795
3283
  logLevel: "error"
796
3284
  };
797
- const key = createHash("sha256").update(JSON.stringify([
3285
+ const key = createHash2("sha256").update(JSON.stringify([
798
3286
  configuration,
799
3287
  Object.entries(process.env).filter(([name]) => name.startsWith("MODAL_")).sort(([left], [right]) => left.localeCompare(right))
800
3288
  ])).digest("hex");
@@ -814,8 +3302,8 @@ async function sharedClient(credentials) {
814
3302
  return client;
815
3303
  }
816
3304
  var ModalSandboxHandle = class _ModalSandboxHandle {
817
- constructor(id, client, failure) {
818
- this.id = id;
3305
+ constructor(id2, client, failure) {
3306
+ this.id = id2;
819
3307
  this.client = client;
820
3308
  this.detachedProcesses = new DetachedProcessController({
821
3309
  provider: "modal",
@@ -855,7 +3343,7 @@ var ModalSandboxHandle = class _ModalSandboxHandle {
855
3343
  const network = modalNetworkOptions(options);
856
3344
  const template = options.template ?? MODAL_DEFAULT_TEMPLATE;
857
3345
  const registryImage = options.registrySecret === void 0 ? client.images.fromRegistry(template) : client.images.fromRegistry(template, await client.secrets.fromName(options.registrySecret));
858
- const image = options.command ? registryImage : registryImage.dockerfileCommands([
3346
+ const image2 = options.command ? registryImage : registryImage.dockerfileCommands([
859
3347
  "USER root",
860
3348
  "RUN apt-get update && apt-get install -y --no-install-recommends bash python3 util-linux coreutils sudo curl ca-certificates && rm -rf /var/lib/apt/lists/*",
861
3349
  // The runtime starts with a fixed PATH, so images with Node elsewhere (say nvm) need links.
@@ -864,7 +3352,7 @@ var ModalSandboxHandle = class _ModalSandboxHandle {
864
3352
  ...network.outboundDomainAllowlist ? ["RUN find /etc/apt -name '*.list' -o -name '*.sources' | xargs -r sed -i 's|http://|https://|g'"] : [],
865
3353
  "WORKDIR /root"
866
3354
  ]);
867
- sandbox = await client.sandboxes.create(app, image, {
3355
+ sandbox = await client.sandboxes.create(app, image2, {
868
3356
  ...network,
869
3357
  ...options.regions ? { regions: options.regions } : {},
870
3358
  timeoutMs: options.timeoutMs ?? MODAL_DEFAULT_TIMEOUT_MS,
@@ -872,7 +3360,7 @@ var ModalSandboxHandle = class _ModalSandboxHandle {
872
3360
  memoryMiB: options.memoryMiB,
873
3361
  ...options.command ? { command: options.command } : { workdir: "/root" },
874
3362
  env: Object.fromEntries(Object.entries(options.envs ?? {}).filter(
875
- (entry) => entry[1] !== void 0
3363
+ (entry2) => entry2[1] !== void 0
876
3364
  ))
877
3365
  // No tunnels: all HTTP access requires a port-scoped Connect Token.
878
3366
  });
@@ -890,16 +3378,22 @@ var ModalSandboxHandle = class _ModalSandboxHandle {
890
3378
  });
891
3379
  await new _ModalSandboxHandle(options.sandboxId, client, failure).destroy();
892
3380
  }
893
- static async connect(options, failure) {
3381
+ /** With `gone`, a sandbox Modal reports finished or unknown throws that failure instead. */
3382
+ static async connect(options, failure, gone) {
894
3383
  const client = await sharedClient({
895
3384
  tokenId: options.tokenId,
896
3385
  tokenSecret: options.tokenSecret,
897
3386
  environment: options.environment
898
3387
  });
899
3388
  const handle = new _ModalSandboxHandle(options.sandboxId, client, failure);
900
- await handle.use(async (sandbox) => {
901
- if (await sandbox.poll() !== null) throw failure("Modal sandbox is no longer running.");
902
- });
3389
+ try {
3390
+ await handle.use(async (sandbox) => {
3391
+ if (await sandbox.poll() !== null) throw (gone ?? failure)("Modal sandbox is no longer running.");
3392
+ });
3393
+ } catch (error) {
3394
+ if (gone && isModalNotFound(error)) throw gone(`Modal sandbox ${options.sandboxId} does not exist.`, error);
3395
+ throw error;
3396
+ }
903
3397
  return handle;
904
3398
  }
905
3399
  async use(operation, timeoutMs) {
@@ -997,38 +3491,416 @@ var ModalSandboxHandle = class _ModalSandboxHandle {
997
3491
  });
998
3492
  }
999
3493
  async destroy() {
1000
- const { NotFoundError } = getModalSdk();
1001
3494
  try {
1002
3495
  await this.use(async (sandbox) => {
1003
3496
  await sandbox.terminate({ wait: true });
1004
3497
  });
1005
3498
  } catch (error) {
1006
- const grpcNotFound = error instanceof Error && error.name === "ClientError" && Reflect.get(error, "code") === 5;
1007
- if (!(error instanceof NotFoundError) && !grpcNotFound) throw error;
3499
+ if (!isModalNotFound(error)) throw error;
1008
3500
  }
1009
3501
  }
1010
3502
  };
3503
+ function isModalNotFound(error) {
3504
+ return error instanceof getModalSdk().NotFoundError || error instanceof Error && error.name === "ClientError" && Reflect.get(error, "code") === 5;
3505
+ }
1011
3506
 
1012
3507
  // src/define.ts
1013
- import { mkdir } from "fs/promises";
1014
- import os from "os";
1015
3508
  import path from "path";
1016
3509
 
3510
+ // src/image-tag.ts
3511
+ var IMAGE_TAG_ENV_VARS = [
3512
+ "NECKBEARD_IMAGE_TAG",
3513
+ "GITHUB_SHA",
3514
+ "CI_COMMIT_SHA",
3515
+ "BITBUCKET_COMMIT",
3516
+ "CODEBUILD_RESOLVED_SOURCE_VERSION",
3517
+ "BUILDKITE_COMMIT",
3518
+ "CIRCLE_SHA1",
3519
+ "CF_PAGES_COMMIT_SHA",
3520
+ "HEROKU_BUILD_COMMIT",
3521
+ "HEROKU_SLUG_COMMIT",
3522
+ "RAILWAY_GIT_COMMIT_SHA",
3523
+ "RENDER_GIT_COMMIT",
3524
+ "VERCEL_GIT_COMMIT_SHA",
3525
+ "SOURCE_VERSION",
3526
+ "GIT_COMMIT"
3527
+ ];
3528
+ function resolveImageTag(env = process.env) {
3529
+ for (const name of IMAGE_TAG_ENV_VARS) {
3530
+ const value = env[name]?.trim();
3531
+ if (value && value !== name) return value;
3532
+ }
3533
+ return void 0;
3534
+ }
3535
+
3536
+ // src/turn-protocol.ts
3537
+ var TURN_PROTOCOL_VERSION = 6;
3538
+ var STARTUP_ENV_KEYS = "NECKBEARD_STARTUP_ENV_KEYS";
3539
+ var MAX_TURN_REQUEST_BYTES = 4 * 1024 * 1024;
3540
+ function isRecord2(value) {
3541
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3542
+ }
3543
+ function parseTurnHealth(value) {
3544
+ if (!isRecord2(value)) throw new Error("Health response must be an object.");
3545
+ const { ok, protocolVersion, busy, turnId } = value;
3546
+ if (ok !== true || typeof protocolVersion !== "number" || typeof busy !== "boolean" || turnId !== null && typeof turnId !== "string") {
3547
+ throw new Error("Health response is not { ok: true, protocolVersion, busy, turnId }.");
3548
+ }
3549
+ return { ok, protocolVersion, busy, turnId };
3550
+ }
3551
+
3552
+ // src/conversation-records.ts
3553
+ var string = (v) => typeof v === "string";
3554
+ var number = (v) => typeof v === "number" && Number.isFinite(v);
3555
+ var bool = (v) => typeof v === "boolean";
3556
+ var id = (v) => typeof v === "number" && Number.isSafeInteger(v) && v > 0;
3557
+ var absent = (v) => v === void 0;
3558
+ var optional = (check) => (v) => v === void 0 || check(v);
3559
+ var array = (check) => (v) => Array.isArray(v) && v.every(check);
3560
+ var values = (check) => (v) => isRecord2(v) && Object.values(v).every(check);
3561
+ var oneOf = (...options) => (v) => typeof v === "string" && options.includes(v);
3562
+ var shape = (fields) => (v) => isRecord2(v) && Object.entries(fields).every(([key, check]) => check(v[key]));
3563
+ var input = shape({
3564
+ id,
3565
+ conversationId: id,
3566
+ requestId: optional(string),
3567
+ trace: optional(values(string)),
3568
+ notify: optional(shape({ taskId: id, key: string }))
3569
+ });
3570
+ function isInputRecord(v) {
3571
+ if (!isRecord2(v) || v.type !== "input" || !input(v)) return false;
3572
+ if (v.status === "unanswered") return optional(id)(v.entry) && absent(v.answer) && string(v.reason);
3573
+ if (v.reason !== void 0 || v.detail !== void 0) return false;
3574
+ switch (v.status) {
3575
+ case "queued":
3576
+ return absent(v.entry) && absent(v.answer);
3577
+ case "placed":
3578
+ return id(v.entry) && absent(v.answer);
3579
+ case "done":
3580
+ return id(v.entry) && id(v.answer);
3581
+ default:
3582
+ return false;
3583
+ }
3584
+ }
3585
+ var text = shape({ type: oneOf("text"), text: string, textSignature: optional(string) });
3586
+ var image = shape({ type: oneOf("image"), data: string, mimeType: string });
3587
+ var thinking = shape({ type: oneOf("thinking"), thinking: string, thinkingSignature: optional(string), redacted: optional(bool) });
3588
+ var toolCall = shape({
3589
+ type: oneOf("toolCall"),
3590
+ id: string,
3591
+ name: string,
3592
+ arguments: isRecord2,
3593
+ thoughtSignature: optional(string),
3594
+ namespace: optional(string),
3595
+ argumentsError: optional(string)
3596
+ });
3597
+ var tokens = { input: number, output: number, cacheRead: number, cacheWrite: number };
3598
+ var usage = shape({
3599
+ ...tokens,
3600
+ totalTokens: number,
3601
+ cacheWrite1h: optional(number),
3602
+ reasoning: optional(number),
3603
+ cost: shape({ ...tokens, total: number, totalFromProvider: optional(bool) })
3604
+ });
3605
+ var diagnostic = shape({
3606
+ type: string,
3607
+ timestamp: number,
3608
+ details: optional(isRecord2),
3609
+ error: optional(shape({ name: optional(string), message: string, stack: optional(string), code: optional((v) => string(v) || number(v)) }))
3610
+ });
3611
+ var assistant = shape({
3612
+ api: string,
3613
+ provider: string,
3614
+ model: string,
3615
+ content: array((v) => text(v) || thinking(v) || toolCall(v)),
3616
+ usage,
3617
+ stopReason: oneOf("pending", "stop", "length", "toolUse", "error", "aborted", "deferred"),
3618
+ responseModel: optional(string),
3619
+ responseId: optional(string),
3620
+ providerThinkingLevel: optional(string),
3621
+ thinkingLevel: optional(oneOf("off", "minimal", "low", "medium", "high", "xhigh", "max")),
3622
+ diagnostics: optional(array(diagnostic)),
3623
+ errorMessage: optional(string),
3624
+ rawStopReason: optional(string),
3625
+ endTurn: optional(bool),
3626
+ durationMs: optional(number),
3627
+ deferred: optional(shape({ provider: string, modelId: string, api: string, id: string, expiresAt: optional(number), pollAfterMs: optional(number) }))
3628
+ });
3629
+ var constrainedSampling = (v) => v === false || isRecord2(v) && (v.type === "json_schema" && oneOf("prefer", "require")(v.strict) || v.type === "grammar" && isRecord2(v.variants) && optional(string)(v.variants.openai_lark) && optional(string)(v.variants.openai_regex));
3630
+ var system = shape({
3631
+ content: (v) => string(v) || array(text)(v),
3632
+ sections: optional(values((v) => v === null || string(v))),
3633
+ toolsAdded: optional(array(shape({ name: string, description: string, parameters: (v) => typeof v === "object" && v !== null, constrainedSampling: optional(constrainedSampling) }))),
3634
+ toolsRemoved: optional(array(shape({ name: string })))
3635
+ });
3636
+ var media = array((v) => text(v) || image(v));
3637
+ var toolResult = shape({
3638
+ toolCallId: string,
3639
+ toolName: string,
3640
+ content: media,
3641
+ isError: bool,
3642
+ usage: optional(usage),
3643
+ durationMs: optional(number),
3644
+ nestedCalls: optional(shape({ complete: bool, calls: array(shape({
3645
+ id: string,
3646
+ name: string,
3647
+ arguments: optional(isRecord2),
3648
+ argumentsBytes: optional(number),
3649
+ status: oneOf("ok", "error", "unfinished"),
3650
+ durationMs: optional(number),
3651
+ error: optional(string)
3652
+ })) }))
3653
+ });
3654
+ function message(v) {
3655
+ if (!isRecord2(v) || !number(v.timestamp)) return false;
3656
+ switch (v.role) {
3657
+ case "user":
3658
+ return string(v.content) || media(v.content);
3659
+ case "system":
3660
+ return system(v);
3661
+ case "assistant":
3662
+ return assistant(v);
3663
+ case "toolResult":
3664
+ return toolResult(v);
3665
+ default:
3666
+ return false;
3667
+ }
3668
+ }
3669
+ var messages = array(message);
3670
+ var edit = (v) => isRecord2(v) && id(v.target) && (v.action === "omit" && absent(v.messages) || v.action === "replace" && messages(v.messages));
3671
+ var entry = shape({ id, conversationId: id, kind: string, head: optional(id), byTaskId: optional(id), model: optional(messages), edits: optional(array(edit)) });
3672
+ function isEntryRecord(v) {
3673
+ return entry(v);
3674
+ }
3675
+
3676
+ // src/remote-conversation.ts
3677
+ async function* chunks(reader) {
3678
+ const decoder = new TextDecoder();
3679
+ for (; ; ) {
3680
+ const part = await reader.read();
3681
+ if (part.done) break;
3682
+ yield decoder.decode(part.value, { stream: true });
3683
+ }
3684
+ yield decoder.decode();
3685
+ }
3686
+ var RemoteAdmissionRejected = class extends Error {
3687
+ };
3688
+ var RemoteSubmissionNotFound = class extends Error {
3689
+ };
3690
+ function remoteConversation(request) {
3691
+ async function send(path2, data, signal, stream = false) {
3692
+ const response = await request("/conversation/" + path2, data, signal, stream);
3693
+ if (!response.ok) {
3694
+ const body = await response.json();
3695
+ const message2 = isRecord2(body) && typeof body.error === "string" ? body.error : "Remote conversation request failed.";
3696
+ if (path2 === "submit" && isRecord2(body) && body.code === "request_rejected" && [400, 409].includes(response.status)) {
3697
+ const error = new RemoteAdmissionRejected(message2);
3698
+ if (typeof body.name === "string") error.name = body.name;
3699
+ throw error;
3700
+ }
3701
+ if (response.status === 404 && isRecord2(body) && body.code === "submission_missing")
3702
+ throw new RemoteSubmissionNotFound(message2);
3703
+ const err = new Error(message2);
3704
+ throw err;
3705
+ }
3706
+ return response;
3707
+ }
3708
+ async function rpc(path2, data, ctx) {
3709
+ for (; ; ) {
3710
+ const response = await send(path2, data, ctx.abortSignal);
3711
+ const result = await response.json();
3712
+ if (response.status !== 202) return result;
3713
+ if (path2 !== "wait" && path2 !== "idle" || !isRecord2(result) || result.pending !== true)
3714
+ throw new Error("Invalid pending response.");
3715
+ }
3716
+ }
3717
+ function handle(value) {
3718
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1)
3719
+ throw new Error("Invalid remote submission ID.");
3720
+ const id2 = value;
3721
+ async function record(op, ctx) {
3722
+ const data = await rpc(op, { id: id2 }, ctx);
3723
+ if (!isInputRecord(data) || data.id !== id2) throw new Error("Invalid remote input record.");
3724
+ return data;
3725
+ }
3726
+ return {
3727
+ id: id2,
3728
+ status: (ctx) => record("status", ctx),
3729
+ async wait(ctx) {
3730
+ const r = await record("wait", ctx);
3731
+ if (r.status !== "done" && r.status !== "unanswered") throw new Error("Expected settled input.");
3732
+ return r;
3733
+ },
3734
+ async abort(ctx) {
3735
+ const result = await rpc("withdraw", { id: id2 }, ctx);
3736
+ if (result !== "already_placed" && result !== "aborted" && result !== "settled")
3737
+ throw new Error("Invalid withdrawal response.");
3738
+ return result;
3739
+ }
3740
+ };
3741
+ }
3742
+ return {
3743
+ submit: async (draft, ctx) => handle(await rpc("submit", { draft }, ctx)),
3744
+ async submissionByRequest(requestId, ctx) {
3745
+ const id2 = await rpc("lookup", { requestId }, ctx);
3746
+ return id2 === null ? void 0 : handle(id2);
3747
+ },
3748
+ async entry(id2, ctx) {
3749
+ const data = await rpc("entry", { id: id2 }, ctx);
3750
+ if (data === null) return void 0;
3751
+ if (!isEntryRecord(data) || data.id !== id2) throw new Error("Invalid remote entry.");
3752
+ return data;
3753
+ },
3754
+ async stopSubmission(id2, ctx) {
3755
+ await rpc("stop", { id: id2 }, ctx);
3756
+ },
3757
+ async abort(ctx, options) {
3758
+ await rpc("abort", options ?? {}, ctx);
3759
+ },
3760
+ async waitForIdle(ctx) {
3761
+ await rpc("idle", {}, ctx);
3762
+ },
3763
+ async watch(ctx, window) {
3764
+ const contextEntry = "@earendil-works/chord/context";
3765
+ const { withoutAbortSignal } = await import(
3766
+ /* webpackIgnore: true */
3767
+ contextEntry
3768
+ );
3769
+ const callbackContext = withoutAbortSignal(ctx);
3770
+ const controller = new AbortController();
3771
+ const signal = ctx.abortSignal ? AbortSignal.any([ctx.abortSignal, controller.signal]) : controller.signal;
3772
+ const res = await send("watch", { window }, signal, true);
3773
+ if (!res.body) throw new Error("Missing watch stream.");
3774
+ const reader = res.body.getReader();
3775
+ void reader.closed.catch((error) => controller.abort(error));
3776
+ const frames = decodeSseStream(chunks(reader), { requireTerminator: true });
3777
+ const opened = await (async () => {
3778
+ const first = await frames.next();
3779
+ if (first.done || first.value.seq !== 0 || !first.value.frame?.opened || !first.value.frame.value) {
3780
+ throw new Error("Missing initial watch value.");
3781
+ }
3782
+ return { id: first.value.frame.opened, value: first.value.frame.value };
3783
+ })().catch((error) => {
3784
+ controller.abort();
3785
+ throw error;
3786
+ });
3787
+ const id2 = opened.id;
3788
+ let value = opened.value;
3789
+ let listener;
3790
+ let start;
3791
+ const started = new Promise((resolve2) => {
3792
+ start = resolve2;
3793
+ });
3794
+ let stopping = false;
3795
+ let ended = false;
3796
+ function interruption() {
3797
+ return ctx.abortSignal?.aborted ? { kind: "aborted" } : { kind: "failed", error: signal.reason };
3798
+ }
3799
+ let onAbort;
3800
+ const interrupted = new Promise((resolve2) => {
3801
+ onAbort = () => {
3802
+ start();
3803
+ resolve2(interruption());
3804
+ };
3805
+ if (signal.aborted) onAbort();
3806
+ else signal.addEventListener("abort", onAbort, { once: true });
3807
+ });
3808
+ let callbacks = Promise.resolve();
3809
+ let pending = 0;
3810
+ let failListener;
3811
+ const listenerFailed = new Promise((resolve2) => {
3812
+ failListener = resolve2;
3813
+ });
3814
+ const delivery = (async () => {
3815
+ try {
3816
+ let seq = 1;
3817
+ for await (const { seq: next, frame, exception } of frames) {
3818
+ if (next !== seq++) throw new Error("Watch delivery interrupted.");
3819
+ if (exception) {
3820
+ if (typeof exception.name !== "string" || typeof exception.message !== "string")
3821
+ throw new Error("Invalid watch exception.");
3822
+ const error = Object.assign(new Error(exception.message), { name: exception.name });
3823
+ if (frame.end?.kind === "failed" || frame.end?.kind === "listener_error")
3824
+ frame.end = { ...frame.end, error };
3825
+ else if (frame.call?.kind === "failed") frame.call = { ...frame.call, error };
3826
+ else throw new Error("Unexpected watch exception.");
3827
+ }
3828
+ if (frame.end) {
3829
+ if (!["stopped", "ended", "aborted", "failed", "listener_error"].includes(frame.end.kind))
3830
+ throw new Error("Invalid watch end.");
3831
+ if (frame.end.kind === "stopped" && !stopping)
3832
+ throw new Error("Watch stopped without a local stop request.");
3833
+ if (frame.end.kind === "stopped" || frame.end.kind === "ended") await callbacks;
3834
+ return frame.end;
3835
+ }
3836
+ const call = frame.call;
3837
+ if (!call || call.kind !== "failed" && (call.kind !== "value" || !Array.isArray(call.ops)))
3838
+ throw new Error("Invalid remote watch call.");
3839
+ if (++pending > 256) throw new Error("Watch listener fell behind by more than 256 callbacks.");
3840
+ callbacks = callbacks.then(async () => {
3841
+ if (!listener) await started;
3842
+ pending--;
3843
+ if (signal.aborted || ended || !listener) return;
3844
+ if (call.kind === "value") value = call.value;
3845
+ try {
3846
+ await listener(call, callbackContext);
3847
+ } catch (error) {
3848
+ failListener({ kind: "listener_error", error: error instanceof Error ? error : new Error(String(error)) });
3849
+ }
3850
+ });
3851
+ }
3852
+ throw new Error("Watch disconnected before its terminal frame.");
3853
+ } catch (error) {
3854
+ return ctx.abortSignal?.aborted ? { kind: "aborted" } : { kind: "failed", error };
3855
+ }
3856
+ })();
3857
+ const closed = Promise.race([delivery, interrupted, listenerFailed]).finally(() => {
3858
+ ended = true;
3859
+ start();
3860
+ signal.removeEventListener("abort", onAbort);
3861
+ controller.abort();
3862
+ reader.releaseLock();
3863
+ });
3864
+ return {
3865
+ get value() {
3866
+ return value;
3867
+ },
3868
+ closed,
3869
+ start(next) {
3870
+ if (listener || stopping || ended) throw new Error("Watch already started or closed.");
3871
+ listener = next;
3872
+ start();
3873
+ },
3874
+ async stop() {
3875
+ if (!stopping && !ended) {
3876
+ stopping = true;
3877
+ start();
3878
+ try {
3879
+ await send("stop-watch", { id: id2 }, signal);
3880
+ } catch (error) {
3881
+ controller.abort(error);
3882
+ }
3883
+ }
3884
+ return closed;
3885
+ }
3886
+ };
3887
+ }
3888
+ };
3889
+ }
3890
+
1017
3891
  // src/agent.ts
1018
- import { createHash as createHash2 } from "crypto";
3892
+ import { createHash as createHash3 } from "crypto";
1019
3893
  var DEFAULT_COMMAND = ["node", "/app/agent.mjs"];
1020
3894
  var DEFAULT_PORT = 8080;
1021
3895
  var DEFAULT_START_TIMEOUT_MS = 12e4;
1022
3896
  var DEFAULT_PREPARE_TIMEOUT_MS = 30 * 6e4;
1023
- var DEFAULT_RECONNECT_TIMEOUT_MS = 12e4;
1024
3897
  var HEALTH_POLL_INTERVAL_MS = 500;
1025
- var RECONNECT_MIN_DELAY_MS = 250;
1026
- var RECONNECT_MAX_DELAY_MS = 5e3;
1027
3898
  var REQUEST_TIMEOUT_MS = 3e4;
1028
3899
  var ARTIFACT_PREFIX = "nb-";
1029
- function filterDefined(envs) {
1030
- return Object.fromEntries(Object.entries(envs ?? {}).filter(
1031
- (entry) => entry[1] !== void 0
3900
+ var RUNTIME_REJECTION_CODES = ["request_rejected", "submission_missing"];
3901
+ function filterDefined(env) {
3902
+ return Object.fromEntries(Object.entries(env ?? {}).filter(
3903
+ (entry2) => entry2[1] !== void 0
1032
3904
  ));
1033
3905
  }
1034
3906
  function delay2(ms, signal) {
@@ -1049,31 +3921,6 @@ function untilDeadline(deadline, signal) {
1049
3921
  const timeout = AbortSignal.timeout(Math.max(0, deadline - Date.now()));
1050
3922
  return signal ? AbortSignal.any([signal, timeout]) : timeout;
1051
3923
  }
1052
- function untilAborted(operation, signal) {
1053
- if (signal?.aborted) return Promise.reject(abortError(signal));
1054
- return settleOperation(operation, signal ? { abort: { signal, createError: () => abortError(signal) } } : {});
1055
- }
1056
- function abortError(signal) {
1057
- if (signal.reason instanceof Error) return signal.reason;
1058
- const error = new Error("Operation aborted.");
1059
- error.name = "AbortError";
1060
- return error;
1061
- }
1062
- async function* textChunks(body, onChunk) {
1063
- const decoder = new TextDecoder();
1064
- const reader = body.getReader();
1065
- try {
1066
- while (true) {
1067
- const { done, value } = await reader.read();
1068
- if (done) break;
1069
- onChunk();
1070
- yield decoder.decode(value, { stream: true });
1071
- }
1072
- } finally {
1073
- await reader.cancel().catch(() => void 0);
1074
- reader.releaseLock();
1075
- }
1076
- }
1077
3924
  var EndpointRejectedError = class extends Error {
1078
3925
  };
1079
3926
  var Agent = class {
@@ -1119,8 +3966,8 @@ var Agent = class {
1119
3966
  get artifactName() {
1120
3967
  const { sandbox } = this.options;
1121
3968
  const resources = sandbox.provider === "daytona" ? sandbox.resources : sandbox.provider === "e2b" ? { cpuCount: sandbox.cpuCount, memoryMB: sandbox.memoryMB } : void 0;
1122
- const hash = createHash2("sha256").update(JSON.stringify([this.image, sandbox.provider === "daytona" ? this.command : [], resources ?? null])).digest("hex").slice(0, 16);
1123
- return `${ARTIFACT_PREFIX}${this.name}-${hash}`;
3969
+ const hash2 = createHash3("sha256").update(JSON.stringify([this.image, sandbox.provider === "daytona" ? this.command : [], resources ?? null])).digest("hex").slice(0, 16);
3970
+ return `${ARTIFACT_PREFIX}${this.name}-${hash2}`;
1124
3971
  }
1125
3972
  /**
1126
3973
  * Creates the Daytona snapshot or E2B template for the image if it is missing and waits until
@@ -1150,27 +3997,45 @@ var Agent = class {
1150
3997
  const preparing = this.preparing;
1151
3998
  return untilAborted(() => preparing, options.signal);
1152
3999
  }
1153
- /** Starts a sandbox from the image and waits for its runtime. Returns the sandbox ID. */
4000
+ /** Launches a sandbox. To reconnect to one, call `attach()`. */
1154
4001
  async start(options = {}) {
4002
+ if ("sandboxId" in options) throw new ConfigurationError("start() always launches a sandbox. Call attach(sandboxId) to reconnect to one.");
1155
4003
  await this.prepare({ ...options.signal ? { signal: options.signal } : {} });
1156
- const envs = {
1157
- ...filterDefined(this.options.envs),
1158
- ...filterDefined(options.envs),
4004
+ const startup = {
4005
+ ...filterDefined(this.options.env),
4006
+ ...filterDefined(options.env)
4007
+ };
4008
+ const env = {
4009
+ ...startup,
4010
+ [STARTUP_ENV_KEYS]: JSON.stringify(Object.keys(startup)),
1159
4011
  ...options.sessionId === void 0 ? {} : { NECKBEARD_SESSION_ID: options.sessionId },
1160
4012
  NECKBEARD_PORT: String(this.port)
1161
4013
  };
1162
4014
  if (options.signal?.aborted) throw abortError(options.signal);
1163
4015
  let sandbox;
4016
+ const creating = this.createSandbox(env);
1164
4017
  try {
1165
- sandbox = await this.createSandbox(envs);
4018
+ sandbox = await untilAborted(() => creating, options.signal);
1166
4019
  } catch (error) {
4020
+ if (options.signal?.aborted) {
4021
+ creating.then(
4022
+ (late) => late.destroy().catch((cleanupError) => {
4023
+ console.warn(`neckbeard: sandbox ${late.id} was created after its start was cancelled, and deleting it failed (${String(cleanupError)}); kill() it.`);
4024
+ }),
4025
+ () => void 0
4026
+ );
4027
+ throw error;
4028
+ }
1167
4029
  this.preparing = void 0;
1168
4030
  throw error;
1169
4031
  }
1170
4032
  try {
1171
- if (this.options.sandbox.provider === "e2b") await this.startE2bRuntime(this.options.sandbox, sandbox.id, envs);
4033
+ if (this.options.sandbox.provider === "e2b") {
4034
+ const e2b = this.options.sandbox;
4035
+ await untilAborted(() => this.startE2bRuntime(e2b, sandbox.id, env), options.signal);
4036
+ }
1172
4037
  await this.waitForRuntime(sandbox.id, options.signal);
1173
- return sandbox.id;
4038
+ return this.handle(sandbox.id);
1174
4039
  } catch (error) {
1175
4040
  this.endpoints.delete(sandbox.id);
1176
4041
  try {
@@ -1188,130 +4053,18 @@ var Agent = class {
1188
4053
  }
1189
4054
  }
1190
4055
  /**
1191
- * Starts a turn and streams its records until its `end` record. Starting a turn whose
1192
- * `turnId` the runtime already has resumes it instead of running it again.
1193
- */
1194
- async *prompt(sandboxId, turn, options = {}) {
1195
- const response = await this.request(sandboxId, "POST", "/turns", turn, options.signal);
1196
- if (response.status === 409) {
1197
- const body = await response.json().catch(() => ({}));
1198
- throw new RuntimeBusyError(`Sandbox ${sandboxId} is running another turn (${body.turnId ?? "unknown"}).`);
1199
- }
1200
- if (response.status !== 200 && response.status !== 202) {
1201
- throw new ExecutionError(`Starting turn ${turn.turnId} failed with ${response.status}: ${await response.text()}`);
1202
- }
1203
- await response.body?.cancel();
1204
- yield* this.events(sandboxId, turn.turnId, options);
1205
- }
1206
- /**
1207
- * Runs a Pi turn to its end and returns its final assistant text, or null when it had none.
1208
- * Throws `ExecutionError` when the turn did not complete or its model did not stop on its own.
1209
- * Running a turn again with the same `turnId` replays its records from the start.
1210
- */
1211
- async run(sandboxId, turn, options = {}) {
1212
- const { onRecord, ...streamOptions } = options;
1213
- const records = [];
1214
- for await (const record of this.prompt(sandboxId, turn, streamOptions)) {
1215
- records.push(record);
1216
- await onRecord?.(record);
1217
- }
1218
- options.signal?.throwIfAborted();
1219
- const result = getPiTurnResult(records);
1220
- if (!result.completed) throw new ExecutionError(`Turn ${turn.turnId} did not finish: ${result.error}`);
1221
- return result.text;
1222
- }
1223
- /**
1224
- * Streams a turn's records after `options.after` until its `end` record, reconnecting when
1225
- * the connection drops. Throws `TurnLostError` when the runtime no longer has the turn.
4056
+ * Reconnects to a running sandbox by its provider ID, including while it is busy. Never creates,
4057
+ * starts or kills a sandbox, and admits no input.
1226
4058
  */
1227
- async *events(sandboxId, turnId, options = {}) {
1228
- let last = options.after ?? -1;
1229
- const reconnectTimeoutMs = options.reconnectTimeoutMs ?? DEFAULT_RECONNECT_TIMEOUT_MS;
1230
- let failingSince;
1231
- let attempt = 0;
1232
- while (true) {
1233
- let lastError;
1234
- const stalled = new AbortController();
1235
- let watchdog;
1236
- const armWatchdog = () => {
1237
- clearTimeout(watchdog);
1238
- const budget = failingSince === void 0 ? reconnectTimeoutMs : Math.max(0, failingSince + reconnectTimeoutMs - Date.now());
1239
- watchdog = setTimeout(() => stalled.abort(new Error(`Turn stream sent nothing for ${budget}ms.`)), budget);
1240
- };
1241
- armWatchdog();
1242
- try {
1243
- const response = await this.request(
1244
- sandboxId,
1245
- "GET",
1246
- `/turns/${encodeURIComponent(turnId)}/events?after=${last}`,
1247
- void 0,
1248
- options.signal ? AbortSignal.any([options.signal, stalled.signal]) : stalled.signal,
1249
- { stream: true }
1250
- );
1251
- if (response.status === 404) {
1252
- await response.body?.cancel();
1253
- throw new TurnLostError(`Sandbox ${sandboxId} has no turn ${turnId}.`);
1254
- }
1255
- if (!response.ok || !response.body) {
1256
- await response.body?.cancel();
1257
- throw new Error(`Turn stream returned ${response.status}.`);
1258
- }
1259
- try {
1260
- const onChunk = () => {
1261
- failingSince = void 0;
1262
- armWatchdog();
1263
- };
1264
- for await (const frame of decodeSseStream(textChunks(response.body, onChunk))) {
1265
- let record;
1266
- try {
1267
- record = parseTurnRecord(frame);
1268
- } catch (error) {
1269
- const message = error instanceof Error ? error.message : String(error);
1270
- throw new ExecutionError(`Sandbox ${sandboxId} sent an invalid record for turn ${turnId}: ${message}`);
1271
- }
1272
- if (record.seq <= last) {
1273
- if (record.type === "end") return;
1274
- continue;
1275
- }
1276
- last = record.seq;
1277
- failingSince = void 0;
1278
- attempt = 0;
1279
- clearTimeout(watchdog);
1280
- yield record;
1281
- armWatchdog();
1282
- if (record.type === "end") return;
1283
- }
1284
- } catch (error) {
1285
- if (error instanceof Error && error.message.startsWith("Malformed SSE data frame")) {
1286
- throw new ExecutionError(`Sandbox ${sandboxId} sent a malformed frame for turn ${turnId}: ${error.message}`);
1287
- }
1288
- if (!(error instanceof IncompleteSseFrameError)) throw error;
1289
- }
1290
- lastError = new Error("Turn stream ended before the turn did.");
1291
- } catch (error) {
1292
- if (error instanceof TurnLostError || error instanceof ExecutionError) throw error;
1293
- if (options.signal?.aborted) throw abortError(options.signal);
1294
- if (error instanceof EndpointRejectedError) this.endpoints.delete(sandboxId);
1295
- lastError = stalled.signal.aborted ? stalled.signal.reason : error;
1296
- } finally {
1297
- clearTimeout(watchdog);
1298
- }
1299
- failingSince ??= Date.now();
1300
- if (Date.now() - failingSince > reconnectTimeoutMs) {
1301
- const message = lastError instanceof Error ? lastError.message : String(lastError);
1302
- throw new ExecutionError(`Lost the stream of turn ${turnId} for over ${reconnectTimeoutMs}ms: ${message}`);
1303
- }
1304
- attempt += 1;
1305
- await delay2(Math.min(RECONNECT_MAX_DELAY_MS, RECONNECT_MIN_DELAY_MS * 2 ** (attempt - 1)), options.signal);
1306
- }
4059
+ async attach(sandboxId, options = {}) {
4060
+ if (typeof sandboxId !== "string" || !sandboxId.trim()) throw new ConfigurationError("attach() requires a nonempty sandboxId.");
4061
+ this.endpoints.delete(sandboxId);
4062
+ this.requireProtocol(await this.health(sandboxId, options.signal));
4063
+ return this.handle(sandboxId);
1307
4064
  }
1308
- /** Asks the runtime to stop the turn; its stream then ends with an `aborted` record. */
1309
- async abort(sandboxId, turnId, signal) {
1310
- const response = await this.request(sandboxId, "POST", `/turns/${encodeURIComponent(turnId)}/abort`, void 0, signal);
1311
- await response.body?.cancel();
1312
- if (response.status !== 202 && response.status !== 404) {
1313
- throw new ExecutionError(`Aborting turn ${turnId} failed with ${response.status}.`);
1314
- }
4065
+ handle(sandboxId) {
4066
+ const conversation = remoteConversation((path2, data, signal, stream) => this.request(sandboxId, "POST", path2, data, signal, { stream }));
4067
+ return { sandboxId, conversation };
1315
4068
  }
1316
4069
  async health(sandboxId, signal) {
1317
4070
  const response = await this.request(sandboxId, "GET", "/health", void 0, signal);
@@ -1325,7 +4078,7 @@ var Agent = class {
1325
4078
  try {
1326
4079
  if (!(await this.health(sandboxId, untilDeadline(deadline, options.signal))).busy) return;
1327
4080
  } catch (error) {
1328
- if (options.signal?.aborted) throw error;
4081
+ if (options.signal?.aborted || error instanceof SandboxGoneError) throw error;
1329
4082
  }
1330
4083
  if (Date.now() > deadline) throw new RuntimeBusyError(`Sandbox ${sandboxId} did not become idle.`);
1331
4084
  await delay2(HEALTH_POLL_INTERVAL_MS, options.signal);
@@ -1348,15 +4101,18 @@ var Agent = class {
1348
4101
  }
1349
4102
  await destroyProviderSandbox({ provider: sandbox.provider, sandboxId, ...sandbox.apiKey ? { apiKey: sandbox.apiKey } : {} });
1350
4103
  }
1351
- /** File and command access to a sandbox, for staging inputs and reading results. */
4104
+ /** File and command access to a sandbox, for staging inputs and reading results. Starts a stopped Daytona sandbox and resumes a paused E2B one. */
1352
4105
  sandbox(sandboxId) {
4106
+ return this.connect(sandboxId, true);
4107
+ }
4108
+ connect(sandboxId, wake) {
1353
4109
  const { sandbox } = this.options;
1354
4110
  if (sandbox.provider === "modal") {
1355
4111
  return SandboxClient.connect({
1356
4112
  provider: "modal",
1357
4113
  sandboxId,
1358
4114
  ...sandbox.environment ? { environment: sandbox.environment } : {}
1359
- });
4115
+ }, { wake });
1360
4116
  }
1361
4117
  if (sandbox.provider === "e2b") {
1362
4118
  return SandboxClient.connect({
@@ -1364,9 +4120,9 @@ var Agent = class {
1364
4120
  sandboxId,
1365
4121
  ...sandbox.apiKey ? { apiKey: sandbox.apiKey } : {},
1366
4122
  ...sandbox.timeoutMs === void 0 ? {} : { timeoutMs: sandbox.timeoutMs }
1367
- });
4123
+ }, { wake });
1368
4124
  }
1369
- return SandboxClient.connect({ provider: "daytona", sandboxId, ...sandbox.apiKey ? { apiKey: sandbox.apiKey } : {} });
4125
+ return SandboxClient.connect({ provider: "daytona", sandboxId, ...sandbox.apiKey ? { apiKey: sandbox.apiKey } : {} }, { wake });
1370
4126
  }
1371
4127
  /**
1372
4128
  * Deletes this agent's Daytona snapshots or E2B templates except the newest `keep` and the
@@ -1384,30 +4140,35 @@ var Agent = class {
1384
4140
  for (const artifact of stale) await artifact.delete();
1385
4141
  return stale.map((artifact) => artifact.name);
1386
4142
  }
1387
- createSandbox(envs) {
4143
+ createSandbox(env) {
1388
4144
  const { sandbox } = this.options;
1389
4145
  if (sandbox.provider === "modal") {
1390
4146
  const { provider: _provider, ...modal } = sandbox;
1391
- return SandboxClient.create({ provider: "modal", ...modal, template: this.image, command: this.command, envs });
4147
+ return SandboxClient.create({ provider: "modal", ...modal, template: this.image, command: this.command, envs: env });
1392
4148
  }
1393
4149
  if (sandbox.provider === "daytona") {
1394
4150
  const { resources: _resources, ...daytona } = sandbox;
1395
- return SandboxClient.create({ ...daytona, template: this.artifactName, envs });
4151
+ return SandboxClient.create({ ...daytona, template: this.artifactName, envs: env });
1396
4152
  }
1397
4153
  const { cpuCount: _cpuCount, memoryMB: _memoryMB, registry: _registry, ...e2b } = sandbox;
1398
- return SandboxClient.create({ ...e2b, template: this.artifactName, envs, allowPublicTraffic: false });
4154
+ return SandboxClient.create({ ...e2b, template: this.artifactName, envs: env, allowPublicTraffic: false });
1399
4155
  }
1400
4156
  // An E2B template's start command runs once at build time, without each sandbox's environment.
1401
- async startE2bRuntime(sandbox, sandboxId, envs) {
4157
+ async startE2bRuntime(sandbox, sandboxId, env) {
1402
4158
  const { Sandbox } = await import("e2b");
1403
4159
  const apiKey = sandbox.apiKey ?? process.env.E2B_API_KEY;
1404
4160
  const e2bSandbox = await Sandbox.connect(sandboxId, {
1405
4161
  ...apiKey ? { apiKey } : {},
1406
4162
  ...sandbox.timeoutMs === void 0 ? {} : { timeoutMs: sandbox.timeoutMs }
1407
4163
  });
1408
- const command = await e2bSandbox.commands.run(this.command.map(shellQuote).join(" "), { background: true, envs, timeoutMs: 0 });
4164
+ const command = await e2bSandbox.commands.run(this.command.map(shellQuote).join(" "), { background: true, envs: env, timeoutMs: 0 });
1409
4165
  await command.disconnect();
1410
4166
  }
4167
+ requireProtocol(health) {
4168
+ if (health.protocolVersion !== TURN_PROTOCOL_VERSION) {
4169
+ throw new DeploymentError(`Sandbox runtime speaks protocol ${health.protocolVersion}; this host speaks ${TURN_PROTOCOL_VERSION}.`);
4170
+ }
4171
+ }
1411
4172
  async waitForRuntime(sandboxId, signal) {
1412
4173
  const timeoutMs = this.options.startTimeoutMs ?? DEFAULT_START_TIMEOUT_MS;
1413
4174
  const deadline = Date.now() + timeoutMs;
@@ -1415,11 +4176,7 @@ var Agent = class {
1415
4176
  while (Date.now() < deadline) {
1416
4177
  try {
1417
4178
  const health = await this.health(sandboxId, untilDeadline(deadline, signal));
1418
- if (health.protocolVersion !== TURN_PROTOCOL_VERSION) {
1419
- throw new DeploymentError(
1420
- `Sandbox runtime speaks protocol ${health.protocolVersion}; this host speaks ${TURN_PROTOCOL_VERSION}.`
1421
- );
1422
- }
4179
+ this.requireProtocol(health);
1423
4180
  return;
1424
4181
  } catch (error) {
1425
4182
  if (error instanceof DeploymentError || signal?.aborted) throw error;
@@ -1427,13 +4184,15 @@ var Agent = class {
1427
4184
  }
1428
4185
  await delay2(HEALTH_POLL_INTERVAL_MS, signal);
1429
4186
  }
1430
- const message = lastError instanceof Error ? lastError.message : String(lastError);
1431
- throw new DeploymentError(`Runtime in sandbox ${sandboxId} did not answer within ${timeoutMs}ms: ${message}`);
4187
+ const message2 = lastError instanceof Error ? lastError.message : String(lastError);
4188
+ throw new DeploymentError(`Runtime in sandbox ${sandboxId} did not answer within ${timeoutMs}ms: ${message2}`);
1432
4189
  }
4190
+ // Runtime requests never start or resume a sandbox: its runtime would come back without the
4191
+ // turns it held in memory, and a repeated requestId would run again.
1433
4192
  endpoint(sandboxId) {
1434
4193
  let endpoint = this.endpoints.get(sandboxId);
1435
4194
  if (!endpoint) {
1436
- endpoint = this.sandbox(sandboxId).then((sandbox) => sandbox.getServerEndpoint(this.port));
4195
+ endpoint = this.connect(sandboxId, false).then((sandbox) => sandbox.getServerEndpoint(this.port));
1437
4196
  endpoint.catch(() => this.endpoints.delete(sandboxId));
1438
4197
  this.endpoints.set(sandboxId, endpoint);
1439
4198
  }
@@ -1441,21 +4200,37 @@ var Agent = class {
1441
4200
  }
1442
4201
  async request(sandboxId, method, path2, body, signal, options = {}) {
1443
4202
  for (let attempt = 0; ; attempt += 1) {
1444
- const endpoint = await untilAborted(() => this.endpoint(sandboxId), signal);
4203
+ const endpoint = await this.lookup(sandboxId, signal);
1445
4204
  const url = new URL(`${endpoint.url}${path2}`);
1446
4205
  for (const [name, value] of Object.entries(endpoint.query)) url.searchParams.set(name, value);
1447
4206
  const timeout = options.stream ? void 0 : AbortSignal.timeout(REQUEST_TIMEOUT_MS);
1448
4207
  const signals = [signal, timeout].filter((value) => value !== void 0);
1449
- const response = await fetch(url, {
1450
- method,
1451
- headers: {
1452
- ...endpoint.headers,
1453
- ...body === void 0 ? {} : { "content-type": "application/json" },
1454
- ...options.stream ? { accept: "text/event-stream" } : {}
1455
- },
1456
- ...body === void 0 ? {} : { body: JSON.stringify(body) },
1457
- ...signals.length ? { signal: AbortSignal.any(signals) } : {}
1458
- });
4208
+ let response;
4209
+ try {
4210
+ response = await fetch(url, {
4211
+ method,
4212
+ headers: {
4213
+ ...endpoint.headers,
4214
+ ...body === void 0 ? {} : { "content-type": "application/json" },
4215
+ ...options.stream ? { accept: "text/event-stream" } : {}
4216
+ },
4217
+ ...body === void 0 ? {} : { body: JSON.stringify(body) },
4218
+ ...signals.length ? { signal: AbortSignal.any(signals) } : {}
4219
+ });
4220
+ } catch (error) {
4221
+ if (!signal?.aborted) await this.throwIfGone(sandboxId, signal);
4222
+ throw error;
4223
+ }
4224
+ const rejection = response.ok ? void 0 : await response.clone().json().catch(() => void 0);
4225
+ const fromRuntime = typeof rejection === "object" && rejection !== null && RUNTIME_REJECTION_CODES.includes(Reflect.get(rejection, "code"));
4226
+ if (!response.ok && !fromRuntime && response.status !== 401 && response.status !== 403) {
4227
+ try {
4228
+ await this.throwIfGone(sandboxId, signal);
4229
+ } catch (error) {
4230
+ await response.body?.cancel();
4231
+ throw error;
4232
+ }
4233
+ }
1459
4234
  if (response.status === 401 || response.status === 403) {
1460
4235
  await response.body?.cancel();
1461
4236
  this.endpoints.delete(sandboxId);
@@ -1465,6 +4240,31 @@ var Agent = class {
1465
4240
  return response;
1466
4241
  }
1467
4242
  }
4243
+ // After a failed request, asks the provider whether the sandbox still runs, without waking it.
4244
+ // The request is not sent again, and any other answer leaves the original failure to the caller.
4245
+ // The caller's cancellation ends the wait, and a provider that does not answer within a request's
4246
+ // time is treated as unable to say.
4247
+ async throwIfGone(sandboxId, signal) {
4248
+ this.endpoints.delete(sandboxId);
4249
+ try {
4250
+ await this.lookup(sandboxId, signal);
4251
+ } catch (error) {
4252
+ if (error instanceof SandboxGoneError || signal?.aborted) throw error;
4253
+ }
4254
+ }
4255
+ // Callers share one provider lookup per sandbox, so each waits on it within its own signal and a
4256
+ // request's time. A lookup that outlasts that is dropped, so the next caller starts a new one.
4257
+ async lookup(sandboxId, signal) {
4258
+ const bound = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
4259
+ const pending = this.endpoint(sandboxId);
4260
+ try {
4261
+ return await untilAborted(() => pending, signal ? AbortSignal.any([signal, bound]) : bound);
4262
+ } catch (error) {
4263
+ if (signal?.aborted || !bound.aborted) throw error;
4264
+ if (this.endpoints.get(sandboxId) === pending) this.endpoints.delete(sandboxId);
4265
+ throw new ExecutionError(`The provider did not resolve sandbox ${sandboxId}'s endpoint within ${REQUEST_TIMEOUT_MS}ms.`);
4266
+ }
4267
+ }
1468
4268
  async prepareDaytonaSnapshot(sandbox, options) {
1469
4269
  const { Daytona, DaytonaNotFoundError } = await import("@daytona/sdk");
1470
4270
  const daytona = new Daytona(sandbox.apiKey ? { apiKey: sandbox.apiKey } : {});
@@ -1552,7 +4352,7 @@ var Agent = class {
1552
4352
  ...connection,
1553
4353
  ...sandbox.cpuCount === void 0 ? {} : { cpuCount: sandbox.cpuCount },
1554
4354
  ...sandbox.memoryMB === void 0 ? {} : { memoryMB: sandbox.memoryMB },
1555
- ...onLog ? { onBuildLogs: (entry) => onLog(entry.toString()) } : {}
4355
+ ...onLog ? { onBuildLogs: (entry2) => onLog(entry2.toString()) } : {}
1556
4356
  });
1557
4357
  }
1558
4358
  async listDaytonaSnapshots(sandbox, ownName) {
@@ -1602,15 +4402,13 @@ var Agent = class {
1602
4402
  // src/braintrust.ts
1603
4403
  var API_KEY = "BRAINTRUST_API_KEY";
1604
4404
  var PROJECT_NAME = "BRAINTRUST_PROJECT_NAME";
1605
- var FLUSH_TIMEOUT_MS = 1e4;
1606
4405
  var BRAINTRUST_PACKAGE = "braintrust";
1607
4406
  var BRAINTRUST_VERSIONS = ">=3.44.0 <4.0.0";
1608
4407
  function isSupportedBraintrustVersion(version) {
1609
4408
  const [major, minor = 0] = version.split(".").map(Number);
1610
4409
  return major === 3 && minor >= 44;
1611
4410
  }
1612
- var warn = (message) => console.warn(`neckbeard: ${message}`);
1613
- var errorText = (error) => error instanceof Error ? error.message : String(error);
4411
+ var warn = (message2) => console.warn(`neckbeard: ${message2}`);
1614
4412
  function readBraintrustSettings(env, where) {
1615
4413
  const apiKey = env[API_KEY]?.trim();
1616
4414
  const projectName = env[PROJECT_NAME]?.trim();
@@ -1618,73 +4416,12 @@ function readBraintrustSettings(env, where) {
1618
4416
  if (apiKey) warn(`Braintrust logging isn't configured ${where}: ${PROJECT_NAME} is not set.`);
1619
4417
  return void 0;
1620
4418
  }
1621
- async function startBraintrust({ apiKey, projectName }) {
1622
- const notTracing = "Braintrust tracing is off in the sandbox";
1623
- let sdk;
1624
- try {
1625
- sdk = await import(
1626
- /* webpackIgnore: true */
1627
- BRAINTRUST_PACKAGE
1628
- );
1629
- } catch (error) {
1630
- if (errorText(error).includes(`Cannot find package '${BRAINTRUST_PACKAGE}'`)) {
1631
- warn(`${notTracing}: add ${BRAINTRUST_PACKAGE} ${BRAINTRUST_VERSIONS} to the agent's package's dependencies so the image has it.`);
1632
- } else {
1633
- warn(`${notTracing}: ${BRAINTRUST_PACKAGE} failed to load: ${errorText(error)}`);
1634
- }
1635
- return void 0;
1636
- }
1637
- if (typeof sdk.wrapPiCodingAgentSDK !== "function") {
1638
- warn(`${notTracing}: its ${BRAINTRUST_PACKAGE} can't trace Pi; use ${BRAINTRUST_VERSIONS}.`);
1639
- return void 0;
1640
- }
1641
- try {
1642
- sdk.initLogger({ projectName, apiKey });
1643
- } catch (error) {
1644
- warn(`${notTracing}: ${errorText(error)}`);
1645
- return void 0;
1646
- }
1647
- return {
1648
- wrapPi: (pi) => sdk.wrapPiCodingAgentSDK(pi),
1649
- async flush() {
1650
- try {
1651
- await withTimeout(sdk.flush(), FLUSH_TIMEOUT_MS, `not sent within ${FLUSH_TIMEOUT_MS / 1e3} seconds; it may arrive later`);
1652
- } catch (error) {
1653
- warn(`could not send the turn's Braintrust trace: ${errorText(error)}`);
1654
- }
1655
- }
1656
- };
1657
- }
1658
4419
 
1659
4420
  // src/define.ts
1660
4421
  var SKILLS_DIR = "/app/.agents/skills";
1661
- var IMAGE_TAG_ENV_VARS = [
1662
- "NECKBEARD_IMAGE_TAG",
1663
- "GITHUB_SHA",
1664
- "CI_COMMIT_SHA",
1665
- "BITBUCKET_COMMIT",
1666
- "CODEBUILD_RESOLVED_SOURCE_VERSION",
1667
- "BUILDKITE_COMMIT",
1668
- "CIRCLE_SHA1",
1669
- "CF_PAGES_COMMIT_SHA",
1670
- "HEROKU_BUILD_COMMIT",
1671
- "HEROKU_SLUG_COMMIT",
1672
- "RAILWAY_GIT_COMMIT_SHA",
1673
- "RENDER_GIT_COMMIT",
1674
- "VERCEL_GIT_COMMIT_SHA",
1675
- "SOURCE_VERSION",
1676
- "GIT_COMMIT"
1677
- ];
1678
- function resolveImageTag(env = process.env) {
1679
- for (const name of IMAGE_TAG_ENV_VARS) {
1680
- const value = env[name]?.trim();
1681
- if (value && value !== name) return value;
1682
- }
1683
- return void 0;
1684
- }
1685
- var PI_PACKAGE = "@earendil-works/pi-coding-agent";
4422
+ var insideEntry = "agent-neckbeard/inside";
1686
4423
  var definedAgentMarker = /* @__PURE__ */ Symbol.for("agent-neckbeard.DefinedAgent");
1687
- var DefinedAgent = class {
4424
+ var AgentImage = class {
1688
4425
  constructor(definition) {
1689
4426
  this.definition = definition;
1690
4427
  if (!definition || typeof definition !== "object") throw new ConfigurationError("Agent definition must be an object.");
@@ -1694,20 +4431,21 @@ var DefinedAgent = class {
1694
4431
  if (Boolean(definition.pi) === Boolean(definition.createSession)) {
1695
4432
  throw new ConfigurationError(`Agent ${definition.name} needs exactly one of pi and createSession.`);
1696
4433
  }
4434
+ if (definition.createSession && definition.maxTurnDurationMs !== void 0) {
4435
+ throw new ConfigurationError("Set the custom session deadline in openInsideConversation(pi, models, maxTurnDurationMs).");
4436
+ }
1697
4437
  if (!definition.image && !definition.registry) {
1698
4438
  throw new ConfigurationError(`Agent ${definition.name} needs a registry or an image.`);
1699
4439
  }
1700
4440
  }
1701
4441
  [definedAgentMarker] = true;
1702
- client;
1703
- braintrustChecked = false;
1704
4442
  get name() {
1705
4443
  return this.definition.name;
1706
4444
  }
1707
4445
  /** The image this host runs: `image`, else `<registry>/<name>:<tag>` with the tag `resolveImageTag()` finds. */
1708
4446
  imageRef(tag = resolveImageTag()) {
1709
- const { image, registry, name } = this.definition;
1710
- if (image) return image;
4447
+ const { image: image2, registry, name } = this.definition;
4448
+ if (image2) return image2;
1711
4449
  if (!tag) {
1712
4450
  throw new ConfigurationError(
1713
4451
  `Set NECKBEARD_IMAGE_TAG to choose agent ${name}'s image, or deploy from a platform that names the commit, such as RENDER_GIT_COMMIT.`
@@ -1715,16 +4453,37 @@ var DefinedAgent = class {
1715
4453
  }
1716
4454
  return `${registry.replace(/\/+$/u, "")}/${name}:${tag}`;
1717
4455
  }
4456
+ };
4457
+ var DefinedHostAgent = class extends AgentImage {
4458
+ constructor(definition) {
4459
+ super(definition);
4460
+ if (!definition.pi || definition.sandbox || definition.env) {
4461
+ throw new ConfigurationError("Harness-outside-sandbox mode requires pi and takes its storage and execution environment at startup.");
4462
+ }
4463
+ }
4464
+ async start(options, context) {
4465
+ const durableEntry = "agent-neckbeard/durable";
4466
+ const durable = await import(
4467
+ /* webpackIgnore: true */
4468
+ durableEntry
4469
+ );
4470
+ return durable.hostSession(this.definition, options, context);
4471
+ }
4472
+ };
4473
+ var DefinedAgent = class extends AgentImage {
4474
+ client;
4475
+ braintrustChecked = false;
1718
4476
  /** The `Agent` for an image, by default the one this host runs. */
1719
- forImage(image = this.imageRef()) {
4477
+ forImage(image2 = this.imageRef()) {
1720
4478
  const { definition } = this;
1721
4479
  const sandbox = typeof definition.sandbox === "function" ? definition.sandbox() : definition.sandbox;
1722
- const envs = typeof definition.envs === "function" ? definition.envs() : definition.envs;
4480
+ if (!sandbox) throw new ConfigurationError("An inside-sandbox agent needs a sandbox provider.");
4481
+ const env = typeof definition.env === "function" ? definition.env() : definition.env;
1723
4482
  return new Agent({
1724
4483
  name: definition.name,
1725
- image,
4484
+ image: image2,
1726
4485
  sandbox,
1727
- ...envs ? { envs } : {},
4486
+ ...env ? { env } : {},
1728
4487
  ...definition.command ? { command: definition.command } : {},
1729
4488
  ...definition.port === void 0 ? {} : { port: definition.port },
1730
4489
  ...definition.startTimeoutMs === void 0 ? {} : { startTimeoutMs: definition.startTimeoutMs },
@@ -1741,25 +4500,25 @@ var DefinedAgent = class {
1741
4500
  prepare(options) {
1742
4501
  return this.agent.prepare(options);
1743
4502
  }
1744
- start(options) {
1745
- if (this.definition.pi && !this.braintrustChecked) {
4503
+ async start(options) {
4504
+ const { pi } = this.definition;
4505
+ if (pi) {
4506
+ const sessionId = options?.sessionId;
4507
+ if (pi.persist && sessionId === void 0) throw new ConfigurationError(`Agent ${this.name} persists its session, so start() needs a sessionId.`);
4508
+ if (!pi.persist && sessionId !== void 0) throw new ConfigurationError(`Agent ${this.name} takes a sessionId only with pi.persist.`);
4509
+ if (sessionId !== void 0 && (typeof sessionId !== "string" || !/^[a-zA-Z0-9_-]+$/.test(sessionId))) {
4510
+ throw new ConfigurationError("A sessionId may contain only letters, digits, underscores and dashes.");
4511
+ }
4512
+ }
4513
+ if (pi && !this.braintrustChecked) {
1746
4514
  this.braintrustChecked = true;
1747
- const envs = typeof this.definition.envs === "function" ? this.definition.envs() : this.definition.envs;
1748
- readBraintrustSettings({ ...filterDefined(envs), ...filterDefined(options?.envs) }, `for agent ${this.name}'s sandboxes`);
4515
+ const env = typeof this.definition.env === "function" ? this.definition.env() : this.definition.env;
4516
+ readBraintrustSettings({ ...filterDefined(env), ...filterDefined(options?.env) }, `for agent ${this.name}'s sandboxes`);
1749
4517
  }
1750
4518
  return this.agent.start(options);
1751
4519
  }
1752
- prompt(sandboxId, turn, options) {
1753
- return this.agent.prompt(sandboxId, turn, options);
1754
- }
1755
- run(sandboxId, turn, options) {
1756
- return this.agent.run(sandboxId, turn, options);
1757
- }
1758
- events(sandboxId, turnId, options) {
1759
- return this.agent.events(sandboxId, turnId, options);
1760
- }
1761
- abort(sandboxId, turnId, signal) {
1762
- return this.agent.abort(sandboxId, turnId, signal);
4520
+ attach(sandboxId, options) {
4521
+ return this.agent.attach(sandboxId, options);
1763
4522
  }
1764
4523
  health(sandboxId, signal) {
1765
4524
  return this.agent.health(sandboxId, signal);
@@ -1778,84 +4537,33 @@ var DefinedAgent = class {
1778
4537
  }
1779
4538
  /** Where a persisted session's file is in a sandbox whose home is `homeDir`, as for copying it out and back. */
1780
4539
  sessionFilePath(homeDir, sessionId) {
1781
- return path.posix.join(homeDir, "agent", ".pi", "sessions", `${sessionId}.jsonl`);
4540
+ return path.posix.join(homeDir, "agent", ".pi", "sessions", `${sessionId}.sqlite`);
1782
4541
  }
1783
4542
  /** Serves the agent's session; the image's entry point, which `neckbeard build` generates, calls it. */
1784
4543
  serve(options = {}) {
1785
4544
  const { definition } = this;
1786
4545
  const { pi } = definition;
4546
+ if (options.createSession && definition.maxTurnDurationMs !== void 0) {
4547
+ throw new ConfigurationError("A custom serve factory must set its own deadline. Remove the definition-level maxTurnDurationMs.");
4548
+ }
1787
4549
  return serve({
1788
- createSession: pi ? () => createPiSession(pi) : definition.createSession,
1789
- ...definition.maxTurnDurationMs === void 0 ? {} : { maxTurnDurationMs: definition.maxTurnDurationMs },
1790
- ...definition.abortGraceMs === void 0 ? {} : { abortGraceMs: definition.abortGraceMs },
4550
+ createSession: pi ? async () => (await import(
4551
+ /* webpackIgnore: true */
4552
+ insideEntry
4553
+ )).openInsideConversation(pi, void 0, definition.maxTurnDurationMs) : definition.createSession,
1791
4554
  ...options
1792
4555
  });
1793
4556
  }
1794
4557
  };
1795
4558
  function defineAgent(definition) {
1796
- return new DefinedAgent(definition);
4559
+ if (definition && "placement" in definition) throw new ConfigurationError("Set mode instead of placement.");
4560
+ if (definition?.mode === "harness-outside-sandbox") return new DefinedHostAgent(definition);
4561
+ if (definition?.mode === "harness-inside-sandbox") return new DefinedAgent(definition);
4562
+ throw new ConfigurationError("Set mode to harness-inside-sandbox or harness-outside-sandbox.");
1797
4563
  }
1798
4564
  function isDefinedAgent(value) {
1799
4565
  return typeof value === "object" && value !== null && definedAgentMarker in value;
1800
4566
  }
1801
- async function createPiSession(config) {
1802
- const home = os.homedir();
1803
- const cwd = path.resolve(home, config.cwd ?? "workspace");
1804
- await mkdir(cwd, { recursive: true });
1805
- process.env.NECKBEARD_CWD = cwd;
1806
- const agentDir = path.join(home, "agent", ".pi");
1807
- const loaded = await import(
1808
- /* webpackIgnore: true */
1809
- PI_PACKAGE
1810
- );
1811
- const braintrustSettings = readBraintrustSettings(process.env, "in the sandbox");
1812
- const braintrust = braintrustSettings && await startBraintrust(braintrustSettings);
1813
- const pi = braintrust ? braintrust.wrapPi(loaded) : loaded;
1814
- const modelRuntime = await pi.ModelRuntime.create({ modelsPath: null });
1815
- const separator = config.model.indexOf("/");
1816
- const model = separator > 0 ? modelRuntime.getModel(config.model.slice(0, separator), config.model.slice(separator + 1)) : void 0;
1817
- if (!model) throw new ConfigurationError(`Pi has no model ${config.model}; name it as provider/model.`);
1818
- const settingsManager = pi.SettingsManager.inMemory();
1819
- const resourceLoader = new pi.DefaultResourceLoader({
1820
- cwd,
1821
- agentDir,
1822
- settingsManager,
1823
- additionalSkillPaths: [SKILLS_DIR],
1824
- noSkills: true,
1825
- noExtensions: true,
1826
- noPromptTemplates: true,
1827
- noContextFiles: true,
1828
- systemPrompt: config.systemPrompt
1829
- });
1830
- await resourceLoader.reload();
1831
- let sessionManager;
1832
- if (config.persist) {
1833
- const sessionId = process.env.NECKBEARD_SESSION_ID;
1834
- if (!sessionId) throw new ConfigurationError("A persisted Pi session needs the sessionId passed to start().");
1835
- const sessionFile = path.join(agentDir, "sessions", `${sessionId}.jsonl`);
1836
- sessionManager = pi.SessionManager.open(sessionFile, path.dirname(sessionFile), cwd);
1837
- } else {
1838
- sessionManager = pi.SessionManager.inMemory(cwd);
1839
- }
1840
- const { session } = await pi.createAgentSession({
1841
- cwd,
1842
- agentDir,
1843
- model,
1844
- modelRuntime,
1845
- resourceLoader,
1846
- settingsManager,
1847
- sessionManager,
1848
- ...config.thinkingLevel ? { thinkingLevel: config.thinkingLevel } : {},
1849
- ...config.tools ? { tools: config.tools } : {}
1850
- });
1851
- if (!braintrust) return session;
1852
- return {
1853
- subscribe: (listener) => session.subscribe(listener),
1854
- prompt: (text) => session.prompt(text),
1855
- abort: () => session.abort(),
1856
- afterTurn: () => braintrust.flush()
1857
- };
1858
- }
1859
4567
 
1860
4568
  // src/providers/docker.ts
1861
4569
  import { spawn } from "child_process";
@@ -1887,7 +4595,7 @@ function validateDockerOptions(options, mode, failure) {
1887
4595
  }
1888
4596
  }
1889
4597
  function exportLines(envs) {
1890
- return Object.entries(envs ?? {}).filter((entry) => entry[1] !== void 0).map(([name, value]) => `export ${name}=${shellQuote(value)}
4598
+ return Object.entries(envs ?? {}).filter((entry2) => entry2[1] !== void 0).map(([name, value]) => `export ${name}=${shellQuote(value)}
1891
4599
  `).join("");
1892
4600
  }
1893
4601
  var runDockerCli = (args, options) => new Promise((resolve2, reject) => {
@@ -1910,14 +4618,14 @@ var runDockerCli = (args, options) => new Promise((resolve2, reject) => {
1910
4618
  child.stdout.on("data", (chunk) => {
1911
4619
  stdout.push(chunk);
1912
4620
  if (options.onStdout) {
1913
- const text = stdoutDecoder.write(chunk);
1914
- if (text) options.onStdout(text);
4621
+ const text2 = stdoutDecoder.write(chunk);
4622
+ if (text2) options.onStdout(text2);
1915
4623
  }
1916
4624
  });
1917
4625
  child.stderr.on("data", (chunk) => {
1918
- const text = stderrDecoder.write(chunk);
1919
- stderr += text;
1920
- if (text) options.onStderr?.(text);
4626
+ const text2 = stderrDecoder.write(chunk);
4627
+ stderr += text2;
4628
+ if (text2) options.onStderr?.(text2);
1921
4629
  });
1922
4630
  child.on("error", (error) => settle(() => reject(
1923
4631
  Reflect.get(error, "code") === "ENOENT" ? new Error("The Docker provider requires the `docker` CLI on PATH.") : error
@@ -1992,8 +4700,8 @@ async function closeTunnels(containerId) {
1992
4700
  }
1993
4701
  }
1994
4702
  var DockerSandboxHandle = class _DockerSandboxHandle {
1995
- constructor(id, managed, failure, cli = runDockerCli) {
1996
- this.id = id;
4703
+ constructor(id2, managed, failure, cli = runDockerCli) {
4704
+ this.id = id2;
1997
4705
  this.managed = managed;
1998
4706
  this.failure = failure;
1999
4707
  this.cli = cli;
@@ -2045,11 +4753,11 @@ var DockerSandboxHandle = class _DockerSandboxHandle {
2045
4753
  options.template ?? DOCKER_DEFAULT_TEMPLATE,
2046
4754
  String(lifetimeSeconds)
2047
4755
  ], { timeoutMs: DOCKER_CREATE_TIMEOUT_MS });
2048
- const id = created.stdout.toString("utf8").trim().split("\n").pop() ?? "";
2049
- if (created.exitCode !== 0 || !/^[a-f0-9]{12,64}$/u.test(id)) {
4756
+ const id2 = created.stdout.toString("utf8").trim().split("\n").pop() ?? "";
4757
+ if (created.exitCode !== 0 || !/^[a-f0-9]{12,64}$/u.test(id2)) {
2050
4758
  throw failure(`Failed to create Docker sandbox: ${created.stderr.trim() || "no container ID returned."}`);
2051
4759
  }
2052
- const handle = new _DockerSandboxHandle(id, true, failure, cli);
4760
+ const handle = new _DockerSandboxHandle(id2, true, failure, cli);
2053
4761
  try {
2054
4762
  await handle.writeFile(DOCKER_ENV_FILE, exportLines(options.envs));
2055
4763
  await handle.ensureTools();
@@ -2089,10 +4797,10 @@ var DockerSandboxHandle = class _DockerSandboxHandle {
2089
4797
  DOCKER_BOOTSTRAP_TIMEOUT_MS
2090
4798
  );
2091
4799
  }
2092
- async control(label, script, args = [], input, timeoutMs = DOCKER_CONTROL_TIMEOUT_MS) {
4800
+ async control(label, script, args = [], input2, timeoutMs = DOCKER_CONTROL_TIMEOUT_MS) {
2093
4801
  const result = await this.cli(
2094
4802
  ["exec", "-i", "--user", "root", this.id, "/bin/sh", "-c", script, "sh", ...args],
2095
- { input, timeoutMs }
4803
+ { input: input2, timeoutMs }
2096
4804
  );
2097
4805
  if (result.exitCode !== 0) {
2098
4806
  throw this.failure(`${label} failed: ${result.stderr.trim() || `exit code ${result.exitCode}`}`);
@@ -2103,8 +4811,8 @@ var DockerSandboxHandle = class _DockerSandboxHandle {
2103
4811
  await this.control("Docker directory creation", 'mkdir -p -- "$1"', [path2]);
2104
4812
  }
2105
4813
  async writeFile(path2, content) {
2106
- const input = typeof content === "string" ? content : content instanceof ArrayBuffer ? new Uint8Array(content) : content;
2107
- await this.control("Docker file write", 'mkdir -p -- "$(dirname -- "$1")" && cat > "$1"', [path2], input, DOCKER_FILE_TIMEOUT_MS);
4814
+ const input2 = typeof content === "string" ? content : content instanceof ArrayBuffer ? new Uint8Array(content) : content;
4815
+ await this.control("Docker file write", 'mkdir -p -- "$(dirname -- "$1")" && cat > "$1"', [path2], input2, DOCKER_FILE_TIMEOUT_MS);
2108
4816
  }
2109
4817
  async readFile(path2) {
2110
4818
  return (await this.control("Docker file read", 'cat -- "$1"', [path2], void 0, DOCKER_FILE_TIMEOUT_MS)).stdout.toString("utf8");
@@ -2184,49 +4892,49 @@ var SERVER_FAILURE_DIAGNOSTIC_TIMEOUT_MS = 1e3;
2184
4892
  var NATIVE_EXT_RE = /\.(node|wasm|gyp|c|cc|cpp|cxx|h|hpp|hxx)$/i;
2185
4893
  var TRACEABLE_SOURCE_EXT_RE = /\.(cjs|cts|js|jsx|mjs|mts|ts|tsx)$/i;
2186
4894
  var NeckbeardError = class extends Error {
2187
- constructor(message) {
2188
- super(message);
4895
+ constructor(message2) {
4896
+ super(message2);
2189
4897
  this.name = "NeckbeardError";
2190
4898
  }
2191
4899
  };
2192
4900
  var DeploymentError = class extends NeckbeardError {
2193
4901
  /** A sandbox the failure left behind, for `kill()`. */
2194
- constructor(message, cause, sandboxId) {
2195
- super(message);
4902
+ constructor(message2, cause, sandboxId) {
4903
+ super(message2);
2196
4904
  this.cause = cause;
2197
4905
  this.sandboxId = sandboxId;
2198
4906
  this.name = "DeploymentError";
2199
4907
  }
2200
4908
  };
4909
+ var SandboxGoneError = class extends DeploymentError {
4910
+ constructor(message2, cause) {
4911
+ super(message2, cause);
4912
+ this.name = "SandboxGoneError";
4913
+ }
4914
+ };
2201
4915
  var ValidationError = class extends NeckbeardError {
2202
- constructor(message, cause) {
2203
- super(message);
4916
+ constructor(message2, cause) {
4917
+ super(message2);
2204
4918
  this.cause = cause;
2205
4919
  this.name = "ValidationError";
2206
4920
  }
2207
4921
  };
2208
4922
  var ExecutionError = class extends NeckbeardError {
2209
- constructor(message, cause) {
2210
- super(message);
4923
+ constructor(message2, cause) {
4924
+ super(message2);
2211
4925
  this.cause = cause;
2212
4926
  this.name = "ExecutionError";
2213
4927
  }
2214
4928
  };
2215
4929
  var RuntimeBusyError = class extends ExecutionError {
2216
- constructor(message) {
2217
- super(message);
4930
+ constructor(message2) {
4931
+ super(message2);
2218
4932
  this.name = "RuntimeBusyError";
2219
4933
  }
2220
4934
  };
2221
- var TurnLostError = class extends ExecutionError {
2222
- constructor(message) {
2223
- super(message);
2224
- this.name = "TurnLostError";
2225
- }
2226
- };
2227
4935
  var ConfigurationError = class extends NeckbeardError {
2228
- constructor(message) {
2229
- super(message);
4936
+ constructor(message2) {
4937
+ super(message2);
2230
4938
  this.name = "ConfigurationError";
2231
4939
  }
2232
4940
  };
@@ -2517,10 +5225,10 @@ function traceSourceDependencyFiles(appDir, sourceFiles) {
2517
5225
  files.add(file);
2518
5226
  }
2519
5227
  };
2520
- for (const [inputPath, input] of Object.entries(metafile.inputs)) {
5228
+ for (const [inputPath, input2] of Object.entries(metafile.inputs)) {
2521
5229
  const absoluteInput = resolveMetafileInput(appDir, inputPath);
2522
5230
  addFile(absoluteInput);
2523
- for (const importRecord of input.imports ?? []) {
5231
+ for (const importRecord of input2.imports ?? []) {
2524
5232
  const importPath = importRecord.original ?? importRecord.path;
2525
5233
  if (!isBareModuleImport(importPath) || isBuiltinModule(importPath)) {
2526
5234
  continue;
@@ -2565,8 +5273,8 @@ function findFiles(root) {
2565
5273
  return [];
2566
5274
  }
2567
5275
  const files = [];
2568
- for (const entry of readdirSync(root)) {
2569
- files.push(...findFiles(join(root, entry)));
5276
+ for (const entry2 of readdirSync(root)) {
5277
+ files.push(...findFiles(join(root, entry2)));
2570
5278
  }
2571
5279
  return files;
2572
5280
  }
@@ -2574,7 +5282,7 @@ function directFiles(root) {
2574
5282
  if (!existsSync(root) || !statSync(root).isDirectory()) {
2575
5283
  return [];
2576
5284
  }
2577
- return readdirSync(root).map((entry) => join(root, entry)).filter((file) => statSync(file).isFile());
5285
+ return readdirSync(root).map((entry2) => join(root, entry2)).filter((file) => statSync(file).isFile());
2578
5286
  }
2579
5287
  function routePathFromTraceFile(outputPath, traceFile) {
2580
5288
  const relativeTrace = relative(outputPath, traceFile).replace(/\\/g, "/");
@@ -2636,20 +5344,20 @@ function asRecord(value) {
2636
5344
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
2637
5345
  }
2638
5346
  function normalizeNonEmptyStrings(name, value) {
2639
- const values = Array.isArray(value) ? value : [value];
2640
- if (values.length === 0) {
5347
+ const values2 = Array.isArray(value) ? value : [value];
5348
+ if (values2.length === 0) {
2641
5349
  throw new ConfigurationError(`${name} must contain at least one entry.`);
2642
5350
  }
2643
- for (const entry of values) {
2644
- if (typeof entry !== "string" || entry.trim() === "") {
5351
+ for (const entry2 of values2) {
5352
+ if (typeof entry2 !== "string" || entry2.trim() === "") {
2645
5353
  throw new ConfigurationError(`${name} entries must be non-empty strings.`);
2646
5354
  }
2647
5355
  }
2648
- return values;
5356
+ return values2;
2649
5357
  }
2650
- function mergeStringArray(existing, values) {
5358
+ function mergeStringArray(existing, values2) {
2651
5359
  const current = Array.isArray(existing) ? existing.filter((value) => typeof value === "string") : [];
2652
- return [.../* @__PURE__ */ new Set([...current, ...values])];
5360
+ return [.../* @__PURE__ */ new Set([...current, ...values2])];
2653
5361
  }
2654
5362
  function mergeTracingIncludes(existing, routeGlobs, sourceFiles) {
2655
5363
  const includes = { ...asRecord(existing) };
@@ -2728,12 +5436,12 @@ function validateLocalDirectoriesConfig(value) {
2728
5436
  if (!Array.isArray(value)) {
2729
5437
  throw new ConfigurationError("localDirectories must be an array when provided.");
2730
5438
  }
2731
- for (const [index, entry] of value.entries()) {
5439
+ for (const [index, entry2] of value.entries()) {
2732
5440
  const name = `localDirectories[${index}]`;
2733
- if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
5441
+ if (!entry2 || typeof entry2 !== "object" || Array.isArray(entry2)) {
2734
5442
  throw new ConfigurationError(`${name} must be an object.`);
2735
5443
  }
2736
- const candidate = entry;
5444
+ const candidate = entry2;
2737
5445
  if (typeof candidate.source !== "string" || candidate.source.trim() === "") {
2738
5446
  throw new ConfigurationError(`${name}.source must be a non-empty string.`);
2739
5447
  }
@@ -2757,9 +5465,9 @@ function validateAgentConfig(config) {
2757
5465
  throw new ConfigurationError('sandbox.provider must be "e2b", "daytona", "modal", or "docker".');
2758
5466
  }
2759
5467
  if (config.sandbox.provider === "modal") {
2760
- validateModalOptions(config.sandbox, "agent", (message) => new ConfigurationError(message));
5468
+ validateModalOptions(config.sandbox, "agent", (message2) => new ConfigurationError(message2));
2761
5469
  } else if (config.sandbox.provider === "docker") {
2762
- validateDockerOptions(config.sandbox, "agent", (message) => new ConfigurationError(message));
5470
+ validateDockerOptions(config.sandbox, "agent", (message2) => new ConfigurationError(message2));
2763
5471
  } else if (typeof config.sandbox.template !== "string" || config.sandbox.template.trim() === "") {
2764
5472
  throw new ConfigurationError("sandbox.template must be a non-empty string.");
2765
5473
  }
@@ -2902,9 +5610,9 @@ async function waitForServerHealthy(healthUrl, descriptor, timeoutMs = SERVER_HE
2902
5610
  }
2903
5611
  await delayWithAbort(SERVER_HEALTH_POLL_INTERVAL_MS, signal);
2904
5612
  }
2905
- const message = lastError instanceof Error ? lastError.message : String(lastError);
5613
+ const message2 = lastError instanceof Error ? lastError.message : String(lastError);
2906
5614
  throw new DeploymentError(
2907
- `Server did not become healthy at ${healthUrl} within ${timeoutMs}ms: ${message}`
5615
+ `Server did not become healthy at ${healthUrl} within ${timeoutMs}ms: ${message2}`
2908
5616
  );
2909
5617
  }
2910
5618
  function requireEnv(name) {
@@ -3108,7 +5816,7 @@ async function readServerFailureDiagnostics(sandbox, command, environment, signa
3108
5816
  signal
3109
5817
  );
3110
5818
  const secrets = Object.entries(environment).filter(
3111
- (entry) => Boolean(entry[1]) && isConfiguredDiagnosticSecret(entry[0], entry[1])
5819
+ (entry2) => Boolean(entry2[1]) && isConfiguredDiagnosticSecret(entry2[0], entry2[1])
3112
5820
  ).map(([, value]) => value);
3113
5821
  secrets.sort((left, right) => right.length - left.length);
3114
5822
  const stdout = redactServerFailureDiagnosticStream(captured.stdout, secrets);
@@ -3133,12 +5841,12 @@ function providerApiKey(provider, explicitApiKey) {
3133
5841
  }
3134
5842
  async function createProviderSandboxHandle(options) {
3135
5843
  if (options.provider === "modal") {
3136
- validateModalOptions(options, "create", (message) => new ConfigurationError(message));
3137
- return ModalSandboxHandle.create(options, (message) => new DeploymentError(message));
5844
+ validateModalOptions(options, "create", (message2) => new ConfigurationError(message2));
5845
+ return ModalSandboxHandle.create(options, (message2) => new DeploymentError(message2));
3138
5846
  }
3139
5847
  if (options.provider === "docker") {
3140
- validateDockerOptions(options, "create", (message) => new ConfigurationError(message));
3141
- return DockerSandboxHandle.create(options, (message) => new DeploymentError(message));
5848
+ validateDockerOptions(options, "create", (message2) => new ConfigurationError(message2));
5849
+ return DockerSandboxHandle.create(options, (message2) => new DeploymentError(message2));
3142
5850
  }
3143
5851
  if (options.provider === "daytona") {
3144
5852
  const apiKey2 = providerApiKey("daytona", options.apiKey);
@@ -3159,7 +5867,7 @@ async function createProviderSandboxHandle(options) {
3159
5867
  try {
3160
5868
  return await DaytonaSandboxHandle.create(
3161
5869
  sandbox2,
3162
- (message) => new DeploymentError(message)
5870
+ (message2) => new DeploymentError(message2)
3163
5871
  );
3164
5872
  } catch (error) {
3165
5873
  await sandbox2.delete(
@@ -3179,44 +5887,57 @@ async function createProviderSandboxHandle(options) {
3179
5887
  network: options.allowPublicTraffic === void 0 ? void 0 : { allowPublicTraffic: options.allowPublicTraffic }
3180
5888
  };
3181
5889
  const sandbox = options.template ? await Sandbox.create(options.template, sandboxOptions) : await Sandbox.create(sandboxOptions);
3182
- return new E2bSandboxHandle(sandbox, (message) => new DeploymentError(message));
5890
+ return new E2bSandboxHandle(sandbox, (message2) => new DeploymentError(message2));
3183
5891
  }
3184
- async function connectProviderSandboxHandle(options) {
5892
+ async function connectProviderSandboxHandle(options, wake = true) {
5893
+ const gone = (message2, cause) => new SandboxGoneError(message2, cause instanceof Error ? cause : void 0);
3185
5894
  if (options.provider === "modal") {
3186
- validateModalOptions(options, "connect", (message) => new ConfigurationError(message));
3187
- return ModalSandboxHandle.connect(options, (message) => new DeploymentError(message));
5895
+ validateModalOptions(options, "connect", (message2) => new ConfigurationError(message2));
5896
+ return ModalSandboxHandle.connect(options, (message2) => new DeploymentError(message2), wake ? void 0 : gone);
3188
5897
  }
3189
5898
  if (options.provider === "docker") {
3190
- validateDockerOptions(options, "connect", (message) => new ConfigurationError(message));
3191
- return DockerSandboxHandle.connect(options, (message) => new DeploymentError(message));
5899
+ validateDockerOptions(options, "connect", (message2) => new ConfigurationError(message2));
5900
+ return DockerSandboxHandle.connect(options, (message2) => new DeploymentError(message2));
3192
5901
  }
3193
5902
  if (options.provider === "daytona") {
3194
5903
  const apiKey2 = providerApiKey("daytona", options.apiKey);
3195
- const { Daytona } = await getDaytona();
5904
+ const { Daytona, DaytonaNotFoundError } = await getDaytona();
3196
5905
  const daytona = new Daytona({ apiKey: apiKey2 });
3197
- const sandbox2 = await daytona.get(options.sandboxId);
5906
+ const sandbox2 = await daytona.get(options.sandboxId).catch((error) => {
5907
+ if (!wake && error instanceof DaytonaNotFoundError) throw gone(`Daytona sandbox ${options.sandboxId} does not exist.`, error);
5908
+ throw error;
5909
+ });
3198
5910
  if (sandbox2.state !== "started") {
5911
+ if (!wake) throw gone(`Daytona sandbox ${options.sandboxId} is ${sandbox2.state}, not started.`);
3199
5912
  if (sandbox2.state === "starting" || sandbox2.state === "creating" || sandbox2.state === "restoring") {
3200
5913
  await sandbox2.waitUntilStarted(options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC);
3201
5914
  } else {
3202
5915
  await sandbox2.start(options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC);
3203
5916
  }
3204
5917
  }
3205
- return DaytonaSandboxHandle.create(sandbox2, (message) => new DeploymentError(message));
5918
+ return DaytonaSandboxHandle.create(sandbox2, (message2) => new DeploymentError(message2));
3206
5919
  }
3207
5920
  const apiKey = providerApiKey("e2b", options.apiKey);
3208
- const { Sandbox } = await getE2b();
5921
+ const { Sandbox, SandboxNotFoundError } = await getE2b();
5922
+ const absent2 = (error) => {
5923
+ if (!wake && error instanceof SandboxNotFoundError) throw gone(`E2B sandbox ${options.sandboxId} does not exist.`, error);
5924
+ throw error;
5925
+ };
5926
+ if (!wake) {
5927
+ const info = await Sandbox.getInfo(options.sandboxId, { apiKey, requestTimeoutMs: options.requestTimeoutMs }).catch(absent2);
5928
+ if (info.state !== "running") throw gone(`E2B sandbox ${options.sandboxId} is ${info.state}, not running.`);
5929
+ }
3209
5930
  const sandbox = await Sandbox.connect(options.sandboxId, {
3210
5931
  apiKey,
3211
5932
  timeoutMs: options.timeoutMs,
3212
5933
  requestTimeoutMs: options.requestTimeoutMs
3213
- });
3214
- return new E2bSandboxHandle(sandbox, (message) => new DeploymentError(message));
5934
+ }).catch(absent2);
5935
+ return new E2bSandboxHandle(sandbox, (message2) => new DeploymentError(message2));
3215
5936
  }
3216
5937
  async function destroyProviderSandbox(options) {
3217
5938
  if (options.provider === "modal") {
3218
- validateModalOptions(options, "connect", (message) => new ConfigurationError(message));
3219
- return ModalSandboxHandle.destroyById(options, (message) => new DeploymentError(message));
5939
+ validateModalOptions(options, "connect", (message2) => new ConfigurationError(message2));
5940
+ return ModalSandboxHandle.destroyById(options, (message2) => new DeploymentError(message2));
3220
5941
  }
3221
5942
  if (options.provider === "daytona") {
3222
5943
  const { Daytona, DaytonaNotFoundError } = await getDaytona();
@@ -3238,8 +5959,8 @@ var SandboxClient = class _SandboxClient {
3238
5959
  static async create(options) {
3239
5960
  return new _SandboxClient(await createProviderSandboxHandle(options));
3240
5961
  }
3241
- static async connect(options) {
3242
- return new _SandboxClient(await connectProviderSandboxHandle(options));
5962
+ static async connect(options, mode = {}) {
5963
+ return new _SandboxClient(await connectProviderSandboxHandle(options, mode.wake ?? true));
3243
5964
  }
3244
5965
  get id() {
3245
5966
  return this.handle.id;
@@ -3284,7 +6005,7 @@ var SandboxClient = class _SandboxClient {
3284
6005
  }
3285
6006
  const normalized = normalizeProviderSandboxDetachedCommandOptions(
3286
6007
  options,
3287
- (message) => new ConfigurationError(message),
6008
+ (message2) => new ConfigurationError(message2),
3288
6009
  { requireObject: true }
3289
6010
  );
3290
6011
  return this.handle.startDetachedCommand(command, normalized.options);
@@ -3465,8 +6186,8 @@ function readConfiguredLocalDirectory(upload) {
3465
6186
  `${upload.name} could not read local directory: ${currentPath} (${errorMessage(error)})`
3466
6187
  );
3467
6188
  }
3468
- for (const entry of entries) {
3469
- const localPath = join(currentPath, entry);
6189
+ for (const entry2 of entries) {
6190
+ const localPath = join(currentPath, entry2);
3470
6191
  const stats = localPathStats(localPath, upload);
3471
6192
  if (stats.isDirectory()) {
3472
6193
  walk(localPath);
@@ -3494,8 +6215,8 @@ function readConfiguredLocalDirectory(upload) {
3494
6215
  return { rootPath, files };
3495
6216
  }
3496
6217
  function prepareLocalDirectoryUploads(localDirectories, claudeDir) {
3497
- const uploads = localDirectories.map((entry, index) => ({
3498
- ...entry,
6218
+ const uploads = localDirectories.map((entry2, index) => ({
6219
+ ...entry2,
3499
6220
  name: `localDirectories[${index}]`,
3500
6221
  rejectSymlinks: true,
3501
6222
  preserveRootDirectory: false
@@ -3588,7 +6309,7 @@ var LegacyBundledAgent = class {
3588
6309
  this._sourceFile = resolveSourceFile(config.sourceFile);
3589
6310
  this.dependencies = config.dependencies ?? DEFAULT_DEPENDENCIES;
3590
6311
  this.files = config.files ?? [];
3591
- this.localDirectories = (config.localDirectories ?? []).map((entry) => ({ ...entry }));
6312
+ this.localDirectories = (config.localDirectories ?? []).map((entry2) => ({ ...entry2 }));
3592
6313
  this.claudeDir = config.claudeDir;
3593
6314
  this.envs = config.envs ?? {};
3594
6315
  this.build = config.build ?? {};
@@ -3977,7 +6698,7 @@ var require = __neckbeard_createRequire(import.meta.url);
3977
6698
  }
3978
6699
  }
3979
6700
  if (localDirectoryUploads.directories.length > 0 || localDirectoryUploads.files.length > 0) {
3980
- const archivePath = posix.join(paths.agentDir, `.neckbeard-local-directories-${randomUUID()}.tar.gz`);
6701
+ const archivePath = posix.join(paths.agentDir, `.neckbeard-local-directories-${randomUUID2()}.tar.gz`);
3981
6702
  await sandbox.writeFile(archivePath, await createTarGz([
3982
6703
  ...localDirectoryUploads.directories.map((directory) => ({ path: directory })),
3983
6704
  ...localDirectoryUploads.files.map((file) => ({ path: file.targetPath, content: file.content }))
@@ -4085,7 +6806,7 @@ var require = __neckbeard_createRequire(import.meta.url);
4085
6806
  * const result = await agent.run({ prompt: 'Hello!' }, { sandboxId });
4086
6807
  * ```
4087
6808
  */
4088
- async run(input, options) {
6809
+ async run(input2, options) {
4089
6810
  const executionId = `exec_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
4090
6811
  if (this.mode !== "run") {
4091
6812
  return {
@@ -4100,11 +6821,11 @@ var require = __neckbeard_createRequire(import.meta.url);
4100
6821
  const connection = await this.resolveRuntimeConnection(options?.sandboxId);
4101
6822
  let validatedInput;
4102
6823
  try {
4103
- validatedInput = this.inputSchema.parse(input);
6824
+ validatedInput = this.inputSchema.parse(input2);
4104
6825
  } catch (error) {
4105
6826
  throw new ValidationError("Input validation failed.", asError(error));
4106
6827
  }
4107
- const { invokeServer } = await import("./invoke-client-P2CPBYTF.js");
6828
+ const { invokeServer } = await import("./invoke-client-QB2NTZ3L.js");
4108
6829
  let output;
4109
6830
  let sawOutput = false;
4110
6831
  for await (const event of invokeServer(validatedInput, {
@@ -4139,7 +6860,7 @@ var require = __neckbeard_createRequire(import.meta.url);
4139
6860
  }
4140
6861
  return { ok: true, executionId, output: validated };
4141
6862
  } catch (err) {
4142
- const { InvokeHttpError } = await import("./invoke-client-P2CPBYTF.js");
6863
+ const { InvokeHttpError } = await import("./invoke-client-QB2NTZ3L.js");
4143
6864
  if (err instanceof InvokeHttpError && err.status === 409) {
4144
6865
  return { ok: false, executionId, error: new RuntimeBusyError(err.message) };
4145
6866
  }
@@ -4185,7 +6906,7 @@ var require = __neckbeard_createRequire(import.meta.url);
4185
6906
  }
4186
6907
  if (durability !== void 0 && durability !== "attached") {
4187
6908
  throw new ConfigurationError(
4188
- "LegacyBundledAgent.createSession() creates caller-owned attached sessions. Gateway-owned durable sessions use the deprecated agent-neckbeard/supervisor APIs."
6909
+ "LegacyBundledAgent.createSession() creates caller-owned attached sessions. Durable sessions are no longer supported."
4189
6910
  );
4190
6911
  }
4191
6912
  if (requestedSandboxId !== void 0 && (typeof requestedSandboxId !== "string" || requestedSandboxId.trim() === "")) {
@@ -4204,21 +6925,21 @@ var require = __neckbeard_createRequire(import.meta.url);
4204
6925
  }
4205
6926
  return createAttachedAgentSession({
4206
6927
  sandboxId,
4207
- runPrompt: (input, signal2) => this.streamSessionPrompt(input, sandboxId, signal2),
6928
+ runPrompt: (input2, signal2) => this.streamSessionPrompt(input2, sandboxId, signal2),
4208
6929
  ...signal === void 0 ? {} : { externalSignal: signal },
4209
- configurationError: (message) => new ConfigurationError(message),
6930
+ configurationError: (message2) => new ConfigurationError(message2),
4210
6931
  abortError: abortSignalError
4211
6932
  });
4212
6933
  }
4213
- async *streamSessionPrompt(input, sandboxId, signal) {
6934
+ async *streamSessionPrompt(input2, sandboxId, signal) {
4214
6935
  const connection = await this.resolveRuntimeConnection(sandboxId, {
4215
6936
  signal,
4216
6937
  reuseMatchingCachedConnection: true
4217
6938
  });
4218
- const { invokeServer, InvokeHttpError } = await import("./invoke-client-P2CPBYTF.js");
6939
+ const { invokeServer, InvokeHttpError } = await import("./invoke-client-QB2NTZ3L.js");
4219
6940
  let validated;
4220
6941
  try {
4221
- validated = this.inputSchema.parse(input);
6942
+ validated = this.inputSchema.parse(input2);
4222
6943
  } catch (error) {
4223
6944
  throw new ValidationError("Input validation failed.", asError(error));
4224
6945
  }
@@ -4298,13 +7019,13 @@ var require = __neckbeard_createRequire(import.meta.url);
4298
7019
  * This compatibility wrapper creates one attached session, streams one turn,
4299
7020
  * and closes the local handle afterward.
4300
7021
  */
4301
- async *invoke(input, options) {
7022
+ async *invoke(input2, options) {
4302
7023
  const session = await this.createSession({
4303
7024
  ...options?.sandboxId === void 0 ? {} : { sandboxId: options.sandboxId },
4304
7025
  ...options?.signal === void 0 ? {} : { signal: options.signal }
4305
7026
  });
4306
7027
  try {
4307
- yield* session.prompt(input);
7028
+ yield* session.prompt(input2);
4308
7029
  } finally {
4309
7030
  await session.close();
4310
7031
  }
@@ -4312,22 +7033,25 @@ var require = __neckbeard_createRequire(import.meta.url);
4312
7033
  };
4313
7034
 
4314
7035
  export {
7036
+ resolveImageTag,
7037
+ TURN_PROTOCOL_VERSION,
7038
+ RemoteAdmissionRejected,
7039
+ RemoteSubmissionNotFound,
4315
7040
  Agent,
4316
7041
  BRAINTRUST_PACKAGE,
4317
7042
  BRAINTRUST_VERSIONS,
4318
7043
  isSupportedBraintrustVersion,
4319
7044
  SKILLS_DIR,
4320
- resolveImageTag,
4321
- PI_PACKAGE,
7045
+ DefinedHostAgent,
4322
7046
  DefinedAgent,
4323
7047
  defineAgent,
4324
7048
  isDefinedAgent,
4325
7049
  NeckbeardError,
4326
7050
  DeploymentError,
7051
+ SandboxGoneError,
4327
7052
  ValidationError,
4328
7053
  ExecutionError,
4329
7054
  RuntimeBusyError,
4330
- TurnLostError,
4331
7055
  ConfigurationError,
4332
7056
  resolveAgentSourceFile,
4333
7057
  withNeckbeardNextConfig,