agent-neckbeard 1.1.18 → 1.1.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +26 -0
- package/README.md +171 -67
- package/dist/chunk-33IXN6MM.js +21 -0
- package/dist/chunk-3EB4CT5S.js +2516 -0
- package/dist/{chunk-AM2J5KBI.js → chunk-DHFC3O44.js} +4 -8
- package/dist/index.cjs +3646 -535
- package/dist/index.d.cts +150 -56
- package/dist/index.d.ts +150 -56
- package/dist/index.js +1161 -501
- package/dist/{invoke-client-XEH6FVRH.js → invoke-client-D5TMTOYM.js} +2 -1
- package/dist/sandbox-capabilities-CFjnZ_kB.d.cts +77 -0
- package/dist/sandbox-capabilities-CFjnZ_kB.d.ts +77 -0
- package/dist/supervisor.cjs +6043 -0
- package/dist/supervisor.d.cts +470 -0
- package/dist/supervisor.d.ts +470 -0
- package/dist/supervisor.js +3535 -0
- package/docs/SUPERVISOR.md +248 -0
- package/package.json +20 -8
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,3042 @@ 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(daytonaTimeoutSeconds(SANDBOX_COMMAND_TIMEOUT_MS));
|
|
2996
|
+
}
|
|
2997
|
+
};
|
|
2998
|
+
|
|
2999
|
+
// src/timeout.ts
|
|
3000
|
+
function settleOperation(operation, options = {}) {
|
|
3001
|
+
const { abort, timeout } = options;
|
|
3002
|
+
if (abort?.signal.aborted) throw abort.createError();
|
|
3003
|
+
if (!abort && !timeout) {
|
|
3004
|
+
try {
|
|
3005
|
+
return Promise.resolve(operation());
|
|
3006
|
+
} catch (error) {
|
|
3007
|
+
return Promise.reject(error);
|
|
3008
|
+
}
|
|
3009
|
+
}
|
|
3010
|
+
return new Promise((resolve2, reject) => {
|
|
3011
|
+
let settled = false;
|
|
3012
|
+
let timer;
|
|
3013
|
+
const cleanup = () => {
|
|
3014
|
+
if (timer !== void 0) {
|
|
3015
|
+
clearTimeout(timer);
|
|
3016
|
+
timer = void 0;
|
|
3017
|
+
}
|
|
3018
|
+
abort?.signal.removeEventListener("abort", onAbort);
|
|
3019
|
+
};
|
|
3020
|
+
const settle = (callback) => {
|
|
3021
|
+
if (settled) return;
|
|
3022
|
+
settled = true;
|
|
3023
|
+
cleanup();
|
|
3024
|
+
callback();
|
|
3025
|
+
};
|
|
3026
|
+
const onAbort = () => settle(() => reject(abort.createError()));
|
|
3027
|
+
abort?.signal.addEventListener("abort", onAbort, { once: true });
|
|
3028
|
+
if (timeout) {
|
|
3029
|
+
timer = setTimeout(
|
|
3030
|
+
() => settle(() => reject(timeout.createError())),
|
|
3031
|
+
timeout.timeoutMs
|
|
3032
|
+
);
|
|
3033
|
+
}
|
|
3034
|
+
let task;
|
|
3035
|
+
try {
|
|
3036
|
+
task = operation();
|
|
3037
|
+
} catch (error) {
|
|
3038
|
+
settle(() => reject(error));
|
|
3039
|
+
return;
|
|
3040
|
+
}
|
|
3041
|
+
void Promise.resolve(task).then(
|
|
3042
|
+
(value) => settle(() => resolve2(value)),
|
|
3043
|
+
(error) => settle(() => reject(error))
|
|
3044
|
+
);
|
|
3045
|
+
});
|
|
3046
|
+
}
|
|
3047
|
+
function withTimeout(task, timeoutMs, message) {
|
|
3048
|
+
return settleOperation(() => task, {
|
|
3049
|
+
timeout: {
|
|
3050
|
+
timeoutMs,
|
|
3051
|
+
createError: () => new Error(message)
|
|
3052
|
+
}
|
|
3053
|
+
});
|
|
3054
|
+
}
|
|
3055
|
+
|
|
3056
|
+
// src/providers/e2b.ts
|
|
3057
|
+
var E2B_SANDBOX_HOME = "/home/user";
|
|
3058
|
+
var LEGACY_E2B_PROCESS_HANDLE_PATTERN = /^e2b:([1-9][0-9]*)$/u;
|
|
3059
|
+
var LEGACY_E2B_EXIT_POLL_INTERVAL_MS = 100;
|
|
3060
|
+
function parseLegacyE2bProcessHandle(value) {
|
|
3061
|
+
const match = LEGACY_E2B_PROCESS_HANDLE_PATTERN.exec(value);
|
|
3062
|
+
if (!match) return null;
|
|
3063
|
+
const pid = Number(match[1]);
|
|
3064
|
+
return Number.isSafeInteger(pid) && pid > 0 ? pid : null;
|
|
3065
|
+
}
|
|
3066
|
+
function remainingTimeoutMs(deadline) {
|
|
3067
|
+
return Math.max(1, Math.ceil(deadline - performance.now()));
|
|
3068
|
+
}
|
|
3069
|
+
function delay(timeoutMs) {
|
|
3070
|
+
return new Promise((resolve2) => setTimeout(resolve2, timeoutMs));
|
|
3071
|
+
}
|
|
3072
|
+
async function withinDeadline(operation, deadline) {
|
|
3073
|
+
return withTimeout(
|
|
3074
|
+
operation,
|
|
3075
|
+
remainingTimeoutMs(deadline),
|
|
3076
|
+
"E2B process control request timed out."
|
|
3077
|
+
);
|
|
3078
|
+
}
|
|
3079
|
+
function numberProperty(value, property) {
|
|
3080
|
+
if (typeof value !== "object" || value === null) return void 0;
|
|
3081
|
+
const propertyValue = Reflect.get(value, property);
|
|
3082
|
+
return typeof propertyValue === "number" ? propertyValue : void 0;
|
|
3083
|
+
}
|
|
3084
|
+
function stringProperty(value, property) {
|
|
3085
|
+
if (typeof value !== "object" || value === null) return void 0;
|
|
3086
|
+
const propertyValue = Reflect.get(value, property);
|
|
3087
|
+
return typeof propertyValue === "string" ? propertyValue : void 0;
|
|
3088
|
+
}
|
|
3089
|
+
function messageFrom2(error) {
|
|
3090
|
+
return error instanceof Error ? error.message : String(error);
|
|
3091
|
+
}
|
|
3092
|
+
function writeContent(content) {
|
|
3093
|
+
if (typeof content === "string") return content;
|
|
3094
|
+
if (content instanceof ArrayBuffer) return content;
|
|
3095
|
+
return Uint8Array.from(content).buffer;
|
|
3096
|
+
}
|
|
3097
|
+
async function runE2bCommand(sandbox, cmd, options) {
|
|
3098
|
+
let stdout = "";
|
|
3099
|
+
let stderr = "";
|
|
3100
|
+
const command = options.cwd ? `cd ${shellQuote(options.cwd)} && ${cmd}` : cmd;
|
|
3101
|
+
try {
|
|
3102
|
+
const result = await sandbox.commands.run(command, {
|
|
3103
|
+
timeoutMs: options.timeoutMs,
|
|
3104
|
+
envs: options.envs,
|
|
3105
|
+
background: false,
|
|
3106
|
+
onStdout: (data) => {
|
|
3107
|
+
stdout += data;
|
|
3108
|
+
options.onStdout?.(data);
|
|
3109
|
+
},
|
|
3110
|
+
onStderr: (data) => {
|
|
3111
|
+
stderr += data;
|
|
3112
|
+
options.onStderr?.(data);
|
|
3113
|
+
}
|
|
3114
|
+
});
|
|
3115
|
+
return {
|
|
3116
|
+
exitCode: result.exitCode,
|
|
3117
|
+
stdout: stdout || result.stdout,
|
|
3118
|
+
stderr: stderr || result.stderr
|
|
3119
|
+
};
|
|
3120
|
+
} catch (error) {
|
|
3121
|
+
return {
|
|
3122
|
+
exitCode: numberProperty(error, "exitCode") ?? 1,
|
|
3123
|
+
stdout: stdout || stringProperty(error, "stdout") || "",
|
|
3124
|
+
stderr: stderr || stringProperty(error, "stderr") || messageFrom2(error)
|
|
3125
|
+
};
|
|
3126
|
+
}
|
|
3127
|
+
}
|
|
3128
|
+
var E2bSandboxHandle = class {
|
|
3129
|
+
constructor(sandbox, failure) {
|
|
3130
|
+
this.sandbox = sandbox;
|
|
3131
|
+
this.failure = failure;
|
|
3132
|
+
this.detachedProcesses = new DetachedProcessController({
|
|
3133
|
+
provider: "e2b",
|
|
3134
|
+
genericPayloadEnvironmentDefaults: { HOME: this.paths.homeDir },
|
|
3135
|
+
execute: async (command, options) => ({
|
|
3136
|
+
state: "completed",
|
|
3137
|
+
result: await runE2bCommand(this.sandbox, command, {
|
|
3138
|
+
cwd: options?.cwd,
|
|
3139
|
+
envs: options?.envs,
|
|
3140
|
+
timeoutMs: DETACHED_PROCESS_CONTROL_TIMEOUT_MS
|
|
3141
|
+
})
|
|
3142
|
+
}),
|
|
3143
|
+
readLegacyLogs: (command) => this.readLegacySessionLogs(command),
|
|
3144
|
+
stopLegacy: (command) => this.stopLegacySession(command),
|
|
3145
|
+
failure
|
|
3146
|
+
});
|
|
3147
|
+
}
|
|
3148
|
+
provider = "e2b";
|
|
3149
|
+
detachedProcesses;
|
|
3150
|
+
paths = createProviderSandboxPaths(
|
|
3151
|
+
"e2b",
|
|
3152
|
+
E2B_SANDBOX_HOME,
|
|
3153
|
+
E2B_SANDBOX_HOME
|
|
3154
|
+
);
|
|
3155
|
+
get id() {
|
|
3156
|
+
return this.sandbox.sandboxId;
|
|
3157
|
+
}
|
|
3158
|
+
async makeDir(path) {
|
|
3159
|
+
await this.sandbox.files.makeDir(path);
|
|
3160
|
+
}
|
|
3161
|
+
writeFile(path, content) {
|
|
3162
|
+
return this.sandbox.files.write(path, writeContent(content)).then(() => void 0);
|
|
3163
|
+
}
|
|
3164
|
+
readFile(path) {
|
|
3165
|
+
return this.sandbox.files.read(path, { format: "text" });
|
|
3166
|
+
}
|
|
3167
|
+
readFileBytes(path) {
|
|
3168
|
+
return this.sandbox.files.read(path, { format: "bytes" });
|
|
3169
|
+
}
|
|
3170
|
+
runCommand(cmd, options) {
|
|
3171
|
+
return runE2bCommand(this.sandbox, cmd, options);
|
|
3172
|
+
}
|
|
3173
|
+
setTimeout(timeoutMs) {
|
|
3174
|
+
return this.sandbox.setTimeout(timeoutMs);
|
|
3175
|
+
}
|
|
3176
|
+
async startDetachedCommand(command, options = {}) {
|
|
3177
|
+
return this.detachedProcesses.start(command, options);
|
|
3178
|
+
}
|
|
3179
|
+
async readSessionLogs(command) {
|
|
3180
|
+
return this.detachedProcesses.readLogs(command);
|
|
3181
|
+
}
|
|
3182
|
+
async readLegacySessionLogs(command) {
|
|
3183
|
+
const { commandId } = command;
|
|
3184
|
+
if (commandId === void 0) return { stdout: "", stderr: "" };
|
|
3185
|
+
try {
|
|
3186
|
+
const handle = await this.sandbox.commands.connect(Number(commandId));
|
|
3187
|
+
return {
|
|
3188
|
+
stdout: boundDetachedProcessLog(handle.stdout ?? ""),
|
|
3189
|
+
stderr: boundDetachedProcessLog(handle.stderr ?? "")
|
|
3190
|
+
};
|
|
3191
|
+
} catch {
|
|
3192
|
+
return { stdout: "", stderr: "" };
|
|
3193
|
+
}
|
|
3194
|
+
}
|
|
3195
|
+
async stopSession(command) {
|
|
3196
|
+
await this.detachedProcesses.stop(command);
|
|
3197
|
+
}
|
|
3198
|
+
async disposeSessionArtifacts(command) {
|
|
3199
|
+
await this.detachedProcesses.dispose(command);
|
|
3200
|
+
}
|
|
3201
|
+
async stopLegacySession(command) {
|
|
3202
|
+
const { sessionId } = command;
|
|
3203
|
+
const legacyPid = parseLegacyE2bProcessHandle(sessionId);
|
|
3204
|
+
if (legacyPid === null) {
|
|
3205
|
+
throw this.failure("Detached process handle is invalid for E2B.");
|
|
3206
|
+
}
|
|
3207
|
+
const deadline = performance.now() + DETACHED_PROCESS_CONTROL_TIMEOUT_MS;
|
|
3208
|
+
let signalled;
|
|
3209
|
+
try {
|
|
3210
|
+
signalled = await withinDeadline(
|
|
3211
|
+
this.sandbox.commands.kill(legacyPid, {
|
|
3212
|
+
requestTimeoutMs: remainingTimeoutMs(deadline)
|
|
3213
|
+
}),
|
|
3214
|
+
deadline
|
|
3215
|
+
);
|
|
3216
|
+
} catch (error) {
|
|
3217
|
+
throw this.failure(
|
|
3218
|
+
`Failed to stop legacy detached E2B process ${legacyPid}: ${messageFrom2(error)}`
|
|
3219
|
+
);
|
|
3220
|
+
}
|
|
3221
|
+
if (!signalled) return;
|
|
3222
|
+
while (performance.now() < deadline) {
|
|
3223
|
+
let processes;
|
|
3224
|
+
try {
|
|
3225
|
+
processes = await withinDeadline(
|
|
3226
|
+
this.sandbox.commands.list({
|
|
3227
|
+
requestTimeoutMs: remainingTimeoutMs(deadline)
|
|
3228
|
+
}),
|
|
3229
|
+
deadline
|
|
3230
|
+
);
|
|
3231
|
+
} catch (error) {
|
|
3232
|
+
throw this.failure(
|
|
3233
|
+
`Failed to confirm legacy detached E2B process ${legacyPid} exit: ${messageFrom2(error)}`
|
|
3234
|
+
);
|
|
3235
|
+
}
|
|
3236
|
+
if (!processes.some((process2) => process2.pid === legacyPid)) return;
|
|
3237
|
+
const remaining = deadline - performance.now();
|
|
3238
|
+
if (remaining <= 0) break;
|
|
3239
|
+
await delay(Math.min(LEGACY_E2B_EXIT_POLL_INTERVAL_MS, remaining));
|
|
3240
|
+
}
|
|
3241
|
+
throw this.failure(
|
|
3242
|
+
`Failed to stop legacy detached E2B process ${legacyPid}: provider still reports it as running.`
|
|
3243
|
+
);
|
|
3244
|
+
}
|
|
3245
|
+
async getServerEndpoint(port) {
|
|
3246
|
+
return {
|
|
3247
|
+
url: `https://${this.sandbox.getHost(port)}`,
|
|
3248
|
+
trafficToken: this.sandbox.trafficAccessToken
|
|
3249
|
+
};
|
|
220
3250
|
}
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
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';
|
|
3251
|
+
async destroy() {
|
|
3252
|
+
await this.sandbox.kill();
|
|
3253
|
+
}
|
|
3254
|
+
};
|
|
247
3255
|
|
|
248
3256
|
// src/index.ts
|
|
249
3257
|
function readPackageJson(path) {
|
|
@@ -253,8 +3261,8 @@ var getEsbuild = () => import("esbuild");
|
|
|
253
3261
|
var getE2b = () => import("e2b");
|
|
254
3262
|
var getDaytona = () => import("@daytona/sdk");
|
|
255
3263
|
var DEFAULT_MAX_DURATION = 300;
|
|
256
|
-
var
|
|
257
|
-
var
|
|
3264
|
+
var SANDBOX_COMMAND_TIMEOUT_MS2 = 3e5;
|
|
3265
|
+
var QUICK_COMMAND_TIMEOUT_MS2 = 3e4;
|
|
258
3266
|
var DAYTONA_CREATE_TIMEOUT_SEC = 120;
|
|
259
3267
|
var NODE_TARGET = "node20";
|
|
260
3268
|
var DEFAULT_EXTERNALS = ["@anthropic-ai/claude-agent-sdk"];
|
|
@@ -266,9 +3274,9 @@ var DEFAULT_SERVER_PORT = 3e3;
|
|
|
266
3274
|
var SERVER_HEALTH_TIMEOUT_MS = 12e4;
|
|
267
3275
|
var SERVER_RECONNECT_HEALTH_TIMEOUT_MS = 3e3;
|
|
268
3276
|
var SERVER_HEALTH_POLL_INTERVAL_MS = 1e3;
|
|
3277
|
+
var SERVER_FAILURE_DIAGNOSTIC_TIMEOUT_MS = 1e3;
|
|
269
3278
|
var NATIVE_EXT_RE = /\.(node|wasm|gyp|c|cc|cpp|cxx|h|hpp|hxx)$/i;
|
|
270
3279
|
var TRACEABLE_SOURCE_EXT_RE = /\.(cjs|cts|js|jsx|mjs|mts|ts|tsx)$/i;
|
|
271
|
-
var E2B_SANDBOX_HOME = "/home/user";
|
|
272
3280
|
var NeckbeardError = class extends Error {
|
|
273
3281
|
constructor(message) {
|
|
274
3282
|
super(message);
|
|
@@ -730,8 +3738,20 @@ function mergeTracingIncludes(existing, routeGlobs, sourceFiles) {
|
|
|
730
3738
|
return includes;
|
|
731
3739
|
}
|
|
732
3740
|
var DEFAULT_DEPENDENCIES = {};
|
|
733
|
-
function
|
|
734
|
-
return "server" in config && config.server !== void 0;
|
|
3741
|
+
function isSessionAgentConfig(config) {
|
|
3742
|
+
return "session" in config && config.session !== void 0 || "server" in config && config.server !== void 0;
|
|
3743
|
+
}
|
|
3744
|
+
function getSessionHandler(config) {
|
|
3745
|
+
const session = "session" in config ? config.session : void 0;
|
|
3746
|
+
const server = "server" in config ? config.server : void 0;
|
|
3747
|
+
if (session && server) {
|
|
3748
|
+
throw new ConfigurationError("Agent config must use session or deprecated server, not both.");
|
|
3749
|
+
}
|
|
3750
|
+
const handler = session ?? server;
|
|
3751
|
+
if (!handler || typeof handler !== "object") {
|
|
3752
|
+
throw new ConfigurationError("session must be an object.");
|
|
3753
|
+
}
|
|
3754
|
+
return handler;
|
|
735
3755
|
}
|
|
736
3756
|
function isSchemaLike(value) {
|
|
737
3757
|
return Boolean(
|
|
@@ -744,6 +3764,20 @@ function requireSchemaLike(name, value) {
|
|
|
744
3764
|
}
|
|
745
3765
|
return value;
|
|
746
3766
|
}
|
|
3767
|
+
function isAbortSignal(value) {
|
|
3768
|
+
if (!value || typeof value !== "object") return false;
|
|
3769
|
+
try {
|
|
3770
|
+
const abortedGetter = Object.getOwnPropertyDescriptor(
|
|
3771
|
+
AbortSignal.prototype,
|
|
3772
|
+
"aborted"
|
|
3773
|
+
)?.get;
|
|
3774
|
+
if (!abortedGetter || typeof abortedGetter.call(value) !== "boolean") return false;
|
|
3775
|
+
const candidate = value;
|
|
3776
|
+
return typeof candidate.aborted === "boolean" && typeof candidate.addEventListener === "function" && typeof candidate.removeEventListener === "function";
|
|
3777
|
+
} catch {
|
|
3778
|
+
return false;
|
|
3779
|
+
}
|
|
3780
|
+
}
|
|
747
3781
|
function normalizeLocalDirectoryDestination(destination, name) {
|
|
748
3782
|
if (destination.trim() === "") {
|
|
749
3783
|
throw new ConfigurationError(`${name}.destination must be a non-empty relative path.`);
|
|
@@ -812,21 +3846,19 @@ function validateAgentConfig(config) {
|
|
|
812
3846
|
throw new ConfigurationError("sourceFile must be a non-empty string when provided.");
|
|
813
3847
|
}
|
|
814
3848
|
validateLocalDirectoriesConfig(config.localDirectories);
|
|
815
|
-
if (
|
|
3849
|
+
if (isSessionAgentConfig(config)) {
|
|
816
3850
|
if ("run" in config && typeof config.run === "function") {
|
|
817
|
-
throw new ConfigurationError("Agent config must use either run or
|
|
818
|
-
}
|
|
819
|
-
if (!config.server || typeof config.server !== "object") {
|
|
820
|
-
throw new ConfigurationError("server must be an object.");
|
|
3851
|
+
throw new ConfigurationError("Agent config must use either run or session.handler, not both.");
|
|
821
3852
|
}
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
3853
|
+
const session = getSessionHandler(config);
|
|
3854
|
+
if (session.port !== void 0) {
|
|
3855
|
+
if (!Number.isInteger(session.port) || session.port < 1 || session.port > 65535) {
|
|
3856
|
+
throw new ConfigurationError("session.port must be an integer between 1 and 65535.");
|
|
825
3857
|
}
|
|
826
3858
|
}
|
|
827
|
-
requireSchemaLike("
|
|
828
|
-
if (typeof
|
|
829
|
-
throw new ConfigurationError("
|
|
3859
|
+
requireSchemaLike("session.frameSchema", session.frameSchema);
|
|
3860
|
+
if (typeof session.handler !== "function") {
|
|
3861
|
+
throw new ConfigurationError("session.handler must be a function.");
|
|
830
3862
|
}
|
|
831
3863
|
return;
|
|
832
3864
|
}
|
|
@@ -851,24 +3883,86 @@ function trafficTokenHeaders(descriptor) {
|
|
|
851
3883
|
}
|
|
852
3884
|
return {};
|
|
853
3885
|
}
|
|
854
|
-
|
|
3886
|
+
function abortSignalError(signal) {
|
|
3887
|
+
if (signal.reason instanceof Error) return signal.reason;
|
|
3888
|
+
const error = new Error(
|
|
3889
|
+
signal.reason === void 0 ? "Operation aborted." : String(signal.reason)
|
|
3890
|
+
);
|
|
3891
|
+
error.name = "AbortError";
|
|
3892
|
+
return error;
|
|
3893
|
+
}
|
|
3894
|
+
function throwIfAborted(signal) {
|
|
3895
|
+
if (signal?.aborted) throw abortSignalError(signal);
|
|
3896
|
+
}
|
|
3897
|
+
function awaitWithAbort(operation, signal) {
|
|
3898
|
+
return settleOperation(operation, {
|
|
3899
|
+
...signal ? {
|
|
3900
|
+
abort: {
|
|
3901
|
+
signal,
|
|
3902
|
+
createError: () => abortSignalError(signal)
|
|
3903
|
+
}
|
|
3904
|
+
} : {}
|
|
3905
|
+
});
|
|
3906
|
+
}
|
|
3907
|
+
function awaitDiagnosticRead(operation, signal) {
|
|
3908
|
+
return settleOperation(operation, {
|
|
3909
|
+
...signal ? {
|
|
3910
|
+
abort: {
|
|
3911
|
+
signal,
|
|
3912
|
+
createError: () => abortSignalError(signal)
|
|
3913
|
+
}
|
|
3914
|
+
} : {},
|
|
3915
|
+
timeout: {
|
|
3916
|
+
timeoutMs: SERVER_FAILURE_DIAGNOSTIC_TIMEOUT_MS,
|
|
3917
|
+
createError: () => new Error("Server diagnostic read timed out.")
|
|
3918
|
+
}
|
|
3919
|
+
});
|
|
3920
|
+
}
|
|
3921
|
+
function delayWithAbort(delayMs, signal) {
|
|
3922
|
+
if (!signal) {
|
|
3923
|
+
return new Promise((resolve2) => setTimeout(resolve2, delayMs));
|
|
3924
|
+
}
|
|
3925
|
+
throwIfAborted(signal);
|
|
3926
|
+
return new Promise((resolve2, reject) => {
|
|
3927
|
+
const onAbort = () => {
|
|
3928
|
+
clearTimeout(timer);
|
|
3929
|
+
reject(abortSignalError(signal));
|
|
3930
|
+
};
|
|
3931
|
+
const timer = setTimeout(() => {
|
|
3932
|
+
signal.removeEventListener("abort", onAbort);
|
|
3933
|
+
resolve2();
|
|
3934
|
+
}, delayMs);
|
|
3935
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
3936
|
+
});
|
|
3937
|
+
}
|
|
3938
|
+
async function waitForServerHealthy(healthUrl, descriptor, timeoutMs = SERVER_HEALTH_TIMEOUT_MS, signal) {
|
|
855
3939
|
const deadline = Date.now() + timeoutMs;
|
|
856
3940
|
let lastError;
|
|
857
3941
|
const urlWithToken = appendTrafficTokenToUrl(healthUrl, descriptor);
|
|
858
3942
|
while (Date.now() < deadline) {
|
|
3943
|
+
throwIfAborted(signal);
|
|
859
3944
|
try {
|
|
860
|
-
const response = await
|
|
861
|
-
|
|
862
|
-
|
|
3945
|
+
const response = await awaitWithAbort(
|
|
3946
|
+
() => fetch(urlWithToken, {
|
|
3947
|
+
headers: trafficTokenHeaders(descriptor),
|
|
3948
|
+
...signal === void 0 ? {} : { signal }
|
|
3949
|
+
}),
|
|
3950
|
+
signal
|
|
3951
|
+
);
|
|
863
3952
|
if (response.ok) {
|
|
864
|
-
|
|
3953
|
+
try {
|
|
3954
|
+
await awaitWithAbort(() => response.text(), signal);
|
|
3955
|
+
} catch {
|
|
3956
|
+
throwIfAborted(signal);
|
|
3957
|
+
}
|
|
865
3958
|
return;
|
|
866
3959
|
}
|
|
867
3960
|
lastError = new Error(`health check returned ${response.status}`);
|
|
868
3961
|
} catch (error) {
|
|
3962
|
+
throwIfAborted(signal);
|
|
869
3963
|
lastError = error;
|
|
870
3964
|
}
|
|
871
|
-
await
|
|
3965
|
+
await delayWithAbort(SERVER_HEALTH_POLL_INTERVAL_MS, signal);
|
|
872
3966
|
}
|
|
873
3967
|
const message = lastError instanceof Error ? lastError.message : String(lastError);
|
|
874
3968
|
throw new DeploymentError(
|
|
@@ -884,9 +3978,6 @@ function requireEnv(name) {
|
|
|
884
3978
|
}
|
|
885
3979
|
return value;
|
|
886
3980
|
}
|
|
887
|
-
function shellEscape(str) {
|
|
888
|
-
return `'${str.replace(/'/g, "'\\''")}'`;
|
|
889
|
-
}
|
|
890
3981
|
var require2 = (0, import_node_module.createRequire)((0, import_node_path.join)(process.cwd(), "__agent_neckbeard__.cjs"));
|
|
891
3982
|
var packageRequire = createPackageRequire();
|
|
892
3983
|
function createPackageRequire() {
|
|
@@ -944,322 +4035,160 @@ function resolvePackageInfoSync(importPath, resolveDir) {
|
|
|
944
4035
|
const parent = (0, import_node_path.dirname)(root);
|
|
945
4036
|
if (parent === root) break;
|
|
946
4037
|
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) {
|
|
4038
|
+
}
|
|
4039
|
+
if (!packageJsonPath) return null;
|
|
4040
|
+
const packageJson = readPackageJson(packageJsonPath);
|
|
4041
|
+
if (!packageJson.name || !packageJson.version) return null;
|
|
4042
|
+
root = (0, import_node_path.dirname)(packageJsonPath);
|
|
1168
4043
|
return {
|
|
1169
|
-
|
|
1170
|
-
|
|
4044
|
+
name: packageJson.name,
|
|
4045
|
+
version: packageJson.version,
|
|
4046
|
+
root,
|
|
4047
|
+
resolvedPath,
|
|
4048
|
+
packageJson
|
|
1171
4049
|
};
|
|
4050
|
+
} catch {
|
|
4051
|
+
return null;
|
|
1172
4052
|
}
|
|
1173
|
-
|
|
1174
|
-
|
|
4053
|
+
}
|
|
4054
|
+
function resolvePackageInfoFromResolvedPath(importPath, resolvedPath) {
|
|
4055
|
+
const packageName = packageNameForImportPath(importPath);
|
|
4056
|
+
let root = (0, import_node_path.dirname)(resolvedPath);
|
|
4057
|
+
while (true) {
|
|
4058
|
+
const packageJsonPath = (0, import_node_path.join)(root, "package.json");
|
|
4059
|
+
if ((0, import_node_fs.existsSync)(packageJsonPath)) {
|
|
4060
|
+
const packageJson = readPackageJson(packageJsonPath);
|
|
4061
|
+
if (packageJson.name === packageName) {
|
|
4062
|
+
if (!packageJson.version) return null;
|
|
4063
|
+
return {
|
|
4064
|
+
name: packageJson.name,
|
|
4065
|
+
version: packageJson.version,
|
|
4066
|
+
root,
|
|
4067
|
+
resolvedPath,
|
|
4068
|
+
packageJson
|
|
4069
|
+
};
|
|
4070
|
+
}
|
|
4071
|
+
}
|
|
4072
|
+
const parent = (0, import_node_path.dirname)(root);
|
|
4073
|
+
if (parent === root) return null;
|
|
4074
|
+
root = parent;
|
|
1175
4075
|
}
|
|
1176
|
-
}
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
4076
|
+
}
|
|
4077
|
+
function hasNativeHints(info) {
|
|
4078
|
+
const files = Array.isArray(info.packageJson.files) ? info.packageJson.files : [];
|
|
4079
|
+
const fields = [info.packageJson.main, info.packageJson.module, info.packageJson.browser].filter(
|
|
4080
|
+
(f) => typeof f === "string"
|
|
4081
|
+
);
|
|
4082
|
+
return files.concat(fields).some((file) => NATIVE_EXT_RE.test(file));
|
|
4083
|
+
}
|
|
4084
|
+
function shouldAutoExternalize(info) {
|
|
4085
|
+
if (info.resolvedPath.endsWith(".node") || info.resolvedPath.endsWith(".wasm")) return true;
|
|
4086
|
+
if (hasNativeHints(info)) return true;
|
|
4087
|
+
if ((0, import_node_fs.existsSync)((0, import_node_path.join)(info.root, "binding.gyp"))) return true;
|
|
4088
|
+
return false;
|
|
4089
|
+
}
|
|
4090
|
+
function normalizeList(value) {
|
|
4091
|
+
if (Array.isArray(value)) return value.filter((v) => typeof v === "string");
|
|
4092
|
+
if (typeof value === "string") return [value];
|
|
4093
|
+
return null;
|
|
4094
|
+
}
|
|
4095
|
+
function listAllowsTarget(list, target) {
|
|
4096
|
+
if (!list || list.length === 0) return true;
|
|
4097
|
+
const negated = list.filter((v) => v.startsWith("!")).map((v) => v.slice(1));
|
|
4098
|
+
if (negated.includes(target)) return false;
|
|
4099
|
+
const positives = list.filter((v) => !v.startsWith("!"));
|
|
4100
|
+
if (positives.length === 0) return true;
|
|
4101
|
+
return positives.includes(target);
|
|
4102
|
+
}
|
|
4103
|
+
function isPackageCompatible(info) {
|
|
4104
|
+
const osList = normalizeList(info.packageJson.os);
|
|
4105
|
+
const cpuList = normalizeList(info.packageJson.cpu);
|
|
4106
|
+
return listAllowsTarget(osList, SANDBOX_PLATFORM) && listAllowsTarget(cpuList, SANDBOX_ARCH);
|
|
4107
|
+
}
|
|
4108
|
+
var INVALID_DETACHED_COMMAND_HANDLE_MESSAGE = "Detached process handle must contain a non-empty sessionId string and an optional commandId string.";
|
|
4109
|
+
function normalizeDetachedCommandHandle(value) {
|
|
4110
|
+
if (!value || typeof value !== "object") {
|
|
4111
|
+
throw new ConfigurationError(INVALID_DETACHED_COMMAND_HANDLE_MESSAGE);
|
|
1181
4112
|
}
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
4113
|
+
let sessionId;
|
|
4114
|
+
let commandId;
|
|
4115
|
+
try {
|
|
4116
|
+
if (Array.isArray(value)) {
|
|
4117
|
+
throw new Error("invalid detached command handle");
|
|
4118
|
+
}
|
|
4119
|
+
sessionId = Reflect.get(value, "sessionId");
|
|
4120
|
+
commandId = Reflect.get(value, "commandId");
|
|
4121
|
+
} catch {
|
|
4122
|
+
throw new ConfigurationError(INVALID_DETACHED_COMMAND_HANDLE_MESSAGE);
|
|
1185
4123
|
}
|
|
1186
|
-
|
|
1187
|
-
|
|
4124
|
+
if (typeof sessionId !== "string" || sessionId.length === 0 || commandId !== void 0 && typeof commandId !== "string") {
|
|
4125
|
+
throw new ConfigurationError(INVALID_DETACHED_COMMAND_HANDLE_MESSAGE);
|
|
1188
4126
|
}
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
if (result.exitCode !== 0) {
|
|
1197
|
-
throw new DeploymentError(result.result || `Failed to create directory ${path}`);
|
|
4127
|
+
return commandId === void 0 ? { sessionId } : { sessionId, commandId };
|
|
4128
|
+
}
|
|
4129
|
+
function filterDefinedEnvs(envs) {
|
|
4130
|
+
const filtered = {};
|
|
4131
|
+
for (const [key, value] of Object.entries(envs)) {
|
|
4132
|
+
if (value !== void 0) {
|
|
4133
|
+
filtered[key] = value;
|
|
1198
4134
|
}
|
|
1199
4135
|
}
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
4136
|
+
return filtered;
|
|
4137
|
+
}
|
|
4138
|
+
function asError(error) {
|
|
4139
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
4140
|
+
}
|
|
4141
|
+
function errorMessage(error) {
|
|
4142
|
+
return error instanceof Error ? error.message : String(error);
|
|
4143
|
+
}
|
|
4144
|
+
var MINIMUM_BULK_DIAGNOSTIC_REDACTION_LENGTH = 8;
|
|
4145
|
+
var CREDENTIAL_ENV_NAME_PATTERN = /(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)/iu;
|
|
4146
|
+
function isConfiguredDiagnosticSecret(name, value) {
|
|
4147
|
+
return CREDENTIAL_ENV_NAME_PATTERN.test(name) || value.length >= MINIMUM_BULK_DIAGNOSTIC_REDACTION_LENGTH;
|
|
4148
|
+
}
|
|
4149
|
+
function redactServerFailureDiagnosticStream(value, secrets) {
|
|
4150
|
+
const mayStartAtTailBoundary = Buffer.byteLength(value, "utf8") >= DETACHED_PROCESS_LOG_MAX_BYTES - 3;
|
|
4151
|
+
let redacted = boundDetachedProcessLog(value);
|
|
4152
|
+
for (const secret of secrets) {
|
|
4153
|
+
const replacement = secret.length < "[REDACTED]".length ? "*" : "[REDACTED]";
|
|
4154
|
+
redacted = redacted.split(secret).join(replacement);
|
|
1206
4155
|
}
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
4156
|
+
let maximumSecretLength = 0;
|
|
4157
|
+
for (const secret of secrets) {
|
|
4158
|
+
maximumSecretLength = Math.max(maximumSecretLength, secret.length);
|
|
1210
4159
|
}
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
return new Uint8Array(content);
|
|
4160
|
+
if (mayStartAtTailBoundary && maximumSecretLength > 0 && redacted.length > 0) {
|
|
4161
|
+
redacted = redacted.slice(maximumSecretLength);
|
|
1214
4162
|
}
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
4163
|
+
return boundDetachedProcessLog(redacted);
|
|
4164
|
+
}
|
|
4165
|
+
async function readServerFailureDiagnostics(sandbox, command, environment, signal) {
|
|
4166
|
+
if (!sandbox.readSessionLogs) return "";
|
|
4167
|
+
try {
|
|
4168
|
+
const captured = await awaitDiagnosticRead(
|
|
4169
|
+
() => sandbox.readSessionLogs(command),
|
|
4170
|
+
signal
|
|
1221
4171
|
);
|
|
1222
|
-
const
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
return
|
|
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));
|
|
4172
|
+
const secrets = Object.entries(environment).filter(
|
|
4173
|
+
(entry) => Boolean(entry[1]) && isConfiguredDiagnosticSecret(entry[0], entry[1])
|
|
4174
|
+
).map(([, value]) => value);
|
|
4175
|
+
secrets.sort((left, right) => right.length - left.length);
|
|
4176
|
+
const stdout = redactServerFailureDiagnosticStream(captured.stdout, secrets);
|
|
4177
|
+
const stderr = redactServerFailureDiagnosticStream(captured.stderr, secrets);
|
|
4178
|
+
const parts = [];
|
|
4179
|
+
if (stdout.trim()) parts.push(`stdout:
|
|
4180
|
+
${stdout}`);
|
|
4181
|
+
if (stderr.trim()) parts.push(`stderr:
|
|
4182
|
+
${stderr}`);
|
|
4183
|
+
if (parts.length === 0) return "";
|
|
4184
|
+
return boundDetachedProcessLog(`
|
|
4185
|
+
--- server logs ---
|
|
4186
|
+
${parts.join("\n\n")}`);
|
|
4187
|
+
} catch {
|
|
4188
|
+
throwIfAborted(signal);
|
|
4189
|
+
return "";
|
|
1261
4190
|
}
|
|
1262
|
-
}
|
|
4191
|
+
}
|
|
1263
4192
|
function providerApiKey(provider, explicitApiKey) {
|
|
1264
4193
|
if (explicitApiKey) return explicitApiKey;
|
|
1265
4194
|
return requireEnv(provider === "e2b" ? "E2B_API_KEY" : "DAYTONA_API_KEY");
|
|
@@ -1276,11 +4205,20 @@ async function createProviderSandboxHandle(options) {
|
|
|
1276
4205
|
...options.networkAllowList === void 0 ? {} : { networkAllowList: options.networkAllowList },
|
|
1277
4206
|
...options.domainAllowList === void 0 ? {} : { domainAllowList: options.domainAllowList },
|
|
1278
4207
|
envVars: filterDefinedEnvs(options.envs ?? {}),
|
|
4208
|
+
autoStopInterval: options.autoStopInterval,
|
|
1279
4209
|
autoDeleteInterval: options.autoDeleteInterval ?? -1
|
|
1280
4210
|
},
|
|
1281
4211
|
{ timeout: options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC }
|
|
1282
4212
|
);
|
|
1283
|
-
|
|
4213
|
+
try {
|
|
4214
|
+
return await DaytonaSandboxHandle.create(
|
|
4215
|
+
sandbox2,
|
|
4216
|
+
(message) => new DeploymentError(message)
|
|
4217
|
+
);
|
|
4218
|
+
} catch (error) {
|
|
4219
|
+
await sandbox2.delete(options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC).catch(() => void 0);
|
|
4220
|
+
throw error;
|
|
4221
|
+
}
|
|
1284
4222
|
}
|
|
1285
4223
|
const apiKey = providerApiKey("e2b", options.apiKey);
|
|
1286
4224
|
const { Sandbox } = await getE2b();
|
|
@@ -1292,7 +4230,7 @@ async function createProviderSandboxHandle(options) {
|
|
|
1292
4230
|
network: options.allowPublicTraffic === void 0 ? void 0 : { allowPublicTraffic: options.allowPublicTraffic }
|
|
1293
4231
|
};
|
|
1294
4232
|
const sandbox = options.template ? await Sandbox.create(options.template, sandboxOptions) : await Sandbox.create(sandboxOptions);
|
|
1295
|
-
return new E2bSandboxHandle(sandbox);
|
|
4233
|
+
return new E2bSandboxHandle(sandbox, (message) => new DeploymentError(message));
|
|
1296
4234
|
}
|
|
1297
4235
|
async function connectProviderSandboxHandle(options) {
|
|
1298
4236
|
if (options.provider === "daytona") {
|
|
@@ -1307,7 +4245,7 @@ async function connectProviderSandboxHandle(options) {
|
|
|
1307
4245
|
await sandbox2.start(options.createTimeoutSec ?? DAYTONA_CREATE_TIMEOUT_SEC);
|
|
1308
4246
|
}
|
|
1309
4247
|
}
|
|
1310
|
-
return DaytonaSandboxHandle.create(sandbox2);
|
|
4248
|
+
return DaytonaSandboxHandle.create(sandbox2, (message) => new DeploymentError(message));
|
|
1311
4249
|
}
|
|
1312
4250
|
const apiKey = providerApiKey("e2b", options.apiKey);
|
|
1313
4251
|
const { Sandbox } = await getE2b();
|
|
@@ -1316,7 +4254,7 @@ async function connectProviderSandboxHandle(options) {
|
|
|
1316
4254
|
timeoutMs: options.timeoutMs,
|
|
1317
4255
|
requestTimeoutMs: options.requestTimeoutMs
|
|
1318
4256
|
});
|
|
1319
|
-
return new E2bSandboxHandle(sandbox);
|
|
4257
|
+
return new E2bSandboxHandle(sandbox, (message) => new DeploymentError(message));
|
|
1320
4258
|
}
|
|
1321
4259
|
var SandboxClient = class _SandboxClient {
|
|
1322
4260
|
constructor(handle) {
|
|
@@ -1360,6 +4298,61 @@ var SandboxClient = class _SandboxClient {
|
|
|
1360
4298
|
async runCommand(command, options) {
|
|
1361
4299
|
return this.handle.runCommand(command, options);
|
|
1362
4300
|
}
|
|
4301
|
+
async startDetachedCommand(command, options = {}) {
|
|
4302
|
+
if (!this.handle.startDetachedCommand) {
|
|
4303
|
+
throw new ConfigurationError(
|
|
4304
|
+
`Sandbox provider "${this.provider}" does not support startDetachedCommand().`
|
|
4305
|
+
);
|
|
4306
|
+
}
|
|
4307
|
+
if (typeof command !== "string") {
|
|
4308
|
+
throw new ConfigurationError("Detached command must be a string.");
|
|
4309
|
+
}
|
|
4310
|
+
const normalized = normalizeProviderSandboxDetachedCommandOptions(
|
|
4311
|
+
options,
|
|
4312
|
+
(message) => new ConfigurationError(message),
|
|
4313
|
+
{ requireObject: true }
|
|
4314
|
+
);
|
|
4315
|
+
return this.handle.startDetachedCommand(command, normalized.options);
|
|
4316
|
+
}
|
|
4317
|
+
async readSessionLogs(commandOrSessionId, legacyCommandId) {
|
|
4318
|
+
if (!this.handle.readSessionLogs) {
|
|
4319
|
+
throw new ConfigurationError(
|
|
4320
|
+
`Sandbox provider "${this.provider}" does not support readSessionLogs().`
|
|
4321
|
+
);
|
|
4322
|
+
}
|
|
4323
|
+
if (typeof commandOrSessionId === "string" && legacyCommandId === void 0) {
|
|
4324
|
+
throw new ConfigurationError(
|
|
4325
|
+
"Legacy detached session log reads require a command ID."
|
|
4326
|
+
);
|
|
4327
|
+
}
|
|
4328
|
+
const command = typeof commandOrSessionId === "string" ? { sessionId: commandOrSessionId, commandId: legacyCommandId } : normalizeDetachedCommandHandle(commandOrSessionId);
|
|
4329
|
+
return this.handle.readSessionLogs(command);
|
|
4330
|
+
}
|
|
4331
|
+
async stopSession(commandOrSessionId) {
|
|
4332
|
+
if (!this.handle.stopSession) {
|
|
4333
|
+
throw new ConfigurationError(
|
|
4334
|
+
`Sandbox provider "${this.provider}" does not support stopSession().`
|
|
4335
|
+
);
|
|
4336
|
+
}
|
|
4337
|
+
const command = typeof commandOrSessionId === "string" ? { sessionId: commandOrSessionId } : normalizeDetachedCommandHandle(commandOrSessionId);
|
|
4338
|
+
await this.handle.stopSession(command);
|
|
4339
|
+
}
|
|
4340
|
+
/**
|
|
4341
|
+
* Irreversibly removes private lifecycle state and captured diagnostics for
|
|
4342
|
+
* one managed detached command. Call `stopSession()` first, then perform any
|
|
4343
|
+
* final `readSessionLogs()` before disposal. Disposal is idempotent after a
|
|
4344
|
+
* confirmed stop but is not itself evidence that the process stopped.
|
|
4345
|
+
*/
|
|
4346
|
+
async disposeSessionArtifacts(command) {
|
|
4347
|
+
if (!this.handle.disposeSessionArtifacts) {
|
|
4348
|
+
throw new ConfigurationError(
|
|
4349
|
+
`Sandbox provider "${this.provider}" does not support disposeSessionArtifacts().`
|
|
4350
|
+
);
|
|
4351
|
+
}
|
|
4352
|
+
await this.handle.disposeSessionArtifacts(
|
|
4353
|
+
normalizeDetachedCommandHandle(command)
|
|
4354
|
+
);
|
|
4355
|
+
}
|
|
1363
4356
|
async setTimeout(timeoutMs) {
|
|
1364
4357
|
if (!this.handle.setTimeout) {
|
|
1365
4358
|
throw new ConfigurationError(`Sandbox provider "${this.provider}" does not support setTimeout().`);
|
|
@@ -1387,17 +4380,26 @@ function normalizeStackFramePath(rawPath, cwd = process.cwd()) {
|
|
|
1387
4380
|
}
|
|
1388
4381
|
function getCallerFile() {
|
|
1389
4382
|
const stack = new Error().stack?.split("\n") ?? [];
|
|
1390
|
-
|
|
4383
|
+
let moduleFile;
|
|
4384
|
+
let bundledFallback;
|
|
4385
|
+
for (const line of stack.slice(1)) {
|
|
1391
4386
|
const match = line.match(/\((.+?):\d+:\d+\)/) || line.match(/at (.+?):\d+:\d+/);
|
|
1392
4387
|
if (!match) continue;
|
|
1393
4388
|
const file = normalizeStackFramePath(match[1]);
|
|
1394
4389
|
if (!file) continue;
|
|
4390
|
+
if (!moduleFile) {
|
|
4391
|
+
moduleFile = file;
|
|
4392
|
+
continue;
|
|
4393
|
+
}
|
|
1395
4394
|
if (file.includes("node:")) continue;
|
|
1396
4395
|
if (file.includes("node_modules/agent-neckbeard")) continue;
|
|
1397
|
-
if (file
|
|
1398
|
-
|
|
4396
|
+
if (file === moduleFile) {
|
|
4397
|
+
bundledFallback ??= file;
|
|
4398
|
+
continue;
|
|
4399
|
+
}
|
|
1399
4400
|
return file;
|
|
1400
4401
|
}
|
|
4402
|
+
if (bundledFallback) return bundledFallback;
|
|
1401
4403
|
throw new Error("Could not determine source file");
|
|
1402
4404
|
}
|
|
1403
4405
|
function isFrameworkBuildOutputPath(file) {
|
|
@@ -1561,10 +4563,13 @@ var Agent = class {
|
|
|
1561
4563
|
provider;
|
|
1562
4564
|
template;
|
|
1563
4565
|
inputSchema;
|
|
1564
|
-
/** Only populated for
|
|
4566
|
+
/** Only populated for structured-task agents; undefined for session agents. */
|
|
1565
4567
|
outputSchema;
|
|
1566
|
-
/** Only populated for
|
|
4568
|
+
/** Only populated for attached-session agents; undefined for run-output agents. */
|
|
1567
4569
|
frameSchema;
|
|
4570
|
+
/** User-facing execution shape. */
|
|
4571
|
+
kind;
|
|
4572
|
+
/** @deprecated Use `kind`; retained for compatibility with `run | stream` checks. */
|
|
1568
4573
|
mode;
|
|
1569
4574
|
maxDuration;
|
|
1570
4575
|
dependencies;
|
|
@@ -1576,7 +4581,7 @@ var Agent = class {
|
|
|
1576
4581
|
build;
|
|
1577
4582
|
/** @internal Used by the in-sandbox server for run-output agents. */
|
|
1578
4583
|
_run;
|
|
1579
|
-
/** @internal Used by the in-sandbox server for
|
|
4584
|
+
/** @internal Used by the in-sandbox server for attached-session agents. */
|
|
1580
4585
|
_server;
|
|
1581
4586
|
/** @internal Runtime state populated by deploy(). */
|
|
1582
4587
|
_serverRuntime;
|
|
@@ -1596,11 +4601,14 @@ var Agent = class {
|
|
|
1596
4601
|
this.claudeDir = config.claudeDir;
|
|
1597
4602
|
this.envs = config.envs ?? {};
|
|
1598
4603
|
this.build = config.build ?? {};
|
|
1599
|
-
if (
|
|
4604
|
+
if (isSessionAgentConfig(config)) {
|
|
4605
|
+
const session = getSessionHandler(config);
|
|
4606
|
+
this.kind = "session";
|
|
1600
4607
|
this.mode = "stream";
|
|
1601
|
-
this._server =
|
|
1602
|
-
this.frameSchema =
|
|
4608
|
+
this._server = session;
|
|
4609
|
+
this.frameSchema = session.frameSchema;
|
|
1603
4610
|
} else {
|
|
4611
|
+
this.kind = "task";
|
|
1604
4612
|
this.mode = "run";
|
|
1605
4613
|
this._run = config.run;
|
|
1606
4614
|
this.outputSchema = config.outputSchema;
|
|
@@ -1685,47 +4693,68 @@ var Agent = class {
|
|
|
1685
4693
|
envs: this.sandboxEnv
|
|
1686
4694
|
});
|
|
1687
4695
|
}
|
|
1688
|
-
async resolveRuntimeConnection(sandboxId) {
|
|
4696
|
+
async resolveRuntimeConnection(sandboxId, options = {}) {
|
|
4697
|
+
const { signal } = options;
|
|
4698
|
+
throwIfAborted(signal);
|
|
1689
4699
|
const targetId = sandboxId ?? this._serverRuntime?.connection.sandboxId ?? this._sandboxId;
|
|
1690
4700
|
if (!targetId) {
|
|
1691
4701
|
throw new ConfigurationError("Agent not deployed. Call agent.deploy() first or pass sandboxId.");
|
|
1692
4702
|
}
|
|
1693
|
-
if (!sandboxId && this._serverRuntime?.connection.sandboxId === targetId) {
|
|
4703
|
+
if ((!sandboxId || options.reuseMatchingCachedConnection) && this._serverRuntime?.connection.sandboxId === targetId) {
|
|
1694
4704
|
return this._serverRuntime.connection;
|
|
1695
4705
|
}
|
|
1696
|
-
const sandbox = await this.connectSandboxHandle(targetId);
|
|
1697
|
-
|
|
4706
|
+
const sandbox = await awaitWithAbort(() => this.connectSandboxHandle(targetId), signal);
|
|
4707
|
+
if (sandbox.id !== targetId) {
|
|
4708
|
+
throw new DeploymentError("Sandbox provider returned an unexpected runtime identity.");
|
|
4709
|
+
}
|
|
4710
|
+
const serverConfig = await awaitWithAbort(
|
|
4711
|
+
() => this.readRuntimeServerConfig(sandbox),
|
|
4712
|
+
signal
|
|
4713
|
+
);
|
|
1698
4714
|
const port = serverConfig?.port ?? this._server?.port ?? DEFAULT_SERVER_PORT;
|
|
1699
|
-
const connection = await
|
|
4715
|
+
const connection = await awaitWithAbort(
|
|
4716
|
+
() => this.createRuntimeConnection(sandbox, port),
|
|
4717
|
+
signal
|
|
4718
|
+
);
|
|
1700
4719
|
const healthUrl = this.healthUrlFor(connection);
|
|
1701
4720
|
try {
|
|
1702
|
-
await waitForServerHealthy(
|
|
1703
|
-
|
|
4721
|
+
await waitForServerHealthy(
|
|
4722
|
+
healthUrl,
|
|
4723
|
+
connection,
|
|
4724
|
+
SERVER_RECONNECT_HEALTH_TIMEOUT_MS,
|
|
4725
|
+
signal
|
|
4726
|
+
);
|
|
4727
|
+
throwIfAborted(signal);
|
|
4728
|
+
const cachedRuntime = this._serverRuntime;
|
|
4729
|
+
this._serverRuntime = cachedRuntime?.connection.sandboxId === targetId ? { ...cachedRuntime, connection } : { connection };
|
|
1704
4730
|
this._sandboxId = targetId;
|
|
1705
4731
|
return connection;
|
|
1706
4732
|
} catch {
|
|
1707
|
-
|
|
4733
|
+
throwIfAborted(signal);
|
|
4734
|
+
const detachedCommand = await awaitWithAbort(
|
|
4735
|
+
() => this.startRuntimeServer(sandbox),
|
|
4736
|
+
signal
|
|
4737
|
+
);
|
|
1708
4738
|
try {
|
|
1709
|
-
await waitForServerHealthy(
|
|
4739
|
+
await waitForServerHealthy(
|
|
4740
|
+
healthUrl,
|
|
4741
|
+
connection,
|
|
4742
|
+
SERVER_HEALTH_TIMEOUT_MS,
|
|
4743
|
+
signal
|
|
4744
|
+
);
|
|
1710
4745
|
} catch (error) {
|
|
4746
|
+
throwIfAborted(signal);
|
|
1711
4747
|
const baseMessage = error instanceof Error ? error.message : String(error);
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
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
|
-
}
|
|
4748
|
+
const logs = await readServerFailureDiagnostics(
|
|
4749
|
+
sandbox,
|
|
4750
|
+
detachedCommand,
|
|
4751
|
+
this.envs,
|
|
4752
|
+
signal
|
|
4753
|
+
);
|
|
1726
4754
|
throw new DeploymentError(`${baseMessage}${logs}`);
|
|
1727
4755
|
}
|
|
1728
|
-
|
|
4756
|
+
throwIfAborted(signal);
|
|
4757
|
+
this._serverRuntime = { detachedCommand, connection };
|
|
1729
4758
|
this._sandboxId = targetId;
|
|
1730
4759
|
return connection;
|
|
1731
4760
|
}
|
|
@@ -1750,8 +4779,8 @@ ${parts.join("\n\n")}`;
|
|
|
1750
4779
|
if (!targetId) return;
|
|
1751
4780
|
try {
|
|
1752
4781
|
const sandbox = await this.connectSandboxHandle(targetId);
|
|
1753
|
-
if (this._serverRuntime && this._serverRuntime.connection.sandboxId === targetId && this._serverRuntime.
|
|
1754
|
-
await sandbox.stopSession(this._serverRuntime.
|
|
4782
|
+
if (this._serverRuntime && this._serverRuntime.connection.sandboxId === targetId && this._serverRuntime.detachedCommand && sandbox.stopSession) {
|
|
4783
|
+
await sandbox.stopSession(this._serverRuntime.detachedCommand).catch(() => void 0);
|
|
1755
4784
|
}
|
|
1756
4785
|
await sandbox.destroy();
|
|
1757
4786
|
} catch {
|
|
@@ -1841,9 +4870,15 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
1841
4870
|
this.outputSchema = config.outputSchema;
|
|
1842
4871
|
this.maxDuration = config.maxDuration ?? 300;
|
|
1843
4872
|
this._run = config.run;
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
this.
|
|
4873
|
+
const session = config.session ?? config.server;
|
|
4874
|
+
if (session) {
|
|
4875
|
+
this.kind = 'session';
|
|
4876
|
+
this.mode = 'stream';
|
|
4877
|
+
this._server = session;
|
|
4878
|
+
this.frameSchema = session.frameSchema;
|
|
4879
|
+
} else {
|
|
4880
|
+
this.kind = 'task';
|
|
4881
|
+
this.mode = 'run';
|
|
1847
4882
|
}
|
|
1848
4883
|
}
|
|
1849
4884
|
}
|
|
@@ -1875,142 +4910,145 @@ var require = __neckbeard_createRequire(import.meta.url);
|
|
|
1875
4910
|
}]
|
|
1876
4911
|
});
|
|
1877
4912
|
const sandbox = await this.createSandboxHandle();
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
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
|
|
4913
|
+
let deploymentCompleted = false;
|
|
4914
|
+
let detachedCommand;
|
|
4915
|
+
try {
|
|
4916
|
+
const { paths } = sandbox;
|
|
4917
|
+
await sandbox.runCommand(`mkdir -p ${shellQuote(paths.agentDir)}`, {
|
|
4918
|
+
timeoutMs: QUICK_COMMAND_TIMEOUT_MS2
|
|
1887
4919
|
});
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
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
|
|
4920
|
+
const { apt, commands } = this.dependencies;
|
|
4921
|
+
if (apt && apt.length > 0) {
|
|
4922
|
+
const aptCmd = `sudo apt-get update && sudo apt-get install -y ${apt.join(" ")}`;
|
|
4923
|
+
const aptResult = await sandbox.runCommand(aptCmd, {
|
|
4924
|
+
timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS2
|
|
1901
4925
|
});
|
|
1902
|
-
if (
|
|
4926
|
+
if (aptResult.exitCode !== 0) {
|
|
1903
4927
|
const details = [
|
|
1904
|
-
`Failed to
|
|
1905
|
-
|
|
1906
|
-
|
|
4928
|
+
`Failed to install apt packages: ${apt.join(", ")}`,
|
|
4929
|
+
aptResult.stderr ? `stderr: ${aptResult.stderr}` : "",
|
|
4930
|
+
aptResult.stdout ? `stdout: ${aptResult.stdout}` : ""
|
|
1907
4931
|
].filter(Boolean).join("\n");
|
|
1908
4932
|
throw new DeploymentError(details);
|
|
1909
4933
|
}
|
|
1910
4934
|
}
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
|
|
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
|
|
4935
|
+
if (commands && commands.length > 0) {
|
|
4936
|
+
for (const cmd of commands) {
|
|
4937
|
+
const cmdResult = await sandbox.runCommand(cmd, {
|
|
4938
|
+
timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS2
|
|
1919
4939
|
});
|
|
4940
|
+
if (cmdResult.exitCode !== 0) {
|
|
4941
|
+
const details = [
|
|
4942
|
+
`Failed to run command: ${cmd}`,
|
|
4943
|
+
cmdResult.stderr ? `stderr: ${cmdResult.stderr}` : "",
|
|
4944
|
+
cmdResult.stdout ? `stdout: ${cmdResult.stdout}` : ""
|
|
4945
|
+
].filter(Boolean).join("\n");
|
|
4946
|
+
throw new DeploymentError(details);
|
|
4947
|
+
}
|
|
1920
4948
|
}
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
`
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
4949
|
+
}
|
|
4950
|
+
if (this.files.length > 0) {
|
|
4951
|
+
for (const file of this.files) {
|
|
4952
|
+
const destPath = file.path.startsWith("/") ? file.path : `${paths.homeDir}/${file.path}`;
|
|
4953
|
+
const parentDir = destPath.substring(0, destPath.lastIndexOf("/"));
|
|
4954
|
+
if (parentDir) {
|
|
4955
|
+
await sandbox.runCommand(`mkdir -p ${shellQuote(parentDir)}`, {
|
|
4956
|
+
timeoutMs: QUICK_COMMAND_TIMEOUT_MS2
|
|
4957
|
+
});
|
|
4958
|
+
}
|
|
4959
|
+
const curlCmd = `curl -fsSL -o ${shellQuote(destPath)} ${shellQuote(file.url)}`;
|
|
4960
|
+
const downloadResult = await sandbox.runCommand(curlCmd, {
|
|
4961
|
+
timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS2
|
|
4962
|
+
});
|
|
4963
|
+
if (downloadResult.exitCode !== 0) {
|
|
4964
|
+
const details = [
|
|
4965
|
+
`Failed to download file from ${file.url} to ${destPath}`,
|
|
4966
|
+
downloadResult.stderr ? `stderr: ${downloadResult.stderr}` : "",
|
|
4967
|
+
downloadResult.stdout ? `stdout: ${downloadResult.stdout}` : ""
|
|
4968
|
+
].filter(Boolean).join("\n");
|
|
4969
|
+
throw new DeploymentError(details);
|
|
4970
|
+
}
|
|
1932
4971
|
}
|
|
1933
4972
|
}
|
|
1934
|
-
|
|
1935
|
-
|
|
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
|
|
4973
|
+
for (const directory of localDirectoryUploads.directories) {
|
|
4974
|
+
await sandbox.makeDir(import_node_path.posix.join(paths.agentDir, directory));
|
|
1958
4975
|
}
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
4976
|
+
for (const file of localDirectoryUploads.files) {
|
|
4977
|
+
await sandbox.writeFile(
|
|
4978
|
+
import_node_path.posix.join(paths.agentDir, file.targetPath),
|
|
4979
|
+
file.content
|
|
4980
|
+
);
|
|
4981
|
+
}
|
|
4982
|
+
await sandbox.writeFile(paths.agentModule, result.outputFiles[0].text);
|
|
4983
|
+
await sandbox.writeFile(paths.serverModule, RUNTIME_SERVER_SOURCE);
|
|
4984
|
+
const serverConfig = {
|
|
4985
|
+
protocolVersion: RUNTIME_PROTOCOL_VERSION,
|
|
4986
|
+
port: this._server?.port ?? DEFAULT_SERVER_PORT,
|
|
4987
|
+
maxDurationMs: this.maxDuration * 1e3,
|
|
4988
|
+
sandboxContext: {
|
|
4989
|
+
provider: paths.provider,
|
|
4990
|
+
homeDir: paths.homeDir,
|
|
4991
|
+
workDir: paths.workDir,
|
|
4992
|
+
agentDir: paths.agentDir,
|
|
4993
|
+
ioDir: paths.ioDir,
|
|
4994
|
+
inputJson: paths.inputJson,
|
|
4995
|
+
outputJson: paths.outputJson
|
|
4996
|
+
}
|
|
4997
|
+
};
|
|
4998
|
+
await sandbox.writeFile(paths.serverConfig, JSON.stringify(serverConfig));
|
|
4999
|
+
if (collectedExternals.size > 0) {
|
|
5000
|
+
const installable = Array.from(collectedExternals.values()).filter(isPackageCompatible);
|
|
5001
|
+
const dependencies = Object.fromEntries(installable.map((info) => [info.name, info.version]));
|
|
5002
|
+
if (Object.keys(dependencies).length > 0) {
|
|
5003
|
+
const pkgJson = JSON.stringify({
|
|
5004
|
+
name: "agent-sandbox",
|
|
5005
|
+
type: "module",
|
|
5006
|
+
dependencies
|
|
5007
|
+
});
|
|
5008
|
+
await sandbox.writeFile(paths.packageJson, pkgJson);
|
|
5009
|
+
const installResult = await sandbox.runCommand("npm install --legacy-peer-deps", {
|
|
5010
|
+
cwd: paths.agentDir,
|
|
5011
|
+
timeoutMs: SANDBOX_COMMAND_TIMEOUT_MS2
|
|
5012
|
+
});
|
|
5013
|
+
if (installResult.exitCode !== 0) {
|
|
5014
|
+
const details = [
|
|
5015
|
+
`Failed to install npm packages: ${Object.keys(dependencies).join(", ")}`,
|
|
5016
|
+
installResult.stderr ? `stderr: ${installResult.stderr}` : "",
|
|
5017
|
+
installResult.stdout ? `stdout: ${installResult.stdout}` : ""
|
|
5018
|
+
].filter(Boolean).join("\n");
|
|
5019
|
+
throw new DeploymentError(details);
|
|
5020
|
+
}
|
|
1982
5021
|
}
|
|
1983
5022
|
}
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
5023
|
+
const port = serverConfig.port;
|
|
5024
|
+
detachedCommand = await this.startRuntimeServer(sandbox);
|
|
5025
|
+
const connection = await this.createRuntimeConnection(sandbox, port);
|
|
5026
|
+
const healthUrl = this.healthUrlFor(connection);
|
|
5027
|
+
try {
|
|
5028
|
+
await waitForServerHealthy(healthUrl, connection);
|
|
5029
|
+
} catch (err) {
|
|
5030
|
+
const baseMessage = err instanceof Error ? err.message : String(err);
|
|
5031
|
+
const logs = await readServerFailureDiagnostics(
|
|
5032
|
+
sandbox,
|
|
5033
|
+
detachedCommand,
|
|
5034
|
+
this.envs
|
|
5035
|
+
);
|
|
5036
|
+
throw new DeploymentError(`${baseMessage}${logs}`);
|
|
5037
|
+
}
|
|
5038
|
+
if (!options?.fresh) {
|
|
5039
|
+
this._sandboxId = sandbox.id;
|
|
5040
|
+
this._serverRuntime = { detachedCommand, connection };
|
|
5041
|
+
}
|
|
5042
|
+
deploymentCompleted = true;
|
|
5043
|
+
return sandbox.id;
|
|
5044
|
+
} finally {
|
|
5045
|
+
if (!deploymentCompleted) {
|
|
5046
|
+
if (detachedCommand && sandbox.stopSession) {
|
|
5047
|
+
await sandbox.stopSession(detachedCommand).catch(() => void 0);
|
|
2005
5048
|
}
|
|
5049
|
+
await sandbox.destroy().catch(() => void 0);
|
|
2006
5050
|
}
|
|
2007
|
-
throw new DeploymentError(`${baseMessage}${logs}`);
|
|
2008
5051
|
}
|
|
2009
|
-
if (!options?.fresh) {
|
|
2010
|
-
this._sandboxId = sandbox.id;
|
|
2011
|
-
this._serverRuntime = { sessionId, commandId, connection };
|
|
2012
|
-
}
|
|
2013
|
-
return sandbox.id;
|
|
2014
5052
|
}
|
|
2015
5053
|
/**
|
|
2016
5054
|
* Executes the agent with the given input.
|
|
@@ -2041,7 +5079,7 @@ ${parts.join("\n\n")}`;
|
|
|
2041
5079
|
ok: false,
|
|
2042
5080
|
executionId,
|
|
2043
5081
|
error: new ExecutionError(
|
|
2044
|
-
"run() is only available on agents configured with a run handler. Use agent.
|
|
5082
|
+
"run() is only available on agents configured with a run handler. Use agent.createSession() for streaming session agents."
|
|
2045
5083
|
)
|
|
2046
5084
|
};
|
|
2047
5085
|
}
|
|
@@ -2092,16 +5130,73 @@ ${parts.join("\n\n")}`;
|
|
|
2092
5130
|
}
|
|
2093
5131
|
}
|
|
2094
5132
|
/**
|
|
2095
|
-
*
|
|
2096
|
-
*
|
|
5133
|
+
* Creates a caller-owned session against the persistent sandbox runtime.
|
|
5134
|
+
* The returned handle supports sequential prompts, active-turn cancellation,
|
|
5135
|
+
* and explicit close without destroying the reusable sandbox.
|
|
2097
5136
|
*/
|
|
2098
|
-
async
|
|
5137
|
+
async createSession(options = {}) {
|
|
2099
5138
|
if (this.mode !== "stream") {
|
|
2100
5139
|
throw new ConfigurationError(
|
|
2101
|
-
"
|
|
5140
|
+
"createSession() is only available on agents configured with session.handler (or deprecated server.handler). Use agent.run() for run-output agents."
|
|
5141
|
+
);
|
|
5142
|
+
}
|
|
5143
|
+
if (!options || typeof options !== "object") {
|
|
5144
|
+
throw new ConfigurationError("Agent.createSession() options must be an object.");
|
|
5145
|
+
}
|
|
5146
|
+
let optionsAreArray;
|
|
5147
|
+
try {
|
|
5148
|
+
optionsAreArray = Array.isArray(options);
|
|
5149
|
+
} catch {
|
|
5150
|
+
throw new ConfigurationError(
|
|
5151
|
+
"Agent.createSession() options must have readable values."
|
|
5152
|
+
);
|
|
5153
|
+
}
|
|
5154
|
+
if (optionsAreArray) {
|
|
5155
|
+
throw new ConfigurationError("Agent.createSession() options must be an object.");
|
|
5156
|
+
}
|
|
5157
|
+
let durability;
|
|
5158
|
+
let requestedSandboxId;
|
|
5159
|
+
let signal;
|
|
5160
|
+
try {
|
|
5161
|
+
durability = options.durability;
|
|
5162
|
+
requestedSandboxId = options.sandboxId;
|
|
5163
|
+
signal = options.signal;
|
|
5164
|
+
} catch {
|
|
5165
|
+
throw new ConfigurationError(
|
|
5166
|
+
"Agent.createSession() options must have readable values."
|
|
5167
|
+
);
|
|
5168
|
+
}
|
|
5169
|
+
if (durability !== void 0 && durability !== "attached") {
|
|
5170
|
+
throw new ConfigurationError(
|
|
5171
|
+
"Agent.createSession() creates caller-owned attached sessions. Use agent-neckbeard/supervisor durable-session APIs for gateway-owned sessions."
|
|
5172
|
+
);
|
|
5173
|
+
}
|
|
5174
|
+
if (requestedSandboxId !== void 0 && (typeof requestedSandboxId !== "string" || requestedSandboxId.trim() === "")) {
|
|
5175
|
+
throw new ConfigurationError(
|
|
5176
|
+
"Agent.createSession() sandboxId must be a non-empty string when provided."
|
|
2102
5177
|
);
|
|
2103
5178
|
}
|
|
2104
|
-
|
|
5179
|
+
if (signal !== void 0 && !isAbortSignal(signal)) {
|
|
5180
|
+
throw new ConfigurationError(
|
|
5181
|
+
"Agent.createSession() signal must be an AbortSignal when provided."
|
|
5182
|
+
);
|
|
5183
|
+
}
|
|
5184
|
+
const sandboxId = requestedSandboxId ?? this._serverRuntime?.connection.sandboxId ?? this._sandboxId;
|
|
5185
|
+
if (!sandboxId) {
|
|
5186
|
+
throw new ConfigurationError("Agent not deployed. Call agent.deploy() first or pass sandboxId.");
|
|
5187
|
+
}
|
|
5188
|
+
return createAttachedAgentSession({
|
|
5189
|
+
sandboxId,
|
|
5190
|
+
runPrompt: (input, signal2) => this.streamSessionPrompt(input, sandboxId, signal2),
|
|
5191
|
+
...signal === void 0 ? {} : { externalSignal: signal },
|
|
5192
|
+
configurationError: (message) => new ConfigurationError(message)
|
|
5193
|
+
});
|
|
5194
|
+
}
|
|
5195
|
+
async *streamSessionPrompt(input, sandboxId, signal) {
|
|
5196
|
+
const connection = await this.resolveRuntimeConnection(sandboxId, {
|
|
5197
|
+
signal,
|
|
5198
|
+
reuseMatchingCachedConnection: true
|
|
5199
|
+
});
|
|
2105
5200
|
const { invokeServer: invokeServer2 } = await Promise.resolve().then(() => (init_invoke_client(), invoke_client_exports));
|
|
2106
5201
|
let validated;
|
|
2107
5202
|
try {
|
|
@@ -2115,7 +5210,7 @@ ${parts.join("\n\n")}`;
|
|
|
2115
5210
|
provider: connection.provider,
|
|
2116
5211
|
trafficToken: getTrafficToken(connection),
|
|
2117
5212
|
frameSchema: this.frameSchema,
|
|
2118
|
-
signal
|
|
5213
|
+
signal
|
|
2119
5214
|
})) {
|
|
2120
5215
|
if (frame.kind === "frame") {
|
|
2121
5216
|
yield frame.data;
|
|
@@ -2130,6 +5225,22 @@ ${parts.join("\n\n")}`;
|
|
|
2130
5225
|
throw error instanceof Error ? error : new Error(String(error));
|
|
2131
5226
|
}
|
|
2132
5227
|
}
|
|
5228
|
+
/**
|
|
5229
|
+
* @deprecated Use `createSession()` and call `session.prompt(input)` instead.
|
|
5230
|
+
* This compatibility wrapper creates one attached session, streams one turn,
|
|
5231
|
+
* and closes the local handle afterward.
|
|
5232
|
+
*/
|
|
5233
|
+
async *invoke(input, options) {
|
|
5234
|
+
const session = await this.createSession({
|
|
5235
|
+
...options?.sandboxId === void 0 ? {} : { sandboxId: options.sandboxId },
|
|
5236
|
+
...options?.signal === void 0 ? {} : { signal: options.signal }
|
|
5237
|
+
});
|
|
5238
|
+
try {
|
|
5239
|
+
yield* session.prompt(input);
|
|
5240
|
+
} finally {
|
|
5241
|
+
await session.close();
|
|
5242
|
+
}
|
|
5243
|
+
}
|
|
2133
5244
|
};
|
|
2134
5245
|
// Annotate the CommonJS export names for ESM import in node:
|
|
2135
5246
|
0 && (module.exports = {
|