agent-neckbeard 1.1.18 → 1.1.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -30,6 +30,18 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
30
30
  ));
31
31
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
32
 
33
+ // src/serialized-error.ts
34
+ function isSerializedError(value) {
35
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
36
+ const candidate = value;
37
+ return typeof candidate.message === "string" && (candidate.name === void 0 || typeof candidate.name === "string") && (candidate.stack === void 0 || typeof candidate.stack === "string");
38
+ }
39
+ var init_serialized_error = __esm({
40
+ "src/serialized-error.ts"() {
41
+ "use strict";
42
+ }
43
+ });
44
+
33
45
  // src/runtime/protocol.ts
34
46
  function isHarnessEvent(value) {
35
47
  if (!value || typeof value !== "object") return false;
@@ -66,18 +78,11 @@ function hasValidMetadata(candidate) {
66
78
  }
67
79
  return true;
68
80
  }
69
- function isSerializedError(value) {
70
- if (!value || typeof value !== "object") return false;
71
- const candidate = value;
72
- if (typeof candidate.message !== "string") return false;
73
- if (candidate.name !== void 0 && typeof candidate.name !== "string") return false;
74
- if (candidate.stack !== void 0 && typeof candidate.stack !== "string") return false;
75
- return true;
76
- }
77
81
  var RUNTIME_PROTOCOL_VERSION;
78
82
  var init_protocol = __esm({
79
83
  "src/runtime/protocol.ts"() {
80
84
  "use strict";
85
+ init_serialized_error();
81
86
  RUNTIME_PROTOCOL_VERSION = 1;
82
87
  }
83
88
  });
@@ -211,39 +216,3045 @@ async function* invokeServer(input, options) {
211
216
  yield rawEvent;
212
217
  }
213
218
  }
214
- }
215
- var init_invoke_client = __esm({
216
- "src/invoke-client.ts"() {
217
- "use strict";
218
- init_sse_framing();
219
- init_protocol();
219
+ }
220
+ var init_invoke_client = __esm({
221
+ "src/invoke-client.ts"() {
222
+ "use strict";
223
+ init_sse_framing();
224
+ init_protocol();
225
+ }
226
+ });
227
+
228
+ // src/index.ts
229
+ var src_exports = {};
230
+ __export(src_exports, {
231
+ Agent: () => Agent,
232
+ ConfigurationError: () => ConfigurationError,
233
+ DEFAULT_DEPENDENCIES: () => DEFAULT_DEPENDENCIES,
234
+ DeploymentError: () => DeploymentError,
235
+ ExecutionError: () => ExecutionError,
236
+ NeckbeardError: () => NeckbeardError,
237
+ SandboxClient: () => SandboxClient,
238
+ ValidationError: () => ValidationError,
239
+ normalizeStackFramePath: () => normalizeStackFramePath,
240
+ resolveAgentSourceFile: () => resolveAgentSourceFile,
241
+ withNeckbeardNextConfig: () => withNeckbeardNextConfig
242
+ });
243
+ module.exports = __toCommonJS(src_exports);
244
+ var import_node_url = require("url");
245
+ var import_node_fs = require("fs");
246
+ var import_node_path = require("path");
247
+ var import_node_module = require("module");
248
+ init_protocol();
249
+
250
+ // src/runtime/server-source.generated.ts
251
+ var RUNTIME_SERVER_SOURCE = '// src/runtime/server.ts\nimport { createServer } from "node:http";\nimport { readFileSync } from "node:fs";\nimport { fileURLToPath } from "node:url";\nimport { dirname, join } from "node:path";\nimport { once } from "node:events";\n\n// src/serialized-error.ts\nfunction serializeError(error) {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n ...error.stack === void 0 ? {} : { stack: error.stack }\n };\n }\n return { message: String(error) };\n}\n\n// src/runtime/protocol.ts\nvar RUNTIME_PROTOCOL_VERSION = 1;\n\n// src/timeout.ts\nfunction settleOperation(operation, options = {}) {\n const { abort, timeout } = options;\n if (abort?.signal.aborted) throw abort.createError();\n if (!abort && !timeout) {\n try {\n return Promise.resolve(operation());\n } catch (error) {\n return Promise.reject(error);\n }\n }\n return new Promise((resolve, reject) => {\n let settled = false;\n let timer;\n const cleanup = () => {\n if (timer !== void 0) {\n clearTimeout(timer);\n timer = void 0;\n }\n abort?.signal.removeEventListener("abort", onAbort);\n };\n const settle = (callback) => {\n if (settled) return;\n settled = true;\n cleanup();\n callback();\n };\n const onAbort = () => settle(() => reject(abort.createError()));\n abort?.signal.addEventListener("abort", onAbort, { once: true });\n if (timeout) {\n timer = setTimeout(\n () => settle(() => reject(timeout.createError())),\n timeout.timeoutMs\n );\n }\n let task;\n try {\n task = operation();\n } catch (error) {\n settle(() => reject(error));\n return;\n }\n void Promise.resolve(task).then(\n (value) => settle(() => resolve(value)),\n (error) => settle(() => reject(error))\n );\n });\n}\n\n// src/runtime/server.ts\nvar CONFIG_PATH = join(dirname(fileURLToPath(import.meta.url)), "server-config.json");\nvar CONFIG = JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));\nvar MAX_REQUEST_BODY_BYTES = 4 * 1024 * 1024;\nvar DEFAULT_SSE_HEARTBEAT_INTERVAL_MS = 15e3;\nvar RequestBodyTooLargeError = class extends Error {\n constructor(limitBytes) {\n super(`request body exceeds ${limitBytes} bytes`);\n this.name = "RequestBodyTooLargeError";\n }\n};\nfunction createLogger() {\n return {\n debug: (message, ...args) => console.log("[DEBUG]", message, ...args),\n info: (message, ...args) => console.log("[INFO]", message, ...args),\n warn: (message, ...args) => console.warn("[WARN]", message, ...args),\n error: (message, ...args) => console.error("[ERROR]", message, ...args)\n };\n}\nfunction sendJson(res, status, body) {\n res.writeHead(status, { "content-type": "application/json" });\n res.end(JSON.stringify(body));\n}\nfunction getSseHeartbeatIntervalMs() {\n const raw = process.env.NECKBEARD_RUNTIME_SSE_HEARTBEAT_MS;\n if (!raw) return DEFAULT_SSE_HEARTBEAT_INTERVAL_MS;\n const parsed = Number(raw);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_SSE_HEARTBEAT_INTERVAL_MS;\n}\nfunction sendSseComment(res, comment) {\n if (res.writableEnded || res.destroyed) return;\n res.write(`: ${comment}\n\n`);\n}\nasync function sendSseFrame(res, event) {\n const canContinue = res.write(`data: ${JSON.stringify(event)}\n\n`);\n if (!canContinue) {\n await once(res, "drain");\n }\n}\nasync function readRequestBody(req, maxBytes = MAX_REQUEST_BODY_BYTES) {\n const chunks = [];\n let totalBytes = 0;\n for await (const chunk of req) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n totalBytes += buffer.byteLength;\n if (totalBytes > maxBytes) {\n throw new RequestBodyTooLargeError(maxBytes);\n }\n chunks.push(buffer);\n }\n return Buffer.concat(chunks).toString("utf-8");\n}\nfunction createTimeoutError(maxDurationMs) {\n const error = new Error(`Agent invocation exceeded maxDuration (${maxDurationMs}ms)`);\n error.name = "TimeoutError";\n return error;\n}\nasync function rejectOnAbort(operation, signal, maxDurationMs) {\n return settleOperation(operation, {\n abort: {\n signal,\n createError: () => createTimeoutError(maxDurationMs)\n }\n });\n}\nasync function loadAgent() {\n const mod = await import(new URL("./agent.mjs", import.meta.url).href);\n const agent = (mod.default && (mod.default._run || mod.default._server) ? mod.default : null) || Object.values(mod).find(\n (value) => value && typeof value === "object" && ("_run" in value || "_server" in value)\n );\n if (!agent || typeof agent !== "object") {\n throw new Error(\n `No agent found in agent.mjs. Exports: ${Object.keys(mod).join(", ")}`\n );\n }\n return agent;\n}\nasync function main() {\n const agent = await loadAgent();\n const server = createServer(async (req, res) => {\n try {\n const url = new URL(req.url ?? "/", "http://localhost");\n if (url.pathname === "/health" && req.method === "GET") {\n return sendJson(res, 200, {\n ok: true,\n protocolVersion: RUNTIME_PROTOCOL_VERSION\n });\n }\n if (url.pathname === "/shutdown" && req.method === "POST") {\n sendJson(res, 200, { ok: true });\n setTimeout(() => shutdown(), 10).unref();\n return;\n }\n if (url.pathname === "/invoke" && req.method === "POST") {\n let rawBody;\n try {\n rawBody = await readRequestBody(req);\n } catch (error) {\n if (error instanceof RequestBodyTooLargeError) {\n return sendJson(res, 413, { error: error.message });\n }\n throw error;\n }\n let requestBody;\n try {\n requestBody = JSON.parse(rawBody);\n } catch {\n return sendJson(res, 400, { error: "invalid JSON body" });\n }\n if (!requestBody || typeof requestBody !== "object" || typeof requestBody.invocationId !== "string") {\n return sendJson(res, 400, { error: "invalid invoke request" });\n }\n let validatedInput;\n try {\n validatedInput = agent.inputSchema.parse(requestBody.input);\n } catch (error) {\n return sendJson(res, 400, {\n error: `input validation failed: ${serializeError(error).message}`\n });\n }\n res.writeHead(200, {\n "content-type": "text/event-stream",\n "cache-control": "no-cache, no-transform",\n connection: "keep-alive",\n "x-accel-buffering": "no"\n });\n const controller = new AbortController();\n req.on("aborted", () => controller.abort());\n res.on("close", () => {\n if (!res.writableEnded) {\n controller.abort();\n }\n });\n const startedAt = Date.now();\n let sequence = 0;\n const timeout = setTimeout(() => controller.abort(), CONFIG.maxDurationMs);\n const invocationId = requestBody.invocationId;\n const heartbeat = setInterval(() => {\n try {\n sendSseComment(res, `heartbeat ${Date.now()}`);\n } catch {\n controller.abort();\n }\n }, getSseHeartbeatIntervalMs());\n heartbeat.unref();\n const emitHarnessEvent = async (event) => {\n if (!res.writableEnded) {\n await sendSseFrame(res, {\n protocolVersion: RUNTIME_PROTOCOL_VERSION,\n sequence: sequence++,\n timestamp: (/* @__PURE__ */ new Date()).toISOString(),\n elapsedMs: Date.now() - startedAt,\n ...event\n });\n }\n };\n const ctx = {\n executionId: invocationId,\n signal: controller.signal,\n env: process.env,\n sandbox: CONFIG.sandboxContext,\n logger: createLogger()\n };\n try {\n await emitHarnessEvent({ kind: "started", invocationId });\n if (agent._server) {\n await rejectOnAbort(\n () => agent._server.handler({\n input: validatedInput,\n ctx,\n signal: controller.signal,\n emit: async (data) => {\n const validatedFrame = agent._server?.frameSchema ? agent._server.frameSchema.parse(data) : data;\n await emitHarnessEvent({ kind: "frame", invocationId, data: validatedFrame });\n }\n }),\n controller.signal,\n CONFIG.maxDurationMs\n );\n } else if (agent._run) {\n const output = await rejectOnAbort(\n () => agent._run(validatedInput, ctx),\n controller.signal,\n CONFIG.maxDurationMs\n );\n const validatedOutput = agent.outputSchema ? agent.outputSchema.parse(output) : output;\n await emitHarnessEvent({ kind: "output", invocationId, output: validatedOutput });\n } else {\n throw new Error("Agent has neither a run handler nor a server handler.");\n }\n await emitHarnessEvent({ kind: "done", invocationId });\n } catch (error) {\n await emitHarnessEvent({ kind: "error", invocationId, error: serializeError(error) });\n } finally {\n clearInterval(heartbeat);\n clearTimeout(timeout);\n if (!res.writableEnded) {\n res.end();\n }\n }\n return;\n }\n return sendJson(res, 404, { error: "not found" });\n } catch (error) {\n console.error("[neckbeard-server] unexpected error", error);\n if (!res.headersSent) {\n sendJson(res, 500, { error: "internal error" });\n } else if (!res.writableEnded) {\n res.end();\n }\n }\n });\n function shutdown() {\n console.log("[neckbeard-server] shutting down");\n server.close(() => process.exit(0));\n setTimeout(() => process.exit(0), 5e3).unref();\n }\n server.listen(CONFIG.port, "0.0.0.0", () => {\n console.log(`[neckbeard-server] listening on port ${CONFIG.port}`);\n });\n process.on("SIGTERM", shutdown);\n process.on("SIGINT", shutdown);\n}\nmain().catch((error) => {\n console.error("[neckbeard-server] failed to start", error);\n process.exit(1);\n});\n';
252
+
253
+ // src/sandbox-capabilities.ts
254
+ var SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV = "NECKBEARD_SUPERVISOR_ENVIRONMENT_V1";
255
+ var SUPERVISOR_ENVIRONMENT_FD_ENV = "NECKBEARD_SUPERVISOR_ENVIRONMENT_FD";
256
+ var SUPERVISOR_ENVIRONMENT_FD = 3;
257
+ var SUPERVISOR_ENVIRONMENT_MAX_BYTES = 64 * 1024;
258
+ var SUPERVISOR_ENVIRONMENT_MAX_ENTRIES = 256;
259
+ var SUPERVISOR_ENVIRONMENT_MAX_NAME_BYTES = 256;
260
+ var SUPERVISOR_ENVIRONMENT_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/u;
261
+ function supervisorEnvironmentByteLength(value) {
262
+ return new TextEncoder().encode(value).byteLength;
263
+ }
264
+ function isRecord(value) {
265
+ if (typeof value !== "object" || value === null) return false;
266
+ try {
267
+ return !Array.isArray(value);
268
+ } catch {
269
+ return false;
270
+ }
271
+ }
272
+ function normalizeSupervisorEnvironment(value) {
273
+ if (!isRecord(value)) return { ok: false, reason: "invalid_environment" };
274
+ let entries;
275
+ try {
276
+ entries = Object.entries(value).sort(
277
+ ([left], [right]) => left < right ? -1 : left > right ? 1 : 0
278
+ );
279
+ } catch {
280
+ return { ok: false, reason: "invalid_environment" };
281
+ }
282
+ if (entries.length > SUPERVISOR_ENVIRONMENT_MAX_ENTRIES) {
283
+ return { ok: false, reason: "entry_limit" };
284
+ }
285
+ const environment = /* @__PURE__ */ Object.create(null);
286
+ let environmentBytes = 0;
287
+ let exceedsByteLimit = false;
288
+ for (const [name, item] of entries) {
289
+ if (name.length > SUPERVISOR_ENVIRONMENT_MAX_NAME_BYTES || !SUPERVISOR_ENVIRONMENT_NAME_PATTERN.test(name) || name === SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV || name === SUPERVISOR_ENVIRONMENT_FD_ENV) {
290
+ return { ok: false, reason: "invalid_name" };
291
+ }
292
+ if (typeof item !== "string" || item.includes("\0")) {
293
+ return { ok: false, reason: "invalid_value" };
294
+ }
295
+ if (!exceedsByteLimit) {
296
+ if (item.length > SUPERVISOR_ENVIRONMENT_MAX_BYTES || environmentBytes + name.length + item.length > SUPERVISOR_ENVIRONMENT_MAX_BYTES) {
297
+ exceedsByteLimit = true;
298
+ } else {
299
+ environmentBytes += name.length + supervisorEnvironmentByteLength(item);
300
+ if (environmentBytes > SUPERVISOR_ENVIRONMENT_MAX_BYTES) {
301
+ exceedsByteLimit = true;
302
+ }
303
+ }
304
+ }
305
+ environment[name] = item;
306
+ }
307
+ if (exceedsByteLimit) return { ok: false, reason: "byte_limit" };
308
+ return {
309
+ ok: true,
310
+ environment,
311
+ environmentKeys: entries.map(([name]) => name)
312
+ };
313
+ }
314
+ function serializeSupervisorEnvironmentHandoff(value, defaults) {
315
+ let normalized = normalizeSupervisorEnvironment(value);
316
+ if (!normalized.ok) return normalized;
317
+ if (defaults !== void 0) {
318
+ const normalizedDefaults = normalizeSupervisorEnvironment(defaults);
319
+ if (!normalizedDefaults.ok) return normalizedDefaults;
320
+ const environment = Object.assign(
321
+ /* @__PURE__ */ Object.create(null),
322
+ normalizedDefaults.environment,
323
+ normalized.environment
324
+ );
325
+ normalized = normalizeSupervisorEnvironment(environment);
326
+ if (!normalized.ok) return normalized;
327
+ }
328
+ let payload;
329
+ try {
330
+ payload = JSON.stringify({ version: 1, environment: normalized.environment });
331
+ } catch {
332
+ return { ok: false, reason: "serialization_failed" };
333
+ }
334
+ if (payload.length > SUPERVISOR_ENVIRONMENT_MAX_BYTES || supervisorEnvironmentByteLength(payload) > SUPERVISOR_ENVIRONMENT_MAX_BYTES) {
335
+ return { ok: false, reason: "byte_limit" };
336
+ }
337
+ return { ...normalized, payload };
338
+ }
339
+ function normalizeProviderSandboxDetachedCommandOptions(value, failure, policy = {}) {
340
+ if (policy.requireObject) {
341
+ try {
342
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
343
+ throw new Error("invalid detached command options");
344
+ }
345
+ } catch {
346
+ throw failure("Detached command options could not be inspected.");
347
+ }
348
+ }
349
+ let cwd;
350
+ let rawEnvironment;
351
+ let launchId;
352
+ let beforeRelease;
353
+ let environmentMode;
354
+ let environmentRevision;
355
+ let restartReleasedWhenExited;
356
+ try {
357
+ cwd = Reflect.get(value, "cwd");
358
+ rawEnvironment = Reflect.get(value, "envs");
359
+ launchId = Reflect.get(value, "launchId");
360
+ beforeRelease = Reflect.get(value, "beforeRelease");
361
+ environmentMode = Reflect.get(value, "environmentMode");
362
+ environmentRevision = Reflect.get(value, "environmentRevision");
363
+ restartReleasedWhenExited = Reflect.get(
364
+ value,
365
+ "restartReleasedWhenExited"
366
+ );
367
+ } catch {
368
+ throw failure("Detached command options could not be inspected.");
369
+ }
370
+ if (cwd !== void 0 && typeof cwd !== "string") {
371
+ throw failure("Detached command cwd must be a string when provided.");
372
+ }
373
+ if (policy.validateBeforeRelease && beforeRelease !== void 0 && typeof beforeRelease !== "function") {
374
+ throw failure("Detached command beforeRelease must be a function.");
375
+ }
376
+ const options = {
377
+ cwd,
378
+ envs: rawEnvironment,
379
+ launchId,
380
+ beforeRelease,
381
+ environmentMode,
382
+ environmentRevision,
383
+ restartReleasedWhenExited
384
+ };
385
+ return {
386
+ options,
387
+ environment: {
388
+ environmentMode,
389
+ environmentRevision,
390
+ restartReleasedWhenExited,
391
+ rawEnvironment
392
+ }
393
+ };
394
+ }
395
+
396
+ // src/attached-session.ts
397
+ function linkAbortSignals(signals) {
398
+ const controller = new AbortController();
399
+ const listeners = /* @__PURE__ */ new Map();
400
+ const abortFrom = (signal) => {
401
+ if (!controller.signal.aborted) controller.abort(signal.reason);
402
+ };
403
+ for (const signal of signals) {
404
+ if (signal.aborted) {
405
+ abortFrom(signal);
406
+ break;
407
+ }
408
+ const listener = () => abortFrom(signal);
409
+ listeners.set(signal, listener);
410
+ signal.addEventListener("abort", listener, { once: true });
411
+ }
412
+ return {
413
+ signal: controller.signal,
414
+ dispose: () => {
415
+ for (const [signal, listener] of listeners) {
416
+ signal.removeEventListener("abort", listener);
417
+ }
418
+ listeners.clear();
419
+ }
420
+ };
421
+ }
422
+ var AttachedAgentSessionImpl = class {
423
+ durability = "attached";
424
+ sandboxId;
425
+ lifetime = new AbortController();
426
+ runPrompt;
427
+ configurationError;
428
+ activeTurn = null;
429
+ externalSignal = null;
430
+ externalAbortListener = null;
431
+ isClosed = false;
432
+ closePromise = null;
433
+ constructor(options) {
434
+ this.sandboxId = options.sandboxId;
435
+ this.runPrompt = options.runPrompt;
436
+ this.configurationError = options.configurationError;
437
+ const { externalSignal } = options;
438
+ if (externalSignal?.aborted) {
439
+ this.isClosed = true;
440
+ this.lifetime.abort(externalSignal.reason);
441
+ } else if (externalSignal) {
442
+ this.externalSignal = externalSignal;
443
+ this.externalAbortListener = () => {
444
+ void this.closeWithReason(externalSignal.reason);
445
+ };
446
+ externalSignal.addEventListener("abort", this.externalAbortListener, { once: true });
447
+ }
448
+ }
449
+ get closed() {
450
+ return this.isClosed;
451
+ }
452
+ prompt(input) {
453
+ return this.runTurn(input);
454
+ }
455
+ async stop(reason = "attached_session_stopped") {
456
+ await this.stopActiveTurn(reason);
457
+ }
458
+ close() {
459
+ return this.closeWithReason("attached_session_closed");
460
+ }
461
+ async *runTurn(input) {
462
+ if (this.isClosed || this.lifetime.signal.aborted) {
463
+ throw this.configurationError("Attached session is closed.");
464
+ }
465
+ if (this.activeTurn) {
466
+ throw this.configurationError("Attached session already has an active turn.");
467
+ }
468
+ const controller = new AbortController();
469
+ const linked = linkAbortSignals([this.lifetime.signal, controller.signal]);
470
+ const iterator = this.runPrompt(input, linked.signal);
471
+ const turn = {
472
+ controller,
473
+ iterator,
474
+ dispose: linked.dispose
475
+ };
476
+ this.activeTurn = turn;
477
+ try {
478
+ while (true) {
479
+ const next = await iterator.next();
480
+ if (next.done) return;
481
+ yield next.value;
482
+ }
483
+ } finally {
484
+ controller.abort("attached_turn_closed");
485
+ await iterator.return(void 0).catch(() => void 0);
486
+ turn.dispose();
487
+ if (this.activeTurn === turn) this.activeTurn = null;
488
+ }
489
+ }
490
+ async stopActiveTurn(reason) {
491
+ const turn = this.activeTurn;
492
+ if (!turn) return;
493
+ turn.controller.abort(reason);
494
+ await turn.iterator.return(void 0).catch(() => void 0);
495
+ turn.dispose();
496
+ if (this.activeTurn === turn) this.activeTurn = null;
497
+ }
498
+ closeWithReason(reason) {
499
+ if (this.closePromise) return this.closePromise;
500
+ this.closePromise = Promise.resolve().then(() => this.finishClose(reason));
501
+ this.isClosed = true;
502
+ this.lifetime.abort(reason);
503
+ return this.closePromise;
504
+ }
505
+ async finishClose(reason) {
506
+ await this.stopActiveTurn(reason);
507
+ if (this.externalSignal && this.externalAbortListener) {
508
+ this.externalSignal.removeEventListener("abort", this.externalAbortListener);
509
+ }
510
+ this.externalSignal = null;
511
+ this.externalAbortListener = null;
512
+ }
513
+ };
514
+ function createAttachedAgentSession(options) {
515
+ return new AttachedAgentSessionImpl(options);
516
+ }
517
+
518
+ // src/shell.ts
519
+ function shellQuote(value) {
520
+ return `'${value.replace(/'/g, `'\\''`)}'`;
521
+ }
522
+
523
+ // src/providers/detached-process.ts
524
+ var import_node_buffer = require("buffer");
525
+ var import_node_crypto = require("crypto");
526
+ var DETACHED_PROCESS_ROOT = "/tmp/agent-neckbeard-detached";
527
+ var DETACHED_PROCESS_CONTROL_TIMEOUT_MS = 3e4;
528
+ var DETACHED_PROCESS_LOG_MAX_BYTES = 8 * 1024 * 1024;
529
+ var DETACHED_PROCESS_CONTROL_OUTPUT_MAX_BYTES = 64 * 1024;
530
+ var DETACHED_PROCESS_LOG_ENVELOPE_MAX_BYTES = 256 + 8 * Math.ceil(DETACHED_PROCESS_LOG_MAX_BYTES / 3);
531
+ var DETACHED_PROCESS_TRUSTED_PATH = "/usr/local/share/nvm/current/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
532
+ var DETACHED_PROCESS_LIFECYCLE_ENVIRONMENT = {
533
+ PATH: DETACHED_PROCESS_TRUSTED_PATH,
534
+ HOME: "/tmp",
535
+ TMPDIR: "/tmp",
536
+ LANG: "C.UTF-8"
537
+ };
538
+ var DETACHED_PROCESS_PROVIDER_CONTROL_ENVIRONMENT = Object.freeze({
539
+ ...DETACHED_PROCESS_LIFECYCLE_ENVIRONMENT,
540
+ HOME: "/nonexistent",
541
+ BASH_ENV: "/dev/null",
542
+ ENV: "/dev/null",
543
+ SHELLOPTS: "",
544
+ BASHOPTS: "",
545
+ PS4: "+ ",
546
+ BASH_XTRACEFD: ""
547
+ });
548
+ var DETACHED_PROCESS_LOG_CHUNK_BYTES = 64 * 1024;
549
+ var DETACHED_PROCESS_LOG_SEGMENT_BYTES = DETACHED_PROCESS_LOG_MAX_BYTES / 2 - DETACHED_PROCESS_LOG_CHUNK_BYTES;
550
+ var DETACHED_PROCESS_LOG_SNAPSHOT_MAX_BYTES = 96;
551
+ var DETACHED_PROCESS_LEGACY_LOG_SNAPSHOT_ATTEMPTS = 100;
552
+ var IDENTITY_PREFIX = "NECKBEARD_PROCESS_V3";
553
+ var LEGACY_IDENTITY_PREFIX = "NECKBEARD_PROCESS_V2";
554
+ var DECISION_PREFIX = "NECKBEARD_DECISION_V1";
555
+ var STARTED_PREFIX = "NECKBEARD_STARTED_V1";
556
+ var QUIESCENT_PREFIX = "NECKBEARD_QUIESCENT_V1";
557
+ var PREPARED_SENTINEL = "NECKBEARD_DETACHED_PREPARED";
558
+ var RELEASED_SENTINEL = "NECKBEARD_DETACHED_RELEASED";
559
+ var RELEASED_GENERATION_UNAVAILABLE_SENTINEL = "NECKBEARD_DETACHED_RELEASED_GENERATION_UNAVAILABLE";
560
+ var CANCELLED_SENTINEL = "NECKBEARD_DETACHED_CANCELLED";
561
+ var STOPPED_SENTINEL = "NECKBEARD_DETACHED_STOPPED";
562
+ var DISPOSED_SENTINEL = "NECKBEARD_DETACHED_ARTIFACTS_DISPOSED";
563
+ var LOGS_PREFIX = "NECKBEARD_DETACHED_LOGS_V1";
564
+ var LEGACY_LOG_SNAPSHOT_PREFIX = "NECKBEARD_LOG_SNAPSHOT_V1";
565
+ var LOG_SNAPSHOT_PREFIX = "NECKBEARD_LOG_SNAPSHOT_V2";
566
+ var DESCRIPTOR_MISMATCH_SENTINEL = "NECKBEARD_DETACHED_DESCRIPTOR_MISMATCH";
567
+ var HASH_PATTERN = "[a-f0-9]{64}";
568
+ var PREPARED_PATTERN = new RegExp(
569
+ `^${PREPARED_SENTINEL} (\\d+) (\\d+) (\\d+) (${HASH_PATTERN})$`,
570
+ "u"
571
+ );
572
+ var RELEASED_PATTERN = new RegExp(
573
+ `^${RELEASED_SENTINEL} (\\d+) (\\d+) (\\d+) (${HASH_PATTERN})$`,
574
+ "u"
575
+ );
576
+ var HANDLE_PATTERN = new RegExp(
577
+ `^(daytona|e2b)-process-v2:(\\d+):(\\d+):(\\d+):(${HASH_PATTERN}):(${HASH_PATTERN})$`,
578
+ "u"
579
+ );
580
+ function boundDetachedProcessLog(value) {
581
+ const candidate = value.length > DETACHED_PROCESS_LOG_MAX_BYTES ? value.slice(-DETACHED_PROCESS_LOG_MAX_BYTES) : value;
582
+ const bytes = Buffer.from(candidate, "utf8");
583
+ if (bytes.byteLength <= DETACHED_PROCESS_LOG_MAX_BYTES) return candidate;
584
+ let offset = bytes.byteLength - DETACHED_PROCESS_LOG_MAX_BYTES;
585
+ while (offset < bytes.byteLength && ((bytes[offset] ?? 0) & 192) === 128) {
586
+ offset += 1;
587
+ }
588
+ return bytes.subarray(offset).toString("utf8");
589
+ }
590
+ var DETACHED_PROCESS_LAUNCH_CANCELLED_MARKER = /* @__PURE__ */ Symbol.for(
591
+ "agent-neckbeard.detached-process-launch-cancelled.v1"
592
+ );
593
+ var DETACHED_PROCESS_RELEASED_GENERATION_UNAVAILABLE_MARKER = /* @__PURE__ */ Symbol.for(
594
+ "agent-neckbeard.detached-process-released-generation-unavailable.v1"
595
+ );
596
+ var DetachedProcessLaunchCancelledError = class extends Error {
597
+ name = "DetachedProcessLaunchCancelledError";
598
+ [DETACHED_PROCESS_LAUNCH_CANCELLED_MARKER] = true;
599
+ constructor() {
600
+ super("Detached process launch was cancelled before release.");
601
+ }
602
+ };
603
+ var DetachedProcessReleasedGenerationUnavailableError = class extends Error {
604
+ name = "DetachedProcessReleasedGenerationUnavailableError";
605
+ [DETACHED_PROCESS_RELEASED_GENERATION_UNAVAILABLE_MARKER] = true;
606
+ constructor() {
607
+ super("Detached released process generation is unavailable.");
608
+ }
609
+ };
610
+ function markDetachedProcessLaunchCancelled(error) {
611
+ return markDetachedProcessError(error, DETACHED_PROCESS_LAUNCH_CANCELLED_MARKER);
612
+ }
613
+ function markDetachedProcessReleasedGenerationUnavailable(error) {
614
+ return markDetachedProcessError(
615
+ error,
616
+ DETACHED_PROCESS_RELEASED_GENERATION_UNAVAILABLE_MARKER
617
+ );
618
+ }
619
+ function markDetachedProcessError(error, marker) {
620
+ if (typeof error !== "object" && typeof error !== "function" || error === null) {
621
+ return error;
622
+ }
623
+ try {
624
+ Reflect.defineProperty(error, marker, {
625
+ configurable: false,
626
+ enumerable: false,
627
+ value: true,
628
+ writable: false
629
+ });
630
+ } catch {
631
+ }
632
+ return error;
633
+ }
634
+ function messageFrom(error) {
635
+ return error instanceof Error ? error.message : String(error);
636
+ }
637
+ function hash(parts) {
638
+ return (0, import_node_crypto.createHash)("sha256").update(JSON.stringify(parts), "utf8").digest("hex");
639
+ }
640
+ function detachedEnvironmentFailureMessage(boundary, reason) {
641
+ const subject = `${boundary} environment`;
642
+ if (reason === "entry_limit") return `${subject} exceeds the entry limit.`;
643
+ if (reason === "invalid_name") {
644
+ return `${subject} contains an invalid or reserved name.`;
645
+ }
646
+ if (reason === "invalid_value") return `${subject} contains an invalid value.`;
647
+ if (reason === "byte_limit") return `${subject} exceeds the byte limit.`;
648
+ if (reason === "invalid_environment" && boundary === "Detached command") {
649
+ return `${subject} could not be inspected.`;
650
+ }
651
+ return `${subject} could not be serialized.`;
652
+ }
653
+ function serializeDetachedEnvironment(value, boundary, defaults) {
654
+ const handoff = serializeSupervisorEnvironmentHandoff(
655
+ value === void 0 ? {} : value,
656
+ defaults
657
+ );
658
+ if (!handoff.ok) {
659
+ throw new Error(detachedEnvironmentFailureMessage(boundary, handoff.reason));
660
+ }
661
+ return handoff;
662
+ }
663
+ function createDetachedEnvironmentTransport(options, genericPayloadEnvironmentDefaults) {
664
+ const {
665
+ environmentMode: mode,
666
+ environmentRevision,
667
+ restartReleasedWhenExited,
668
+ rawEnvironment
669
+ } = options;
670
+ const hasSupervisorControl = mode !== void 0 || environmentRevision !== void 0 || restartReleasedWhenExited !== void 0;
671
+ if (!hasSupervisorControl) {
672
+ const handoff2 = serializeDetachedEnvironment(
673
+ rawEnvironment,
674
+ "Detached command",
675
+ genericPayloadEnvironmentDefaults
676
+ );
677
+ return {
678
+ mode: "exec",
679
+ providerEnvironment: {
680
+ ...DETACHED_PROCESS_PROVIDER_CONTROL_ENVIRONMENT,
681
+ [SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV]: handoff2.payload
682
+ },
683
+ environmentKeys: handoff2.environmentKeys
684
+ };
685
+ }
686
+ if (mode !== "supervisor-fd-v1" || typeof environmentRevision !== "string" || !/^[a-f0-9]{64}$/u.test(environmentRevision) || restartReleasedWhenExited !== true) {
687
+ throw new Error(
688
+ "Supervisor detached commands require FD mode, a lowercase SHA-256 environment revision, and exited-generation restart control."
689
+ );
690
+ }
691
+ const handoff = serializeDetachedEnvironment(rawEnvironment, "Supervisor");
692
+ return {
693
+ mode: "supervisor-fd-v1",
694
+ providerEnvironment: {
695
+ ...DETACHED_PROCESS_PROVIDER_CONTROL_ENVIRONMENT,
696
+ [SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV]: handoff.payload
697
+ },
698
+ environmentKeys: handoff.environmentKeys,
699
+ environmentRevision
700
+ };
701
+ }
702
+ function createDetachedLaunchDescriptor(command, cwd, environment, restartReleasedWhenExited = false) {
703
+ return hash([
704
+ "detached-command-v2",
705
+ command,
706
+ cwd ?? null,
707
+ environment?.mode ?? "exec",
708
+ ...environment?.environmentKeys ?? [],
709
+ ...environment?.environmentRevision === void 0 ? [] : ["environment-revision-v1", environment.environmentRevision],
710
+ ...restartReleasedWhenExited ? ["replacement-policy-v1"] : []
711
+ ]);
712
+ }
713
+ function createDetachedLaunchPaths(launchId) {
714
+ const semanticId = launchId === void 0 ? (0, import_node_crypto.randomUUID)() : launchId;
715
+ if (typeof semanticId !== "string" || !semanticId || semanticId.length > 512) {
716
+ throw new Error("Detached command launchId must contain between 1 and 512 characters.");
717
+ }
718
+ const launchKey = hash(["detached-launch-v1", semanticId]);
719
+ return pathsForLaunchKey(launchKey);
720
+ }
721
+ function pathsForLaunchKey(launchKey) {
722
+ const directory = `${DETACHED_PROCESS_ROOT}/${launchKey}`;
723
+ return detachedLaunchPathsForDirectory(
724
+ launchKey,
725
+ directory,
726
+ `${DETACHED_PROCESS_ROOT}/${launchKey}.lock`,
727
+ `${DETACHED_PROCESS_ROOT}/.${launchKey}.retired`
728
+ );
729
+ }
730
+ function detachedLaunchPathsForDirectory(launchKey, directory, controlLock, retiredDirectory) {
731
+ return {
732
+ launchKey,
733
+ directory,
734
+ record: `${directory}/identity`,
735
+ recordPartial: `${directory}/.identity.partial`,
736
+ decision: `${directory}/decision`,
737
+ releaseDecisionPartial: `${directory}/.release-decision.partial`,
738
+ cancelDecisionPartial: `${directory}/.cancel-decision.partial`,
739
+ started: `${directory}/started`,
740
+ startedPartial: `${directory}/.started.partial`,
741
+ quiescent: `${directory}/quiescent`,
742
+ controlLock,
743
+ retiredDirectory,
744
+ stdout: `${directory}/stdout.log`,
745
+ stderr: `${directory}/stderr.log`
746
+ };
747
+ }
748
+ function pathsForDetachedLaunchDirectory(paths, directory) {
749
+ return detachedLaunchPathsForDirectory(
750
+ paths.launchKey,
751
+ directory,
752
+ paths.controlLock,
753
+ paths.retiredDirectory
754
+ );
755
+ }
756
+ function parseIdentityOutput(pattern, provider, paths, descriptorKey, output) {
757
+ const match = pattern.exec(output.trim());
758
+ if (!match) return null;
759
+ const [, pid, startTicks, sessionId, returnedDescriptor] = match;
760
+ if (!pid || !startTicks || !sessionId || !returnedDescriptor || pid !== sessionId || returnedDescriptor !== descriptorKey) {
761
+ return null;
762
+ }
763
+ return { provider, pid, startTicks, sessionId, launchKey: paths.launchKey, descriptorKey };
764
+ }
765
+ function parsePreparedIdentity(provider, paths, descriptorKey, output) {
766
+ return parseIdentityOutput(PREPARED_PATTERN, provider, paths, descriptorKey, output);
767
+ }
768
+ function parseReleasedIdentity(provider, paths, descriptorKey, output) {
769
+ return parseIdentityOutput(RELEASED_PATTERN, provider, paths, descriptorKey, output);
770
+ }
771
+ function isDescriptorMismatch(output) {
772
+ return output.trim() === DESCRIPTOR_MISMATCH_SENTINEL;
773
+ }
774
+ function formatDetachedCommand(identity) {
775
+ return {
776
+ sessionId: `${identity.provider}-process-v2:${identity.pid}:${identity.startTicks}:${identity.sessionId}:${identity.launchKey}:${identity.descriptorKey}`,
777
+ commandId: identity.pid
778
+ };
779
+ }
780
+ function parseDetachedCommand(sessionId) {
781
+ const match = HANDLE_PATTERN.exec(sessionId);
782
+ if (!match) return null;
783
+ const [, provider, pid, startTicks, processSessionId, launchKey, descriptorKey] = match;
784
+ if (provider !== "daytona" && provider !== "e2b" || !pid || !startTicks || !processSessionId || !launchKey || !descriptorKey || pid !== processSessionId) {
785
+ return null;
786
+ }
787
+ return {
788
+ provider,
789
+ pid,
790
+ startTicks,
791
+ sessionId: processSessionId,
792
+ launchKey,
793
+ descriptorKey
794
+ };
795
+ }
796
+ function hasDetachedProcessV2Prefix(sessionId) {
797
+ return /^(?:daytona|e2b)-process-v2/u.test(sessionId);
798
+ }
799
+ function detachedProcessProviderName(provider) {
800
+ return provider === "daytona" ? "Daytona" : "E2B";
801
+ }
802
+ function resolveDetachedCommandForProvider(sessionId, expectedProvider, failure, commandId) {
803
+ const identity = parseDetachedCommand(sessionId);
804
+ if (identity?.provider === expectedProvider) {
805
+ if (commandId !== void 0 && commandId !== identity.pid) {
806
+ throw failure(
807
+ `Detached process handle is invalid for ${detachedProcessProviderName(expectedProvider)}.`
808
+ );
809
+ }
810
+ return identity;
811
+ }
812
+ if (identity || hasDetachedProcessV2Prefix(sessionId)) {
813
+ throw failure(
814
+ `Detached process handle is invalid for ${detachedProcessProviderName(expectedProvider)}.`
815
+ );
816
+ }
817
+ return null;
818
+ }
819
+ function pathsForIdentity(identity) {
820
+ return pathsForLaunchKey(identity.launchKey);
821
+ }
822
+ function disposedDirectoryForIdentity(identity) {
823
+ const disposalKey = hash([
824
+ "detached-disposal-v1",
825
+ identity.provider,
826
+ identity.pid,
827
+ identity.startTicks,
828
+ identity.sessionId,
829
+ identity.launchKey,
830
+ identity.descriptorKey
831
+ ]);
832
+ return `${DETACHED_PROCESS_ROOT}/.${identity.launchKey}.${disposalKey}.disposed`;
833
+ }
834
+ var DetachedProcessController = class {
835
+ constructor(options) {
836
+ this.options = options;
837
+ }
838
+ get providerName() {
839
+ return detachedProcessProviderName(this.options.provider);
840
+ }
841
+ resolve(command) {
842
+ return resolveDetachedCommandForProvider(
843
+ command.sessionId,
844
+ this.options.provider,
845
+ this.options.failure,
846
+ command.commandId
847
+ );
848
+ }
849
+ async executeControl(command, options, stdoutMaxBytes = DETACHED_PROCESS_CONTROL_OUTPUT_MAX_BYTES) {
850
+ try {
851
+ const response = await this.options.execute(command, {
852
+ ...options,
853
+ envs: options?.envs ?? {
854
+ ...DETACHED_PROCESS_PROVIDER_CONTROL_ENVIRONMENT
855
+ }
856
+ });
857
+ if (!response || typeof response !== "object") {
858
+ throw new Error("invalid detached control response");
859
+ }
860
+ const state = Reflect.get(response, "state");
861
+ if (state === "failed") {
862
+ return {
863
+ state: "failed",
864
+ error: new Error(`${this.providerName} detached command control request failed.`)
865
+ };
866
+ }
867
+ if (state !== "completed") {
868
+ throw new Error("invalid detached control response");
869
+ }
870
+ const result = Reflect.get(response, "result");
871
+ if (!result || typeof result !== "object") {
872
+ throw new Error("invalid detached control result");
873
+ }
874
+ const exitCode = Reflect.get(result, "exitCode");
875
+ const stdout = Reflect.get(result, "stdout");
876
+ const stderr = Reflect.get(result, "stderr");
877
+ 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) {
878
+ throw new Error("invalid detached control result");
879
+ }
880
+ return {
881
+ state: "completed",
882
+ result: { exitCode, stdout, stderr }
883
+ };
884
+ } catch {
885
+ return {
886
+ state: "failed",
887
+ error: new Error(`${this.providerName} detached command control request failed.`)
888
+ };
889
+ }
890
+ }
891
+ async start(command, options = {}) {
892
+ if (typeof command !== "string") {
893
+ throw this.options.failure("Detached command must be a string.");
894
+ }
895
+ const normalized = normalizeProviderSandboxDetachedCommandOptions(
896
+ options,
897
+ this.options.failure,
898
+ { validateBeforeRelease: true }
899
+ );
900
+ const inspectedOptions = normalized.options;
901
+ const environment = createDetachedEnvironmentTransport(
902
+ normalized.environment,
903
+ this.options.genericPayloadEnvironmentDefaults
904
+ );
905
+ const protectProviderDiagnostics = environment.mode === "supervisor-fd-v1";
906
+ const restartReleasedWhenExited = protectProviderDiagnostics;
907
+ const paths = createDetachedLaunchPaths(inspectedOptions.launchId);
908
+ const descriptorKey = createDetachedLaunchDescriptor(
909
+ command,
910
+ inspectedOptions.cwd,
911
+ environment,
912
+ restartReleasedWhenExited
913
+ );
914
+ const identity = await this.prepareWithAdoption(
915
+ command,
916
+ paths,
917
+ descriptorKey,
918
+ inspectedOptions,
919
+ environment,
920
+ restartReleasedWhenExited
921
+ );
922
+ const detached = formatDetachedCommand(identity);
923
+ try {
924
+ await inspectedOptions.beforeRelease?.(detached);
925
+ } catch (error) {
926
+ const resolution2 = await this.cancelOrAdopt(
927
+ paths,
928
+ descriptorKey,
929
+ identity,
930
+ "Detached command preparation callback failed",
931
+ error,
932
+ protectProviderDiagnostics,
933
+ restartReleasedWhenExited
934
+ );
935
+ if (resolution2.state === "cancelled") {
936
+ throw markDetachedProcessLaunchCancelled(error);
937
+ }
938
+ if (resolution2.state === "released_generation_unavailable") {
939
+ throw markDetachedProcessReleasedGenerationUnavailable(error);
940
+ }
941
+ throw error;
942
+ }
943
+ let releaseFailure;
944
+ for (let attempt = 0; attempt < 2; attempt += 1) {
945
+ const release = await this.executeControl(
946
+ buildReleaseDetachedCommand(paths, identity, restartReleasedWhenExited)
947
+ );
948
+ if (release.state === "completed" && release.result.exitCode === 0 && isReleaseConfirmation(release.result.stdout, identity)) {
949
+ return detached;
950
+ }
951
+ if (restartReleasedWhenExited && release.state === "completed" && release.result.exitCode === 0 && release.result.stdout.trim() === RELEASED_GENERATION_UNAVAILABLE_SENTINEL) {
952
+ throw new DetachedProcessReleasedGenerationUnavailableError();
953
+ }
954
+ if (release.state === "failed") {
955
+ releaseFailure = protectProviderDiagnostics ? new Error(`${this.providerName} supervisor detached command release failed.`) : new Error(`${this.providerName} detached command release failed.`);
956
+ } else if (protectProviderDiagnostics) {
957
+ releaseFailure = new Error(
958
+ `${this.providerName} did not confirm supervisor detached command release.`
959
+ );
960
+ } else {
961
+ releaseFailure = new Error(`${this.providerName} did not confirm detached command release.`);
962
+ }
963
+ }
964
+ const resolution = await this.cancelOrAdopt(
965
+ paths,
966
+ descriptorKey,
967
+ identity,
968
+ `${this.providerName} detached command release was uncertain`,
969
+ releaseFailure,
970
+ protectProviderDiagnostics,
971
+ restartReleasedWhenExited
972
+ );
973
+ if (resolution.state === "released") return formatDetachedCommand(resolution.identity);
974
+ const failedRelease = this.options.failure(
975
+ protectProviderDiagnostics ? `${this.providerName} detached command release failed: ${messageFrom(releaseFailure)}` : `${this.providerName} detached command release failed.`
976
+ );
977
+ throw resolution.state === "released_generation_unavailable" ? markDetachedProcessReleasedGenerationUnavailable(failedRelease) : markDetachedProcessLaunchCancelled(failedRelease);
978
+ }
979
+ async prepareWithAdoption(command, paths, descriptorKey, options, environment, restartReleasedWhenExited) {
980
+ let failure;
981
+ for (let attempt = 0; attempt < 2; attempt += 1) {
982
+ await this.options.beforePrepareMutation?.();
983
+ const prepared = await this.executeControl(
984
+ buildPrepareDetachedCommand(
985
+ paths,
986
+ descriptorKey,
987
+ command,
988
+ environment.mode,
989
+ restartReleasedWhenExited
990
+ ),
991
+ { cwd: options.cwd, envs: environment.providerEnvironment }
992
+ );
993
+ if (prepared.state === "failed") {
994
+ failure = environment.mode === "supervisor-fd-v1" ? new Error(`${this.providerName} supervisor environment handoff failed.`) : new Error(`${this.providerName} detached command preparation failed.`);
995
+ continue;
996
+ }
997
+ const { result } = prepared;
998
+ const identity = result.exitCode === 0 ? parsePreparedIdentity(this.options.provider, paths, descriptorKey, result.stdout) : null;
999
+ if (identity) return identity;
1000
+ if (isDescriptorMismatch(result.stdout)) {
1001
+ throw this.options.failure(
1002
+ "Detached command launchId is already bound to a different launch descriptor."
1003
+ );
1004
+ }
1005
+ if (environment.mode === "supervisor-fd-v1") {
1006
+ failure = new Error(
1007
+ `${this.providerName} did not confirm the supervisor environment handoff.`
1008
+ );
1009
+ } else {
1010
+ failure = new Error(`${this.providerName} did not confirm detached command preparation.`);
1011
+ }
1012
+ }
1013
+ const resolution = await this.cancelOrAdopt(
1014
+ paths,
1015
+ descriptorKey,
1016
+ void 0,
1017
+ `${this.providerName} detached command preparation was uncertain`,
1018
+ failure,
1019
+ environment.mode === "supervisor-fd-v1",
1020
+ restartReleasedWhenExited
1021
+ );
1022
+ if (resolution.state === "released") return resolution.identity;
1023
+ const failedPreparation = this.options.failure(
1024
+ environment.mode === "supervisor-fd-v1" ? `Failed to prepare detached ${this.providerName} process: ${messageFrom(failure)}` : `Failed to prepare detached ${this.providerName} process.`
1025
+ );
1026
+ throw resolution.state === "released_generation_unavailable" ? markDetachedProcessReleasedGenerationUnavailable(failedPreparation) : markDetachedProcessLaunchCancelled(failedPreparation);
1027
+ }
1028
+ async cancelOrAdopt(paths, descriptorKey, identity, context, cause, protectProviderDiagnostics = false, serializeGenerationChanges = false) {
1029
+ let cleanupFailure;
1030
+ for (let attempt = 0; attempt < 2; attempt += 1) {
1031
+ if (identity === void 0) {
1032
+ await this.options.beforePrepareMutation?.();
1033
+ }
1034
+ const stopped = await this.executeControl(
1035
+ buildCancelDetachedCommand(
1036
+ paths,
1037
+ descriptorKey,
1038
+ identity,
1039
+ serializeGenerationChanges
1040
+ )
1041
+ );
1042
+ if (stopped.state === "failed") {
1043
+ cleanupFailure = protectProviderDiagnostics ? new Error(`${this.providerName} supervisor detached command cleanup failed.`) : new Error(`${this.providerName} detached command cleanup failed.`);
1044
+ continue;
1045
+ }
1046
+ const { result } = stopped;
1047
+ const parsedResolution = result.exitCode === 0 ? parseCancellationResult(
1048
+ this.options.provider,
1049
+ paths,
1050
+ descriptorKey,
1051
+ result.stdout
1052
+ ) : null;
1053
+ const resolution = parsedResolution?.state === "released_generation_unavailable" && !serializeGenerationChanges ? null : parsedResolution;
1054
+ if (resolution) return resolution;
1055
+ if (isDescriptorMismatch(result.stdout)) {
1056
+ throw this.options.failure(
1057
+ "Detached command launchId is already bound to a different launch descriptor."
1058
+ );
1059
+ }
1060
+ cleanupFailure = protectProviderDiagnostics ? new Error(`${this.providerName} did not confirm supervisor detached command cleanup.`) : new Error(`${this.providerName} did not confirm detached command cleanup.`);
1061
+ }
1062
+ throw this.options.failure(
1063
+ protectProviderDiagnostics ? `${context}: ${messageFrom(cause)}. Cleanup could not be confirmed: ${messageFrom(cleanupFailure)}` : `${context}. Cleanup could not be confirmed.`
1064
+ );
1065
+ }
1066
+ async stop(command) {
1067
+ const identity = this.resolve(command);
1068
+ if (!identity) return this.options.stopLegacy(command);
1069
+ for (let attempt = 0; attempt < 2; attempt += 1) {
1070
+ await this.options.beforeStopOrDisposeMutation?.();
1071
+ const stopped = await this.executeControl(
1072
+ buildStopDetachedCommand(pathsForIdentity(identity), identity)
1073
+ );
1074
+ if (stopped.state === "failed") {
1075
+ continue;
1076
+ }
1077
+ if (stopped.result.exitCode === 0 && isStopConfirmation(stopped.result.stdout)) return;
1078
+ }
1079
+ throw this.options.failure(`Failed to stop detached ${this.providerName} process.`);
1080
+ }
1081
+ /**
1082
+ * Irreversibly removes the private lifecycle state and diagnostics for one
1083
+ * exact managed generation. This is deliberately separate from `stop()`:
1084
+ * callers must first obtain exact stop confirmation and perform any final
1085
+ * diagnostic read they need.
1086
+ */
1087
+ async dispose(command) {
1088
+ const identity = this.resolve(command);
1089
+ if (!identity) {
1090
+ throw this.options.failure(
1091
+ `Detached ${this.providerName} artifact disposal requires a managed process handle.`
1092
+ );
1093
+ }
1094
+ for (let attempt = 0; attempt < 2; attempt += 1) {
1095
+ await this.options.beforeStopOrDisposeMutation?.();
1096
+ const disposed = await this.executeControl(
1097
+ buildDisposeDetachedArtifactsCommand(pathsForIdentity(identity), identity)
1098
+ );
1099
+ if (disposed.state === "failed") continue;
1100
+ if (disposed.result.exitCode === 0 && isDisposeConfirmation(disposed.result.stdout)) {
1101
+ return;
1102
+ }
1103
+ }
1104
+ throw this.options.failure(
1105
+ `Failed to dispose detached ${this.providerName} process artifacts.`
1106
+ );
1107
+ }
1108
+ async readLogs(command) {
1109
+ const identity = this.resolve(command);
1110
+ if (!identity) return this.options.readLegacyLogs(command);
1111
+ const read = await this.executeControl(
1112
+ buildReadDetachedLogsCommand(identity),
1113
+ void 0,
1114
+ DETACHED_PROCESS_LOG_ENVELOPE_MAX_BYTES
1115
+ );
1116
+ if (read.state !== "completed" || read.result.exitCode !== 0) {
1117
+ return { stdout: "", stderr: "" };
1118
+ }
1119
+ return parseDetachedProcessLogs(read.result.stdout) ?? { stdout: "", stderr: "" };
1120
+ }
1121
+ };
1122
+ function processStatParserFunctions() {
1123
+ return [
1124
+ "read_process_stat_file() {",
1125
+ " proc_stat_raw=",
1126
+ " proc_stat_separator=",
1127
+ " proc_stat_seen=no",
1128
+ " proc_stat_newline=$(printf '\\n_') || return 1",
1129
+ " proc_stat_newline=${proc_stat_newline%_}",
1130
+ " {",
1131
+ " while :; do",
1132
+ " proc_stat_line=",
1133
+ " IFS= read -r proc_stat_line",
1134
+ " proc_stat_read_status=$?",
1135
+ ' if [ "$proc_stat_read_status" -ne 0 ] && [ -z "$proc_stat_line" ]; then break; fi',
1136
+ ' proc_stat_raw="${proc_stat_raw}${proc_stat_separator}${proc_stat_line}"',
1137
+ " proc_stat_separator=$proc_stat_newline",
1138
+ " proc_stat_seen=yes",
1139
+ ' [ "$proc_stat_read_status" -eq 0 ] || break',
1140
+ ' done < "$1"',
1141
+ " } 2>/dev/null",
1142
+ ' [ "$proc_stat_seen" = yes ]',
1143
+ "}",
1144
+ "parse_process_stat() {",
1145
+ " proc_stat_fields=${1##*) }",
1146
+ " proc_stat_index=1",
1147
+ " proc_stat_state=",
1148
+ " proc_stat_pgrp=",
1149
+ " proc_stat_session=",
1150
+ " proc_stat_ticks=",
1151
+ ' while [ "$proc_stat_index" -le 20 ]; do',
1152
+ ' case "$proc_stat_fields" in',
1153
+ " *' '*) proc_stat_field=${proc_stat_fields%% *}; proc_stat_fields=${proc_stat_fields#* } ;;",
1154
+ " *) proc_stat_field=$proc_stat_fields; proc_stat_fields= ;;",
1155
+ " esac",
1156
+ ' [ -n "$proc_stat_field" ] || return 1',
1157
+ ' case "$proc_stat_index" in',
1158
+ " 1) proc_stat_state=$proc_stat_field ;;",
1159
+ " 3) proc_stat_pgrp=$proc_stat_field ;;",
1160
+ " 4) proc_stat_session=$proc_stat_field ;;",
1161
+ " 20) proc_stat_ticks=$proc_stat_field ;;",
1162
+ " esac",
1163
+ " proc_stat_index=$((proc_stat_index + 1))",
1164
+ " done",
1165
+ ' [ -n "$proc_stat_state" ] && [ -n "$proc_stat_pgrp" ] && [ -n "$proc_stat_session" ] && [ -n "$proc_stat_ticks" ]',
1166
+ "}"
1167
+ ];
1168
+ }
1169
+ function identityFunctions(paths) {
1170
+ return [
1171
+ ...processStatParserFunctions(),
1172
+ "read_launch_identity() {",
1173
+ ...assertSafeRegularFile(paths.record).map((line) => ` ${line}`),
1174
+ ` [ -s ${shellQuote(paths.record)} ] || return 1`,
1175
+ ` identity=$(cat ${shellQuote(paths.record)}) || return 1`,
1176
+ ` identity_prefix=$(printf '%s\\n' "$identity" | awk 'NF == 5 { print $1 }')`,
1177
+ ` target_pid=$(printf '%s\\n' "$identity" | awk 'NF == 5 && $2 ~ /^[0-9]+$/ { print $2 }')`,
1178
+ ` target_ticks=$(printf '%s\\n' "$identity" | awk 'NF == 5 && $3 ~ /^[0-9]+$/ { print $3 }')`,
1179
+ ` target_session=$(printf '%s\\n' "$identity" | awk 'NF == 5 && $4 ~ /^[0-9]+$/ { print $4 }')`,
1180
+ ` target_descriptor=$(printf '%s\\n' "$identity" | awk 'NF == 5 && $5 ~ /^[a-f0-9]+$/ { print $5 }')`,
1181
+ ' case "$identity_prefix" in',
1182
+ ` ${IDENTITY_PREFIX}) target_reaper_protocol=v3 ;;`,
1183
+ ` ${LEGACY_IDENTITY_PREFIX}) target_reaper_protocol=v2 ;;`,
1184
+ " *) return 1 ;;",
1185
+ " esac",
1186
+ ' [ -n "$target_pid" ] && [ -n "$target_ticks" ] && [ "$target_pid" = "$target_session" ] && [ ${#target_descriptor} -eq 64 ]',
1187
+ "}",
1188
+ "leader_identity_status() {",
1189
+ ' read_process_stat_file "/proc/$target_pid/stat" || return 1',
1190
+ ' parse_process_stat "$proc_stat_raw" || return 1',
1191
+ " state=$proc_stat_state",
1192
+ " pgrp=$proc_stat_pgrp",
1193
+ " current_session=$proc_stat_session",
1194
+ " current_ticks=$proc_stat_ticks",
1195
+ ' [ "$current_ticks" = "$target_ticks" ] && [ "$pgrp" = "$target_pid" ] && [ "$current_session" = "$target_session" ] || return 2',
1196
+ ' [ "$state" != "Z" ] || return 1',
1197
+ " return 0",
1198
+ "}"
1199
+ ];
1200
+ }
1201
+ function decisionFunctions(paths) {
1202
+ return [
1203
+ "read_launch_decision() {",
1204
+ ...assertSafeRegularFile(paths.decision).map((line) => ` ${line}`),
1205
+ ` [ -s ${shellQuote(paths.decision)} ] || return 1`,
1206
+ ` decision=$(cat ${shellQuote(paths.decision)}) || return 1`,
1207
+ ` decision_prefix=$(printf '%s\\n' "$decision" | awk 'NF == 6 { print $1 }')`,
1208
+ ` decision_action=$(printf '%s\\n' "$decision" | awk 'NF == 6 { print $2 }')`,
1209
+ ` decision_pid=$(printf '%s\\n' "$decision" | awk 'NF == 6 && $3 ~ /^[0-9]+$/ { print $3 }')`,
1210
+ ` decision_ticks=$(printf '%s\\n' "$decision" | awk 'NF == 6 && $4 ~ /^[0-9]+$/ { print $4 }')`,
1211
+ ` decision_session=$(printf '%s\\n' "$decision" | awk 'NF == 6 && $5 ~ /^[0-9]+$/ { print $5 }')`,
1212
+ ` decision_descriptor=$(printf '%s\\n' "$decision" | awk 'NF == 6 && $6 ~ /^[a-f0-9]+$/ { print $6 }')`,
1213
+ ` [ "$decision_prefix" = ${shellQuote(DECISION_PREFIX)} ] || return 1`,
1214
+ ' case "$decision_action" in RELEASE|CANCEL) ;; *) return 1 ;; esac',
1215
+ ' [ -n "$decision_pid" ] && [ -n "$decision_ticks" ] && [ -n "$decision_session" ] && [ ${#decision_descriptor} -eq 64 ]',
1216
+ "}",
1217
+ "read_started_identity() {",
1218
+ ...assertSafeRegularFile(paths.started).map((line) => ` ${line}`),
1219
+ ` [ -s ${shellQuote(paths.started)} ] || return 1`,
1220
+ ` started=$(cat ${shellQuote(paths.started)}) || return 1`,
1221
+ ` started_prefix=$(printf '%s\\n' "$started" | awk 'NF == 5 { print $1 }')`,
1222
+ ` started_pid=$(printf '%s\\n' "$started" | awk 'NF == 5 && $2 ~ /^[0-9]+$/ { print $2 }')`,
1223
+ ` started_ticks=$(printf '%s\\n' "$started" | awk 'NF == 5 && $3 ~ /^[0-9]+$/ { print $3 }')`,
1224
+ ` started_session=$(printf '%s\\n' "$started" | awk 'NF == 5 && $4 ~ /^[0-9]+$/ { print $4 }')`,
1225
+ ` started_descriptor=$(printf '%s\\n' "$started" | awk 'NF == 5 && $5 ~ /^[a-f0-9]+$/ { print $5 }')`,
1226
+ ` [ "$started_prefix" = ${shellQuote(STARTED_PREFIX)} ] || return 1`,
1227
+ ' [ "$started_pid:$started_ticks:$started_session:$started_descriptor" = "$decision_pid:$decision_ticks:$decision_session:$decision_descriptor" ]',
1228
+ "}"
1229
+ ];
1230
+ }
1231
+ function exactLifecycleMarkerFunction(functionName, variablePrefix, path, expectation) {
1232
+ const quotedPath = shellQuote(path);
1233
+ const missingMarker = expectation.kind === "populated" ? [
1234
+ ` if [ ! -e ${quotedPath} ] && [ ! -L ${quotedPath} ]; then return 1; fi`
1235
+ ] : [];
1236
+ const expectedMarker = expectation.kind === "populated" ? [
1237
+ ` ${variablePrefix}_expected="${expectation.markerPrefix} $target_pid $target_ticks $target_session $target_descriptor"`,
1238
+ ` ${variablePrefix}_expected_size=$((\${#${variablePrefix}_expected} + 1))`
1239
+ ] : [];
1240
+ const expectedSize = expectation.kind === "populated" ? `$${variablePrefix}_expected_size` : "0";
1241
+ const exactContentProof = expectation.kind === "populated" ? [
1242
+ ` printf '%s\\n' "$${variablePrefix}_expected" | cmp -s - /proc/self/fd/8 || { exec 8<&-; return 2; }`
1243
+ ] : [];
1244
+ return [
1245
+ `${functionName}() {`,
1246
+ ...missingMarker,
1247
+ ` [ -f ${quotedPath} ] && [ ! -L ${quotedPath} ] || return 2`,
1248
+ ...expectedMarker,
1249
+ ` ${variablePrefix}_path_metadata=$(stat -c %u:%a:%h:%s ${quotedPath} 2>/dev/null) || return 2`,
1250
+ ` [ "$${variablePrefix}_path_metadata" = "$(id -u):600:1:${expectedSize}" ] || return 2`,
1251
+ ` exec 8<${quotedPath} || return 2`,
1252
+ ` ${variablePrefix}_descriptor_metadata=$(stat -Lc %u:%a:%h:%s /proc/self/fd/8 2>/dev/null) || { exec 8<&-; return 2; }`,
1253
+ ` [ "$${variablePrefix}_descriptor_metadata" = "$${variablePrefix}_path_metadata" ] || { exec 8<&-; return 2; }`,
1254
+ ` ${variablePrefix}_path_inode=$(stat -c %d:%i ${quotedPath} 2>/dev/null) || { exec 8<&-; return 2; }`,
1255
+ ` ${variablePrefix}_descriptor_inode=$(stat -Lc %d:%i /proc/self/fd/8 2>/dev/null) || { exec 8<&-; return 2; }`,
1256
+ ` [ "$${variablePrefix}_descriptor_inode" = "$${variablePrefix}_path_inode" ] || { exec 8<&-; return 2; }`,
1257
+ ...exactContentProof,
1258
+ ` ${variablePrefix}_path_metadata_after=$(stat -c %u:%a:%h:%s ${quotedPath} 2>/dev/null) || { exec 8<&-; return 2; }`,
1259
+ ` ${variablePrefix}_path_inode_after=$(stat -c %d:%i ${quotedPath} 2>/dev/null) || { exec 8<&-; return 2; }`,
1260
+ ` ${variablePrefix}_descriptor_metadata_after=$(stat -Lc %u:%a:%h:%s /proc/self/fd/8 2>/dev/null) || { exec 8<&-; return 2; }`,
1261
+ ` ${variablePrefix}_descriptor_inode_after=$(stat -Lc %d:%i /proc/self/fd/8 2>/dev/null) || { exec 8<&-; return 2; }`,
1262
+ " exec 8<&-",
1263
+ ` [ "$${variablePrefix}_path_metadata_after:$${variablePrefix}_path_inode_after" = "$${variablePrefix}_descriptor_metadata_after:$${variablePrefix}_descriptor_inode_after" ] || return 2`,
1264
+ ` [ "$${variablePrefix}_path_metadata_after:$${variablePrefix}_path_inode_after" = "$${variablePrefix}_path_metadata:$${variablePrefix}_path_inode" ] || return 2`,
1265
+ " return 0",
1266
+ "}"
1267
+ ];
1268
+ }
1269
+ function processTreeFunctions(paths) {
1270
+ const liveness = paths === void 0 ? [
1271
+ // Pre-V2 provider handles have no durable reaper proof. Preserve
1272
+ // their documented best-effort session scan without using it for a
1273
+ // current V3 generation.
1274
+ "target_has_live_processes() {",
1275
+ " for stat_path in /proc/[0-9]*/stat; do",
1276
+ " assert_no_pid_reuse || return 2",
1277
+ ' read_process_stat_file "$stat_path" || continue',
1278
+ ' parse_process_stat "$proc_stat_raw" || continue',
1279
+ " state=$proc_stat_state",
1280
+ " process_session=$proc_stat_session",
1281
+ ' [ "$process_session" = "$target_session" ] && [ "$state" != "Z" ] && return 0',
1282
+ " done",
1283
+ " return 1",
1284
+ "}",
1285
+ "assert_no_pid_reuse() {",
1286
+ " leader_identity_status",
1287
+ " identity_status=$?",
1288
+ ' [ "$identity_status" -ne 2 ]',
1289
+ "}"
1290
+ ] : [
1291
+ ...exactLifecycleMarkerFunction(
1292
+ "read_exact_started_marker",
1293
+ "exact_started",
1294
+ paths.started,
1295
+ { kind: "populated", markerPrefix: STARTED_PREFIX }
1296
+ ),
1297
+ ...exactLifecycleMarkerFunction(
1298
+ "read_exact_quiescent_marker",
1299
+ "exact_quiescent",
1300
+ paths.quiescent,
1301
+ { kind: "populated", markerPrefix: QUIESCENT_PREFIX }
1302
+ ),
1303
+ "target_has_live_processes() {",
1304
+ " leader_identity_status",
1305
+ " target_leader_status=$?",
1306
+ ' [ "$target_leader_status" -ne 0 ] || return 0',
1307
+ " read_exact_started_marker",
1308
+ " target_started_status=$?",
1309
+ ' if [ "$target_leader_status" -eq 2 ]; then',
1310
+ ' if [ "$target_reaper_protocol" = v3 ] && [ "$target_started_status" -eq 1 ]; then',
1311
+ " return 1",
1312
+ " fi",
1313
+ ' if [ "$target_reaper_protocol" = v3 ] && [ "$target_started_status" -eq 0 ]; then',
1314
+ " read_exact_quiescent_marker",
1315
+ ' [ "$?" -eq 0 ] && return 1',
1316
+ " fi",
1317
+ " return 2",
1318
+ " fi",
1319
+ ' case "$target_started_status" in',
1320
+ " 1) return 1 ;;",
1321
+ " 2) return 2 ;;",
1322
+ " esac",
1323
+ ' [ "$target_reaper_protocol" = v3 ] || return 2',
1324
+ " read_exact_quiescent_marker",
1325
+ ' [ "$?" -eq 0 ] && return 1',
1326
+ " return 2",
1327
+ "}"
1328
+ ];
1329
+ return [
1330
+ ...liveness,
1331
+ "signal_target_session() {",
1332
+ " signal_name=$1",
1333
+ ` PATH=${shellQuote(DETACHED_PROCESS_TRUSTED_PATH)}`,
1334
+ " export PATH",
1335
+ " command -v python3 >/dev/null 2>&1 || return 1",
1336
+ " preserve_target_leader=no",
1337
+ ...paths === void 0 ? [] : [
1338
+ ' if [ "$target_reaper_protocol" = v3 ]; then',
1339
+ " read_exact_started_marker",
1340
+ " target_started_status=$?",
1341
+ ' [ "$target_started_status" -ne 2 ] || return 2',
1342
+ ' [ "$target_started_status" -ne 0 ] || preserve_target_leader=yes',
1343
+ " fi"
1344
+ ],
1345
+ " # pidfds bind every candidate before its session is checked and signaled.",
1346
+ // -I excludes the caller working directory and PYTHON* settings from
1347
+ // module lookup; -S prevents sitecustomize from running before fencing.
1348
+ ` python3 -I -S - "$target_pid" "$target_ticks" "$target_session" "$signal_name" "$preserve_target_leader" <<'PY'`,
1349
+ "import os",
1350
+ "import signal",
1351
+ "import sys",
1352
+ "",
1353
+ "target_pid = int(sys.argv[1])",
1354
+ "target_ticks = int(sys.argv[2])",
1355
+ "target_session = int(sys.argv[3])",
1356
+ 'signal_value = getattr(signal, "SIG" + sys.argv[4])',
1357
+ 'preserve_target_leader = sys.argv[5] == "yes"',
1358
+ 'if not hasattr(os, "pidfd_open") or not hasattr(signal, "pidfd_send_signal"):',
1359
+ " raise SystemExit(1)",
1360
+ "",
1361
+ "def read_identity(pid):",
1362
+ " try:",
1363
+ ' with open(f"/proc/{pid}/stat", "rb") as stat_file:',
1364
+ " raw = stat_file.read()",
1365
+ " except (FileNotFoundError, ProcessLookupError):",
1366
+ " return None",
1367
+ ' marker = raw.rfind(b") ")',
1368
+ " fields = raw[marker + 2:].split() if marker >= 0 else []",
1369
+ " if len(fields) <= 19:",
1370
+ " raise SystemExit(1)",
1371
+ " return fields[0], int(fields[2]), int(fields[3]), int(fields[19])",
1372
+ "",
1373
+ "def leader_was_reused():",
1374
+ " identity = read_identity(target_pid)",
1375
+ " if identity is None:",
1376
+ " return False",
1377
+ " _state, pgrp, session_id, ticks = identity",
1378
+ " return (pgrp, session_id, ticks) != (target_pid, target_session, target_ticks)",
1379
+ "",
1380
+ 'for entry in os.scandir("/proc"):',
1381
+ " if not entry.name.isdecimal():",
1382
+ " continue",
1383
+ " pid = int(entry.name)",
1384
+ " if pid == target_pid:",
1385
+ " if preserve_target_leader:",
1386
+ " continue",
1387
+ " try:",
1388
+ " pidfd = os.pidfd_open(pid)",
1389
+ " except (PermissionError, ProcessLookupError):",
1390
+ " continue",
1391
+ " try:",
1392
+ " identity = read_identity(pid)",
1393
+ " if identity is None:",
1394
+ " continue",
1395
+ " state, _pgrp, session_id, _ticks = identity",
1396
+ ' if session_id != target_session or state == b"Z":',
1397
+ " continue",
1398
+ " if leader_was_reused():",
1399
+ " raise SystemExit(2)",
1400
+ " try:",
1401
+ " signal.pidfd_send_signal(pidfd, signal_value)",
1402
+ " except ProcessLookupError:",
1403
+ " pass",
1404
+ " finally:",
1405
+ " os.close(pidfd)",
1406
+ "PY",
1407
+ "}"
1408
+ ];
1409
+ }
1410
+ function stopTargetCommands(options) {
1411
+ const stoppedAction = options?.exitAsSoonAsStopped ? "exit 0" : "break";
1412
+ return [
1413
+ "target_has_live_processes",
1414
+ "target_status=$?",
1415
+ '[ "$target_status" -ne 2 ] || exit 2',
1416
+ ...options?.exitAsSoonAsStopped ? ['[ "$target_status" -eq 0 ] || exit 0'] : [],
1417
+ 'if [ "$target_status" -eq 0 ]; then signal_target_session TERM || exit $?; fi',
1418
+ "attempt=0",
1419
+ 'while [ "$attempt" -lt 150 ]; do',
1420
+ " target_has_live_processes",
1421
+ " target_status=$?",
1422
+ ' [ "$target_status" -ne 2 ] || exit 2',
1423
+ ` [ "$target_status" -eq 0 ] || ${stoppedAction}`,
1424
+ " sleep 0.1",
1425
+ " attempt=$((attempt + 1))",
1426
+ "done",
1427
+ 'if [ "$target_status" -eq 0 ]; then signal_target_session KILL || exit $?; fi',
1428
+ "attempt=0",
1429
+ 'while [ "$attempt" -lt 50 ]; do',
1430
+ " target_has_live_processes",
1431
+ " target_status=$?",
1432
+ ' [ "$target_status" -ne 2 ] || exit 2',
1433
+ ` [ "$target_status" -eq 0 ] || ${stoppedAction}`,
1434
+ " sleep 0.1",
1435
+ " attempt=$((attempt + 1))",
1436
+ "done",
1437
+ ...options?.failureMessage === void 0 ? ['[ "$target_status" -ne 0 ] || exit 1'] : [
1438
+ 'if [ "$target_status" -eq 0 ]; then',
1439
+ ` printf '%s\\n' ${shellQuote(options.failureMessage)} >&2`,
1440
+ " exit 1",
1441
+ "fi"
1442
+ ]
1443
+ ];
1444
+ }
1445
+ function buildLegacyDetachedStopCommand(pid, startTicks, providerName) {
1446
+ return [
1447
+ "umask 077",
1448
+ ...secureDetachedRoot(),
1449
+ `target_pid=${shellQuote(pid)}`,
1450
+ `target_ticks=${shellQuote(startTicks)}`,
1451
+ "target_session=$target_pid",
1452
+ ...processStatParserFunctions(),
1453
+ "leader_identity_status() {",
1454
+ ' read_process_stat_file "/proc/$target_pid/stat" || return 1',
1455
+ ' parse_process_stat "$proc_stat_raw" || return 1',
1456
+ " current_ticks=$proc_stat_ticks",
1457
+ ' [ "$current_ticks" = "$target_ticks" ] || return 2',
1458
+ " return 0",
1459
+ "}",
1460
+ "target_reaper_protocol=legacy",
1461
+ ...processTreeFunctions(),
1462
+ "# Revalidate the leader birth immediately before every scan and every kill.",
1463
+ ...stopTargetCommands({
1464
+ exitAsSoonAsStopped: true,
1465
+ failureMessage: `Detached ${providerName} process ${pid} did not stop.`
1466
+ })
1467
+ ].join("\n");
1468
+ }
1469
+ function atomicFile(partialPath, path, parentDirectory, write) {
1470
+ return [
1471
+ `${write} || exit 1`,
1472
+ `sync -f ${shellQuote(partialPath)} || exit 1`,
1473
+ `mv -f ${shellQuote(partialPath)} ${shellQuote(path)} || exit 1`,
1474
+ `sync -f ${shellQuote(parentDirectory)} || exit 1`
1475
+ ];
1476
+ }
1477
+ function secureDirectory(path, create) {
1478
+ return [
1479
+ ...create ? [
1480
+ `if [ ! -e ${shellQuote(path)} ] && [ ! -L ${shellQuote(path)} ]; then`,
1481
+ ` mkdir ${shellQuote(path)} 2>/dev/null || true`,
1482
+ "fi"
1483
+ ] : [],
1484
+ `[ -d ${shellQuote(path)} ] && [ ! -L ${shellQuote(path)} ] || exit 1`,
1485
+ `directory_owner=$(stat -c %u ${shellQuote(path)} 2>/dev/null) || exit 1`,
1486
+ '[ "$directory_owner" = "$(id -u)" ] || exit 1',
1487
+ `directory_mode=$(stat -c %a ${shellQuote(path)} 2>/dev/null) || exit 1`,
1488
+ '[ "$directory_mode" = 700 ] || exit 1'
1489
+ ];
1490
+ }
1491
+ function secureDetachedRoot() {
1492
+ return secureDirectory(DETACHED_PROCESS_ROOT, true);
1493
+ }
1494
+ function secureLaunchDirectory(paths, create) {
1495
+ return secureDirectory(paths.directory, create);
1496
+ }
1497
+ function assertSafeRegularFile(path) {
1498
+ return [
1499
+ `[ -e ${shellQuote(path)} ] || return 1`,
1500
+ `[ -f ${shellQuote(path)} ] && [ ! -L ${shellQuote(path)} ] || exit 1`
1501
+ ];
1502
+ }
1503
+ function publishDecision(paths, action, partialPath) {
1504
+ return [
1505
+ `printf '${DECISION_PREFIX} ${action} %s %s %s %s\\n' "$publish_pid" "$publish_ticks" "$publish_session" "$publish_descriptor" > ${shellQuote(partialPath)} || exit 1`,
1506
+ `sync -f ${shellQuote(partialPath)} || exit 1`,
1507
+ `ln ${shellQuote(partialPath)} ${shellQuote(paths.decision)} 2>/dev/null || true`,
1508
+ `rm -f ${shellQuote(partialPath)} || exit 1`,
1509
+ `sync -f ${shellQuote(paths.directory)} || exit 1`,
1510
+ "read_launch_decision || exit 1"
1511
+ ];
1512
+ }
1513
+ function waitForStarted(paths) {
1514
+ return [
1515
+ "attempt=0",
1516
+ `while [ ! -s ${shellQuote(paths.started)} ] && [ "$attempt" -lt 400 ]; do`,
1517
+ " sleep 0.05",
1518
+ " attempt=$((attempt + 1))",
1519
+ "done",
1520
+ "read_started_identity || exit 1"
1521
+ ];
1522
+ }
1523
+ function releasedAdoptionOutcome(paths, descriptorKey, serializeGenerationChanges) {
1524
+ if (!serializeGenerationChanges) {
1525
+ return [
1526
+ ...waitForStarted(paths),
1527
+ `printf '${RELEASED_SENTINEL} %s %s %s %s\\n' "$decision_pid" "$decision_ticks" "$decision_session" "$decision_descriptor"`,
1528
+ "exit 0"
1529
+ ];
1530
+ }
1531
+ return [
1532
+ // Replacement-capable adoption runs under the generation lock. Rebind the
1533
+ // durable decision to the exact current record before returning any handle.
1534
+ "read_launch_identity || exit 1",
1535
+ `[ "$target_descriptor" = ${shellQuote(descriptorKey)} ] || { printf '${DESCRIPTOR_MISMATCH_SENTINEL}\\n'; exit 2; }`,
1536
+ '[ "$decision_pid:$decision_ticks:$decision_session:$decision_descriptor" = "$target_pid:$target_ticks:$target_session:$target_descriptor" ] || exit 1',
1537
+ '[ "$target_reaper_protocol" = v3 ] || exit 1',
1538
+ ...waitForStarted(paths),
1539
+ "read_exact_started_marker || exit 1",
1540
+ "leader_identity_status",
1541
+ "released_leader_status=$?",
1542
+ 'if [ "$released_leader_status" -eq 0 ]; then',
1543
+ ` printf '${RELEASED_SENTINEL} %s %s %s %s\\n' "$decision_pid" "$decision_ticks" "$decision_session" "$decision_descriptor"`,
1544
+ " exit 0",
1545
+ "fi",
1546
+ // Exact quiescence is recoverable by retrying the same deterministic
1547
+ // launch. Any absent or ambiguous proof after exact STARTED is a distinct
1548
+ // reset-required outcome, never a stale released-handle adoption.
1549
+ "read_exact_quiescent_marker",
1550
+ "released_quiescent_status=$?",
1551
+ '[ "$released_quiescent_status" -ne 0 ] || exit 1',
1552
+ `printf '${RELEASED_GENERATION_UNAVAILABLE_SENTINEL}\\n'`,
1553
+ "exit 0"
1554
+ ];
1555
+ }
1556
+ function renderShellLockAssertion(options) {
1557
+ const { functionName, variablePrefix, path, descriptorFd } = options;
1558
+ const pathExpression = shellQuote(path);
1559
+ const descriptorPathExpression = `/proc/self/fd/${descriptorFd}`;
1560
+ const descriptorChecks = [
1561
+ `[ -f ${descriptorPathExpression} ] || return 1`,
1562
+ `${variablePrefix}_descriptor_metadata=$(stat -Lc %u:%a:%h:%s ${descriptorPathExpression} 2>/dev/null) || return 1`,
1563
+ `[ "$${variablePrefix}_descriptor_metadata" = "$${variablePrefix}_path_metadata" ] || return 1`,
1564
+ `${variablePrefix}_path_inode=$(stat -c %d:%i ${pathExpression} 2>/dev/null) || return 1`,
1565
+ `${variablePrefix}_descriptor_inode=$(stat -Lc %d:%i ${descriptorPathExpression} 2>/dev/null) || return 1`,
1566
+ `[ "$${variablePrefix}_descriptor_inode" = "$${variablePrefix}_path_inode" ] || return 1`
1567
+ ];
1568
+ return [
1569
+ `${functionName}() {`,
1570
+ ` [ -f ${pathExpression} ] && [ ! -L ${pathExpression} ] || return 1`,
1571
+ ` ${variablePrefix}_path_metadata=$(stat -c %u:%a:%h:%s ${pathExpression} 2>/dev/null) || return 1`,
1572
+ ` [ "$${variablePrefix}_path_metadata" = "$(id -u):600:1:0" ] || return 1`,
1573
+ ...descriptorChecks.map((line) => ` ${line}`),
1574
+ " return 0",
1575
+ "}"
1576
+ ];
1577
+ }
1578
+ function generationLock(paths) {
1579
+ return [
1580
+ "command -v flock >/dev/null 2>&1 || exit 1",
1581
+ `if [ -e ${shellQuote(paths.controlLock)} ] || [ -L ${shellQuote(paths.controlLock)} ]; then [ -f ${shellQuote(paths.controlLock)} ] && [ ! -L ${shellQuote(paths.controlLock)} ] || exit 1; fi`,
1582
+ `exec 9>>${shellQuote(paths.controlLock)} || exit 1`,
1583
+ ...renderShellLockAssertion({
1584
+ functionName: "assert_generation_lock",
1585
+ variablePrefix: "generation_lock",
1586
+ path: paths.controlLock,
1587
+ descriptorFd: 9
1588
+ }),
1589
+ "assert_generation_lock || exit 1",
1590
+ "flock -w 8 9 || exit 1",
1591
+ "assert_generation_lock || exit 1"
1592
+ ];
1593
+ }
1594
+ function acquireGenerationLock(paths) {
1595
+ return [...secureDetachedRoot(), ...generationLock(paths)];
1596
+ }
1597
+ function retireExitedReleasedLaunch(paths, descriptorKey) {
1598
+ return [
1599
+ `if [ -e ${shellQuote(paths.retiredDirectory)} ] || [ -L ${shellQuote(paths.retiredDirectory)} ]; then`,
1600
+ ...secureDirectory(paths.retiredDirectory, false).map((line) => ` ${line}`),
1601
+ ` rm -rf -- ${shellQuote(paths.retiredDirectory)} || exit 1`,
1602
+ ` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
1603
+ "fi",
1604
+ `if [ -e ${shellQuote(paths.directory)} ] || [ -L ${shellQuote(paths.directory)} ]; then`,
1605
+ ...secureLaunchDirectory(paths, false).map((line) => ` ${line}`),
1606
+ ` if [ ! -e ${shellQuote(paths.record)} ] && [ ! -L ${shellQuote(paths.record)} ]; then`,
1607
+ ` [ ! -e ${shellQuote(paths.decision)} ] && [ ! -L ${shellQuote(paths.decision)} ] || exit 1`,
1608
+ ` mv -- ${shellQuote(paths.directory)} ${shellQuote(paths.retiredDirectory)} || exit 1`,
1609
+ ` [ -d ${shellQuote(paths.retiredDirectory)} ] && [ ! -L ${shellQuote(paths.retiredDirectory)} ] || exit 1`,
1610
+ ` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
1611
+ ` rm -rf -- ${shellQuote(paths.retiredDirectory)} || exit 1`,
1612
+ ` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
1613
+ " elif read_launch_identity; then",
1614
+ ` [ "$target_descriptor" = ${shellQuote(descriptorKey)} ] || { printf '${DESCRIPTOR_MISMATCH_SENTINEL}\\n'; exit 2; }`,
1615
+ " if read_launch_decision; then",
1616
+ ` [ "$decision_descriptor" = ${shellQuote(descriptorKey)} ] || { printf '${DESCRIPTOR_MISMATCH_SENTINEL}\\n'; exit 2; }`,
1617
+ ' [ "$decision_pid:$decision_ticks:$decision_session:$decision_descriptor" = "$target_pid:$target_ticks:$target_session:$target_descriptor" ] || exit 1',
1618
+ ' if [ "$decision_action" = RELEASE ]; then',
1619
+ ` if [ -e ${shellQuote(paths.started)} ] || [ -L ${shellQuote(paths.started)} ]; then`,
1620
+ " read_started_identity || exit 1",
1621
+ " fi",
1622
+ " target_has_live_processes",
1623
+ " target_status=$?",
1624
+ ' [ "$target_status" -ne 2 ] || exit 1',
1625
+ ' if [ "$target_status" -ne 0 ]; then',
1626
+ ` mv -- ${shellQuote(paths.directory)} ${shellQuote(paths.retiredDirectory)} || exit 1`,
1627
+ ` [ -d ${shellQuote(paths.retiredDirectory)} ] && [ ! -L ${shellQuote(paths.retiredDirectory)} ] || exit 1`,
1628
+ ` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
1629
+ ` rm -rf -- ${shellQuote(paths.retiredDirectory)} || exit 1`,
1630
+ ` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
1631
+ " fi",
1632
+ " fi",
1633
+ " fi",
1634
+ " fi",
1635
+ "fi"
1636
+ ];
1637
+ }
1638
+ function buildEnvironmentFdLaunch(paths, child, environmentMode) {
1639
+ const handoff = `${paths.directory}/.supervisor-environment-v1.empty`;
1640
+ 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<&- &`;
1641
+ return [
1642
+ `: > ${shellQuote(handoff)} || exit 1`,
1643
+ `chmod 600 ${shellQuote(handoff)} || exit 1`,
1644
+ // Keep the inherited reader writable so the selected payload boundary can
1645
+ // erase the anonymous inode before closing its copy. This also clears any
1646
+ // duplicate retained by a generic parent shell after it forks the command.
1647
+ `exec 7<>${shellQuote(handoff)} || exit 1`,
1648
+ `exec 8>${shellQuote(handoff)} || exit 1`,
1649
+ `rm -f -- ${shellQuote(handoff)} || exit 1`,
1650
+ `printf '%s' "$${SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV}" >&8 || exit 1`,
1651
+ "exec 8>&-",
1652
+ `unset ${SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV}`,
1653
+ cleanLaunch,
1654
+ "exec 7<&-"
1655
+ ];
1656
+ }
1657
+ function cleanLifecycleShell(script, environmentMode) {
1658
+ let suffix = 0;
1659
+ let delimiter = "NECKBEARD_DETACHED_LIFECYCLE";
1660
+ const lines = new Set(script.split("\n"));
1661
+ while (lines.has(delimiter)) {
1662
+ suffix += 1;
1663
+ delimiter = `NECKBEARD_DETACHED_LIFECYCLE_${suffix}`;
1664
+ }
1665
+ const fixedEnvironment = Object.entries(
1666
+ DETACHED_PROCESS_LIFECYCLE_ENVIRONMENT
1667
+ ).map(([name, value]) => shellQuote(`${name}=${value}`)).join(" ");
1668
+ return [
1669
+ `export PATH=${shellQuote(DETACHED_PROCESS_TRUSTED_PATH)}`,
1670
+ ...environmentMode === "exec" ? [
1671
+ `if [ -z "\${${SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV}+present}" ]; then ${SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV}=${shellQuote('{"version":1,"environment":{}}')}; fi`
1672
+ ] : [],
1673
+ `exec env -i ${fixedEnvironment} ${SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV}="$${SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV}" sh -s <<'${delimiter}'`,
1674
+ script,
1675
+ delimiter
1676
+ ].join("\n");
1677
+ }
1678
+ function previousLogPath(path) {
1679
+ return `${path}.previous`;
1680
+ }
1681
+ function logPipePath(path) {
1682
+ return `${path}.pipe`;
1683
+ }
1684
+ function logSnapshotPath(path) {
1685
+ return `${path}.snapshot`;
1686
+ }
1687
+ function logSnapshotStagingPath(path) {
1688
+ return `${logSnapshotPath(path)}.partial`;
1689
+ }
1690
+ function legacyLogSnapshotLockPath(path) {
1691
+ return `${logSnapshotPath(path)}.lock`;
1692
+ }
1693
+ function logChunkPath(path) {
1694
+ return `${path}.chunk`;
1695
+ }
1696
+ function boundedLogProgram() {
1697
+ return [
1698
+ "const fs = require('node:fs');",
1699
+ "const [input, output, previous, snapshot, snapshotStaging] = process.argv.slice(1);",
1700
+ "let generation = 0;",
1701
+ "let captureEnabled = true;",
1702
+ "const waitArray = new Int32Array(new SharedArrayBuffer(4));",
1703
+ "function assertSafeLeaf(path, optional = false) {",
1704
+ " let stats;",
1705
+ " try { stats = fs.lstatSync(path); } catch (error) { if (optional && error?.code === 'ENOENT') return; throw error; }",
1706
+ " if (!stats.isFile() || stats.isSymbolicLink()) throw new Error('unsafe log leaf');",
1707
+ "}",
1708
+ "function publishSnapshot(state) {",
1709
+ ` fs.writeFileSync(snapshotStaging, \`${LOG_SNAPSHOT_PREFIX} \${state} \${generation}\\n\`, { encoding: 'utf8', mode: 0o600, flag: 'wx' });`,
1710
+ " fs.chmodSync(snapshotStaging, 0o600);",
1711
+ " fs.renameSync(snapshotStaging, snapshot);",
1712
+ "}",
1713
+ "void (async () => {",
1714
+ ` for await (const chunk of fs.createReadStream(input, { highWaterMark: ${DETACHED_PROCESS_LOG_CHUNK_BYTES} })) {`,
1715
+ " if (captureEnabled) {",
1716
+ " try {",
1717
+ " generation += 1;",
1718
+ " publishSnapshot('ROTATING');",
1719
+ " assertSafeLeaf(output);",
1720
+ " assertSafeLeaf(previous, true);",
1721
+ " fs.appendFileSync(output, chunk);",
1722
+ ` if (fs.statSync(output).size >= ${DETACHED_PROCESS_LOG_SEGMENT_BYTES}) {`,
1723
+ " fs.renameSync(output, previous);",
1724
+ " fs.writeFileSync(output, '', { mode: 0o600, flag: 'wx' });",
1725
+ " fs.chmodSync(output, 0o600);",
1726
+ " }",
1727
+ " publishSnapshot('STABLE');",
1728
+ " } catch {",
1729
+ " // Diagnostic capture failure must never close the target pipe.",
1730
+ " captureEnabled = false;",
1731
+ " }",
1732
+ " }",
1733
+ " // Avoid monopolizing the process while the pipe remains continuously readable.",
1734
+ " Atomics.wait(waitArray, 0, 0, 10);",
1735
+ " }",
1736
+ " fs.rmSync(input);",
1737
+ "})().catch(() => { process.exitCode = 1; });"
1738
+ ].join("\n");
1739
+ }
1740
+ function boundedLogShellFunctions() {
1741
+ return [
1742
+ "bounded_log_shell() {",
1743
+ " log_input=$1",
1744
+ " log_output=$2",
1745
+ " log_previous=$3",
1746
+ " log_snapshot=$4",
1747
+ " log_snapshot_staging=$5",
1748
+ " log_chunk=$6",
1749
+ " log_generation=0",
1750
+ " log_capture_enabled=yes",
1751
+ ' exec 6<"$log_input" || exit 1',
1752
+ " while :; do",
1753
+ ' if [ "$log_capture_enabled" != yes ]; then',
1754
+ " cat <&6 >/dev/null 2>&1 || true",
1755
+ " break",
1756
+ " fi",
1757
+ ` if ! dd bs=${DETACHED_PROCESS_LOG_CHUNK_BYTES} count=1 <&6 >"$log_chunk" 2>/dev/null; then`,
1758
+ " cat <&6 >/dev/null 2>&1 || true",
1759
+ " break",
1760
+ " fi",
1761
+ ' if ! log_chunk_size=$(stat -c %s "$log_chunk" 2>/dev/null); then',
1762
+ " log_capture_enabled=no",
1763
+ " continue",
1764
+ " fi",
1765
+ ' [ "$log_chunk_size" -gt 0 ] || break',
1766
+ " log_generation=$((log_generation + 1))",
1767
+ " if ! (",
1768
+ ' publish_log_snapshot ROTATING "$log_generation" "$log_snapshot" "$log_snapshot_staging" || exit 1',
1769
+ ' [ -f "$log_output" ] && [ ! -L "$log_output" ] || exit 1',
1770
+ ' if [ -e "$log_previous" ] || [ -L "$log_previous" ]; then [ -f "$log_previous" ] && [ ! -L "$log_previous" ] || exit 1; fi',
1771
+ ' cat "$log_chunk" >> "$log_output" || exit 1',
1772
+ ' log_after=$(stat -c %s "$log_output" 2>/dev/null) || exit 1',
1773
+ ` if [ "$log_after" -ge ${DETACHED_PROCESS_LOG_SEGMENT_BYTES} ]; then`,
1774
+ ' mv -f -- "$log_output" "$log_previous" || exit 1',
1775
+ ' ( set -C; : > "$log_output" ) 2>/dev/null || exit 1',
1776
+ ' chmod 600 "$log_output" || exit 1',
1777
+ " fi",
1778
+ ' publish_log_snapshot STABLE "$log_generation" "$log_snapshot" "$log_snapshot_staging" || exit 1',
1779
+ " ); then",
1780
+ " # Keep draining even when diagnostic capture becomes unavailable.",
1781
+ " log_capture_enabled=no",
1782
+ " fi",
1783
+ " # Avoid monopolizing the shell while the pipe remains continuously readable.",
1784
+ " sleep 0.01",
1785
+ " done",
1786
+ " exec 6<&-",
1787
+ ' rm -f -- "$log_input" 2>/dev/null || true',
1788
+ "}",
1789
+ "publish_log_snapshot() {",
1790
+ " log_snapshot_state=$1",
1791
+ " log_snapshot_generation=$2",
1792
+ " log_snapshot_path=$3",
1793
+ " log_snapshot_staging_path=$4",
1794
+ ' [ ! -e "$log_snapshot_staging_path" ] && [ ! -L "$log_snapshot_staging_path" ] || return 1',
1795
+ ` printf '${LOG_SNAPSHOT_PREFIX} %s %s\\n' "$log_snapshot_state" "$log_snapshot_generation" > "$log_snapshot_staging_path" || return 1`,
1796
+ ' chmod 600 "$log_snapshot_staging_path" || return 1',
1797
+ ' mv -f -- "$log_snapshot_staging_path" "$log_snapshot_path" || return 1',
1798
+ "}",
1799
+ "assert_legacy_log_lock_leaf() {",
1800
+ " legacy_log_lock_path=$1",
1801
+ ' [ -f "$legacy_log_lock_path" ] && [ ! -L "$legacy_log_lock_path" ] || return 1',
1802
+ ' legacy_log_lock_metadata=$(stat -c %u:%a:%h:%s "$legacy_log_lock_path" 2>/dev/null) || return 1',
1803
+ ' [ "$legacy_log_lock_metadata" = "$(id -u):600:1:0" ]',
1804
+ "}"
1805
+ ];
1806
+ }
1807
+ function boundedLogCaptureSetup(paths) {
1808
+ const stdoutPipe = logPipePath(paths.stdout);
1809
+ const stderrPipe = logPipePath(paths.stderr);
1810
+ return [
1811
+ ...boundedLogShellFunctions(),
1812
+ "if ! command -v node >/dev/null 2>&1; then",
1813
+ " command -v dd >/dev/null 2>&1 || exit 1",
1814
+ "fi",
1815
+ "command -v python3 >/dev/null 2>&1 || exit 1",
1816
+ `: > ${shellQuote(paths.stdout)} || exit 1`,
1817
+ `: > ${shellQuote(paths.stderr)} || exit 1`,
1818
+ `: > ${shellQuote(logChunkPath(paths.stdout))} || exit 1`,
1819
+ `: > ${shellQuote(logChunkPath(paths.stderr))} || exit 1`,
1820
+ `( set -C; : > ${shellQuote(legacyLogSnapshotLockPath(paths.stdout))} ) 2>/dev/null || exit 1`,
1821
+ `( set -C; : > ${shellQuote(legacyLogSnapshotLockPath(paths.stderr))} ) 2>/dev/null || exit 1`,
1822
+ `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`,
1823
+ `assert_legacy_log_lock_leaf ${shellQuote(legacyLogSnapshotLockPath(paths.stdout))} || exit 1`,
1824
+ `assert_legacy_log_lock_leaf ${shellQuote(legacyLogSnapshotLockPath(paths.stderr))} || exit 1`,
1825
+ `publish_log_snapshot STABLE 0 ${shellQuote(logSnapshotPath(paths.stdout))} ${shellQuote(logSnapshotStagingPath(paths.stdout))} || exit 1`,
1826
+ `publish_log_snapshot STABLE 0 ${shellQuote(logSnapshotPath(paths.stderr))} ${shellQuote(logSnapshotStagingPath(paths.stderr))} || exit 1`,
1827
+ `mkfifo -m 600 ${shellQuote(stdoutPipe)} ${shellQuote(stderrPipe)} || exit 1`,
1828
+ ...assertSafeRegularFile(paths.stdout).map((line) => line.replace("return 1", "exit 1")),
1829
+ ...assertSafeRegularFile(paths.stderr).map((line) => line.replace("return 1", "exit 1")),
1830
+ `[ -p ${shellQuote(stdoutPipe)} ] && [ ! -L ${shellQuote(stdoutPipe)} ] || exit 1`,
1831
+ `[ -p ${shellQuote(stderrPipe)} ] && [ ! -L ${shellQuote(stderrPipe)} ] || exit 1`,
1832
+ `( set -C; : > ${shellQuote(paths.quiescent)} ) 2>/dev/null || exit 1`,
1833
+ `chmod 600 ${shellQuote(paths.quiescent)} || exit 1`,
1834
+ `exec 6<>${shellQuote(paths.quiescent)} || exit 1`,
1835
+ ...renderShellLockAssertion({
1836
+ functionName: "assert_quiescent_descriptor",
1837
+ variablePrefix: "quiescent",
1838
+ path: paths.quiescent,
1839
+ descriptorFd: 6
1840
+ }),
1841
+ "assert_quiescent_descriptor || exit 1",
1842
+ "sync -f /proc/self/fd/6 || exit 1",
1843
+ `sync -f ${shellQuote(paths.directory)} || exit 1`
1844
+ ];
1845
+ }
1846
+ function detachedProcessReaperProgram() {
1847
+ return [
1848
+ "import ctypes",
1849
+ "import errno",
1850
+ "import fcntl",
1851
+ "import json",
1852
+ "import os",
1853
+ "import re",
1854
+ "import stat",
1855
+ "import subprocess",
1856
+ "import sys",
1857
+ "import time",
1858
+ "",
1859
+ "PR_SET_CHILD_SUBREAPER = 36",
1860
+ "command = sys.argv[1]",
1861
+ "logger_mode = sys.argv[2]",
1862
+ "node_program = sys.argv[3]",
1863
+ "shell_program = sys.argv[4]",
1864
+ "stdout_args = sys.argv[5:11]",
1865
+ "stderr_args = sys.argv[11:17]",
1866
+ "completion_path = sys.argv[17]",
1867
+ "started_partial_path = sys.argv[18]",
1868
+ "started_path = sys.argv[19]",
1869
+ "launch_directory = sys.argv[20]",
1870
+ "target_pid = int(sys.argv[21])",
1871
+ "target_ticks = sys.argv[22]",
1872
+ "target_session = int(sys.argv[23])",
1873
+ "target_descriptor = sys.argv[24]",
1874
+ "environment_mode = sys.argv[25]",
1875
+ "environment_fd = int(sys.argv[26])",
1876
+ "completion_fd = int(sys.argv[27])",
1877
+ "if len(stdout_args) != 6 or len(stderr_args) != 6:",
1878
+ " raise SystemExit(1)",
1879
+ 'if environment_mode not in ("exec", "supervisor-fd-v1"):',
1880
+ " raise SystemExit(1)",
1881
+ "if os.getpid() != target_pid or os.getpgrp() != target_pid or os.getsid(0) != target_session:",
1882
+ " raise SystemExit(1)",
1883
+ "",
1884
+ "def process_start_ticks(pid):",
1885
+ ' with open(f"/proc/{pid}/stat", "rb") as stat_file:',
1886
+ " raw = stat_file.read()",
1887
+ ' marker = raw.rfind(b") ")',
1888
+ " fields = raw[marker + 2:].split() if marker >= 0 else []",
1889
+ " if len(fields) <= 19:",
1890
+ " raise SystemExit(1)",
1891
+ ' return fields[19].decode("ascii")',
1892
+ "",
1893
+ "def consume_exec_environment():",
1894
+ " descriptor_stats = os.fstat(environment_fd)",
1895
+ " if (",
1896
+ " not stat.S_ISREG(descriptor_stats.st_mode)",
1897
+ " or stat.S_IMODE(descriptor_stats.st_mode) != 0o600",
1898
+ " or descriptor_stats.st_uid != os.geteuid()",
1899
+ " or descriptor_stats.st_nlink != 0",
1900
+ " or descriptor_stats.st_size <= 0",
1901
+ ` or descriptor_stats.st_size > ${SUPERVISOR_ENVIRONMENT_MAX_BYTES}`,
1902
+ " ):",
1903
+ " raise SystemExit(1)",
1904
+ ' source = b""',
1905
+ " try:",
1906
+ ` while len(source) <= ${SUPERVISOR_ENVIRONMENT_MAX_BYTES}:`,
1907
+ ` chunk = os.read(environment_fd, ${SUPERVISOR_ENVIRONMENT_MAX_BYTES + 1} - len(source))`,
1908
+ " if not chunk:",
1909
+ " break",
1910
+ " source += chunk",
1911
+ " finally:",
1912
+ " os.ftruncate(environment_fd, 0)",
1913
+ " os.close(environment_fd)",
1914
+ ` if not source or len(source) > ${SUPERVISOR_ENVIRONMENT_MAX_BYTES}:`,
1915
+ " raise SystemExit(1)",
1916
+ " try:",
1917
+ ' payload = json.loads(source.decode("utf-8", errors="strict"))',
1918
+ " except (UnicodeDecodeError, json.JSONDecodeError):",
1919
+ " raise SystemExit(1)",
1920
+ " if (",
1921
+ " type(payload) is not dict",
1922
+ ' or set(payload) != {"version", "environment"}',
1923
+ ' or type(payload.get("version")) is not int',
1924
+ ' or payload.get("version") != 1',
1925
+ ' or type(payload.get("environment")) is not dict',
1926
+ " ):",
1927
+ " raise SystemExit(1)",
1928
+ ' environment = payload["environment"]',
1929
+ ` if len(environment) > ${SUPERVISOR_ENVIRONMENT_MAX_ENTRIES} or any(`,
1930
+ " type(name) is not str",
1931
+ ` or len(name) > ${SUPERVISOR_ENVIRONMENT_MAX_NAME_BYTES}`,
1932
+ ' or re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name) is None',
1933
+ ` or name in (${JSON.stringify(SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV)}, ${JSON.stringify(SUPERVISOR_ENVIRONMENT_FD_ENV)})`,
1934
+ ' or "\\x00" in name',
1935
+ " or type(value) is not str",
1936
+ ' or "\\x00" in value',
1937
+ " for name, value in environment.items()",
1938
+ " ):",
1939
+ " raise SystemExit(1)",
1940
+ " payload_environment = {",
1941
+ ...Object.entries(DETACHED_PROCESS_LIFECYCLE_ENVIRONMENT).map(
1942
+ ([name, value]) => ` ${JSON.stringify(name)}: ${JSON.stringify(value)},`
1943
+ ),
1944
+ " }",
1945
+ " payload_environment.update(environment)",
1946
+ " return payload_environment",
1947
+ "",
1948
+ "def validate_completion_descriptor(expected_size=None):",
1949
+ " descriptor_stats = os.fstat(completion_fd)",
1950
+ " path_stats = os.lstat(completion_path)",
1951
+ " if (",
1952
+ " not stat.S_ISREG(descriptor_stats.st_mode)",
1953
+ " or not stat.S_ISREG(path_stats.st_mode)",
1954
+ " or stat.S_IMODE(descriptor_stats.st_mode) != 0o600",
1955
+ " or stat.S_IMODE(path_stats.st_mode) != 0o600",
1956
+ " or descriptor_stats.st_uid != os.geteuid()",
1957
+ " or path_stats.st_uid != os.geteuid()",
1958
+ " or descriptor_stats.st_nlink != 1",
1959
+ " or path_stats.st_nlink != 1",
1960
+ " or (descriptor_stats.st_dev, descriptor_stats.st_ino) != (path_stats.st_dev, path_stats.st_ino)",
1961
+ " or (expected_size is not None and descriptor_stats.st_size != expected_size)",
1962
+ " ):",
1963
+ " raise SystemExit(1)",
1964
+ " return descriptor_stats",
1965
+ "",
1966
+ "def validate_launch_directory(directory_fd):",
1967
+ " descriptor_stats = os.fstat(directory_fd)",
1968
+ " path_stats = os.lstat(launch_directory)",
1969
+ " if (",
1970
+ " not stat.S_ISDIR(descriptor_stats.st_mode)",
1971
+ " or not stat.S_ISDIR(path_stats.st_mode)",
1972
+ " or stat.S_IMODE(descriptor_stats.st_mode) != 0o700",
1973
+ " or stat.S_IMODE(path_stats.st_mode) != 0o700",
1974
+ " or descriptor_stats.st_uid != os.geteuid()",
1975
+ " or path_stats.st_uid != os.geteuid()",
1976
+ " or (descriptor_stats.st_dev, descriptor_stats.st_ino) != (path_stats.st_dev, path_stats.st_ino)",
1977
+ " ):",
1978
+ " raise SystemExit(1)",
1979
+ "",
1980
+ "def publish_started():",
1981
+ " if (",
1982
+ " os.path.dirname(started_partial_path) != launch_directory",
1983
+ " or os.path.dirname(started_path) != launch_directory",
1984
+ " ):",
1985
+ " raise SystemExit(1)",
1986
+ " partial_leaf = os.path.basename(started_partial_path)",
1987
+ " started_leaf = os.path.basename(started_path)",
1988
+ ` value = f"${STARTED_PREFIX} {target_pid} {target_ticks} {target_session} {target_descriptor}\\n".encode("ascii")`,
1989
+ " directory_fd = os.open(",
1990
+ " launch_directory,",
1991
+ " os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC | os.O_NOFOLLOW,",
1992
+ " )",
1993
+ " started_fd = -1",
1994
+ " try:",
1995
+ " validate_launch_directory(directory_fd)",
1996
+ " started_fd = os.open(",
1997
+ " partial_leaf,",
1998
+ " os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_CLOEXEC | os.O_NOFOLLOW,",
1999
+ " 0o600,",
2000
+ " dir_fd=directory_fd,",
2001
+ " )",
2002
+ " os.fchmod(started_fd, 0o600)",
2003
+ " offset = 0",
2004
+ " while offset < len(value):",
2005
+ " written = os.write(started_fd, value[offset:])",
2006
+ " if written <= 0:",
2007
+ " raise SystemExit(1)",
2008
+ " offset += written",
2009
+ " os.fsync(started_fd)",
2010
+ " partial_stats = os.fstat(started_fd)",
2011
+ " if (",
2012
+ " not stat.S_ISREG(partial_stats.st_mode)",
2013
+ " or stat.S_IMODE(partial_stats.st_mode) != 0o600",
2014
+ " or partial_stats.st_uid != os.geteuid()",
2015
+ " or partial_stats.st_nlink != 1",
2016
+ " or partial_stats.st_size != len(value)",
2017
+ " ):",
2018
+ " raise SystemExit(1)",
2019
+ " os.replace(",
2020
+ " partial_leaf,",
2021
+ " started_leaf,",
2022
+ " src_dir_fd=directory_fd,",
2023
+ " dst_dir_fd=directory_fd,",
2024
+ " )",
2025
+ " os.fsync(directory_fd)",
2026
+ " validate_launch_directory(directory_fd)",
2027
+ " published_stats = os.stat(started_leaf, dir_fd=directory_fd, follow_symlinks=False)",
2028
+ " full_path_stats = os.lstat(started_path)",
2029
+ " if (",
2030
+ " (published_stats.st_dev, published_stats.st_ino)",
2031
+ " != (partial_stats.st_dev, partial_stats.st_ino)",
2032
+ " or (full_path_stats.st_dev, full_path_stats.st_ino)",
2033
+ " != (partial_stats.st_dev, partial_stats.st_ino)",
2034
+ " or published_stats.st_nlink != 1",
2035
+ " or full_path_stats.st_nlink != 1",
2036
+ " or published_stats.st_size != len(value)",
2037
+ " or full_path_stats.st_size != len(value)",
2038
+ " ):",
2039
+ " raise SystemExit(1)",
2040
+ " finally:",
2041
+ " if started_fd >= 0:",
2042
+ " os.close(started_fd)",
2043
+ " os.close(directory_fd)",
2044
+ "",
2045
+ "if process_start_ticks(target_pid) != target_ticks:",
2046
+ " raise SystemExit(1)",
2047
+ "validate_completion_descriptor(0)",
2048
+ "os.set_inheritable(completion_fd, False)",
2049
+ "libc = ctypes.CDLL(None, use_errno=True)",
2050
+ "if libc.prctl(PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0) != 0:",
2051
+ " raise SystemExit(1)",
2052
+ "payload_environment = None",
2053
+ 'if environment_mode == "exec":',
2054
+ " payload_environment = consume_exec_environment()",
2055
+ " environment_fd = -1",
2056
+ "publish_started()",
2057
+ "",
2058
+ "def spawn_logger(arguments):",
2059
+ ' if logger_mode == "node":',
2060
+ ' argv = ["node", "-e", node_program, *arguments]',
2061
+ ' elif logger_mode == "shell":',
2062
+ ' argv = ["sh", "-c", shell_program, "bounded-log", *arguments]',
2063
+ " else:",
2064
+ " raise SystemExit(1)",
2065
+ " return subprocess.Popen(",
2066
+ " argv,",
2067
+ " stdin=subprocess.DEVNULL,",
2068
+ " stdout=subprocess.DEVNULL,",
2069
+ " stderr=subprocess.DEVNULL,",
2070
+ " close_fds=True,",
2071
+ " )",
2072
+ "",
2073
+ "def open_fifo_writer(path, logger):",
2074
+ " deadline = time.monotonic() + 5",
2075
+ " while True:",
2076
+ " try:",
2077
+ " descriptor = os.open(",
2078
+ " path,",
2079
+ " os.O_WRONLY | os.O_NONBLOCK | os.O_NOFOLLOW | os.O_CLOEXEC,",
2080
+ " )",
2081
+ " break",
2082
+ " except OSError as error:",
2083
+ " if error.errno != errno.ENXIO or logger.poll() is not None or time.monotonic() >= deadline:",
2084
+ " raise",
2085
+ " time.sleep(0.01)",
2086
+ " descriptor_stats = os.fstat(descriptor)",
2087
+ " path_stats = os.lstat(path)",
2088
+ " if (",
2089
+ " not stat.S_ISFIFO(descriptor_stats.st_mode)",
2090
+ " or not stat.S_ISFIFO(path_stats.st_mode)",
2091
+ " or stat.S_IMODE(descriptor_stats.st_mode) != 0o600",
2092
+ " or stat.S_IMODE(path_stats.st_mode) != 0o600",
2093
+ " or descriptor_stats.st_uid != os.geteuid()",
2094
+ " or path_stats.st_uid != os.geteuid()",
2095
+ " or (descriptor_stats.st_dev, descriptor_stats.st_ino) != (path_stats.st_dev, path_stats.st_ino)",
2096
+ " ):",
2097
+ " os.close(descriptor)",
2098
+ " raise SystemExit(1)",
2099
+ " flags = fcntl.fcntl(descriptor, fcntl.F_GETFL)",
2100
+ " fcntl.fcntl(descriptor, fcntl.F_SETFL, flags & ~os.O_NONBLOCK)",
2101
+ ' return os.fdopen(descriptor, "wb", buffering=0)',
2102
+ "",
2103
+ "if environment_fd < 0:",
2104
+ " try:",
2105
+ ` os.close(${SUPERVISOR_ENVIRONMENT_FD})`,
2106
+ " except OSError:",
2107
+ " pass",
2108
+ "children = []",
2109
+ "writers = []",
2110
+ "payload = None",
2111
+ "payload_returncode = 1",
2112
+ "initialization_failed = False",
2113
+ "try:",
2114
+ " stdout_logger = spawn_logger(stdout_args)",
2115
+ " children.append(stdout_logger)",
2116
+ " stderr_logger = spawn_logger(stderr_args)",
2117
+ " children.append(stderr_logger)",
2118
+ " stdout_writer = open_fifo_writer(stdout_args[0], stdout_logger)",
2119
+ " writers.append(stdout_writer)",
2120
+ " stderr_writer = open_fifo_writer(stderr_args[0], stderr_logger)",
2121
+ " writers.append(stderr_writer)",
2122
+ " payload = subprocess.Popen(",
2123
+ ' ["/bin/sh", "-c", command],',
2124
+ " stdin=subprocess.DEVNULL,",
2125
+ " stdout=stdout_writer,",
2126
+ " stderr=stderr_writer,",
2127
+ " env=payload_environment,",
2128
+ " close_fds=True,",
2129
+ " pass_fds=(() if environment_fd < 0 else (environment_fd,)),",
2130
+ " )",
2131
+ " children.append(payload)",
2132
+ "except BaseException:",
2133
+ " initialization_failed = True",
2134
+ "finally:",
2135
+ " for writer in writers:",
2136
+ " try:",
2137
+ " writer.close()",
2138
+ " except OSError:",
2139
+ " pass",
2140
+ " if environment_fd >= 0:",
2141
+ " try:",
2142
+ " os.close(environment_fd)",
2143
+ " except OSError:",
2144
+ " pass",
2145
+ "",
2146
+ "if initialization_failed:",
2147
+ " for child in children:",
2148
+ " if child.poll() is None:",
2149
+ " try:",
2150
+ " child.terminate()",
2151
+ " except ProcessLookupError:",
2152
+ " pass",
2153
+ " for child in children:",
2154
+ " try:",
2155
+ " child.wait(timeout=2)",
2156
+ " except subprocess.TimeoutExpired:",
2157
+ " try:",
2158
+ " child.kill()",
2159
+ " except ProcessLookupError:",
2160
+ " pass",
2161
+ " child.wait()",
2162
+ "else:",
2163
+ " payload_returncode = payload.wait()",
2164
+ " stdout_logger.wait()",
2165
+ " stderr_logger.wait()",
2166
+ "while True:",
2167
+ " try:",
2168
+ " os.wait()",
2169
+ " except InterruptedError:",
2170
+ " continue",
2171
+ " except ChildProcessError:",
2172
+ " break",
2173
+ "",
2174
+ `completion = f"${QUIESCENT_PREFIX} {target_pid} {target_ticks} {target_session} {target_descriptor}\\n".encode("ascii")`,
2175
+ "validate_completion_descriptor()",
2176
+ "os.ftruncate(completion_fd, 0)",
2177
+ "os.lseek(completion_fd, 0, os.SEEK_SET)",
2178
+ "offset = 0",
2179
+ "while offset < len(completion):",
2180
+ " written = os.write(completion_fd, completion[offset:])",
2181
+ " if written <= 0:",
2182
+ " raise SystemExit(1)",
2183
+ " offset += written",
2184
+ "os.fsync(completion_fd)",
2185
+ "validate_completion_descriptor(len(completion))",
2186
+ "raise SystemExit(payload_returncode if 0 <= payload_returncode <= 255 else 1)"
2187
+ ].join("\n");
2188
+ }
2189
+ function boundedLogCaptureLaunch(paths, descriptorKey, environmentMode) {
2190
+ const stdoutArgs = [
2191
+ logPipePath(paths.stdout),
2192
+ paths.stdout,
2193
+ previousLogPath(paths.stdout),
2194
+ logSnapshotPath(paths.stdout),
2195
+ logSnapshotStagingPath(paths.stdout),
2196
+ logChunkPath(paths.stdout)
2197
+ ];
2198
+ const stderrArgs = [
2199
+ logPipePath(paths.stderr),
2200
+ paths.stderr,
2201
+ previousLogPath(paths.stderr),
2202
+ logSnapshotPath(paths.stderr),
2203
+ logSnapshotStagingPath(paths.stderr),
2204
+ logChunkPath(paths.stderr)
2205
+ ];
2206
+ const shellLogger = [...boundedLogShellFunctions(), 'bounded_log_shell "$@"'].join("\n");
2207
+ const args = [
2208
+ '"$1"',
2209
+ '"$logger_mode"',
2210
+ shellQuote(boundedLogProgram()),
2211
+ shellQuote(shellLogger),
2212
+ ...stdoutArgs.map(shellQuote),
2213
+ ...stderrArgs.map(shellQuote),
2214
+ shellQuote(paths.quiescent),
2215
+ shellQuote(paths.startedPartial),
2216
+ shellQuote(paths.started),
2217
+ shellQuote(paths.directory),
2218
+ '"$pid"',
2219
+ '"$ticks"',
2220
+ '"$session"',
2221
+ shellQuote(descriptorKey),
2222
+ shellQuote(environmentMode),
2223
+ String(SUPERVISOR_ENVIRONMENT_FD),
2224
+ "6"
2225
+ ];
2226
+ return [
2227
+ "if command -v node >/dev/null 2>&1; then logger_mode=node; else logger_mode=shell; fi",
2228
+ // The provider-selected cwd is payload state, not trusted lifecycle code.
2229
+ // Isolated/no-site mode keeps it and sitecustomize out of reaper startup.
2230
+ `exec python3 -I -S -c ${shellQuote(detachedProcessReaperProgram())} ${args.join(" ")}`
2231
+ ];
2232
+ }
2233
+ function buildPrepareDetachedCommand(paths, descriptorKey, command, environmentMode = "exec", restartReleasedWhenExited = false) {
2234
+ const recordWrite = `printf '${IDENTITY_PREFIX} %s %s %s ${descriptorKey}\\n' "$pid" "$ticks" "$session" > ` + shellQuote(paths.recordPartial);
2235
+ const child = [
2236
+ "pid=$$",
2237
+ "stat=$(cat /proc/$$/stat 2>/dev/null) || exit 1",
2238
+ "rest=${stat##*) }",
2239
+ `pgrp=$(printf '%s\\n' "$rest" | awk '{print $3}')`,
2240
+ `session=$(printf '%s\\n' "$rest" | awk '{print $4}')`,
2241
+ `ticks=$(printf '%s\\n' "$rest" | awk '{print $20}')`,
2242
+ `case "$pid:$pgrp:$session:$ticks" in *[!0-9:]*) exit 1 ;; esac`,
2243
+ '[ "$pid" = "$pgrp" ] && [ "$pid" = "$session" ] && [ -n "$ticks" ] || exit 1',
2244
+ ...boundedLogCaptureSetup(paths),
2245
+ ...atomicFile(paths.recordPartial, paths.record, paths.directory, recordWrite),
2246
+ ...restartReleasedWhenExited ? ["exec 9>&-"] : [],
2247
+ "attempt=0",
2248
+ `while [ ! -s ${shellQuote(paths.decision)} ] && [ "$attempt" -lt 1200 ]; do`,
2249
+ " sleep 0.05",
2250
+ " attempt=$((attempt + 1))",
2251
+ "done",
2252
+ ...decisionFunctions(paths),
2253
+ "read_launch_decision || exit 1",
2254
+ `[ "$decision_descriptor" = ${shellQuote(descriptorKey)} ] || exit 1`,
2255
+ '[ "$decision_action" = RELEASE ] || exit 1',
2256
+ '[ "$decision_pid:$decision_ticks:$decision_session" = "$pid:$ticks:$session" ] || exit 1',
2257
+ ...boundedLogCaptureLaunch(paths, descriptorKey, environmentMode)
2258
+ ].join("\n");
2259
+ const childCommand = `set -- ${shellQuote(command)}
2260
+ ${child}`;
2261
+ const launch = buildEnvironmentFdLaunch(paths, childCommand, environmentMode);
2262
+ return cleanLifecycleShell(
2263
+ [
2264
+ "umask 077",
2265
+ ...secureDetachedRoot(),
2266
+ ...restartReleasedWhenExited ? generationLock(paths) : [],
2267
+ ...identityFunctions(paths),
2268
+ ...decisionFunctions(paths),
2269
+ ...processTreeFunctions(paths),
2270
+ ...restartReleasedWhenExited ? retireExitedReleasedLaunch(paths, descriptorKey) : [],
2271
+ `if [ ! -e ${shellQuote(paths.directory)} ] && [ ! -L ${shellQuote(paths.directory)} ] && mkdir ${shellQuote(paths.directory)} 2>/dev/null; then`,
2272
+ ...secureLaunchDirectory(paths, false).map((line) => ` ${line}`),
2273
+ ` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
2274
+ ...launch.map((line) => ` ${line}`),
2275
+ "fi",
2276
+ ...secureLaunchDirectory(paths, false),
2277
+ "attempt=0",
2278
+ `while [ ! -s ${shellQuote(paths.record)} ] && [ "$attempt" -lt 200 ]; do`,
2279
+ " sleep 0.05",
2280
+ " attempt=$((attempt + 1))",
2281
+ "done",
2282
+ "read_launch_identity || exit 1",
2283
+ `if [ "$target_descriptor" != ${shellQuote(descriptorKey)} ]; then`,
2284
+ ` printf '${DESCRIPTOR_MISMATCH_SENTINEL}\\n'`,
2285
+ " exit 2",
2286
+ "fi",
2287
+ "if read_launch_decision; then",
2288
+ ` [ "$decision_descriptor" = ${shellQuote(descriptorKey)} ] || { printf '${DESCRIPTOR_MISMATCH_SENTINEL}\\n'; exit 2; }`,
2289
+ ` [ "$decision_action" = RELEASE ] || { printf '${CANCELLED_SENTINEL}\\n'; exit 3; }`,
2290
+ ...waitForStarted(paths).map((line) => ` ${line}`),
2291
+ "else",
2292
+ " leader_identity_status || exit 1",
2293
+ "fi",
2294
+ ...restartReleasedWhenExited ? ["exec 9>&-"] : [],
2295
+ `printf '${PREPARED_SENTINEL} %s %s %s %s\\n' "$target_pid" "$target_ticks" "$target_session" "$target_descriptor"`
2296
+ ].join("\n"),
2297
+ environmentMode
2298
+ );
2299
+ }
2300
+ function buildReleaseDetachedCommand(paths, identity, serializeGenerationChanges = false) {
2301
+ return [
2302
+ "umask 077",
2303
+ ...serializeGenerationChanges ? acquireGenerationLock(paths) : [],
2304
+ ...serializeGenerationChanges ? [] : secureDetachedRoot(),
2305
+ ...secureLaunchDirectory(paths, false),
2306
+ ...identityFunctions(paths),
2307
+ ...decisionFunctions(paths),
2308
+ ...serializeGenerationChanges ? processTreeFunctions(paths) : [],
2309
+ "read_launch_identity || exit 1",
2310
+ `[ "$target_pid:$target_ticks:$target_session:$target_descriptor" = ${shellQuote(
2311
+ `${identity.pid}:${identity.startTicks}:${identity.sessionId}:${identity.descriptorKey}`
2312
+ )} ] || exit 1`,
2313
+ "publish_pid=$target_pid",
2314
+ "publish_ticks=$target_ticks",
2315
+ "publish_session=$target_session",
2316
+ "publish_descriptor=$target_descriptor",
2317
+ ...publishDecision(paths, "RELEASE", paths.releaseDecisionPartial),
2318
+ '[ "$decision_action" = RELEASE ] || exit 3',
2319
+ '[ "$decision_pid:$decision_ticks:$decision_session:$decision_descriptor" = "$target_pid:$target_ticks:$target_session:$target_descriptor" ] || exit 1',
2320
+ ...releasedAdoptionOutcome(
2321
+ paths,
2322
+ identity.descriptorKey,
2323
+ serializeGenerationChanges
2324
+ )
2325
+ ].join("\n");
2326
+ }
2327
+ function isReleaseConfirmation(output, identity) {
2328
+ return Boolean(
2329
+ parseIdentityOutput(
2330
+ RELEASED_PATTERN,
2331
+ identity.provider,
2332
+ pathsForIdentity(identity),
2333
+ identity.descriptorKey,
2334
+ output
2335
+ )
2336
+ );
2337
+ }
2338
+ function buildCancelDetachedCommand(paths, descriptorKey, expected, serializeGenerationChanges = false) {
2339
+ return [
2340
+ "umask 077",
2341
+ ...serializeGenerationChanges ? acquireGenerationLock(paths) : secureDetachedRoot(),
2342
+ ...secureLaunchDirectory(paths, true),
2343
+ `sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
2344
+ ...identityFunctions(paths),
2345
+ ...decisionFunctions(paths),
2346
+ ...processTreeFunctions(paths),
2347
+ "if read_launch_identity; then",
2348
+ ` [ "$target_descriptor" = ${shellQuote(descriptorKey)} ] || { printf '${DESCRIPTOR_MISMATCH_SENTINEL}\\n'; exit 2; }`,
2349
+ ...expected ? [
2350
+ ` [ "$target_pid:$target_ticks:$target_session:$target_descriptor" = ${shellQuote(
2351
+ `${expected.pid}:${expected.startTicks}:${expected.sessionId}:${expected.descriptorKey}`
2352
+ )} ] || exit 1`
2353
+ ] : [],
2354
+ " publish_pid=$target_pid",
2355
+ " publish_ticks=$target_ticks",
2356
+ " publish_session=$target_session",
2357
+ "else",
2358
+ " publish_pid=0",
2359
+ " publish_ticks=0",
2360
+ " publish_session=0",
2361
+ "fi",
2362
+ `publish_descriptor=${shellQuote(descriptorKey)}`,
2363
+ ...publishDecision(paths, "CANCEL", paths.cancelDecisionPartial),
2364
+ `[ "$decision_descriptor" = ${shellQuote(descriptorKey)} ] || { printf '${DESCRIPTOR_MISMATCH_SENTINEL}\\n'; exit 2; }`,
2365
+ 'if [ "$decision_action" = RELEASE ]; then',
2366
+ ...releasedAdoptionOutcome(paths, descriptorKey, serializeGenerationChanges).map(
2367
+ (line) => ` ${line}`
2368
+ ),
2369
+ "fi",
2370
+ "# CANCEL won the only durable decision. The child can never execute the requested command.",
2371
+ "if read_launch_identity; then",
2372
+ ...stopTargetCommands().map((line) => ` ${line}`),
2373
+ "fi",
2374
+ `printf '${CANCELLED_SENTINEL}\\n'`
2375
+ ].join("\n");
2376
+ }
2377
+ function parseCancellationResult(provider, paths, descriptorKey, output) {
2378
+ if (output.trim() === CANCELLED_SENTINEL) return { state: "cancelled" };
2379
+ if (output.trim() === RELEASED_GENERATION_UNAVAILABLE_SENTINEL) {
2380
+ return { state: "released_generation_unavailable" };
2381
+ }
2382
+ const identity = parseReleasedIdentity(
2383
+ provider,
2384
+ paths,
2385
+ descriptorKey,
2386
+ output
2387
+ );
2388
+ return identity ? { state: "released", identity } : null;
2389
+ }
2390
+ function buildStopDetachedCommand(paths, expected) {
2391
+ return [
2392
+ "umask 077",
2393
+ ...secureDetachedRoot(),
2394
+ ...secureLaunchDirectory(paths, false),
2395
+ ...identityFunctions(paths),
2396
+ ...processTreeFunctions(paths),
2397
+ "read_launch_identity || exit 1",
2398
+ `[ "$target_pid:$target_ticks:$target_session:$target_descriptor" = ${shellQuote(
2399
+ `${expected.pid}:${expected.startTicks}:${expected.sessionId}:${expected.descriptorKey}`
2400
+ )} ] || exit 1`,
2401
+ "# Revalidate the leader birth immediately before every scan and every kill.",
2402
+ ...stopTargetCommands(),
2403
+ `printf '${STOPPED_SENTINEL}\\n'`
2404
+ ].join("\n");
2405
+ }
2406
+ function disposableLaunchDirectoryProof(paths, expected, namespace) {
2407
+ const readIdentity = `read_exact_${namespace}_identity`;
2408
+ const readStarted = `read_exact_${namespace}_started`;
2409
+ const readQuiescent = `read_exact_${namespace}_quiescent`;
2410
+ const readEmptyQuiescent = `read_exact_${namespace}_empty_quiescent`;
2411
+ const expectedIdentity = `${expected.pid}:${expected.startTicks}:${expected.sessionId}:` + expected.descriptorKey;
2412
+ return [
2413
+ ...secureLaunchDirectory(paths, false),
2414
+ ...identityFunctions(paths),
2415
+ ...exactLifecycleMarkerFunction(
2416
+ readIdentity,
2417
+ `exact_${namespace}_identity`,
2418
+ paths.record,
2419
+ { kind: "populated", markerPrefix: IDENTITY_PREFIX }
2420
+ ),
2421
+ ...exactLifecycleMarkerFunction(
2422
+ readStarted,
2423
+ `exact_${namespace}_started`,
2424
+ paths.started,
2425
+ { kind: "populated", markerPrefix: STARTED_PREFIX }
2426
+ ),
2427
+ ...exactLifecycleMarkerFunction(
2428
+ readQuiescent,
2429
+ `exact_${namespace}_quiescent`,
2430
+ paths.quiescent,
2431
+ { kind: "populated", markerPrefix: QUIESCENT_PREFIX }
2432
+ ),
2433
+ ...exactLifecycleMarkerFunction(
2434
+ readEmptyQuiescent,
2435
+ `exact_${namespace}_empty_quiescent`,
2436
+ paths.quiescent,
2437
+ { kind: "empty" }
2438
+ ),
2439
+ "read_launch_identity || exit 1",
2440
+ `[ "$target_pid:$target_ticks:$target_session:$target_descriptor" = ${shellQuote(expectedIdentity)} ] || exit 1`,
2441
+ '[ "$target_reaper_protocol" = v3 ] || exit 1',
2442
+ `${readIdentity} || exit 1`,
2443
+ "leader_identity_status",
2444
+ `${namespace}_leader_status=$?`,
2445
+ `[ "$${namespace}_leader_status" -ne 0 ] || exit 1`,
2446
+ `${readStarted}`,
2447
+ `${namespace}_started_status=$?`,
2448
+ `case "$${namespace}_started_status" in`,
2449
+ ` 0) ${readQuiescent} || exit 1 ;;`,
2450
+ ` 1) ${readEmptyQuiescent} || exit 1 ;;`,
2451
+ " *) exit 1 ;;",
2452
+ "esac"
2453
+ ];
2454
+ }
2455
+ function buildDisposeDetachedArtifactsCommand(paths, expected) {
2456
+ const disposedDirectory = disposedDirectoryForIdentity(expected);
2457
+ const retiredPaths = pathsForDetachedLaunchDirectory(
2458
+ paths,
2459
+ paths.retiredDirectory
2460
+ );
2461
+ return [
2462
+ "umask 077",
2463
+ ...acquireGenerationLock(paths),
2464
+ `if [ -e ${shellQuote(disposedDirectory)} ] || [ -L ${shellQuote(disposedDirectory)} ]; then`,
2465
+ ...secureDirectory(disposedDirectory, false).map((line) => ` ${line}`),
2466
+ ` rm -rf -- ${shellQuote(disposedDirectory)} || exit 1`,
2467
+ ` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
2468
+ "fi",
2469
+ `if [ -e ${shellQuote(paths.retiredDirectory)} ] || [ -L ${shellQuote(paths.retiredDirectory)} ]; then`,
2470
+ ...disposableLaunchDirectoryProof(
2471
+ retiredPaths,
2472
+ expected,
2473
+ "retired_disposal"
2474
+ ).map((line) => ` ${line}`),
2475
+ ` mv -- ${shellQuote(paths.retiredDirectory)} ${shellQuote(disposedDirectory)} || exit 1`,
2476
+ ...secureDirectory(disposedDirectory, false).map((line) => ` ${line}`),
2477
+ ` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
2478
+ ` rm -rf -- ${shellQuote(disposedDirectory)} || exit 1`,
2479
+ ` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
2480
+ "fi",
2481
+ `if [ -e ${shellQuote(paths.directory)} ] || [ -L ${shellQuote(paths.directory)} ]; then`,
2482
+ ...disposableLaunchDirectoryProof(paths, expected, "live_disposal").map(
2483
+ (line) => ` ${line}`
2484
+ ),
2485
+ ` mv -- ${shellQuote(paths.directory)} ${shellQuote(disposedDirectory)} || exit 1`,
2486
+ ...secureDirectory(disposedDirectory, false).map((line) => ` ${line}`),
2487
+ ` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
2488
+ ` rm -rf -- ${shellQuote(disposedDirectory)} || exit 1`,
2489
+ ` sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
2490
+ "fi",
2491
+ `if [ -e ${shellQuote(disposedDirectory)} ] || [ -L ${shellQuote(disposedDirectory)} ]; then exit 1; fi`,
2492
+ `if [ -e ${shellQuote(paths.retiredDirectory)} ] || [ -L ${shellQuote(paths.retiredDirectory)} ]; then exit 1; fi`,
2493
+ `if [ -e ${shellQuote(paths.directory)} ] || [ -L ${shellQuote(paths.directory)} ]; then exit 1; fi`,
2494
+ "assert_generation_lock || exit 1",
2495
+ `rm -f -- ${shellQuote(paths.controlLock)} || exit 1`,
2496
+ `if [ -e ${shellQuote(paths.controlLock)} ] || [ -L ${shellQuote(paths.controlLock)} ]; then exit 1; fi`,
2497
+ `sync -f ${shellQuote(DETACHED_PROCESS_ROOT)} || exit 1`,
2498
+ `printf '${DISPOSED_SENTINEL}
2499
+ '`
2500
+ ].join("\n");
2501
+ }
2502
+ function isDisposeConfirmation(output) {
2503
+ return output.trim() === DISPOSED_SENTINEL;
2504
+ }
2505
+ function buildReadDetachedLogsCommand(expected) {
2506
+ const paths = pathsForIdentity(expected);
2507
+ const expectedIdentity = `${expected.pid}:${expected.startTicks}:${expected.sessionId}:${expected.descriptorKey}`;
2508
+ return [
2509
+ "umask 077",
2510
+ ...secureDetachedRoot(),
2511
+ ...secureLaunchDirectory(paths, false),
2512
+ ...identityFunctions(paths),
2513
+ ...processTreeFunctions(paths),
2514
+ "read_launch_identity || exit 1",
2515
+ `[ "$target_pid:$target_ticks:$target_session:$target_descriptor" = ${shellQuote(expectedIdentity)} ] || exit 3`,
2516
+ ...readLogFiles(
2517
+ paths.stdout,
2518
+ paths.stderr,
2519
+ {
2520
+ stdout: previousLogPath(paths.stdout),
2521
+ stderr: previousLogPath(paths.stderr)
2522
+ },
2523
+ [
2524
+ "read_launch_identity || exit 1",
2525
+ `[ "$target_pid:$target_ticks:$target_session:$target_descriptor" = ${shellQuote(expectedIdentity)} ] || exit 3`
2526
+ ]
2527
+ )
2528
+ ].join("\n");
2529
+ }
2530
+ function buildReadLegacyDetachedLogsCommand(nonce) {
2531
+ const stdout = `${DETACHED_PROCESS_ROOT}/${nonce}.stdout.log`;
2532
+ const stderr = `${DETACHED_PROCESS_ROOT}/${nonce}.stderr.log`;
2533
+ return [
2534
+ "umask 077",
2535
+ ...secureDetachedRoot(),
2536
+ ...readLogFiles(stdout, stderr)
2537
+ ].join("\n");
2538
+ }
2539
+ function readLogFiles(stdout, stderr, previous, beforePrint = []) {
2540
+ const optionalPrevious = (path) => [
2541
+ `if [ -e ${shellQuote(path)} ] || [ -L ${shellQuote(path)} ]; then`,
2542
+ ...assertSafeRegularFile(path).map((line) => line.replace("return 1", "exit 1")).map((line) => ` ${line}`),
2543
+ "fi"
2544
+ ];
2545
+ const boundedPayload = (current, prior) => prior === void 0 ? `read_bounded_log_file ${shellQuote(current)}` : `read_bounded_log_snapshot ${shellQuote(current)} ${shellQuote(prior)} ${shellQuote(logSnapshotPath(current))}`;
2546
+ return [
2547
+ ...previous === void 0 ? [] : [...optionalPrevious(previous.stdout), ...optionalPrevious(previous.stderr)],
2548
+ "command -v base64 >/dev/null 2>&1 || exit 1",
2549
+ ...previous === void 0 ? [] : ["command -v head >/dev/null 2>&1 || exit 1"],
2550
+ "command -v tail >/dev/null 2>&1 || exit 1",
2551
+ "command -v tr >/dev/null 2>&1 || exit 1",
2552
+ "close_log_segment_descriptors() {",
2553
+ " exec 6<&-",
2554
+ " exec 7<&-",
2555
+ "}",
2556
+ "assert_log_segment_descriptor() {",
2557
+ " snapshot_log_path=$1",
2558
+ " snapshot_log_fd=$2",
2559
+ ' [ -f "$snapshot_log_path" ] && [ ! -L "$snapshot_log_path" ] || return 1',
2560
+ ' [ -f "/proc/self/fd/$snapshot_log_fd" ] || return 1',
2561
+ ' snapshot_log_path_metadata=$(stat -c %u:%a:%h "$snapshot_log_path" 2>/dev/null) || return 1',
2562
+ ' snapshot_log_descriptor_metadata=$(stat -Lc %u:%a:%h "/proc/self/fd/$snapshot_log_fd" 2>/dev/null) || return 1',
2563
+ ' [ "$snapshot_log_path_metadata" = "$(id -u):600:1" ] || return 1',
2564
+ ' [ "$snapshot_log_descriptor_metadata" = "$snapshot_log_path_metadata" ] || return 1',
2565
+ ' snapshot_log_path_inode=$(stat -c %d:%i "$snapshot_log_path" 2>/dev/null) || return 1',
2566
+ ' snapshot_log_descriptor_inode=$(stat -Lc %d:%i "/proc/self/fd/$snapshot_log_fd" 2>/dev/null) || return 1',
2567
+ ' [ "$snapshot_log_descriptor_inode" = "$snapshot_log_path_inode" ]',
2568
+ "}",
2569
+ "read_bounded_log_file() {",
2570
+ " snapshot_current=$1",
2571
+ " close_log_segment_descriptors",
2572
+ ' [ -f "$snapshot_current" ] && [ ! -L "$snapshot_current" ] || return 1',
2573
+ ' exec 6<"$snapshot_current" || return 1',
2574
+ ' assert_log_segment_descriptor "$snapshot_current" 6 || { close_log_segment_descriptors; return 1; }',
2575
+ ` tail -c ${DETACHED_PROCESS_LOG_MAX_BYTES} -- /proc/self/fd/6 | base64 6<&- 7<&- | tr -d '\\n' 6<&- 7<&-`,
2576
+ " snapshot_segment_status=$?",
2577
+ " close_log_segment_descriptors",
2578
+ ' return "$snapshot_segment_status"',
2579
+ "}",
2580
+ ...previous === void 0 ? [] : [
2581
+ "read_log_snapshot_marker() {",
2582
+ " snapshot_marker_path=$1",
2583
+ ' [ -e "$snapshot_marker_path" ] || return 1',
2584
+ ' [ -f "$snapshot_marker_path" ] && [ ! -L "$snapshot_marker_path" ] || return 1',
2585
+ ` snapshot_marker=$(head -c ${DETACHED_PROCESS_LOG_SNAPSHOT_MAX_BYTES + 1} -- "$snapshot_marker_path") || return 1`,
2586
+ ` [ "\${#snapshot_marker}" -le ${DETACHED_PROCESS_LOG_SNAPSHOT_MAX_BYTES} ] || return 1`,
2587
+ ` 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" }')`,
2588
+ ' [ "$snapshot_marker_valid" = yes ] || return 1',
2589
+ ` printf '%s\\n' "$snapshot_marker"`,
2590
+ "}",
2591
+ "read_legacy_log_snapshot() {",
2592
+ " snapshot_current=$1",
2593
+ " snapshot_previous=$2",
2594
+ " snapshot_marker_path=$3",
2595
+ " snapshot_attempt=0",
2596
+ ` while [ "$snapshot_attempt" -lt ${DETACHED_PROCESS_LEGACY_LOG_SNAPSHOT_ATTEMPTS} ]; do`,
2597
+ ' snapshot_before=$(read_log_snapshot_marker "$snapshot_marker_path") || return 1',
2598
+ ` 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`,
2599
+ ' snapshot_payload=$(read_bounded_log_segments "$snapshot_current" "$snapshot_previous") || return 1',
2600
+ ' snapshot_after=$(read_log_snapshot_marker "$snapshot_marker_path") || return 1',
2601
+ ' if [ "$snapshot_before" = "$snapshot_after" ]; then',
2602
+ ` printf '%s' "$snapshot_payload"`,
2603
+ " return 0",
2604
+ " fi",
2605
+ " snapshot_attempt=$((snapshot_attempt + 1))",
2606
+ " sleep 0.01",
2607
+ " done",
2608
+ " return 1",
2609
+ "}",
2610
+ "target_is_quiescent() {",
2611
+ " target_has_live_processes",
2612
+ " snapshot_process_status=$?",
2613
+ ' [ "$snapshot_process_status" -eq 1 ]',
2614
+ "}",
2615
+ "open_log_segment_descriptors() {",
2616
+ " snapshot_current=$1",
2617
+ " snapshot_previous=$2",
2618
+ " close_log_segment_descriptors",
2619
+ ' [ -f "$snapshot_current" ] && [ ! -L "$snapshot_current" ] || return 1',
2620
+ ' exec 6<"$snapshot_current" || return 1',
2621
+ ' assert_log_segment_descriptor "$snapshot_current" 6 || { close_log_segment_descriptors; return 1; }',
2622
+ " snapshot_has_previous=no",
2623
+ ' if [ -e "$snapshot_previous" ] || [ -L "$snapshot_previous" ]; then',
2624
+ ' [ -f "$snapshot_previous" ] && [ ! -L "$snapshot_previous" ] || { close_log_segment_descriptors; return 1; }',
2625
+ ' exec 7<"$snapshot_previous" || { close_log_segment_descriptors; return 1; }',
2626
+ ' assert_log_segment_descriptor "$snapshot_previous" 7 || { close_log_segment_descriptors; return 1; }',
2627
+ " snapshot_has_previous=yes",
2628
+ " fi",
2629
+ ' assert_log_segment_descriptor "$snapshot_current" 6 || { close_log_segment_descriptors; return 1; }',
2630
+ ' if [ "$snapshot_has_previous" = yes ]; then',
2631
+ ' assert_log_segment_descriptor "$snapshot_previous" 7 || { close_log_segment_descriptors; return 1; }',
2632
+ " fi",
2633
+ "}",
2634
+ "read_bounded_log_segments() {",
2635
+ " snapshot_current=$1",
2636
+ " snapshot_previous=$2",
2637
+ ' open_log_segment_descriptors "$snapshot_current" "$snapshot_previous" || return 1',
2638
+ ` { 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<&-`,
2639
+ " snapshot_segment_status=$?",
2640
+ " close_log_segment_descriptors",
2641
+ ' return "$snapshot_segment_status"',
2642
+ "}",
2643
+ "read_v2_log_snapshot() {",
2644
+ " snapshot_current=$1",
2645
+ " snapshot_previous=$2",
2646
+ " snapshot_marker_path=$3",
2647
+ " snapshot_attempt=0",
2648
+ ` while [ "$snapshot_attempt" -lt ${DETACHED_PROCESS_LEGACY_LOG_SNAPSHOT_ATTEMPTS} ]; do`,
2649
+ " snapshot_before=",
2650
+ ' if [ ! -e "$snapshot_marker_path" ] && [ ! -L "$snapshot_marker_path" ]; then',
2651
+ " # Markerless V2 logs predate marker coordination and are safe",
2652
+ " # to inspect only after their exact process session is quiescent.",
2653
+ " target_is_quiescent || return 1",
2654
+ " else",
2655
+ ' snapshot_before=$(read_log_snapshot_marker "$snapshot_marker_path") || return 1',
2656
+ ` 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`,
2657
+ " fi",
2658
+ ' if [ ! -e "$snapshot_current" ] && [ ! -L "$snapshot_current" ]; then',
2659
+ " # A crashed rotation may strand current absent after it became",
2660
+ " # previous. Recreate it only after the captured session is gone.",
2661
+ " target_is_quiescent || return 1",
2662
+ ' ( set -C; : > "$snapshot_current" ) 2>/dev/null || true',
2663
+ ' [ -e "$snapshot_current" ] || return 1',
2664
+ ' chmod 600 "$snapshot_current" || return 1',
2665
+ " fi",
2666
+ ' [ -f "$snapshot_current" ] && [ ! -L "$snapshot_current" ] || return 1',
2667
+ ' if [ -e "$snapshot_previous" ] || [ -L "$snapshot_previous" ]; then',
2668
+ ' [ -f "$snapshot_previous" ] && [ ! -L "$snapshot_previous" ] || return 1',
2669
+ " fi",
2670
+ ' snapshot_payload=$(read_bounded_log_segments "$snapshot_current" "$snapshot_previous") || return 1',
2671
+ ' if [ -z "$snapshot_before" ]; then',
2672
+ ` printf '%s' "$snapshot_payload"`,
2673
+ " return 0",
2674
+ " fi",
2675
+ ' snapshot_after=$(read_log_snapshot_marker "$snapshot_marker_path") || return 1',
2676
+ ' if [ "$snapshot_before" = "$snapshot_after" ]; then',
2677
+ ` printf '%s' "$snapshot_payload"`,
2678
+ " return 0",
2679
+ " fi",
2680
+ " snapshot_attempt=$((snapshot_attempt + 1))",
2681
+ " sleep 0.01",
2682
+ " done",
2683
+ " return 1",
2684
+ "}",
2685
+ "read_bounded_log_snapshot() {",
2686
+ " snapshot_current=$1",
2687
+ " snapshot_previous=$2",
2688
+ " snapshot_marker_path=$3",
2689
+ ' if [ -e "$snapshot_marker_path" ] && [ ! -L "$snapshot_marker_path" ]; then',
2690
+ ' snapshot_protocol=$(read_log_snapshot_marker "$snapshot_marker_path") || return 1',
2691
+ ` case "$snapshot_protocol" in '${LEGACY_LOG_SNAPSHOT_PREFIX} '*) read_legacy_log_snapshot "$snapshot_current" "$snapshot_previous" "$snapshot_marker_path"; return $? ;; esac`,
2692
+ " fi",
2693
+ ' read_v2_log_snapshot "$snapshot_current" "$snapshot_previous" "$snapshot_marker_path"',
2694
+ "}"
2695
+ ],
2696
+ `stdout_payload=$(${boundedPayload(stdout, previous?.stdout)}) || exit 1`,
2697
+ `stderr_payload=$(${boundedPayload(stderr, previous?.stderr)}) || exit 1`,
2698
+ ...beforePrint,
2699
+ 'stdout_padding=0; case "$stdout_payload" in *==) stdout_padding=2 ;; *=) stdout_padding=1 ;; esac',
2700
+ 'stderr_padding=0; case "$stderr_payload" in *==) stderr_padding=2 ;; *=) stderr_padding=1 ;; esac',
2701
+ "stdout_size=$((${#stdout_payload} / 4 * 3 - stdout_padding))",
2702
+ "stderr_size=$((${#stderr_payload} / 4 * 3 - stderr_padding))",
2703
+ `printf '${LOGS_PREFIX} %s %s\\n' "$stdout_size" "$stderr_size"`,
2704
+ `printf '%s\\n%s\\n' "$stdout_payload" "$stderr_payload"`
2705
+ ];
2706
+ }
2707
+ function parseDetachedProcessLogs(output) {
2708
+ const lineEnd = output.indexOf("\n");
2709
+ if (lineEnd < 0) return null;
2710
+ const header = output.slice(0, lineEnd);
2711
+ const match = new RegExp(`^${LOGS_PREFIX} (0|[1-9][0-9]*) (0|[1-9][0-9]*)$`, "u").exec(
2712
+ header
2713
+ );
2714
+ if (!match?.[1] || !match[2]) return null;
2715
+ const stdoutBytes = Number(match[1]);
2716
+ const stderrBytes = Number(match[2]);
2717
+ if (!Number.isSafeInteger(stdoutBytes) || !Number.isSafeInteger(stderrBytes) || stdoutBytes > DETACHED_PROCESS_LOG_MAX_BYTES || stderrBytes > DETACHED_PROCESS_LOG_MAX_BYTES) {
2718
+ return null;
2719
+ }
2720
+ const payloadLines = output.slice(lineEnd + 1).split("\n");
2721
+ if (payloadLines.length !== 3 || payloadLines[2] !== "") return null;
2722
+ const [stdoutBase64, stderrBase64] = payloadLines;
2723
+ if (stdoutBase64 === void 0 || stderrBase64 === void 0) return null;
2724
+ if (stdoutBase64.length !== 4 * Math.ceil(stdoutBytes / 3) || stderrBase64.length !== 4 * Math.ceil(stderrBytes / 3)) {
2725
+ return null;
2726
+ }
2727
+ const decodeCanonicalBase64 = (value) => {
2728
+ const decoded = Buffer.from(value, "base64");
2729
+ return decoded.toString("base64") === value ? decoded : null;
2730
+ };
2731
+ const stdout = decodeCanonicalBase64(stdoutBase64);
2732
+ const stderr = decodeCanonicalBase64(stderrBase64);
2733
+ if (!stdout || !stderr || stdout.byteLength !== stdoutBytes || stderr.byteLength !== stderrBytes || !(0, import_node_buffer.isUtf8)(stdout) || !(0, import_node_buffer.isUtf8)(stderr)) {
2734
+ return null;
2735
+ }
2736
+ return {
2737
+ stdout: stdout.toString("utf8"),
2738
+ stderr: stderr.toString("utf8")
2739
+ };
2740
+ }
2741
+ function isStopConfirmation(output) {
2742
+ return output.trim() === STOPPED_SENTINEL;
2743
+ }
2744
+
2745
+ // src/providers/daytona-transport.ts
2746
+ var import_node_buffer2 = require("buffer");
2747
+ function daytonaTimeoutSeconds(timeoutMs) {
2748
+ return Math.max(1, Math.ceil(timeoutMs / 1e3));
2749
+ }
2750
+ function daytonaCommandOutput(result) {
2751
+ return result.artifacts?.stdout || result.result || "";
2752
+ }
2753
+ async function discoverDaytonaSandboxDirectories(sandbox, options) {
2754
+ await options.beforeIo?.();
2755
+ const reportedWorkDir = await sandbox.getWorkDir();
2756
+ await options.beforeIo?.();
2757
+ const reportedHomeDir = await sandbox.getUserHomeDir();
2758
+ const workDir = reportedWorkDir ?? reportedHomeDir;
2759
+ const homeDir = reportedHomeDir ?? workDir;
2760
+ if (!homeDir || !workDir) {
2761
+ throw options.failure(
2762
+ "Daytona sandbox did not report a home or working directory."
2763
+ );
2764
+ }
2765
+ return { homeDir, workDir };
2766
+ }
2767
+ async function executeDaytonaCommand(sandbox, command, options) {
2768
+ const result = await executeRawDaytonaCommand(sandbox, command, options);
2769
+ return {
2770
+ exitCode: result.exitCode,
2771
+ stdout: daytonaCommandOutput(result),
2772
+ stderr: ""
2773
+ };
2774
+ }
2775
+ async function executeRawDaytonaCommand(sandbox, command, options) {
2776
+ await options.beforeIo?.();
2777
+ return sandbox.process.executeCommand(
2778
+ command,
2779
+ options.cwd,
2780
+ options.envs,
2781
+ daytonaTimeoutSeconds(options.timeoutMs)
2782
+ );
2783
+ }
2784
+ async function makeDaytonaDirectory(sandbox, path, options) {
2785
+ return executeRawDaytonaCommand(
2786
+ sandbox,
2787
+ `mkdir -p -- ${shellQuote(path)}`,
2788
+ options
2789
+ );
2790
+ }
2791
+ function daytonaUploadContent(content) {
2792
+ if (import_node_buffer2.Buffer.isBuffer(content)) return content;
2793
+ if (typeof content === "string") return import_node_buffer2.Buffer.from(content);
2794
+ if (content instanceof Uint8Array) return import_node_buffer2.Buffer.from(content);
2795
+ return import_node_buffer2.Buffer.from(content);
2796
+ }
2797
+ async function uploadDaytonaFile(sandbox, path, content, options) {
2798
+ await options.beforeIo?.();
2799
+ await sandbox.fs.uploadFile(
2800
+ daytonaUploadContent(content),
2801
+ path,
2802
+ daytonaTimeoutSeconds(options.timeoutMs)
2803
+ );
2804
+ }
2805
+ function createDaytonaProcessController(sandbox, options) {
2806
+ return new DetachedProcessController({
2807
+ provider: "daytona",
2808
+ ...options.homeDir === void 0 ? {} : { genericPayloadEnvironmentDefaults: { HOME: options.homeDir } },
2809
+ ...options.beforePrepareMutation === void 0 ? {} : { beforePrepareMutation: options.beforePrepareMutation },
2810
+ ...options.beforeStopOrDisposeMutation === void 0 ? {} : {
2811
+ beforeStopOrDisposeMutation: options.beforeStopOrDisposeMutation
2812
+ },
2813
+ execute: async (command, commandOptions) => {
2814
+ try {
2815
+ const result = await executeDaytonaCommand(sandbox, command, {
2816
+ timeoutMs: DETACHED_PROCESS_CONTROL_TIMEOUT_MS,
2817
+ ...commandOptions?.cwd === void 0 ? {} : { cwd: commandOptions.cwd },
2818
+ ...commandOptions?.envs === void 0 ? {} : { envs: commandOptions.envs }
2819
+ });
2820
+ return { state: "completed", result };
2821
+ } catch (error) {
2822
+ return { state: "failed", error };
2823
+ }
2824
+ },
2825
+ readLegacyLogs: options.readLegacyLogs,
2826
+ stopLegacy: options.stopLegacy,
2827
+ failure: options.failure
2828
+ });
2829
+ }
2830
+ function createDaytonaDetachedProcessController(sandbox, options) {
2831
+ const controller = createDaytonaProcessController(sandbox, options);
2832
+ return {
2833
+ start: (command, startOptions) => controller.start(command, startOptions),
2834
+ readLogs: (command) => controller.readLogs(command),
2835
+ stop: (command) => controller.stop(command),
2836
+ dispose: (command) => controller.dispose(command)
2837
+ };
2838
+ }
2839
+
2840
+ // src/providers/types.ts
2841
+ function createProviderSandboxPaths(provider, homeDir, workDir) {
2842
+ const agentDir = `${homeDir}/agent`;
2843
+ const ioDir = `${homeDir}/io`;
2844
+ return {
2845
+ provider,
2846
+ homeDir,
2847
+ workDir,
2848
+ agentDir,
2849
+ ioDir,
2850
+ inputJson: `${ioDir}/input.json`,
2851
+ outputJson: `${ioDir}/output.json`,
2852
+ agentModule: `${agentDir}/agent.mjs`,
2853
+ serverModule: `${agentDir}/server.mjs`,
2854
+ serverConfig: `${agentDir}/server-config.json`,
2855
+ claudeDir: `${agentDir}/.claude`,
2856
+ packageJson: `${agentDir}/package.json`
2857
+ };
2858
+ }
2859
+
2860
+ // src/providers/daytona.ts
2861
+ var SANDBOX_COMMAND_TIMEOUT_MS = 3e5;
2862
+ var QUICK_COMMAND_TIMEOUT_MS = 3e4;
2863
+ var LEGACY_DAYTONA_PROCESS_PATTERN = /^daytona-process:(\d+):(\d+):([a-z0-9-]+)$/iu;
2864
+ function parseLegacyDaytonaProcessHandle(sessionId) {
2865
+ const match = LEGACY_DAYTONA_PROCESS_PATTERN.exec(sessionId);
2866
+ if (!match) return null;
2867
+ const [, pid, startTicks, nonce] = match;
2868
+ return pid && startTicks && nonce ? { pid, startTicks, nonce } : null;
2869
+ }
2870
+ var DaytonaSandboxHandle = class _DaytonaSandboxHandle {
2871
+ constructor(sandbox, paths, failure) {
2872
+ this.sandbox = sandbox;
2873
+ this.paths = paths;
2874
+ this.failure = failure;
2875
+ this.detachedProcesses = createDaytonaDetachedProcessController(this.sandbox, {
2876
+ homeDir: this.paths.homeDir,
2877
+ readLegacyLogs: (command) => this.readLegacySessionLogs(command),
2878
+ stopLegacy: (command) => this.stopLegacySession(command),
2879
+ failure
2880
+ });
2881
+ }
2882
+ provider = "daytona";
2883
+ detachedProcesses;
2884
+ static async create(sandbox, failure) {
2885
+ const { homeDir, workDir } = await discoverDaytonaSandboxDirectories(
2886
+ sandbox,
2887
+ { failure }
2888
+ );
2889
+ return new _DaytonaSandboxHandle(
2890
+ sandbox,
2891
+ createProviderSandboxPaths("daytona", homeDir, workDir),
2892
+ failure
2893
+ );
2894
+ }
2895
+ get id() {
2896
+ return this.sandbox.id;
2897
+ }
2898
+ async makeDir(path) {
2899
+ const result = await makeDaytonaDirectory(this.sandbox, path, {
2900
+ timeoutMs: QUICK_COMMAND_TIMEOUT_MS
2901
+ });
2902
+ if (result.exitCode !== 0) {
2903
+ throw this.failure(result.result || `Failed to create directory ${path}`);
2904
+ }
2905
+ }
2906
+ writeFile(path, content) {
2907
+ return uploadDaytonaFile(this.sandbox, path, content, {
2908
+ timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
2909
+ });
2910
+ }
2911
+ async readFile(path) {
2912
+ const content = await this.sandbox.fs.downloadFile(
2913
+ path,
2914
+ daytonaTimeoutSeconds(SANDBOX_COMMAND_TIMEOUT_MS)
2915
+ );
2916
+ return content.toString("utf8");
2917
+ }
2918
+ async readFileBytes(path) {
2919
+ const content = await this.sandbox.fs.downloadFile(
2920
+ path,
2921
+ daytonaTimeoutSeconds(SANDBOX_COMMAND_TIMEOUT_MS)
2922
+ );
2923
+ return new Uint8Array(content);
2924
+ }
2925
+ async runCommand(cmd, options) {
2926
+ const result = await executeDaytonaCommand(this.sandbox, cmd, {
2927
+ timeoutMs: options.timeoutMs,
2928
+ ...options.cwd === void 0 ? {} : { cwd: options.cwd },
2929
+ ...options.envs === void 0 ? {} : { envs: options.envs }
2930
+ });
2931
+ if (result.stdout) options.onStdout?.(result.stdout);
2932
+ return result;
2933
+ }
2934
+ async startDetachedCommand(command, options = {}) {
2935
+ return this.detachedProcesses.start(command, options);
2936
+ }
2937
+ async readSessionLogs(command) {
2938
+ return this.detachedProcesses.readLogs(command);
2939
+ }
2940
+ async readLegacySessionLogs(command) {
2941
+ const { sessionId, commandId } = command;
2942
+ const legacy = parseLegacyDaytonaProcessHandle(sessionId);
2943
+ if (legacy) {
2944
+ try {
2945
+ const result = await executeDaytonaCommand(
2946
+ this.sandbox,
2947
+ buildReadLegacyDetachedLogsCommand(legacy.nonce),
2948
+ { timeoutMs: QUICK_COMMAND_TIMEOUT_MS }
2949
+ );
2950
+ return result.exitCode === 0 ? parseDetachedProcessLogs(result.stdout) ?? { stdout: "", stderr: "" } : { stdout: "", stderr: "" };
2951
+ } catch {
2952
+ return { stdout: "", stderr: "" };
2953
+ }
2954
+ }
2955
+ if (commandId === void 0) return { stdout: "", stderr: "" };
2956
+ try {
2957
+ const logs = await this.sandbox.process.getSessionCommandLogs(sessionId, commandId);
2958
+ return {
2959
+ stdout: boundDetachedProcessLog(logs.stdout ?? logs.output ?? ""),
2960
+ stderr: boundDetachedProcessLog(logs.stderr ?? "")
2961
+ };
2962
+ } catch {
2963
+ return { stdout: "", stderr: "" };
2964
+ }
2965
+ }
2966
+ async stopSession(command) {
2967
+ await this.detachedProcesses.stop(command);
2968
+ }
2969
+ async disposeSessionArtifacts(command) {
2970
+ await this.detachedProcesses.dispose(command);
2971
+ }
2972
+ async stopLegacySession(command) {
2973
+ const { sessionId } = command;
2974
+ const detached = parseLegacyDaytonaProcessHandle(sessionId);
2975
+ if (!detached) {
2976
+ await this.sandbox.process.deleteSession(sessionId);
2977
+ return;
2978
+ }
2979
+ const result = await executeRawDaytonaCommand(
2980
+ this.sandbox,
2981
+ buildLegacyDetachedStopCommand(detached.pid, detached.startTicks, "Daytona"),
2982
+ { timeoutMs: QUICK_COMMAND_TIMEOUT_MS }
2983
+ );
2984
+ if (result.exitCode !== 0) {
2985
+ throw this.failure(
2986
+ result.result || `Failed to stop detached Daytona process ${detached.pid}.`
2987
+ );
2988
+ }
2989
+ }
2990
+ async getServerEndpoint(port) {
2991
+ const preview = await this.sandbox.getPreviewLink(port);
2992
+ return { url: preview.url, trafficToken: preview.token };
2993
+ }
2994
+ destroy() {
2995
+ return this.sandbox.delete(
2996
+ daytonaTimeoutSeconds(SANDBOX_COMMAND_TIMEOUT_MS),
2997
+ true
2998
+ );
2999
+ }
3000
+ };
3001
+
3002
+ // src/timeout.ts
3003
+ function settleOperation(operation, options = {}) {
3004
+ const { abort, timeout } = options;
3005
+ if (abort?.signal.aborted) throw abort.createError();
3006
+ if (!abort && !timeout) {
3007
+ try {
3008
+ return Promise.resolve(operation());
3009
+ } catch (error) {
3010
+ return Promise.reject(error);
3011
+ }
3012
+ }
3013
+ return new Promise((resolve2, reject) => {
3014
+ let settled = false;
3015
+ let timer;
3016
+ const cleanup = () => {
3017
+ if (timer !== void 0) {
3018
+ clearTimeout(timer);
3019
+ timer = void 0;
3020
+ }
3021
+ abort?.signal.removeEventListener("abort", onAbort);
3022
+ };
3023
+ const settle = (callback) => {
3024
+ if (settled) return;
3025
+ settled = true;
3026
+ cleanup();
3027
+ callback();
3028
+ };
3029
+ const onAbort = () => settle(() => reject(abort.createError()));
3030
+ abort?.signal.addEventListener("abort", onAbort, { once: true });
3031
+ if (timeout) {
3032
+ timer = setTimeout(
3033
+ () => settle(() => reject(timeout.createError())),
3034
+ timeout.timeoutMs
3035
+ );
3036
+ }
3037
+ let task;
3038
+ try {
3039
+ task = operation();
3040
+ } catch (error) {
3041
+ settle(() => reject(error));
3042
+ return;
3043
+ }
3044
+ void Promise.resolve(task).then(
3045
+ (value) => settle(() => resolve2(value)),
3046
+ (error) => settle(() => reject(error))
3047
+ );
3048
+ });
3049
+ }
3050
+ function withTimeout(task, timeoutMs, message) {
3051
+ return settleOperation(() => task, {
3052
+ timeout: {
3053
+ timeoutMs,
3054
+ createError: () => new Error(message)
3055
+ }
3056
+ });
3057
+ }
3058
+
3059
+ // src/providers/e2b.ts
3060
+ var E2B_SANDBOX_HOME = "/home/user";
3061
+ var LEGACY_E2B_PROCESS_HANDLE_PATTERN = /^e2b:([1-9][0-9]*)$/u;
3062
+ var LEGACY_E2B_EXIT_POLL_INTERVAL_MS = 100;
3063
+ function parseLegacyE2bProcessHandle(value) {
3064
+ const match = LEGACY_E2B_PROCESS_HANDLE_PATTERN.exec(value);
3065
+ if (!match) return null;
3066
+ const pid = Number(match[1]);
3067
+ return Number.isSafeInteger(pid) && pid > 0 ? pid : null;
3068
+ }
3069
+ function remainingTimeoutMs(deadline) {
3070
+ return Math.max(1, Math.ceil(deadline - performance.now()));
3071
+ }
3072
+ function delay(timeoutMs) {
3073
+ return new Promise((resolve2) => setTimeout(resolve2, timeoutMs));
3074
+ }
3075
+ async function withinDeadline(operation, deadline) {
3076
+ return withTimeout(
3077
+ operation,
3078
+ remainingTimeoutMs(deadline),
3079
+ "E2B process control request timed out."
3080
+ );
3081
+ }
3082
+ function numberProperty(value, property) {
3083
+ if (typeof value !== "object" || value === null) return void 0;
3084
+ const propertyValue = Reflect.get(value, property);
3085
+ return typeof propertyValue === "number" ? propertyValue : void 0;
3086
+ }
3087
+ function stringProperty(value, property) {
3088
+ if (typeof value !== "object" || value === null) return void 0;
3089
+ const propertyValue = Reflect.get(value, property);
3090
+ return typeof propertyValue === "string" ? propertyValue : void 0;
3091
+ }
3092
+ function messageFrom2(error) {
3093
+ return error instanceof Error ? error.message : String(error);
3094
+ }
3095
+ function writeContent(content) {
3096
+ if (typeof content === "string") return content;
3097
+ if (content instanceof ArrayBuffer) return content;
3098
+ return Uint8Array.from(content).buffer;
3099
+ }
3100
+ async function runE2bCommand(sandbox, cmd, options) {
3101
+ let stdout = "";
3102
+ let stderr = "";
3103
+ const command = options.cwd ? `cd ${shellQuote(options.cwd)} && ${cmd}` : cmd;
3104
+ try {
3105
+ const result = await sandbox.commands.run(command, {
3106
+ timeoutMs: options.timeoutMs,
3107
+ envs: options.envs,
3108
+ background: false,
3109
+ onStdout: (data) => {
3110
+ stdout += data;
3111
+ options.onStdout?.(data);
3112
+ },
3113
+ onStderr: (data) => {
3114
+ stderr += data;
3115
+ options.onStderr?.(data);
3116
+ }
3117
+ });
3118
+ return {
3119
+ exitCode: result.exitCode,
3120
+ stdout: stdout || result.stdout,
3121
+ stderr: stderr || result.stderr
3122
+ };
3123
+ } catch (error) {
3124
+ return {
3125
+ exitCode: numberProperty(error, "exitCode") ?? 1,
3126
+ stdout: stdout || stringProperty(error, "stdout") || "",
3127
+ stderr: stderr || stringProperty(error, "stderr") || messageFrom2(error)
3128
+ };
3129
+ }
3130
+ }
3131
+ var E2bSandboxHandle = class {
3132
+ constructor(sandbox, failure) {
3133
+ this.sandbox = sandbox;
3134
+ this.failure = failure;
3135
+ this.detachedProcesses = new DetachedProcessController({
3136
+ provider: "e2b",
3137
+ genericPayloadEnvironmentDefaults: { HOME: this.paths.homeDir },
3138
+ execute: async (command, options) => ({
3139
+ state: "completed",
3140
+ result: await runE2bCommand(this.sandbox, command, {
3141
+ cwd: options?.cwd,
3142
+ envs: options?.envs,
3143
+ timeoutMs: DETACHED_PROCESS_CONTROL_TIMEOUT_MS
3144
+ })
3145
+ }),
3146
+ readLegacyLogs: (command) => this.readLegacySessionLogs(command),
3147
+ stopLegacy: (command) => this.stopLegacySession(command),
3148
+ failure
3149
+ });
3150
+ }
3151
+ provider = "e2b";
3152
+ detachedProcesses;
3153
+ paths = createProviderSandboxPaths(
3154
+ "e2b",
3155
+ E2B_SANDBOX_HOME,
3156
+ E2B_SANDBOX_HOME
3157
+ );
3158
+ get id() {
3159
+ return this.sandbox.sandboxId;
3160
+ }
3161
+ async makeDir(path) {
3162
+ await this.sandbox.files.makeDir(path);
3163
+ }
3164
+ writeFile(path, content) {
3165
+ return this.sandbox.files.write(path, writeContent(content)).then(() => void 0);
3166
+ }
3167
+ readFile(path) {
3168
+ return this.sandbox.files.read(path, { format: "text" });
3169
+ }
3170
+ readFileBytes(path) {
3171
+ return this.sandbox.files.read(path, { format: "bytes" });
3172
+ }
3173
+ runCommand(cmd, options) {
3174
+ return runE2bCommand(this.sandbox, cmd, options);
3175
+ }
3176
+ setTimeout(timeoutMs) {
3177
+ return this.sandbox.setTimeout(timeoutMs);
3178
+ }
3179
+ async startDetachedCommand(command, options = {}) {
3180
+ return this.detachedProcesses.start(command, options);
3181
+ }
3182
+ async readSessionLogs(command) {
3183
+ return this.detachedProcesses.readLogs(command);
3184
+ }
3185
+ async readLegacySessionLogs(command) {
3186
+ const { commandId } = command;
3187
+ if (commandId === void 0) return { stdout: "", stderr: "" };
3188
+ try {
3189
+ const handle = await this.sandbox.commands.connect(Number(commandId));
3190
+ return {
3191
+ stdout: boundDetachedProcessLog(handle.stdout ?? ""),
3192
+ stderr: boundDetachedProcessLog(handle.stderr ?? "")
3193
+ };
3194
+ } catch {
3195
+ return { stdout: "", stderr: "" };
3196
+ }
3197
+ }
3198
+ async stopSession(command) {
3199
+ await this.detachedProcesses.stop(command);
3200
+ }
3201
+ async disposeSessionArtifacts(command) {
3202
+ await this.detachedProcesses.dispose(command);
3203
+ }
3204
+ async stopLegacySession(command) {
3205
+ const { sessionId } = command;
3206
+ const legacyPid = parseLegacyE2bProcessHandle(sessionId);
3207
+ if (legacyPid === null) {
3208
+ throw this.failure("Detached process handle is invalid for E2B.");
3209
+ }
3210
+ const deadline = performance.now() + DETACHED_PROCESS_CONTROL_TIMEOUT_MS;
3211
+ let signalled;
3212
+ try {
3213
+ signalled = await withinDeadline(
3214
+ this.sandbox.commands.kill(legacyPid, {
3215
+ requestTimeoutMs: remainingTimeoutMs(deadline)
3216
+ }),
3217
+ deadline
3218
+ );
3219
+ } catch (error) {
3220
+ throw this.failure(
3221
+ `Failed to stop legacy detached E2B process ${legacyPid}: ${messageFrom2(error)}`
3222
+ );
3223
+ }
3224
+ if (!signalled) return;
3225
+ while (performance.now() < deadline) {
3226
+ let processes;
3227
+ try {
3228
+ processes = await withinDeadline(
3229
+ this.sandbox.commands.list({
3230
+ requestTimeoutMs: remainingTimeoutMs(deadline)
3231
+ }),
3232
+ deadline
3233
+ );
3234
+ } catch (error) {
3235
+ throw this.failure(
3236
+ `Failed to confirm legacy detached E2B process ${legacyPid} exit: ${messageFrom2(error)}`
3237
+ );
3238
+ }
3239
+ if (!processes.some((process2) => process2.pid === legacyPid)) return;
3240
+ const remaining = deadline - performance.now();
3241
+ if (remaining <= 0) break;
3242
+ await delay(Math.min(LEGACY_E2B_EXIT_POLL_INTERVAL_MS, remaining));
3243
+ }
3244
+ throw this.failure(
3245
+ `Failed to stop legacy detached E2B process ${legacyPid}: provider still reports it as running.`
3246
+ );
3247
+ }
3248
+ async getServerEndpoint(port) {
3249
+ return {
3250
+ url: `https://${this.sandbox.getHost(port)}`,
3251
+ trafficToken: this.sandbox.trafficAccessToken
3252
+ };
220
3253
  }
221
- });
222
-
223
- // src/index.ts
224
- var index_exports = {};
225
- __export(index_exports, {
226
- Agent: () => Agent,
227
- ConfigurationError: () => ConfigurationError,
228
- DEFAULT_DEPENDENCIES: () => DEFAULT_DEPENDENCIES,
229
- DeploymentError: () => DeploymentError,
230
- ExecutionError: () => ExecutionError,
231
- NeckbeardError: () => NeckbeardError,
232
- SandboxClient: () => SandboxClient,
233
- ValidationError: () => ValidationError,
234
- normalizeStackFramePath: () => normalizeStackFramePath,
235
- resolveAgentSourceFile: () => resolveAgentSourceFile,
236
- withNeckbeardNextConfig: () => withNeckbeardNextConfig
237
- });
238
- module.exports = __toCommonJS(index_exports);
239
- var import_node_url = require("url");
240
- var import_node_fs = require("fs");
241
- var import_node_path = require("path");
242
- var import_node_module = require("module");
243
- init_protocol();
244
-
245
- // src/runtime/server-source.generated.ts
246
- 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/runtime/protocol.ts\nvar RUNTIME_PROTOCOL_VERSION = 1;\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 serializeError(error) {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n stack: error.stack\n };\n }\n return { message: String(error) };\n}\nfunction sendJson(res, status, body) {\n res.writeHead(status, { "content-type": "application/json" });\n res.end(JSON.stringify(body));\n}\nfunction getSseHeartbeatIntervalMs() {\n const raw = process.env.NECKBEARD_RUNTIME_SSE_HEARTBEAT_MS;\n if (!raw) return DEFAULT_SSE_HEARTBEAT_INTERVAL_MS;\n const parsed = Number(raw);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_SSE_HEARTBEAT_INTERVAL_MS;\n}\nfunction sendSseComment(res, comment) {\n if (res.writableEnded || res.destroyed) return;\n res.write(`: ${comment}\n\n`);\n}\nasync function sendSseFrame(res, event) {\n const canContinue = res.write(`data: ${JSON.stringify(event)}\n\n`);\n if (!canContinue) {\n await once(res, "drain");\n }\n}\nasync function readRequestBody(req, maxBytes = MAX_REQUEST_BODY_BYTES) {\n const chunks = [];\n let totalBytes = 0;\n for await (const chunk of req) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n totalBytes += buffer.byteLength;\n if (totalBytes > maxBytes) {\n throw new RequestBodyTooLargeError(maxBytes);\n }\n chunks.push(buffer);\n }\n return Buffer.concat(chunks).toString("utf-8");\n}\nfunction createTimeoutError(maxDurationMs) {\n const error = new Error(`Agent invocation exceeded maxDuration (${maxDurationMs}ms)`);\n error.name = "TimeoutError";\n return error;\n}\nasync function rejectOnAbort(promise, signal, maxDurationMs) {\n if (signal.aborted) {\n throw createTimeoutError(maxDurationMs);\n }\n let cleanup = () => void 0;\n const abortPromise = new Promise((_, reject) => {\n const onAbort = () => reject(createTimeoutError(maxDurationMs));\n cleanup = () => signal.removeEventListener("abort", onAbort);\n signal.addEventListener("abort", onAbort, { once: true });\n });\n try {\n return await Promise.race([promise, abortPromise]);\n } finally {\n cleanup();\n }\n}\nasync function loadAgent() {\n const mod = await import(new URL("./agent.mjs", import.meta.url).href);\n const agent = (mod.default && (mod.default._run || mod.default._server) ? mod.default : null) || Object.values(mod).find(\n (value) => value && typeof value === "object" && ("_run" in value || "_server" in value)\n );\n if (!agent || typeof agent !== "object") {\n throw new Error(\n `No agent found in agent.mjs. Exports: ${Object.keys(mod).join(", ")}`\n );\n }\n return agent;\n}\nasync function main() {\n const agent = await loadAgent();\n const server = createServer(async (req, res) => {\n try {\n const url = new URL(req.url ?? "/", "http://localhost");\n if (url.pathname === "/health" && req.method === "GET") {\n return sendJson(res, 200, {\n ok: true,\n protocolVersion: RUNTIME_PROTOCOL_VERSION\n });\n }\n if (url.pathname === "/shutdown" && req.method === "POST") {\n sendJson(res, 200, { ok: true });\n setTimeout(() => shutdown(), 10).unref();\n return;\n }\n if (url.pathname === "/invoke" && req.method === "POST") {\n let rawBody;\n try {\n rawBody = await readRequestBody(req);\n } catch (error) {\n if (error instanceof RequestBodyTooLargeError) {\n return sendJson(res, 413, { error: error.message });\n }\n throw error;\n }\n let requestBody;\n try {\n requestBody = JSON.parse(rawBody);\n } catch {\n return sendJson(res, 400, { error: "invalid JSON body" });\n }\n if (!requestBody || typeof requestBody !== "object" || typeof requestBody.invocationId !== "string") {\n return sendJson(res, 400, { error: "invalid invoke request" });\n }\n let validatedInput;\n try {\n validatedInput = agent.inputSchema.parse(requestBody.input);\n } catch (error) {\n return sendJson(res, 400, {\n error: `input validation failed: ${serializeError(error).message}`\n });\n }\n res.writeHead(200, {\n "content-type": "text/event-stream",\n "cache-control": "no-cache, no-transform",\n connection: "keep-alive",\n "x-accel-buffering": "no"\n });\n const controller = new AbortController();\n req.on("aborted", () => controller.abort());\n res.on("close", () => {\n if (!res.writableEnded) {\n controller.abort();\n }\n });\n const startedAt = Date.now();\n let sequence = 0;\n const timeout = setTimeout(() => controller.abort(), CONFIG.maxDurationMs);\n const invocationId = requestBody.invocationId;\n const heartbeat = setInterval(() => {\n try {\n sendSseComment(res, `heartbeat ${Date.now()}`);\n } catch {\n controller.abort();\n }\n }, getSseHeartbeatIntervalMs());\n heartbeat.unref();\n const emitHarnessEvent = async (event) => {\n if (!res.writableEnded) {\n await sendSseFrame(res, {\n protocolVersion: RUNTIME_PROTOCOL_VERSION,\n sequence: sequence++,\n timestamp: (/* @__PURE__ */ new Date()).toISOString(),\n elapsedMs: Date.now() - startedAt,\n ...event\n });\n }\n };\n const ctx = {\n executionId: invocationId,\n signal: controller.signal,\n env: process.env,\n sandbox: CONFIG.sandboxContext,\n logger: createLogger()\n };\n try {\n await emitHarnessEvent({ kind: "started", invocationId });\n if (agent._server) {\n await rejectOnAbort(\n agent._server.handler({\n input: validatedInput,\n ctx,\n signal: controller.signal,\n emit: async (data) => {\n const validatedFrame = agent._server?.frameSchema ? agent._server.frameSchema.parse(data) : data;\n await emitHarnessEvent({ kind: "frame", invocationId, data: validatedFrame });\n }\n }),\n controller.signal,\n CONFIG.maxDurationMs\n );\n } else if (agent._run) {\n const output = await rejectOnAbort(\n agent._run(validatedInput, ctx),\n controller.signal,\n CONFIG.maxDurationMs\n );\n const validatedOutput = agent.outputSchema ? agent.outputSchema.parse(output) : output;\n await emitHarnessEvent({ kind: "output", invocationId, output: validatedOutput });\n } else {\n throw new Error("Agent has neither a run handler nor a server handler.");\n }\n await emitHarnessEvent({ kind: "done", invocationId });\n } catch (error) {\n await emitHarnessEvent({ kind: "error", invocationId, error: serializeError(error) });\n } finally {\n clearInterval(heartbeat);\n clearTimeout(timeout);\n if (!res.writableEnded) {\n res.end();\n }\n }\n return;\n }\n return sendJson(res, 404, { error: "not found" });\n } catch (error) {\n console.error("[neckbeard-server] unexpected error", error);\n if (!res.headersSent) {\n sendJson(res, 500, { error: "internal error" });\n } else if (!res.writableEnded) {\n res.end();\n }\n }\n });\n function shutdown() {\n console.log("[neckbeard-server] shutting down");\n server.close(() => process.exit(0));\n setTimeout(() => process.exit(0), 5e3).unref();\n }\n server.listen(CONFIG.port, "0.0.0.0", () => {\n console.log(`[neckbeard-server] listening on port ${CONFIG.port}`);\n });\n process.on("SIGTERM", shutdown);\n process.on("SIGINT", shutdown);\n}\nmain().catch((error) => {\n console.error("[neckbeard-server] failed to start", error);\n process.exit(1);\n});\n';
3254
+ async destroy() {
3255
+ await this.sandbox.kill();
3256
+ }
3257
+ };
247
3258
 
248
3259
  // src/index.ts
249
3260
  function readPackageJson(path) {
@@ -253,8 +3264,8 @@ var getEsbuild = () => import("esbuild");
253
3264
  var getE2b = () => import("e2b");
254
3265
  var getDaytona = () => import("@daytona/sdk");
255
3266
  var DEFAULT_MAX_DURATION = 300;
256
- var SANDBOX_COMMAND_TIMEOUT_MS = 3e5;
257
- var QUICK_COMMAND_TIMEOUT_MS = 3e4;
3267
+ var SANDBOX_COMMAND_TIMEOUT_MS2 = 3e5;
3268
+ var QUICK_COMMAND_TIMEOUT_MS2 = 3e4;
258
3269
  var DAYTONA_CREATE_TIMEOUT_SEC = 120;
259
3270
  var NODE_TARGET = "node20";
260
3271
  var DEFAULT_EXTERNALS = ["@anthropic-ai/claude-agent-sdk"];
@@ -266,9 +3277,9 @@ var DEFAULT_SERVER_PORT = 3e3;
266
3277
  var SERVER_HEALTH_TIMEOUT_MS = 12e4;
267
3278
  var SERVER_RECONNECT_HEALTH_TIMEOUT_MS = 3e3;
268
3279
  var SERVER_HEALTH_POLL_INTERVAL_MS = 1e3;
3280
+ var SERVER_FAILURE_DIAGNOSTIC_TIMEOUT_MS = 1e3;
269
3281
  var NATIVE_EXT_RE = /\.(node|wasm|gyp|c|cc|cpp|cxx|h|hpp|hxx)$/i;
270
3282
  var TRACEABLE_SOURCE_EXT_RE = /\.(cjs|cts|js|jsx|mjs|mts|ts|tsx)$/i;
271
- var E2B_SANDBOX_HOME = "/home/user";
272
3283
  var NeckbeardError = class extends Error {
273
3284
  constructor(message) {
274
3285
  super(message);
@@ -730,8 +3741,20 @@ function mergeTracingIncludes(existing, routeGlobs, sourceFiles) {
730
3741
  return includes;
731
3742
  }
732
3743
  var DEFAULT_DEPENDENCIES = {};
733
- function isServerAgentConfig(config) {
734
- return "server" in config && config.server !== void 0;
3744
+ function isSessionAgentConfig(config) {
3745
+ return "session" in config && config.session !== void 0 || "server" in config && config.server !== void 0;
3746
+ }
3747
+ function getSessionHandler(config) {
3748
+ const session = "session" in config ? config.session : void 0;
3749
+ const server = "server" in config ? config.server : void 0;
3750
+ if (session && server) {
3751
+ throw new ConfigurationError("Agent config must use session or deprecated server, not both.");
3752
+ }
3753
+ const handler = session ?? server;
3754
+ if (!handler || typeof handler !== "object") {
3755
+ throw new ConfigurationError("session must be an object.");
3756
+ }
3757
+ return handler;
735
3758
  }
736
3759
  function isSchemaLike(value) {
737
3760
  return Boolean(
@@ -744,6 +3767,20 @@ function requireSchemaLike(name, value) {
744
3767
  }
745
3768
  return value;
746
3769
  }
3770
+ function isAbortSignal(value) {
3771
+ if (!value || typeof value !== "object") return false;
3772
+ try {
3773
+ const abortedGetter = Object.getOwnPropertyDescriptor(
3774
+ AbortSignal.prototype,
3775
+ "aborted"
3776
+ )?.get;
3777
+ if (!abortedGetter || typeof abortedGetter.call(value) !== "boolean") return false;
3778
+ const candidate = value;
3779
+ return typeof candidate.aborted === "boolean" && typeof candidate.addEventListener === "function" && typeof candidate.removeEventListener === "function";
3780
+ } catch {
3781
+ return false;
3782
+ }
3783
+ }
747
3784
  function normalizeLocalDirectoryDestination(destination, name) {
748
3785
  if (destination.trim() === "") {
749
3786
  throw new ConfigurationError(`${name}.destination must be a non-empty relative path.`);
@@ -812,21 +3849,19 @@ function validateAgentConfig(config) {
812
3849
  throw new ConfigurationError("sourceFile must be a non-empty string when provided.");
813
3850
  }
814
3851
  validateLocalDirectoriesConfig(config.localDirectories);
815
- if (isServerAgentConfig(config)) {
3852
+ if (isSessionAgentConfig(config)) {
816
3853
  if ("run" in config && typeof config.run === "function") {
817
- throw new ConfigurationError("Agent config must use either run or server.handler, not both.");
818
- }
819
- if (!config.server || typeof config.server !== "object") {
820
- throw new ConfigurationError("server must be an object.");
3854
+ throw new ConfigurationError("Agent config must use either run or session.handler, not both.");
821
3855
  }
822
- if (config.server.port !== void 0) {
823
- if (!Number.isInteger(config.server.port) || config.server.port < 1 || config.server.port > 65535) {
824
- throw new ConfigurationError("server.port must be an integer between 1 and 65535.");
3856
+ const session = getSessionHandler(config);
3857
+ if (session.port !== void 0) {
3858
+ if (!Number.isInteger(session.port) || session.port < 1 || session.port > 65535) {
3859
+ throw new ConfigurationError("session.port must be an integer between 1 and 65535.");
825
3860
  }
826
3861
  }
827
- requireSchemaLike("server.frameSchema", config.server.frameSchema);
828
- if (typeof config.server.handler !== "function") {
829
- throw new ConfigurationError("server.handler must be a function.");
3862
+ requireSchemaLike("session.frameSchema", session.frameSchema);
3863
+ if (typeof session.handler !== "function") {
3864
+ throw new ConfigurationError("session.handler must be a function.");
830
3865
  }
831
3866
  return;
832
3867
  }
@@ -851,24 +3886,86 @@ function trafficTokenHeaders(descriptor) {
851
3886
  }
852
3887
  return {};
853
3888
  }
854
- async function waitForServerHealthy(healthUrl, descriptor, timeoutMs = SERVER_HEALTH_TIMEOUT_MS) {
3889
+ function abortSignalError(signal) {
3890
+ if (signal.reason instanceof Error) return signal.reason;
3891
+ const error = new Error(
3892
+ signal.reason === void 0 ? "Operation aborted." : String(signal.reason)
3893
+ );
3894
+ error.name = "AbortError";
3895
+ return error;
3896
+ }
3897
+ function throwIfAborted(signal) {
3898
+ if (signal?.aborted) throw abortSignalError(signal);
3899
+ }
3900
+ function awaitWithAbort(operation, signal) {
3901
+ return settleOperation(operation, {
3902
+ ...signal ? {
3903
+ abort: {
3904
+ signal,
3905
+ createError: () => abortSignalError(signal)
3906
+ }
3907
+ } : {}
3908
+ });
3909
+ }
3910
+ function awaitDiagnosticRead(operation, signal) {
3911
+ return settleOperation(operation, {
3912
+ ...signal ? {
3913
+ abort: {
3914
+ signal,
3915
+ createError: () => abortSignalError(signal)
3916
+ }
3917
+ } : {},
3918
+ timeout: {
3919
+ timeoutMs: SERVER_FAILURE_DIAGNOSTIC_TIMEOUT_MS,
3920
+ createError: () => new Error("Server diagnostic read timed out.")
3921
+ }
3922
+ });
3923
+ }
3924
+ function delayWithAbort(delayMs, signal) {
3925
+ if (!signal) {
3926
+ return new Promise((resolve2) => setTimeout(resolve2, delayMs));
3927
+ }
3928
+ throwIfAborted(signal);
3929
+ return new Promise((resolve2, reject) => {
3930
+ const onAbort = () => {
3931
+ clearTimeout(timer);
3932
+ reject(abortSignalError(signal));
3933
+ };
3934
+ const timer = setTimeout(() => {
3935
+ signal.removeEventListener("abort", onAbort);
3936
+ resolve2();
3937
+ }, delayMs);
3938
+ signal.addEventListener("abort", onAbort, { once: true });
3939
+ });
3940
+ }
3941
+ async function waitForServerHealthy(healthUrl, descriptor, timeoutMs = SERVER_HEALTH_TIMEOUT_MS, signal) {
855
3942
  const deadline = Date.now() + timeoutMs;
856
3943
  let lastError;
857
3944
  const urlWithToken = appendTrafficTokenToUrl(healthUrl, descriptor);
858
3945
  while (Date.now() < deadline) {
3946
+ throwIfAborted(signal);
859
3947
  try {
860
- const response = await fetch(urlWithToken, {
861
- headers: trafficTokenHeaders(descriptor)
862
- });
3948
+ const response = await awaitWithAbort(
3949
+ () => fetch(urlWithToken, {
3950
+ headers: trafficTokenHeaders(descriptor),
3951
+ ...signal === void 0 ? {} : { signal }
3952
+ }),
3953
+ signal
3954
+ );
863
3955
  if (response.ok) {
864
- await response.text().catch(() => void 0);
3956
+ try {
3957
+ await awaitWithAbort(() => response.text(), signal);
3958
+ } catch {
3959
+ throwIfAborted(signal);
3960
+ }
865
3961
  return;
866
3962
  }
867
3963
  lastError = new Error(`health check returned ${response.status}`);
868
3964
  } catch (error) {
3965
+ throwIfAborted(signal);
869
3966
  lastError = error;
870
3967
  }
871
- await new Promise((resolve2) => setTimeout(resolve2, SERVER_HEALTH_POLL_INTERVAL_MS));
3968
+ await delayWithAbort(SERVER_HEALTH_POLL_INTERVAL_MS, signal);
872
3969
  }
873
3970
  const message = lastError instanceof Error ? lastError.message : String(lastError);
874
3971
  throw new DeploymentError(
@@ -884,9 +3981,6 @@ function requireEnv(name) {
884
3981
  }
885
3982
  return value;
886
3983
  }
887
- function shellEscape(str) {
888
- return `'${str.replace(/'/g, "'\\''")}'`;
889
- }
890
3984
  var require2 = (0, import_node_module.createRequire)((0, import_node_path.join)(process.cwd(), "__agent_neckbeard__.cjs"));
891
3985
  var packageRequire = createPackageRequire();
892
3986
  function createPackageRequire() {
@@ -944,322 +4038,160 @@ function resolvePackageInfoSync(importPath, resolveDir) {
944
4038
  const parent = (0, import_node_path.dirname)(root);
945
4039
  if (parent === root) break;
946
4040
  root = parent;
947
- }
948
- if (!packageJsonPath) return null;
949
- const packageJson = readPackageJson(packageJsonPath);
950
- if (!packageJson.name || !packageJson.version) return null;
951
- root = (0, import_node_path.dirname)(packageJsonPath);
952
- return {
953
- name: packageJson.name,
954
- version: packageJson.version,
955
- root,
956
- resolvedPath,
957
- packageJson
958
- };
959
- } catch {
960
- return null;
961
- }
962
- }
963
- function resolvePackageInfoFromResolvedPath(importPath, resolvedPath) {
964
- const packageName = packageNameForImportPath(importPath);
965
- let root = (0, import_node_path.dirname)(resolvedPath);
966
- while (true) {
967
- const packageJsonPath = (0, import_node_path.join)(root, "package.json");
968
- if ((0, import_node_fs.existsSync)(packageJsonPath)) {
969
- const packageJson = readPackageJson(packageJsonPath);
970
- if (packageJson.name === packageName) {
971
- if (!packageJson.version) return null;
972
- return {
973
- name: packageJson.name,
974
- version: packageJson.version,
975
- root,
976
- resolvedPath,
977
- packageJson
978
- };
979
- }
980
- }
981
- const parent = (0, import_node_path.dirname)(root);
982
- if (parent === root) return null;
983
- root = parent;
984
- }
985
- }
986
- function hasNativeHints(info) {
987
- const files = Array.isArray(info.packageJson.files) ? info.packageJson.files : [];
988
- const fields = [info.packageJson.main, info.packageJson.module, info.packageJson.browser].filter(
989
- (f) => typeof f === "string"
990
- );
991
- return files.concat(fields).some((file) => NATIVE_EXT_RE.test(file));
992
- }
993
- function shouldAutoExternalize(info) {
994
- if (info.resolvedPath.endsWith(".node") || info.resolvedPath.endsWith(".wasm")) return true;
995
- if (hasNativeHints(info)) return true;
996
- if ((0, import_node_fs.existsSync)((0, import_node_path.join)(info.root, "binding.gyp"))) return true;
997
- return false;
998
- }
999
- function normalizeList(value) {
1000
- if (Array.isArray(value)) return value.filter((v) => typeof v === "string");
1001
- if (typeof value === "string") return [value];
1002
- return null;
1003
- }
1004
- function listAllowsTarget(list, target) {
1005
- if (!list || list.length === 0) return true;
1006
- const negated = list.filter((v) => v.startsWith("!")).map((v) => v.slice(1));
1007
- if (negated.includes(target)) return false;
1008
- const positives = list.filter((v) => !v.startsWith("!"));
1009
- if (positives.length === 0) return true;
1010
- return positives.includes(target);
1011
- }
1012
- function isPackageCompatible(info) {
1013
- const osList = normalizeList(info.packageJson.os);
1014
- const cpuList = normalizeList(info.packageJson.cpu);
1015
- return listAllowsTarget(osList, SANDBOX_PLATFORM) && listAllowsTarget(cpuList, SANDBOX_ARCH);
1016
- }
1017
- function filterDefinedEnvs(envs) {
1018
- const filtered = {};
1019
- for (const [key, value] of Object.entries(envs)) {
1020
- if (value !== void 0) {
1021
- filtered[key] = value;
1022
- }
1023
- }
1024
- return filtered;
1025
- }
1026
- function arrayBufferToBuffer(value) {
1027
- return Buffer.from(value);
1028
- }
1029
- function toDaytonaUploadContent(content) {
1030
- if (typeof content === "string") return Buffer.from(content);
1031
- if (Buffer.isBuffer(content)) return content;
1032
- if (content instanceof Uint8Array) return Buffer.from(content);
1033
- return arrayBufferToBuffer(content);
1034
- }
1035
- function toE2bWriteContent(content) {
1036
- if (typeof content === "string") return content;
1037
- if (content instanceof ArrayBuffer) return content;
1038
- return Uint8Array.from(content).buffer;
1039
- }
1040
- function createSandboxPaths(provider, homeDir, workDir) {
1041
- const agentDir = `${homeDir}/agent`;
1042
- const ioDir = `${homeDir}/io`;
1043
- return {
1044
- provider,
1045
- homeDir,
1046
- workDir,
1047
- agentDir,
1048
- ioDir,
1049
- inputJson: `${ioDir}/input.json`,
1050
- outputJson: `${ioDir}/output.json`,
1051
- agentModule: `${agentDir}/agent.mjs`,
1052
- serverModule: `${agentDir}/server.mjs`,
1053
- serverConfig: `${agentDir}/server-config.json`,
1054
- claudeDir: `${agentDir}/.claude`,
1055
- packageJson: `${agentDir}/package.json`
1056
- };
1057
- }
1058
- function timeoutMsToSeconds(timeoutMs) {
1059
- return Math.max(1, Math.ceil(timeoutMs / 1e3));
1060
- }
1061
- function asError(error) {
1062
- return error instanceof Error ? error : new Error(String(error));
1063
- }
1064
- function errorMessage(error) {
1065
- return error instanceof Error ? error.message : String(error);
1066
- }
1067
- async function resolveDaytonaPaths(sandbox) {
1068
- const workDir = await sandbox.getWorkDir() ?? await sandbox.getUserHomeDir();
1069
- const homeDir = await sandbox.getUserHomeDir() ?? workDir;
1070
- if (!homeDir || !workDir) {
1071
- throw new DeploymentError("Daytona sandbox did not report a home or working directory.");
1072
- }
1073
- return createSandboxPaths("daytona", homeDir, workDir);
1074
- }
1075
- function numberProperty(value, property) {
1076
- if (typeof value !== "object" || value === null) return void 0;
1077
- const propertyValue = Reflect.get(value, property);
1078
- return typeof propertyValue === "number" ? propertyValue : void 0;
1079
- }
1080
- function stringProperty(value, property) {
1081
- if (typeof value !== "object" || value === null) return void 0;
1082
- const propertyValue = Reflect.get(value, property);
1083
- return typeof propertyValue === "string" ? propertyValue : void 0;
1084
- }
1085
- async function runE2bCommand(sandbox, cmd, options) {
1086
- let stdout = "";
1087
- let stderr = "";
1088
- try {
1089
- const result = await sandbox.commands.run(cmd, {
1090
- timeoutMs: options.timeoutMs,
1091
- envs: options.envs,
1092
- background: false,
1093
- onStdout: (data) => {
1094
- stdout += data;
1095
- options.onStdout?.(data);
1096
- },
1097
- onStderr: (data) => {
1098
- stderr += data;
1099
- options.onStderr?.(data);
1100
- }
1101
- });
1102
- return {
1103
- exitCode: result.exitCode,
1104
- stdout: stdout || result.stdout,
1105
- stderr: stderr || result.stderr
1106
- };
1107
- } catch (error) {
1108
- const exitCode = numberProperty(error, "exitCode") ?? 1;
1109
- return {
1110
- exitCode,
1111
- stdout: stdout || stringProperty(error, "stdout") || "",
1112
- stderr: stderr || stringProperty(error, "stderr") || errorMessage(error)
1113
- };
1114
- }
1115
- }
1116
- var E2bSandboxHandle = class {
1117
- constructor(sandbox) {
1118
- this.sandbox = sandbox;
1119
- }
1120
- provider = "e2b";
1121
- paths = createSandboxPaths("e2b", E2B_SANDBOX_HOME, E2B_SANDBOX_HOME);
1122
- get id() {
1123
- return this.sandbox.sandboxId;
1124
- }
1125
- async makeDir(path) {
1126
- await this.sandbox.files.makeDir(path);
1127
- }
1128
- writeFile(path, content) {
1129
- return this.sandbox.files.write(path, toE2bWriteContent(content)).then(() => void 0);
1130
- }
1131
- readFile(path) {
1132
- return this.sandbox.files.read(path, { format: "text" });
1133
- }
1134
- readFileBytes(path) {
1135
- return this.sandbox.files.read(path, { format: "bytes" });
1136
- }
1137
- runCommand(cmd, options) {
1138
- const command = options.cwd ? `cd ${shellEscape(options.cwd)} && ${cmd}` : cmd;
1139
- return runE2bCommand(this.sandbox, command, options);
1140
- }
1141
- setTimeout(timeoutMs) {
1142
- return this.sandbox.setTimeout(timeoutMs);
1143
- }
1144
- async startDetachedCommand(cmd, options) {
1145
- const command = options.cwd ? `cd ${shellEscape(options.cwd)} && ${cmd}` : cmd;
1146
- const handle = await this.sandbox.commands.run(command, {
1147
- timeoutMs: 0,
1148
- envs: options.envs,
1149
- background: true
1150
- });
1151
- return { sessionId: `e2b:${handle.pid}`, commandId: String(handle.pid) };
1152
- }
1153
- async readSessionLogs(_sessionId, commandId) {
1154
- try {
1155
- const handle = await this.sandbox.commands.connect(Number(commandId));
1156
- return { stdout: handle.stdout ?? "", stderr: handle.stderr ?? "" };
1157
- } catch {
1158
- return { stdout: "", stderr: "" };
1159
- }
1160
- }
1161
- async stopSession(sessionId) {
1162
- const pid = Number(sessionId.replace(/^e2b:/, ""));
1163
- if (Number.isFinite(pid)) {
1164
- await this.sandbox.commands.kill(pid);
1165
- }
1166
- }
1167
- async getServerEndpoint(port) {
4041
+ }
4042
+ if (!packageJsonPath) return null;
4043
+ const packageJson = readPackageJson(packageJsonPath);
4044
+ if (!packageJson.name || !packageJson.version) return null;
4045
+ root = (0, import_node_path.dirname)(packageJsonPath);
1168
4046
  return {
1169
- url: `https://${this.sandbox.getHost(port)}`,
1170
- trafficToken: this.sandbox.trafficAccessToken
4047
+ name: packageJson.name,
4048
+ version: packageJson.version,
4049
+ root,
4050
+ resolvedPath,
4051
+ packageJson
1171
4052
  };
4053
+ } catch {
4054
+ return null;
1172
4055
  }
1173
- async destroy() {
1174
- await this.sandbox.kill();
4056
+ }
4057
+ function resolvePackageInfoFromResolvedPath(importPath, resolvedPath) {
4058
+ const packageName = packageNameForImportPath(importPath);
4059
+ let root = (0, import_node_path.dirname)(resolvedPath);
4060
+ while (true) {
4061
+ const packageJsonPath = (0, import_node_path.join)(root, "package.json");
4062
+ if ((0, import_node_fs.existsSync)(packageJsonPath)) {
4063
+ const packageJson = readPackageJson(packageJsonPath);
4064
+ if (packageJson.name === packageName) {
4065
+ if (!packageJson.version) return null;
4066
+ return {
4067
+ name: packageJson.name,
4068
+ version: packageJson.version,
4069
+ root,
4070
+ resolvedPath,
4071
+ packageJson
4072
+ };
4073
+ }
4074
+ }
4075
+ const parent = (0, import_node_path.dirname)(root);
4076
+ if (parent === root) return null;
4077
+ root = parent;
1175
4078
  }
1176
- };
1177
- var DaytonaSandboxHandle = class _DaytonaSandboxHandle {
1178
- constructor(sandbox, paths) {
1179
- this.sandbox = sandbox;
1180
- this.paths = paths;
4079
+ }
4080
+ function hasNativeHints(info) {
4081
+ const files = Array.isArray(info.packageJson.files) ? info.packageJson.files : [];
4082
+ const fields = [info.packageJson.main, info.packageJson.module, info.packageJson.browser].filter(
4083
+ (f) => typeof f === "string"
4084
+ );
4085
+ return files.concat(fields).some((file) => NATIVE_EXT_RE.test(file));
4086
+ }
4087
+ function shouldAutoExternalize(info) {
4088
+ if (info.resolvedPath.endsWith(".node") || info.resolvedPath.endsWith(".wasm")) return true;
4089
+ if (hasNativeHints(info)) return true;
4090
+ if ((0, import_node_fs.existsSync)((0, import_node_path.join)(info.root, "binding.gyp"))) return true;
4091
+ return false;
4092
+ }
4093
+ function normalizeList(value) {
4094
+ if (Array.isArray(value)) return value.filter((v) => typeof v === "string");
4095
+ if (typeof value === "string") return [value];
4096
+ return null;
4097
+ }
4098
+ function listAllowsTarget(list, target) {
4099
+ if (!list || list.length === 0) return true;
4100
+ const negated = list.filter((v) => v.startsWith("!")).map((v) => v.slice(1));
4101
+ if (negated.includes(target)) return false;
4102
+ const positives = list.filter((v) => !v.startsWith("!"));
4103
+ if (positives.length === 0) return true;
4104
+ return positives.includes(target);
4105
+ }
4106
+ function isPackageCompatible(info) {
4107
+ const osList = normalizeList(info.packageJson.os);
4108
+ const cpuList = normalizeList(info.packageJson.cpu);
4109
+ return listAllowsTarget(osList, SANDBOX_PLATFORM) && listAllowsTarget(cpuList, SANDBOX_ARCH);
4110
+ }
4111
+ var INVALID_DETACHED_COMMAND_HANDLE_MESSAGE = "Detached process handle must contain a non-empty sessionId string and an optional commandId string.";
4112
+ function normalizeDetachedCommandHandle(value) {
4113
+ if (!value || typeof value !== "object") {
4114
+ throw new ConfigurationError(INVALID_DETACHED_COMMAND_HANDLE_MESSAGE);
1181
4115
  }
1182
- provider = "daytona";
1183
- static async create(sandbox) {
1184
- return new _DaytonaSandboxHandle(sandbox, await resolveDaytonaPaths(sandbox));
4116
+ let sessionId;
4117
+ let commandId;
4118
+ try {
4119
+ if (Array.isArray(value)) {
4120
+ throw new Error("invalid detached command handle");
4121
+ }
4122
+ sessionId = Reflect.get(value, "sessionId");
4123
+ commandId = Reflect.get(value, "commandId");
4124
+ } catch {
4125
+ throw new ConfigurationError(INVALID_DETACHED_COMMAND_HANDLE_MESSAGE);
1185
4126
  }
1186
- get id() {
1187
- return this.sandbox.id;
4127
+ if (typeof sessionId !== "string" || sessionId.length === 0 || commandId !== void 0 && typeof commandId !== "string") {
4128
+ throw new ConfigurationError(INVALID_DETACHED_COMMAND_HANDLE_MESSAGE);
1188
4129
  }
1189
- async makeDir(path) {
1190
- const result = await this.sandbox.process.executeCommand(
1191
- `mkdir -p ${shellEscape(path)}`,
1192
- void 0,
1193
- void 0,
1194
- timeoutMsToSeconds(QUICK_COMMAND_TIMEOUT_MS)
1195
- );
1196
- if (result.exitCode !== 0) {
1197
- throw new DeploymentError(result.result || `Failed to create directory ${path}`);
4130
+ return commandId === void 0 ? { sessionId } : { sessionId, commandId };
4131
+ }
4132
+ function filterDefinedEnvs(envs) {
4133
+ const filtered = {};
4134
+ for (const [key, value] of Object.entries(envs)) {
4135
+ if (value !== void 0) {
4136
+ filtered[key] = value;
1198
4137
  }
1199
4138
  }
1200
- writeFile(path, content) {
1201
- return this.sandbox.fs.uploadFile(
1202
- toDaytonaUploadContent(content),
1203
- path,
1204
- timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS)
1205
- );
4139
+ return filtered;
4140
+ }
4141
+ function asError(error) {
4142
+ return error instanceof Error ? error : new Error(String(error));
4143
+ }
4144
+ function errorMessage(error) {
4145
+ return error instanceof Error ? error.message : String(error);
4146
+ }
4147
+ var MINIMUM_BULK_DIAGNOSTIC_REDACTION_LENGTH = 8;
4148
+ var CREDENTIAL_ENV_NAME_PATTERN = /(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)/iu;
4149
+ function isConfiguredDiagnosticSecret(name, value) {
4150
+ return CREDENTIAL_ENV_NAME_PATTERN.test(name) || value.length >= MINIMUM_BULK_DIAGNOSTIC_REDACTION_LENGTH;
4151
+ }
4152
+ function redactServerFailureDiagnosticStream(value, secrets) {
4153
+ const mayStartAtTailBoundary = Buffer.byteLength(value, "utf8") >= DETACHED_PROCESS_LOG_MAX_BYTES - 3;
4154
+ let redacted = boundDetachedProcessLog(value);
4155
+ for (const secret of secrets) {
4156
+ const replacement = secret.length < "[REDACTED]".length ? "*" : "[REDACTED]";
4157
+ redacted = redacted.split(secret).join(replacement);
1206
4158
  }
1207
- async readFile(path) {
1208
- const content = await this.sandbox.fs.downloadFile(path, timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS));
1209
- return content.toString("utf-8");
4159
+ let maximumSecretLength = 0;
4160
+ for (const secret of secrets) {
4161
+ maximumSecretLength = Math.max(maximumSecretLength, secret.length);
1210
4162
  }
1211
- async readFileBytes(path) {
1212
- const content = await this.sandbox.fs.downloadFile(path, timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS));
1213
- return new Uint8Array(content);
4163
+ if (mayStartAtTailBoundary && maximumSecretLength > 0 && redacted.length > 0) {
4164
+ redacted = redacted.slice(maximumSecretLength);
1214
4165
  }
1215
- async runCommand(cmd, options) {
1216
- const result = await this.sandbox.process.executeCommand(
1217
- cmd,
1218
- options.cwd,
1219
- options.envs,
1220
- timeoutMsToSeconds(options.timeoutMs)
4166
+ return boundDetachedProcessLog(redacted);
4167
+ }
4168
+ async function readServerFailureDiagnostics(sandbox, command, environment, signal) {
4169
+ if (!sandbox.readSessionLogs) return "";
4170
+ try {
4171
+ const captured = await awaitDiagnosticRead(
4172
+ () => sandbox.readSessionLogs(command),
4173
+ signal
1221
4174
  );
1222
- const stdout = result.artifacts?.stdout ?? result.result ?? "";
1223
- if (stdout) options.onStdout?.(stdout);
1224
- return {
1225
- exitCode: result.exitCode,
1226
- stdout,
1227
- stderr: ""
1228
- };
1229
- }
1230
- async startDetachedCommand(cmd, options) {
1231
- const sessionId = `neckbeard-server-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
1232
- await this.sandbox.process.createSession(sessionId);
1233
- const envPrefix = options.envs ? Object.entries(options.envs).map(([key, value]) => `${key}=${shellEscape(value)}`).join(" ") + " " : "";
1234
- const cwdPrefix = options.cwd ? `cd ${shellEscape(options.cwd)} && ` : "";
1235
- const result = await this.sandbox.process.executeSessionCommand(sessionId, {
1236
- command: `${cwdPrefix}${envPrefix}${cmd}`,
1237
- runAsync: true
1238
- });
1239
- return { sessionId, commandId: result.cmdId };
1240
- }
1241
- async readSessionLogs(sessionId, commandId) {
1242
- try {
1243
- const logs = await this.sandbox.process.getSessionCommandLogs(sessionId, commandId);
1244
- return {
1245
- stdout: logs.stdout ?? logs.output ?? "",
1246
- stderr: logs.stderr ?? ""
1247
- };
1248
- } catch {
1249
- return { stdout: "", stderr: "" };
1250
- }
1251
- }
1252
- stopSession(sessionId) {
1253
- return this.sandbox.process.deleteSession(sessionId);
1254
- }
1255
- async getServerEndpoint(port) {
1256
- const preview = await this.sandbox.getPreviewLink(port);
1257
- return { url: preview.url, trafficToken: preview.token };
1258
- }
1259
- destroy() {
1260
- return this.sandbox.delete(timeoutMsToSeconds(SANDBOX_COMMAND_TIMEOUT_MS));
4175
+ const secrets = Object.entries(environment).filter(
4176
+ (entry) => Boolean(entry[1]) && isConfiguredDiagnosticSecret(entry[0], entry[1])
4177
+ ).map(([, value]) => value);
4178
+ secrets.sort((left, right) => right.length - left.length);
4179
+ const stdout = redactServerFailureDiagnosticStream(captured.stdout, secrets);
4180
+ const stderr = redactServerFailureDiagnosticStream(captured.stderr, secrets);
4181
+ const parts = [];
4182
+ if (stdout.trim()) parts.push(`stdout:
4183
+ ${stdout}`);
4184
+ if (stderr.trim()) parts.push(`stderr:
4185
+ ${stderr}`);
4186
+ if (parts.length === 0) return "";
4187
+ return boundDetachedProcessLog(`
4188
+ --- server logs ---
4189
+ ${parts.join("\n\n")}`);
4190
+ } catch {
4191
+ throwIfAborted(signal);
4192
+ return "";
1261
4193
  }
1262
- };
4194
+ }
1263
4195
  function providerApiKey(provider, explicitApiKey) {
1264
4196
  if (explicitApiKey) return explicitApiKey;
1265
4197
  return requireEnv(provider === "e2b" ? "E2B_API_KEY" : "DAYTONA_API_KEY");
@@ -1276,11 +4208,23 @@ async function createProviderSandboxHandle(options) {
1276
4208
  ...options.networkAllowList === void 0 ? {} : { networkAllowList: options.networkAllowList },
1277
4209
  ...options.domainAllowList === void 0 ? {} : { domainAllowList: options.domainAllowList },
1278
4210
  envVars: filterDefinedEnvs(options.envs ?? {}),
4211
+ autoStopInterval: options.autoStopInterval,
1279
4212
  autoDeleteInterval: options.autoDeleteInterval ?? -1
1280
4213
  },
1281
4214
  { timeout: options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC }
1282
4215
  );
1283
- return DaytonaSandboxHandle.create(sandbox2);
4216
+ try {
4217
+ return await DaytonaSandboxHandle.create(
4218
+ sandbox2,
4219
+ (message) => new DeploymentError(message)
4220
+ );
4221
+ } catch (error) {
4222
+ await sandbox2.delete(
4223
+ options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC,
4224
+ true
4225
+ ).catch(() => void 0);
4226
+ throw error;
4227
+ }
1284
4228
  }
1285
4229
  const apiKey = providerApiKey("e2b", options.apiKey);
1286
4230
  const { Sandbox } = await getE2b();
@@ -1292,7 +4236,7 @@ async function createProviderSandboxHandle(options) {
1292
4236
  network: options.allowPublicTraffic === void 0 ? void 0 : { allowPublicTraffic: options.allowPublicTraffic }
1293
4237
  };
1294
4238
  const sandbox = options.template ? await Sandbox.create(options.template, sandboxOptions) : await Sandbox.create(sandboxOptions);
1295
- return new E2bSandboxHandle(sandbox);
4239
+ return new E2bSandboxHandle(sandbox, (message) => new DeploymentError(message));
1296
4240
  }
1297
4241
  async function connectProviderSandboxHandle(options) {
1298
4242
  if (options.provider === "daytona") {
@@ -1307,7 +4251,7 @@ async function connectProviderSandboxHandle(options) {
1307
4251
  await sandbox2.start(options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC);
1308
4252
  }
1309
4253
  }
1310
- return DaytonaSandboxHandle.create(sandbox2);
4254
+ return DaytonaSandboxHandle.create(sandbox2, (message) => new DeploymentError(message));
1311
4255
  }
1312
4256
  const apiKey = providerApiKey("e2b", options.apiKey);
1313
4257
  const { Sandbox } = await getE2b();
@@ -1316,7 +4260,7 @@ async function connectProviderSandboxHandle(options) {
1316
4260
  timeoutMs: options.timeoutMs,
1317
4261
  requestTimeoutMs: options.requestTimeoutMs
1318
4262
  });
1319
- return new E2bSandboxHandle(sandbox);
4263
+ return new E2bSandboxHandle(sandbox, (message) => new DeploymentError(message));
1320
4264
  }
1321
4265
  var SandboxClient = class _SandboxClient {
1322
4266
  constructor(handle) {
@@ -1360,6 +4304,61 @@ var SandboxClient = class _SandboxClient {
1360
4304
  async runCommand(command, options) {
1361
4305
  return this.handle.runCommand(command, options);
1362
4306
  }
4307
+ async startDetachedCommand(command, options = {}) {
4308
+ if (!this.handle.startDetachedCommand) {
4309
+ throw new ConfigurationError(
4310
+ `Sandbox provider "${this.provider}" does not support startDetachedCommand().`
4311
+ );
4312
+ }
4313
+ if (typeof command !== "string") {
4314
+ throw new ConfigurationError("Detached command must be a string.");
4315
+ }
4316
+ const normalized = normalizeProviderSandboxDetachedCommandOptions(
4317
+ options,
4318
+ (message) => new ConfigurationError(message),
4319
+ { requireObject: true }
4320
+ );
4321
+ return this.handle.startDetachedCommand(command, normalized.options);
4322
+ }
4323
+ async readSessionLogs(commandOrSessionId, legacyCommandId) {
4324
+ if (!this.handle.readSessionLogs) {
4325
+ throw new ConfigurationError(
4326
+ `Sandbox provider "${this.provider}" does not support readSessionLogs().`
4327
+ );
4328
+ }
4329
+ if (typeof commandOrSessionId === "string" && legacyCommandId === void 0) {
4330
+ throw new ConfigurationError(
4331
+ "Legacy detached session log reads require a command ID."
4332
+ );
4333
+ }
4334
+ const command = typeof commandOrSessionId === "string" ? { sessionId: commandOrSessionId, commandId: legacyCommandId } : normalizeDetachedCommandHandle(commandOrSessionId);
4335
+ return this.handle.readSessionLogs(command);
4336
+ }
4337
+ async stopSession(commandOrSessionId) {
4338
+ if (!this.handle.stopSession) {
4339
+ throw new ConfigurationError(
4340
+ `Sandbox provider "${this.provider}" does not support stopSession().`
4341
+ );
4342
+ }
4343
+ const command = typeof commandOrSessionId === "string" ? { sessionId: commandOrSessionId } : normalizeDetachedCommandHandle(commandOrSessionId);
4344
+ await this.handle.stopSession(command);
4345
+ }
4346
+ /**
4347
+ * Irreversibly removes private lifecycle state and captured diagnostics for
4348
+ * one managed detached command. Call `stopSession()` first, then perform any
4349
+ * final `readSessionLogs()` before disposal. Disposal is idempotent after a
4350
+ * confirmed stop but is not itself evidence that the process stopped.
4351
+ */
4352
+ async disposeSessionArtifacts(command) {
4353
+ if (!this.handle.disposeSessionArtifacts) {
4354
+ throw new ConfigurationError(
4355
+ `Sandbox provider "${this.provider}" does not support disposeSessionArtifacts().`
4356
+ );
4357
+ }
4358
+ await this.handle.disposeSessionArtifacts(
4359
+ normalizeDetachedCommandHandle(command)
4360
+ );
4361
+ }
1363
4362
  async setTimeout(timeoutMs) {
1364
4363
  if (!this.handle.setTimeout) {
1365
4364
  throw new ConfigurationError(`Sandbox provider "${this.provider}" does not support setTimeout().`);
@@ -1387,17 +4386,26 @@ function normalizeStackFramePath(rawPath, cwd = process.cwd()) {
1387
4386
  }
1388
4387
  function getCallerFile() {
1389
4388
  const stack = new Error().stack?.split("\n") ?? [];
1390
- for (const line of stack.slice(2)) {
4389
+ let moduleFile;
4390
+ let bundledFallback;
4391
+ for (const line of stack.slice(1)) {
1391
4392
  const match = line.match(/\((.+?):\d+:\d+\)/) || line.match(/at (.+?):\d+:\d+/);
1392
4393
  if (!match) continue;
1393
4394
  const file = normalizeStackFramePath(match[1]);
1394
4395
  if (!file) continue;
4396
+ if (!moduleFile) {
4397
+ moduleFile = file;
4398
+ continue;
4399
+ }
1395
4400
  if (file.includes("node:")) continue;
1396
4401
  if (file.includes("node_modules/agent-neckbeard")) continue;
1397
- if (file.includes("agent-neckbeard/dist")) continue;
1398
- if (file.endsWith("/src/index.ts")) continue;
4402
+ if (file === moduleFile) {
4403
+ bundledFallback ??= file;
4404
+ continue;
4405
+ }
1399
4406
  return file;
1400
4407
  }
4408
+ if (bundledFallback) return bundledFallback;
1401
4409
  throw new Error("Could not determine source file");
1402
4410
  }
1403
4411
  function isFrameworkBuildOutputPath(file) {
@@ -1561,10 +4569,13 @@ var Agent = class {
1561
4569
  provider;
1562
4570
  template;
1563
4571
  inputSchema;
1564
- /** Only populated for run-output agents; undefined for streaming agents. */
4572
+ /** Only populated for structured-task agents; undefined for session agents. */
1565
4573
  outputSchema;
1566
- /** Only populated for streaming agents; undefined for run-output agents. */
4574
+ /** Only populated for attached-session agents; undefined for run-output agents. */
1567
4575
  frameSchema;
4576
+ /** User-facing execution shape. */
4577
+ kind;
4578
+ /** @deprecated Use `kind`; retained for compatibility with `run | stream` checks. */
1568
4579
  mode;
1569
4580
  maxDuration;
1570
4581
  dependencies;
@@ -1576,7 +4587,7 @@ var Agent = class {
1576
4587
  build;
1577
4588
  /** @internal Used by the in-sandbox server for run-output agents. */
1578
4589
  _run;
1579
- /** @internal Used by the in-sandbox server for streaming agents. */
4590
+ /** @internal Used by the in-sandbox server for attached-session agents. */
1580
4591
  _server;
1581
4592
  /** @internal Runtime state populated by deploy(). */
1582
4593
  _serverRuntime;
@@ -1596,11 +4607,14 @@ var Agent = class {
1596
4607
  this.claudeDir = config.claudeDir;
1597
4608
  this.envs = config.envs ?? {};
1598
4609
  this.build = config.build ?? {};
1599
- if (isServerAgentConfig(config)) {
4610
+ if (isSessionAgentConfig(config)) {
4611
+ const session = getSessionHandler(config);
4612
+ this.kind = "session";
1600
4613
  this.mode = "stream";
1601
- this._server = config.server;
1602
- this.frameSchema = config.server.frameSchema;
4614
+ this._server = session;
4615
+ this.frameSchema = session.frameSchema;
1603
4616
  } else {
4617
+ this.kind = "task";
1604
4618
  this.mode = "run";
1605
4619
  this._run = config.run;
1606
4620
  this.outputSchema = config.outputSchema;
@@ -1685,47 +4699,68 @@ var Agent = class {
1685
4699
  envs: this.sandboxEnv
1686
4700
  });
1687
4701
  }
1688
- async resolveRuntimeConnection(sandboxId) {
4702
+ async resolveRuntimeConnection(sandboxId, options = {}) {
4703
+ const { signal } = options;
4704
+ throwIfAborted(signal);
1689
4705
  const targetId = sandboxId ?? this._serverRuntime?.connection.sandboxId ?? this._sandboxId;
1690
4706
  if (!targetId) {
1691
4707
  throw new ConfigurationError("Agent not deployed. Call agent.deploy() first or pass sandboxId.");
1692
4708
  }
1693
- if (!sandboxId && this._serverRuntime?.connection.sandboxId === targetId) {
4709
+ if ((!sandboxId || options.reuseMatchingCachedConnection) && this._serverRuntime?.connection.sandboxId === targetId) {
1694
4710
  return this._serverRuntime.connection;
1695
4711
  }
1696
- const sandbox = await this.connectSandboxHandle(targetId);
1697
- const serverConfig = await this.readRuntimeServerConfig(sandbox);
4712
+ const sandbox = await awaitWithAbort(() => this.connectSandboxHandle(targetId), signal);
4713
+ if (sandbox.id !== targetId) {
4714
+ throw new DeploymentError("Sandbox provider returned an unexpected runtime identity.");
4715
+ }
4716
+ const serverConfig = await awaitWithAbort(
4717
+ () => this.readRuntimeServerConfig(sandbox),
4718
+ signal
4719
+ );
1698
4720
  const port = serverConfig?.port ?? this._server?.port ?? DEFAULT_SERVER_PORT;
1699
- const connection = await this.createRuntimeConnection(sandbox, port);
4721
+ const connection = await awaitWithAbort(
4722
+ () => this.createRuntimeConnection(sandbox, port),
4723
+ signal
4724
+ );
1700
4725
  const healthUrl = this.healthUrlFor(connection);
1701
4726
  try {
1702
- await waitForServerHealthy(healthUrl, connection, SERVER_RECONNECT_HEALTH_TIMEOUT_MS);
1703
- this._serverRuntime = { connection };
4727
+ await waitForServerHealthy(
4728
+ healthUrl,
4729
+ connection,
4730
+ SERVER_RECONNECT_HEALTH_TIMEOUT_MS,
4731
+ signal
4732
+ );
4733
+ throwIfAborted(signal);
4734
+ const cachedRuntime = this._serverRuntime;
4735
+ this._serverRuntime = cachedRuntime?.connection.sandboxId === targetId ? { ...cachedRuntime, connection } : { connection };
1704
4736
  this._sandboxId = targetId;
1705
4737
  return connection;
1706
4738
  } catch {
1707
- const { sessionId, commandId } = await this.startRuntimeServer(sandbox);
4739
+ throwIfAborted(signal);
4740
+ const detachedCommand = await awaitWithAbort(
4741
+ () => this.startRuntimeServer(sandbox),
4742
+ signal
4743
+ );
1708
4744
  try {
1709
- await waitForServerHealthy(healthUrl, connection);
4745
+ await waitForServerHealthy(
4746
+ healthUrl,
4747
+ connection,
4748
+ SERVER_HEALTH_TIMEOUT_MS,
4749
+ signal
4750
+ );
1710
4751
  } catch (error) {
4752
+ throwIfAborted(signal);
1711
4753
  const baseMessage = error instanceof Error ? error.message : String(error);
1712
- let logs = "";
1713
- if (commandId && sandbox.readSessionLogs) {
1714
- const captured = await sandbox.readSessionLogs(sessionId, commandId);
1715
- const parts = [];
1716
- if (captured.stdout.trim()) parts.push(`stdout:
1717
- ${captured.stdout}`);
1718
- if (captured.stderr.trim()) parts.push(`stderr:
1719
- ${captured.stderr}`);
1720
- if (parts.length > 0) {
1721
- logs = `
1722
- --- server logs ---
1723
- ${parts.join("\n\n")}`;
1724
- }
1725
- }
4754
+ const logs = await readServerFailureDiagnostics(
4755
+ sandbox,
4756
+ detachedCommand,
4757
+ this.envs,
4758
+ signal
4759
+ );
1726
4760
  throw new DeploymentError(`${baseMessage}${logs}`);
1727
4761
  }
1728
- this._serverRuntime = { sessionId, commandId, connection };
4762
+ throwIfAborted(signal);
4763
+ this._serverRuntime = { detachedCommand, connection };
1729
4764
  this._sandboxId = targetId;
1730
4765
  return connection;
1731
4766
  }
@@ -1750,8 +4785,8 @@ ${parts.join("\n\n")}`;
1750
4785
  if (!targetId) return;
1751
4786
  try {
1752
4787
  const sandbox = await this.connectSandboxHandle(targetId);
1753
- if (this._serverRuntime && this._serverRuntime.connection.sandboxId === targetId && this._serverRuntime.sessionId && sandbox.stopSession) {
1754
- await sandbox.stopSession(this._serverRuntime.sessionId).catch(() => void 0);
4788
+ if (this._serverRuntime && this._serverRuntime.connection.sandboxId === targetId && this._serverRuntime.detachedCommand && sandbox.stopSession) {
4789
+ await sandbox.stopSession(this._serverRuntime.detachedCommand).catch(() => void 0);
1755
4790
  }
1756
4791
  await sandbox.destroy();
1757
4792
  } catch {
@@ -1841,9 +4876,15 @@ var require = __neckbeard_createRequire(import.meta.url);
1841
4876
  this.outputSchema = config.outputSchema;
1842
4877
  this.maxDuration = config.maxDuration ?? 300;
1843
4878
  this._run = config.run;
1844
- if (config.server) {
1845
- this._server = config.server;
1846
- this.frameSchema = config.server.frameSchema;
4879
+ const session = config.session ?? config.server;
4880
+ if (session) {
4881
+ this.kind = 'session';
4882
+ this.mode = 'stream';
4883
+ this._server = session;
4884
+ this.frameSchema = session.frameSchema;
4885
+ } else {
4886
+ this.kind = 'task';
4887
+ this.mode = 'run';
1847
4888
  }
1848
4889
  }
1849
4890
  }
@@ -1875,142 +4916,145 @@ var require = __neckbeard_createRequire(import.meta.url);
1875
4916
  }]
1876
4917
  });
1877
4918
  const sandbox = await this.createSandboxHandle();
1878
- const { paths } = sandbox;
1879
- await sandbox.runCommand(`mkdir -p ${shellEscape(paths.agentDir)}`, {
1880
- timeoutMs: QUICK_COMMAND_TIMEOUT_MS
1881
- });
1882
- const { apt, commands } = this.dependencies;
1883
- if (apt && apt.length > 0) {
1884
- const aptCmd = `sudo apt-get update && sudo apt-get install -y ${apt.join(" ")}`;
1885
- const aptResult = await sandbox.runCommand(aptCmd, {
1886
- timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
4919
+ let deploymentCompleted = false;
4920
+ let detachedCommand;
4921
+ try {
4922
+ const { paths } = sandbox;
4923
+ await sandbox.runCommand(`mkdir -p ${shellQuote(paths.agentDir)}`, {
4924
+ timeoutMs: QUICK_COMMAND_TIMEOUT_MS2
1887
4925
  });
1888
- if (aptResult.exitCode !== 0) {
1889
- const details = [
1890
- `Failed to install apt packages: ${apt.join(", ")}`,
1891
- aptResult.stderr ? `stderr: ${aptResult.stderr}` : "",
1892
- aptResult.stdout ? `stdout: ${aptResult.stdout}` : ""
1893
- ].filter(Boolean).join("\n");
1894
- throw new DeploymentError(details);
1895
- }
1896
- }
1897
- if (commands && commands.length > 0) {
1898
- for (const cmd of commands) {
1899
- const cmdResult = await sandbox.runCommand(cmd, {
1900
- timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
4926
+ const { apt, commands } = this.dependencies;
4927
+ if (apt && apt.length > 0) {
4928
+ const aptCmd = `sudo apt-get update && sudo apt-get install -y ${apt.join(" ")}`;
4929
+ const aptResult = await sandbox.runCommand(aptCmd, {
4930
+ timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS2
1901
4931
  });
1902
- if (cmdResult.exitCode !== 0) {
4932
+ if (aptResult.exitCode !== 0) {
1903
4933
  const details = [
1904
- `Failed to run command: ${cmd}`,
1905
- cmdResult.stderr ? `stderr: ${cmdResult.stderr}` : "",
1906
- cmdResult.stdout ? `stdout: ${cmdResult.stdout}` : ""
4934
+ `Failed to install apt packages: ${apt.join(", ")}`,
4935
+ aptResult.stderr ? `stderr: ${aptResult.stderr}` : "",
4936
+ aptResult.stdout ? `stdout: ${aptResult.stdout}` : ""
1907
4937
  ].filter(Boolean).join("\n");
1908
4938
  throw new DeploymentError(details);
1909
4939
  }
1910
4940
  }
1911
- }
1912
- if (this.files.length > 0) {
1913
- for (const file of this.files) {
1914
- const destPath = file.path.startsWith("/") ? file.path : `${paths.homeDir}/${file.path}`;
1915
- const parentDir = destPath.substring(0, destPath.lastIndexOf("/"));
1916
- if (parentDir) {
1917
- await sandbox.runCommand(`mkdir -p ${shellEscape(parentDir)}`, {
1918
- timeoutMs: QUICK_COMMAND_TIMEOUT_MS
4941
+ if (commands && commands.length > 0) {
4942
+ for (const cmd of commands) {
4943
+ const cmdResult = await sandbox.runCommand(cmd, {
4944
+ timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS2
1919
4945
  });
4946
+ if (cmdResult.exitCode !== 0) {
4947
+ const details = [
4948
+ `Failed to run command: ${cmd}`,
4949
+ cmdResult.stderr ? `stderr: ${cmdResult.stderr}` : "",
4950
+ cmdResult.stdout ? `stdout: ${cmdResult.stdout}` : ""
4951
+ ].filter(Boolean).join("\n");
4952
+ throw new DeploymentError(details);
4953
+ }
1920
4954
  }
1921
- const curlCmd = `curl -fsSL -o ${shellEscape(destPath)} ${shellEscape(file.url)}`;
1922
- const downloadResult = await sandbox.runCommand(curlCmd, {
1923
- timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
1924
- });
1925
- if (downloadResult.exitCode !== 0) {
1926
- const details = [
1927
- `Failed to download file from ${file.url} to ${destPath}`,
1928
- downloadResult.stderr ? `stderr: ${downloadResult.stderr}` : "",
1929
- downloadResult.stdout ? `stdout: ${downloadResult.stdout}` : ""
1930
- ].filter(Boolean).join("\n");
1931
- throw new DeploymentError(details);
4955
+ }
4956
+ if (this.files.length > 0) {
4957
+ for (const file of this.files) {
4958
+ const destPath = file.path.startsWith("/") ? file.path : `${paths.homeDir}/${file.path}`;
4959
+ const parentDir = destPath.substring(0, destPath.lastIndexOf("/"));
4960
+ if (parentDir) {
4961
+ await sandbox.runCommand(`mkdir -p ${shellQuote(parentDir)}`, {
4962
+ timeoutMs: QUICK_COMMAND_TIMEOUT_MS2
4963
+ });
4964
+ }
4965
+ const curlCmd = `curl -fsSL -o ${shellQuote(destPath)} ${shellQuote(file.url)}`;
4966
+ const downloadResult = await sandbox.runCommand(curlCmd, {
4967
+ timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS2
4968
+ });
4969
+ if (downloadResult.exitCode !== 0) {
4970
+ const details = [
4971
+ `Failed to download file from ${file.url} to ${destPath}`,
4972
+ downloadResult.stderr ? `stderr: ${downloadResult.stderr}` : "",
4973
+ downloadResult.stdout ? `stdout: ${downloadResult.stdout}` : ""
4974
+ ].filter(Boolean).join("\n");
4975
+ throw new DeploymentError(details);
4976
+ }
1932
4977
  }
1933
4978
  }
1934
- }
1935
- for (const directory of localDirectoryUploads.directories) {
1936
- await sandbox.makeDir(import_node_path.posix.join(paths.agentDir, directory));
1937
- }
1938
- for (const file of localDirectoryUploads.files) {
1939
- await sandbox.writeFile(
1940
- import_node_path.posix.join(paths.agentDir, file.targetPath),
1941
- file.content
1942
- );
1943
- }
1944
- await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
1945
- await sandbox.writeFile(paths.serverModule, RUNTIME_SERVER_SOURCE);
1946
- const serverConfig = {
1947
- protocolVersion: RUNTIME_PROTOCOL_VERSION,
1948
- port: this._server?.port ?? DEFAULT_SERVER_PORT,
1949
- maxDurationMs: this.maxDuration * 1e3,
1950
- sandboxContext: {
1951
- provider: paths.provider,
1952
- homeDir: paths.homeDir,
1953
- workDir: paths.workDir,
1954
- agentDir: paths.agentDir,
1955
- ioDir: paths.ioDir,
1956
- inputJson: paths.inputJson,
1957
- outputJson: paths.outputJson
4979
+ for (const directory of localDirectoryUploads.directories) {
4980
+ await sandbox.makeDir(import_node_path.posix.join(paths.agentDir, directory));
1958
4981
  }
1959
- };
1960
- await sandbox.writeFile(paths.serverConfig, JSON.stringify(serverConfig));
1961
- if (collectedExternals.size > 0) {
1962
- const installable = Array.from(collectedExternals.values()).filter(isPackageCompatible);
1963
- const dependencies = Object.fromEntries(installable.map((info) => [info.name, info.version]));
1964
- if (Object.keys(dependencies).length > 0) {
1965
- const pkgJson = JSON.stringify({
1966
- name: "agent-sandbox",
1967
- type: "module",
1968
- dependencies
1969
- });
1970
- await sandbox.writeFile(paths.packageJson, pkgJson);
1971
- const installResult = await sandbox.runCommand("npm install --legacy-peer-deps", {
1972
- cwd: paths.agentDir,
1973
- timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS
1974
- });
1975
- if (installResult.exitCode !== 0) {
1976
- const details = [
1977
- `Failed to install npm packages: ${Object.keys(dependencies).join(", ")}`,
1978
- installResult.stderr ? `stderr: ${installResult.stderr}` : "",
1979
- installResult.stdout ? `stdout: ${installResult.stdout}` : ""
1980
- ].filter(Boolean).join("\n");
1981
- throw new DeploymentError(details);
4982
+ for (const file of localDirectoryUploads.files) {
4983
+ await sandbox.writeFile(
4984
+ import_node_path.posix.join(paths.agentDir, file.targetPath),
4985
+ file.content
4986
+ );
4987
+ }
4988
+ await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
4989
+ await sandbox.writeFile(paths.serverModule, RUNTIME_SERVER_SOURCE);
4990
+ const serverConfig = {
4991
+ protocolVersion: RUNTIME_PROTOCOL_VERSION,
4992
+ port: this._server?.port ?? DEFAULT_SERVER_PORT,
4993
+ maxDurationMs: this.maxDuration * 1e3,
4994
+ sandboxContext: {
4995
+ provider: paths.provider,
4996
+ homeDir: paths.homeDir,
4997
+ workDir: paths.workDir,
4998
+ agentDir: paths.agentDir,
4999
+ ioDir: paths.ioDir,
5000
+ inputJson: paths.inputJson,
5001
+ outputJson: paths.outputJson
5002
+ }
5003
+ };
5004
+ await sandbox.writeFile(paths.serverConfig, JSON.stringify(serverConfig));
5005
+ if (collectedExternals.size > 0) {
5006
+ const installable = Array.from(collectedExternals.values()).filter(isPackageCompatible);
5007
+ const dependencies = Object.fromEntries(installable.map((info) => [info.name, info.version]));
5008
+ if (Object.keys(dependencies).length > 0) {
5009
+ const pkgJson = JSON.stringify({
5010
+ name: "agent-sandbox",
5011
+ type: "module",
5012
+ dependencies
5013
+ });
5014
+ await sandbox.writeFile(paths.packageJson, pkgJson);
5015
+ const installResult = await sandbox.runCommand("npm install --legacy-peer-deps", {
5016
+ cwd: paths.agentDir,
5017
+ timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS2
5018
+ });
5019
+ if (installResult.exitCode !== 0) {
5020
+ const details = [
5021
+ `Failed to install npm packages: ${Object.keys(dependencies).join(", ")}`,
5022
+ installResult.stderr ? `stderr: ${installResult.stderr}` : "",
5023
+ installResult.stdout ? `stdout: ${installResult.stdout}` : ""
5024
+ ].filter(Boolean).join("\n");
5025
+ throw new DeploymentError(details);
5026
+ }
1982
5027
  }
1983
5028
  }
1984
- }
1985
- const port = serverConfig.port;
1986
- const { sessionId, commandId } = await this.startRuntimeServer(sandbox);
1987
- const connection = await this.createRuntimeConnection(sandbox, port);
1988
- const healthUrl = this.healthUrlFor(connection);
1989
- try {
1990
- await waitForServerHealthy(healthUrl, connection);
1991
- } catch (err) {
1992
- const baseMessage = err instanceof Error ? err.message : String(err);
1993
- let logs = "";
1994
- if (commandId && sandbox.readSessionLogs) {
1995
- const captured = await sandbox.readSessionLogs(sessionId, commandId);
1996
- const parts = [];
1997
- if (captured.stdout.trim()) parts.push(`stdout:
1998
- ${captured.stdout}`);
1999
- if (captured.stderr.trim()) parts.push(`stderr:
2000
- ${captured.stderr}`);
2001
- if (parts.length > 0) {
2002
- logs = `
2003
- --- server logs ---
2004
- ${parts.join("\n\n")}`;
5029
+ const port = serverConfig.port;
5030
+ detachedCommand = await this.startRuntimeServer(sandbox);
5031
+ const connection = await this.createRuntimeConnection(sandbox, port);
5032
+ const healthUrl = this.healthUrlFor(connection);
5033
+ try {
5034
+ await waitForServerHealthy(healthUrl, connection);
5035
+ } catch (err) {
5036
+ const baseMessage = err instanceof Error ? err.message : String(err);
5037
+ const logs = await readServerFailureDiagnostics(
5038
+ sandbox,
5039
+ detachedCommand,
5040
+ this.envs
5041
+ );
5042
+ throw new DeploymentError(`${baseMessage}${logs}`);
5043
+ }
5044
+ if (!options?.fresh) {
5045
+ this._sandboxId = sandbox.id;
5046
+ this._serverRuntime = { detachedCommand, connection };
5047
+ }
5048
+ deploymentCompleted = true;
5049
+ return sandbox.id;
5050
+ } finally {
5051
+ if (!deploymentCompleted) {
5052
+ if (detachedCommand && sandbox.stopSession) {
5053
+ await sandbox.stopSession(detachedCommand).catch(() => void 0);
2005
5054
  }
5055
+ await sandbox.destroy().catch(() => void 0);
2006
5056
  }
2007
- throw new DeploymentError(`${baseMessage}${logs}`);
2008
5057
  }
2009
- if (!options?.fresh) {
2010
- this._sandboxId = sandbox.id;
2011
- this._serverRuntime = { sessionId, commandId, connection };
2012
- }
2013
- return sandbox.id;
2014
5058
  }
2015
5059
  /**
2016
5060
  * Executes the agent with the given input.
@@ -2041,7 +5085,7 @@ ${parts.join("\n\n")}`;
2041
5085
  ok: false,
2042
5086
  executionId,
2043
5087
  error: new ExecutionError(
2044
- "run() is only available on agents configured with a run handler. Use agent.invoke() for streaming agents."
5088
+ "run() is only available on agents configured with a run handler. Use agent.createSession() for streaming session agents."
2045
5089
  )
2046
5090
  };
2047
5091
  }
@@ -2092,16 +5136,73 @@ ${parts.join("\n\n")}`;
2092
5136
  }
2093
5137
  }
2094
5138
  /**
2095
- * Invoke a streaming agent. Streams user frames emitted by the in-sandbox
2096
- * handler as an async iterator.
5139
+ * Creates a caller-owned session against the persistent sandbox runtime.
5140
+ * The returned handle supports sequential prompts, active-turn cancellation,
5141
+ * and explicit close without destroying the reusable sandbox.
2097
5142
  */
2098
- async *invoke(input, options) {
5143
+ async createSession(options = {}) {
2099
5144
  if (this.mode !== "stream") {
2100
5145
  throw new ConfigurationError(
2101
- "invoke() is only available on agents configured with server.handler. Use agent.run() for run-output agents."
5146
+ "createSession() is only available on agents configured with session.handler (or deprecated server.handler). Use agent.run() for run-output agents."
5147
+ );
5148
+ }
5149
+ if (!options || typeof options !== "object") {
5150
+ throw new ConfigurationError("Agent.createSession() options must be an object.");
5151
+ }
5152
+ let optionsAreArray;
5153
+ try {
5154
+ optionsAreArray = Array.isArray(options);
5155
+ } catch {
5156
+ throw new ConfigurationError(
5157
+ "Agent.createSession() options must have readable values."
5158
+ );
5159
+ }
5160
+ if (optionsAreArray) {
5161
+ throw new ConfigurationError("Agent.createSession() options must be an object.");
5162
+ }
5163
+ let durability;
5164
+ let requestedSandboxId;
5165
+ let signal;
5166
+ try {
5167
+ durability = options.durability;
5168
+ requestedSandboxId = options.sandboxId;
5169
+ signal = options.signal;
5170
+ } catch {
5171
+ throw new ConfigurationError(
5172
+ "Agent.createSession() options must have readable values."
5173
+ );
5174
+ }
5175
+ if (durability !== void 0 && durability !== "attached") {
5176
+ throw new ConfigurationError(
5177
+ "Agent.createSession() creates caller-owned attached sessions. Use agent-neckbeard/supervisor durable-session APIs for gateway-owned sessions."
5178
+ );
5179
+ }
5180
+ if (requestedSandboxId !== void 0 && (typeof requestedSandboxId !== "string" || requestedSandboxId.trim() === "")) {
5181
+ throw new ConfigurationError(
5182
+ "Agent.createSession() sandboxId must be a non-empty string when provided."
2102
5183
  );
2103
5184
  }
2104
- const connection = await this.resolveRuntimeConnection(options?.sandboxId);
5185
+ if (signal !== void 0 && !isAbortSignal(signal)) {
5186
+ throw new ConfigurationError(
5187
+ "Agent.createSession() signal must be an AbortSignal when provided."
5188
+ );
5189
+ }
5190
+ const sandboxId = requestedSandboxId ?? this._serverRuntime?.connection.sandboxId ?? this._sandboxId;
5191
+ if (!sandboxId) {
5192
+ throw new ConfigurationError("Agent not deployed. Call agent.deploy() first or pass sandboxId.");
5193
+ }
5194
+ return createAttachedAgentSession({
5195
+ sandboxId,
5196
+ runPrompt: (input, signal2) => this.streamSessionPrompt(input, sandboxId, signal2),
5197
+ ...signal === void 0 ? {} : { externalSignal: signal },
5198
+ configurationError: (message) => new ConfigurationError(message)
5199
+ });
5200
+ }
5201
+ async *streamSessionPrompt(input, sandboxId, signal) {
5202
+ const connection = await this.resolveRuntimeConnection(sandboxId, {
5203
+ signal,
5204
+ reuseMatchingCachedConnection: true
5205
+ });
2105
5206
  const { invokeServer: invokeServer2 } = await Promise.resolve().then(() => (init_invoke_client(), invoke_client_exports));
2106
5207
  let validated;
2107
5208
  try {
@@ -2115,7 +5216,7 @@ ${parts.join("\n\n")}`;
2115
5216
  provider: connection.provider,
2116
5217
  trafficToken: getTrafficToken(connection),
2117
5218
  frameSchema: this.frameSchema,
2118
- signal: options?.signal
5219
+ signal
2119
5220
  })) {
2120
5221
  if (frame.kind === "frame") {
2121
5222
  yield frame.data;
@@ -2130,6 +5231,22 @@ ${parts.join("\n\n")}`;
2130
5231
  throw error instanceof Error ? error : new Error(String(error));
2131
5232
  }
2132
5233
  }
5234
+ /**
5235
+ * @deprecated Use `createSession()` and call `session.prompt(input)` instead.
5236
+ * This compatibility wrapper creates one attached session, streams one turn,
5237
+ * and closes the local handle afterward.
5238
+ */
5239
+ async *invoke(input, options) {
5240
+ const session = await this.createSession({
5241
+ ...options?.sandboxId === void 0 ? {} : { sandboxId: options.sandboxId },
5242
+ ...options?.signal === void 0 ? {} : { signal: options.signal }
5243
+ });
5244
+ try {
5245
+ yield* session.prompt(input);
5246
+ } finally {
5247
+ await session.close();
5248
+ }
5249
+ }
2133
5250
  };
2134
5251
  // Annotate the CommonJS export names for ESM import in node:
2135
5252
  0 && (module.exports = {