agent-neckbeard 1.1.28 → 1.1.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +28 -30
  3. package/dist/archil.d.ts +73 -0
  4. package/dist/archil.js +673 -0
  5. package/dist/build.cjs +129 -5160
  6. package/dist/build.d.cts +9 -5
  7. package/dist/build.d.ts +9 -5
  8. package/dist/build.js +4 -6
  9. package/dist/{chunk-JF5YPOBY.js → chunk-FHNQ5DNA.js} +3235 -511
  10. package/dist/{chunk-M7XNBKG4.js → chunk-I5GIWADK.js} +29 -7
  11. package/dist/chunk-I5NULOJP.js +129 -0
  12. package/dist/chunk-PKUGXECR.js +13 -0
  13. package/dist/chunk-QA4L7ZI2.js +72 -0
  14. package/dist/{chunk-KG6SJM74.js → chunk-VHBDBB3N.js} +8 -5
  15. package/dist/cli.cjs +124 -5154
  16. package/dist/cli.js +7 -8
  17. package/dist/define-gdmBe9RA.d.ts +227 -0
  18. package/dist/durable.d.ts +53 -0
  19. package/dist/durable.js +92 -0
  20. package/dist/index.cjs +720 -833
  21. package/dist/index.d.cts +139 -78
  22. package/dist/index.d.ts +139 -78
  23. package/dist/index.js +12 -11
  24. package/dist/inside.d.ts +15 -0
  25. package/dist/inside.js +530 -0
  26. package/dist/{invoke-client-P2CPBYTF.js → invoke-client-QB2NTZ3L.js} +1 -2
  27. package/dist/pi-watch-legacy.d.ts +4503 -0
  28. package/dist/serve.cjs +9 -309
  29. package/dist/serve.d.cts +14 -1
  30. package/dist/serve.d.ts +14 -1
  31. package/dist/serve.js +3 -5
  32. package/docs/AGENT.md +95 -59
  33. package/docs/DAYTONA.md +2 -0
  34. package/docs/DOCKER.md +0 -1
  35. package/docs/E2B.md +1 -1
  36. package/docs/LEGACY.md +1 -8
  37. package/docs/MODAL.md +1 -1
  38. package/package.json +57 -23
  39. package/types/pi-watch.d.cts +68 -0
  40. package/dist/chunk-33IXN6MM.js +0 -21
  41. package/dist/chunk-6P5I7ZCH.js +0 -2552
  42. package/dist/chunk-M3FISP7J.js +0 -377
  43. package/dist/sandbox-capabilities-CFjnZ_kB.d.cts +0 -77
  44. package/dist/sandbox-capabilities-CFjnZ_kB.d.ts +0 -77
  45. package/dist/serve-Dan1HQKN.d.cts +0 -89
  46. package/dist/serve-Dan1HQKN.d.ts +0 -89
  47. package/dist/supervisor.cjs +0 -5731
  48. package/dist/supervisor.d.cts +0 -482
  49. package/dist/supervisor.d.ts +0 -482
  50. package/dist/supervisor.js +0 -3187
  51. package/docs/SUPERVISOR.md +0 -258
@@ -1,3187 +0,0 @@
1
- import {
2
- createDaytonaDetachedProcessController,
3
- createDaytonaTerminalDetachedProcessController,
4
- discoverDaytonaSandboxDirectories,
5
- executeDaytonaCommand,
6
- isDetachedProcessLaunchCancelledError,
7
- isDetachedProcessReleasedGenerationUnavailableError,
8
- makeDaytonaDirectory,
9
- serializeSupervisorEnvironmentHandoff,
10
- shellQuote,
11
- uploadDaytonaFile
12
- } from "./chunk-6P5I7ZCH.js";
13
- import {
14
- serializeError
15
- } from "./chunk-33IXN6MM.js";
16
-
17
- // src/supervisor/artifact.ts
18
- import { Buffer as Buffer2 } from "buffer";
19
- import { createHash as createHash2, createHmac } from "crypto";
20
-
21
- // src/supervisor/runtime-source.generated.ts
22
- var SUPERVISOR_RUNTIME_SOURCE = '// src/supervisor/runtime-entry.ts\nimport {\n closeSync,\n constants as fsConstants4,\n ftruncateSync,\n fstatSync as fstatSync2,\n readSync as readSync2\n} from "node:fs";\nimport { access, readFile } from "node:fs/promises";\nimport { resolve } from "node:path";\nimport { pathToFileURL } from "node:url";\n\n// src/sandbox-capabilities.ts\nvar SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV = "NECKBEARD_SUPERVISOR_ENVIRONMENT_V1";\nvar SUPERVISOR_ENVIRONMENT_FD_ENV = "NECKBEARD_SUPERVISOR_ENVIRONMENT_FD";\nvar SUPERVISOR_ENVIRONMENT_FD = 3;\nvar SUPERVISOR_ENVIRONMENT_MAX_BYTES = 64 * 1024;\nvar SUPERVISOR_ENVIRONMENT_MAX_ENTRIES = 256;\nvar SUPERVISOR_ENVIRONMENT_MAX_NAME_BYTES = 256;\nvar SUPERVISOR_ENVIRONMENT_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/u;\nfunction supervisorEnvironmentByteLength(value) {\n return new TextEncoder().encode(value).byteLength;\n}\nfunction isRecord(value) {\n if (typeof value !== "object" || value === null) return false;\n try {\n return !Array.isArray(value);\n } catch {\n return false;\n }\n}\nfunction normalizeSupervisorEnvironment(value) {\n if (!isRecord(value)) return { ok: false, reason: "invalid_environment" };\n let entries;\n try {\n entries = Object.entries(value).sort(\n ([left], [right]) => left < right ? -1 : left > right ? 1 : 0\n );\n } catch {\n return { ok: false, reason: "invalid_environment" };\n }\n if (entries.length > SUPERVISOR_ENVIRONMENT_MAX_ENTRIES) {\n return { ok: false, reason: "entry_limit" };\n }\n const environment = /* @__PURE__ */ Object.create(null);\n let environmentBytes = 0;\n let exceedsByteLimit = false;\n for (const [name, item] of entries) {\n if (name.length > SUPERVISOR_ENVIRONMENT_MAX_NAME_BYTES || !SUPERVISOR_ENVIRONMENT_NAME_PATTERN.test(name) || name === SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV || name === SUPERVISOR_ENVIRONMENT_FD_ENV) {\n return { ok: false, reason: "invalid_name" };\n }\n if (typeof item !== "string" || item.includes("\\0")) {\n return { ok: false, reason: "invalid_value" };\n }\n if (!exceedsByteLimit) {\n if (item.length > SUPERVISOR_ENVIRONMENT_MAX_BYTES || environmentBytes + name.length + item.length > SUPERVISOR_ENVIRONMENT_MAX_BYTES) {\n exceedsByteLimit = true;\n } else {\n environmentBytes += name.length + supervisorEnvironmentByteLength(item);\n if (environmentBytes > SUPERVISOR_ENVIRONMENT_MAX_BYTES) {\n exceedsByteLimit = true;\n }\n }\n }\n environment[name] = item;\n }\n if (exceedsByteLimit) return { ok: false, reason: "byte_limit" };\n return {\n ok: true,\n environment,\n environmentKeys: entries.map(([name]) => name)\n };\n}\nfunction deserializeSupervisorEnvironmentHandoff(source) {\n if (typeof source !== "string" || source.length === 0 || source.length > SUPERVISOR_ENVIRONMENT_MAX_BYTES || supervisorEnvironmentByteLength(source) > SUPERVISOR_ENVIRONMENT_MAX_BYTES) {\n return { ok: false, reason: "invalid_payload" };\n }\n let value;\n try {\n value = JSON.parse(source);\n } catch {\n return { ok: false, reason: "invalid_payload" };\n }\n if (!isRecord(value) || value.version !== 1 || !isRecord(value.environment) || Object.keys(value).length !== 2 || !Object.hasOwn(value, "version") || !Object.hasOwn(value, "environment")) {\n return { ok: false, reason: "invalid_payload" };\n }\n const normalized = normalizeSupervisorEnvironment(value.environment);\n return normalized.ok ? { ...normalized, payload: source } : normalized;\n}\n\n// src/supervisor/protocol.ts\nimport { createHash } from "node:crypto";\n\n// src/serialized-error.ts\nfunction isSerializedError(value) {\n if (typeof value !== "object" || value === null || Array.isArray(value)) return false;\n const candidate = value;\n return typeof candidate.message === "string" && (candidate.name === void 0 || typeof candidate.name === "string") && (candidate.stack === void 0 || typeof candidate.stack === "string");\n}\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/supervisor/runtime-limits.ts\nvar SUPERVISOR_CREDENTIAL_BYTE_LENGTH = 32;\nvar SUPERVISOR_CREDENTIAL_ENCODED_LENGTH = 43;\nfunction isSupervisorAttemptCredential(value) {\n if (typeof value !== "string" || value.length !== SUPERVISOR_CREDENTIAL_ENCODED_LENGTH || !/^[A-Za-z0-9_-]+$/u.test(value)) {\n return false;\n }\n const decoded = Buffer.from(value, "base64url");\n return decoded.byteLength === SUPERVISOR_CREDENTIAL_BYTE_LENGTH && decoded.toString("base64url") === value;\n}\nvar SUPERVISOR_MAX_FRAME_BYTES = 1e6;\nvar SUPERVISOR_MAX_STORE_METADATA_BYTES = 1024 * 1024;\nvar SUPERVISOR_MAX_ACTIVE_TURN_BYTES = 16 * 1024;\nvar SUPERVISOR_MAX_ATTEMPT_POINTER_BYTES = 1024;\nvar SUPERVISOR_MAX_WIRE_ID_BYTES = 512;\nfunction isBoundedUtf8Identifier(value, maxBytes = SUPERVISOR_MAX_WIRE_ID_BYTES) {\n return typeof value === "string" && value.length > 0 && Buffer.byteLength(value, "utf8") <= maxBytes;\n}\nvar SUPERVISOR_MAX_REASON_LENGTH = 2e3;\nvar SUPERVISOR_MAX_ATTACHMENT_ID_LENGTH = SUPERVISOR_MAX_WIRE_ID_BYTES;\nvar SUPERVISOR_MAX_COMMAND_ID_LENGTH = SUPERVISOR_MAX_WIRE_ID_BYTES;\nvar SUPERVISOR_MAX_COMMAND_LEDGER_BYTES = 64 * 1024 * 1024;\nvar SUPERVISOR_COMMAND_LEDGER_RECOVERY_BYTES = 8 * 1024 * 1024;\nvar SUPERVISOR_MAX_COMMAND_LEDGER_RECORDS = 131072;\nvar SUPERVISOR_COMMAND_LEDGER_RECOVERY_RECORDS = 512;\nvar SUPERVISOR_MAX_DISTINCT_COMMANDS = 65536;\nvar SUPERVISOR_MAX_PI_SESSION_HISTORY_BYTES = 64 * 1024 * 1024;\nvar SUPERVISOR_PI_SESSION_HISTORY_TURN_HEADROOM_BYTES = 8 * 1024 * 1024;\nvar SUPERVISOR_PI_SESSION_HISTORY_PROMPT_LIMIT_BYTES = SUPERVISOR_MAX_PI_SESSION_HISTORY_BYTES - SUPERVISOR_PI_SESSION_HISTORY_TURN_HEADROOM_BYTES;\nvar SUPERVISOR_MAX_PENDING_COMMANDS = 256;\nvar SUPERVISOR_MAX_PENDING_COMMAND_BYTES = 8 * 1024 * 1024;\nvar SUPERVISOR_PENDING_COMMAND_SEQUENCE_WINDOW = 256;\n\n// src/supervisor/protocol.ts\nvar SUPERVISOR_PROTOCOL_VERSION = 1;\nvar SUPERVISOR_RUNTIME_VERSION = 2;\nvar DAYTONA_SUPERVISOR_PROVIDER_VERSION = 1;\nvar SUPERVISOR_RECOVERY_STOP_REASON = "supervisor_restarted_during_prompt";\nvar SUPERVISOR_COMMAND_FINGERPRINT_VERSION = 1;\nvar SUPERVISOR_COMMAND_FINGERPRINT_PATTERN = new RegExp(\n `^sha256-v${SUPERVISOR_COMMAND_FINGERPRINT_VERSION}:[a-f0-9]{64}$`,\n "u"\n);\nfunction createSupervisorCommandFingerprint(command) {\n const payload = command.payload.kind === "stop" ? {\n kind: command.payload.kind,\n ...command.payload.reason === void 0 ? {} : { reason: command.payload.reason }\n } : {\n kind: command.payload.kind,\n message: command.payload.message,\n ...!command.payload.attachments?.length ? {} : {\n attachments: command.payload.attachments.map((attachment) => ({\n id: attachment.id,\n path: attachment.path,\n ...attachment.mimeType === void 0 ? {} : { mimeType: attachment.mimeType },\n sha256: attachment.sha256.toLowerCase(),\n sizeBytes: attachment.sizeBytes\n }))\n }\n };\n const canonical = JSON.stringify({\n fingerprintVersion: SUPERVISOR_COMMAND_FINGERPRINT_VERSION,\n protocolVersion: command.protocolVersion,\n sessionId: command.sessionId,\n runId: command.runId,\n attemptId: command.attemptId,\n commandId: command.commandId,\n commandSequence: command.commandSequence,\n payload\n });\n return `sha256-v${SUPERVISOR_COMMAND_FINGERPRINT_VERSION}:${createHash("sha256").update(canonical, "utf8").digest("hex")}`;\n}\nfunction isSupervisorCommandFingerprint(value) {\n return typeof value === "string" && SUPERVISOR_COMMAND_FINGERPRINT_PATTERN.test(value);\n}\nfunction isRecord2(value) {\n return typeof value === "object" && value !== null && !Array.isArray(value);\n}\nfunction isNonEmptyString(value) {\n return typeof value === "string" && value.length > 0;\n}\nfunction isCommandId(value) {\n return isBoundedUtf8Identifier(value, SUPERVISOR_MAX_COMMAND_ID_LENGTH);\n}\nfunction isNonNegativeInteger(value) {\n return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;\n}\nfunction isPositiveInteger(value) {\n return typeof value === "number" && Number.isSafeInteger(value) && value > 0;\n}\nfunction isFiniteNumber(value) {\n return typeof value === "number" && Number.isFinite(value);\n}\nfunction hasOptionalCommandId(value) {\n return value.commandId === void 0 || isCommandId(value.commandId);\n}\nfunction isSupervisorTurnUsage(value) {\n return isRecord2(value) && isNonNegativeInteger(value.inputTokens) && isNonNegativeInteger(value.outputTokens) && isNonNegativeInteger(value.cacheReadTokens) && isNonNegativeInteger(value.cacheWriteTokens) && isNonNegativeInteger(value.totalTokens) && (value.costUsd === void 0 || isFiniteNumber(value.costUsd) && value.costUsd >= 0);\n}\nfunction hasOptionalUsage(value) {\n return value.usage === void 0 || isSupervisorTurnUsage(value.usage);\n}\nfunction isCommandKind(value) {\n return value === "prompt" || value === "steer" || value === "stop";\n}\nfunction isSupervisorReason(value) {\n return typeof value === "string" && value.length <= SUPERVISOR_MAX_REASON_LENGTH;\n}\nfunction sanitizeSupervisorReason(value) {\n if (value.length <= SUPERVISOR_MAX_REASON_LENGTH) return value;\n let end = SUPERVISOR_MAX_REASON_LENGTH;\n const finalCodeUnit = value.charCodeAt(end - 1);\n if (finalCodeUnit >= 55296 && finalCodeUnit <= 56319) end -= 1;\n return value.slice(0, end);\n}\nfunction isSupervisorEvent(value) {\n if (!isRecord2(value) || typeof value.kind !== "string") return false;\n if (value.kind === "supervisor_started") return typeof value.recovered === "boolean";\n if (value.kind === "harness_started") {\n return typeof value.adapter === "string" && (value.pid === void 0 || isPositiveInteger(value.pid));\n }\n if (value.kind === "harness_event") {\n return typeof value.adapter === "string" && Object.hasOwn(value, "payload");\n }\n if (value.kind === "harness_stderr") {\n return typeof value.adapter === "string" && typeof value.data === "string";\n }\n if (value.kind === "harness_exited") {\n return typeof value.adapter === "string" && (value.exitCode === null || isNonNegativeInteger(value.exitCode)) && (value.signal === null || typeof value.signal === "string");\n }\n if (value.kind === "turn_started") {\n return typeof value.adapter === "string" && hasOptionalCommandId(value);\n }\n if (value.kind === "turn_completed") {\n return typeof value.adapter === "string" && hasOptionalCommandId(value) && (value.stopReason === void 0 || isSupervisorReason(value.stopReason)) && hasOptionalUsage(value);\n }\n if (value.kind === "turn_failed") {\n return typeof value.adapter === "string" && hasOptionalCommandId(value) && (value.stopReason === void 0 || isSupervisorReason(value.stopReason)) && isSerializedError(value.error) && hasOptionalUsage(value);\n }\n if (value.kind === "turn_stopped") {\n return typeof value.adapter === "string" && hasOptionalCommandId(value) && (value.reason === void 0 || isSupervisorReason(value.reason)) && hasOptionalUsage(value);\n }\n if (value.kind === "command_received" || value.kind === "command_applied") {\n return isCommandId(value.commandId) && isPositiveInteger(value.commandSequence) && isCommandKind(value.commandKind);\n }\n if (value.kind === "command_failed") {\n return isCommandId(value.commandId) && isPositiveInteger(value.commandSequence) && isCommandKind(value.commandKind) && isSerializedError(value.error);\n }\n if (value.kind === "interrupted" || value.kind === "supervisor_stopping") {\n return isSupervisorReason(value.reason);\n }\n if (value.kind === "protocol_error") return typeof value.message === "string";\n return false;\n}\nfunction hasCurrentProtocolVersion(value) {\n return value.protocolVersion === SUPERVISOR_PROTOCOL_VERSION;\n}\nfunction hasAttemptIdentity(value) {\n return isBoundedUtf8Identifier(value.sessionId) && isBoundedUtf8Identifier(value.runId) && isBoundedUtf8Identifier(value.attemptId);\n}\nfunction parseAttachments(value) {\n if (value === void 0) return void 0;\n if (!Array.isArray(value)) return void 0;\n const attachments = [];\n for (const attachment of value) {\n if (!isRecord2(attachment) || !isBoundedUtf8Identifier(\n attachment.id,\n SUPERVISOR_MAX_ATTACHMENT_ID_LENGTH\n ) || !isNonEmptyString(attachment.url) || !isNonEmptyString(attachment.path) || attachment.mimeType !== void 0 && typeof attachment.mimeType !== "string" || typeof attachment.sha256 !== "string" || !/^[a-fA-F0-9]{64}$/.test(attachment.sha256) || !isNonNegativeInteger(attachment.sizeBytes)) {\n return void 0;\n }\n attachments.push({\n id: attachment.id,\n url: attachment.url,\n path: attachment.path,\n ...attachment.mimeType === void 0 ? {} : { mimeType: attachment.mimeType },\n sha256: attachment.sha256.toLowerCase(),\n sizeBytes: attachment.sizeBytes\n });\n }\n return attachments;\n}\nfunction parseCommandPayload(value) {\n if (!isRecord2(value) || typeof value.kind !== "string") return null;\n if (value.kind === "stop") {\n if (value.reason !== void 0 && !isSupervisorReason(value.reason)) return null;\n return {\n kind: "stop",\n ...value.reason === void 0 ? {} : { reason: value.reason }\n };\n }\n if ((value.kind === "prompt" || value.kind === "steer") && typeof value.message === "string") {\n const attachments = parseAttachments(value.attachments);\n if (value.attachments !== void 0 && attachments === void 0) return null;\n return {\n kind: value.kind,\n message: value.message,\n ...attachments === void 0 ? {} : { attachments }\n };\n }\n return null;\n}\nfunction parseCommandFrame(value) {\n if (!isRecord2(value) || value.type !== "command" || !hasCurrentProtocolVersion(value) || !hasAttemptIdentity(value) || !isCommandId(value.commandId) || !isPositiveInteger(value.commandSequence)) {\n return null;\n }\n const payload = parseCommandPayload(value.payload);\n if (!payload) return null;\n return {\n type: "command",\n protocolVersion: SUPERVISOR_PROTOCOL_VERSION,\n sessionId: value.sessionId,\n runId: value.runId,\n attemptId: value.attemptId,\n commandId: value.commandId,\n commandSequence: value.commandSequence,\n payload\n };\n}\nfunction parseGatewayToSupervisorFrame(value) {\n if (!isRecord2(value) || !hasCurrentProtocolVersion(value) || !hasAttemptIdentity(value)) {\n return null;\n }\n const identity = {\n sessionId: value.sessionId,\n runId: value.runId,\n attemptId: value.attemptId\n };\n if (value.type === "command") return parseCommandFrame(value);\n if (value.type === "event_ack" && isNonNegativeInteger(value.acknowledgedEventSequence)) {\n return {\n type: "event_ack",\n protocolVersion: SUPERVISOR_PROTOCOL_VERSION,\n ...identity,\n acknowledgedEventSequence: value.acknowledgedEventSequence\n };\n }\n if (value.type === "resume_ok" && isNonNegativeInteger(value.acknowledgedEventSequence) && isNonNegativeInteger(value.lastAppliedCommandSequence) && Array.isArray(value.pendingCommands) && value.pendingCommands.length <= SUPERVISOR_MAX_PENDING_COMMANDS) {\n const pendingCommands = value.pendingCommands.map(parseCommandFrame);\n if (pendingCommands.some((command) => command === null)) return null;\n return {\n type: "resume_ok",\n protocolVersion: SUPERVISOR_PROTOCOL_VERSION,\n ...identity,\n acknowledgedEventSequence: value.acknowledgedEventSequence,\n lastAppliedCommandSequence: value.lastAppliedCommandSequence,\n pendingCommands\n };\n }\n if (value.type === "attempt_superseded" && (value.reason === void 0 || isSupervisorReason(value.reason))) {\n return {\n type: "attempt_superseded",\n protocolVersion: SUPERVISOR_PROTOCOL_VERSION,\n ...identity,\n ...value.reason === void 0 ? {} : { reason: value.reason }\n };\n }\n if (value.type === "pong" && typeof value.sentAt === "string") {\n return {\n type: "pong",\n protocolVersion: SUPERVISOR_PROTOCOL_VERSION,\n ...identity,\n sentAt: value.sentAt\n };\n }\n return null;\n}\nfunction hasMatchingAttempt(identity, frame) {\n return identity.sessionId === frame.sessionId && identity.runId === frame.runId && identity.attemptId === frame.attemptId;\n}\nfunction createSupervisorEventId(attemptId, attemptSequence) {\n return `${attemptId}:${attemptSequence}`;\n}\nfunction serializeSupervisorError(error) {\n return serializeError(error);\n}\n\n// src/supervisor/path-policy.ts\nimport { posix } from "node:path";\nfunction containsControlCharacter(value) {\n return /[\\u0000-\\u001f\\u007f]/u.test(value);\n}\nfunction assertCanonicalSandboxPath(name, value) {\n if (!posix.isAbsolute(value) || value === "/" || value.endsWith("/") || value !== posix.normalize(value) || value.includes("\\\\") || containsControlCharacter(value)) {\n throw new Error(\n `${name} must be a canonical absolute non-root POSIX sandbox path.`\n );\n }\n}\nfunction sandboxPathIsEqualToOrBelow(parent, child) {\n const relativePath = posix.relative(parent, child);\n return !posix.isAbsolute(relativePath) && relativePath !== ".." && !relativePath.startsWith("../");\n}\nfunction sandboxPathsOverlap(left, right) {\n return sandboxPathIsEqualToOrBelow(left, right) || sandboxPathIsEqualToOrBelow(right, left);\n}\nfunction assertSafePathSegment(name, value) {\n if (value.length === 0 || value === "." || value === ".." || value.includes("/") || value.includes("\\\\") || containsControlCharacter(value) || Buffer.byteLength(value, "utf8") > 255) {\n throw new Error(\n `${name} must be one safe POSIX path segment of 1 to 255 bytes.`\n );\n }\n}\n\n// src/supervisor/config.ts\nvar PI_THINKING_LEVELS = [\n "off",\n "minimal",\n "low",\n "medium",\n "high",\n "xhigh"\n];\nvar SUPERVISOR_MAX_TIMER_DELAY_MS = 2147483647;\nvar DEFAULT_SUPERVISOR_ATTACHMENT_CONFIG = {\n maxBytesPerAttachment: 100 * 1024 * 1024,\n maxBytesPerCommand: 500 * 1024 * 1024,\n maxFilesPerAttempt: 100,\n maxBytesPerAttempt: 500 * 1024 * 1024,\n downloadTimeoutMs: 12e4\n};\nfunction assertSupervisorHarnessPathOwnership(stateDir, sessionPath, agentDir) {\n const effectiveAgentDir = agentDir ?? `${stateDir}/pi/agent`;\n const reservedStateRoots = [\n `${stateDir}/attempts`,\n `${stateDir}/attempt-data-v${SUPERVISOR_RUNTIME_VERSION}`,\n `${stateDir}/.neckbeard-resource-snapshots`\n ];\n if (reservedStateRoots.some((path) => sandboxPathsOverlap(sessionPath, path))) {\n throw new Error(\n "Supervisor config harness.sessionPath must not overlap supervisor-owned state."\n );\n }\n if (reservedStateRoots.some((path) => sandboxPathsOverlap(effectiveAgentDir, path))) {\n throw new Error(\n "Supervisor config harness.agentDir must not overlap supervisor-owned state."\n );\n }\n if (sandboxPathsOverlap(sessionPath, effectiveAgentDir)) {\n throw new Error(\n "Supervisor config harness.sessionPath and harness.agentDir must not overlap."\n );\n }\n}\nfunction isRecord3(value) {\n return typeof value === "object" && value !== null && !Array.isArray(value);\n}\nfunction isNonEmptyString2(value) {\n return typeof value === "string" && value.length > 0;\n}\nfunction isPositiveInteger2(value) {\n return typeof value === "number" && Number.isSafeInteger(value) && value > 0;\n}\nfunction isTimerDelay(value) {\n return isPositiveInteger2(value) && value <= SUPERVISOR_MAX_TIMER_DELAY_MS;\n}\nfunction isNonNegativeNumber(value) {\n return typeof value === "number" && Number.isFinite(value) && value >= 0;\n}\nfunction parseSupervisorRuntimeConfig(value) {\n if (!isRecord3(value)) throw new Error("Supervisor config must be an object.");\n if (value.protocolVersion !== SUPERVISOR_PROTOCOL_VERSION) {\n throw new Error(\n `Unsupported supervisor protocol version: ${String(value.protocolVersion)}.`\n );\n }\n if (value.runtimeVersion !== SUPERVISOR_RUNTIME_VERSION) {\n throw new Error(\n `Unsupported supervisor runtime version: ${String(value.runtimeVersion)}.`\n );\n }\n if (value.provider !== "daytona") {\n throw new Error(\'Supervisor provider must be "daytona".\');\n }\n if (value.providerVersion !== DAYTONA_SUPERVISOR_PROVIDER_VERSION) {\n throw new Error(\n `Unsupported Daytona supervisor provider version: ${String(value.providerVersion)}.`\n );\n }\n for (const field of [\n "sessionId",\n "runId",\n "attemptId",\n "gatewayUrl",\n "credentialEnv",\n "workspaceDir",\n "stateDurabilityAnchor",\n "stateDir"\n ]) {\n if (!isNonEmptyString2(value[field])) {\n throw new Error(`Supervisor config ${field} must be a non-empty string.`);\n }\n }\n for (const field of ["sessionId", "runId"]) {\n if (!isBoundedUtf8Identifier(value[field])) {\n throw new Error(\n `Supervisor config ${field} must be at most ${SUPERVISOR_MAX_WIRE_ID_BYTES} UTF-8 bytes.`\n );\n }\n }\n assertSafePathSegment(\n "Supervisor config attemptId",\n value.attemptId\n );\n assertCanonicalSandboxPath(\n "Supervisor config workspaceDir",\n value.workspaceDir\n );\n assertCanonicalSandboxPath(\n "Supervisor config stateDurabilityAnchor",\n value.stateDurabilityAnchor\n );\n assertCanonicalSandboxPath(\n "Supervisor config stateDir",\n value.stateDir\n );\n if (!sandboxPathIsEqualToOrBelow(\n value.stateDurabilityAnchor,\n value.stateDir\n )) {\n throw new Error(\n "Supervisor config stateDir must be equal to or below stateDurabilityAnchor."\n );\n }\n if (sandboxPathsOverlap(value.workspaceDir, value.stateDir)) {\n throw new Error(\n "Supervisor config workspaceDir and stateDir must not overlap."\n );\n }\n if (!isTimerDelay(value.heartbeatIntervalMs)) {\n throw new Error(\n `Supervisor config heartbeatIntervalMs must be a positive integer no greater than ${SUPERVISOR_MAX_TIMER_DELAY_MS}.`\n );\n }\n if (!isTimerDelay(value.handshakeTimeoutMs)) {\n throw new Error(\n `Supervisor config handshakeTimeoutMs must be a positive integer no greater than ${SUPERVISOR_MAX_TIMER_DELAY_MS}.`\n );\n }\n if (!isPositiveInteger2(value.maxInFlightEvents)) {\n throw new Error(\n "Supervisor config maxInFlightEvents must be a positive integer."\n );\n }\n if (typeof value.allowInsecureGateway !== "boolean") {\n throw new Error(\n "Supervisor config allowInsecureGateway must be a boolean."\n );\n }\n let gatewayUrl;\n try {\n gatewayUrl = new URL(value.gatewayUrl);\n } catch {\n throw new Error("Supervisor config gatewayUrl must be a valid URL.");\n }\n if (gatewayUrl.protocol !== "wss:" && !(value.allowInsecureGateway && gatewayUrl.protocol === "ws:")) {\n throw new Error("Supervisor config gatewayUrl must use wss://.");\n }\n if (gatewayUrl.username || gatewayUrl.password) {\n throw new Error(\n "Supervisor config gatewayUrl must not contain credentials."\n );\n }\n if (gatewayUrl.search || gatewayUrl.hash) {\n throw new Error(\n "Supervisor config gatewayUrl must not contain a query or fragment."\n );\n }\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(value.credentialEnv)) {\n throw new Error(\n "Supervisor config credentialEnv must be a valid environment variable name."\n );\n }\n const attachments = value.attachments === void 0 ? DEFAULT_SUPERVISOR_ATTACHMENT_CONFIG : value.attachments;\n if (!isRecord3(attachments)) {\n throw new Error("Supervisor config attachments must be an object.");\n }\n if (!isPositiveInteger2(attachments.maxBytesPerAttachment)) {\n throw new Error(\n "Supervisor attachments.maxBytesPerAttachment must be a positive integer."\n );\n }\n if (!isPositiveInteger2(attachments.maxBytesPerCommand)) {\n throw new Error(\n "Supervisor attachments.maxBytesPerCommand must be a positive integer."\n );\n }\n const maxFilesPerAttempt = attachments.maxFilesPerAttempt === void 0 ? DEFAULT_SUPERVISOR_ATTACHMENT_CONFIG.maxFilesPerAttempt : attachments.maxFilesPerAttempt;\n if (!isPositiveInteger2(maxFilesPerAttempt)) {\n throw new Error(\n "Supervisor attachments.maxFilesPerAttempt must be a positive integer."\n );\n }\n const maxBytesPerAttempt = attachments.maxBytesPerAttempt === void 0 ? attachments.maxBytesPerCommand : attachments.maxBytesPerAttempt;\n if (!isPositiveInteger2(maxBytesPerAttempt)) {\n throw new Error(\n "Supervisor attachments.maxBytesPerAttempt must be a positive integer."\n );\n }\n if (!isTimerDelay(attachments.downloadTimeoutMs)) {\n throw new Error(\n `Supervisor attachments.downloadTimeoutMs must be a positive integer no greater than ${SUPERVISOR_MAX_TIMER_DELAY_MS}.`\n );\n }\n if (!isRecord3(value.reconnect)) {\n throw new Error("Supervisor config reconnect must be an object.");\n }\n if (!isTimerDelay(value.reconnect.initialDelayMs)) {\n throw new Error(\n `Supervisor reconnect.initialDelayMs must be a positive integer no greater than ${SUPERVISOR_MAX_TIMER_DELAY_MS}.`\n );\n }\n if (!isTimerDelay(value.reconnect.maximumDelayMs)) {\n throw new Error(\n `Supervisor reconnect.maximumDelayMs must be a positive integer no greater than ${SUPERVISOR_MAX_TIMER_DELAY_MS}.`\n );\n }\n if (value.reconnect.maximumDelayMs < value.reconnect.initialDelayMs) {\n throw new Error(\n "Supervisor reconnect.maximumDelayMs must be >= initialDelayMs."\n );\n }\n if (typeof value.reconnect.multiplier !== "number" || !Number.isFinite(value.reconnect.multiplier) || value.reconnect.multiplier < 1) {\n throw new Error("Supervisor reconnect.multiplier must be at least 1.");\n }\n if (!isNonNegativeNumber(value.reconnect.jitterRatio) || value.reconnect.jitterRatio > 1) {\n throw new Error(\n "Supervisor reconnect.jitterRatio must be between 0 and 1."\n );\n }\n if (value.reconnect.maximumDelayMs * (1 + value.reconnect.jitterRatio) > SUPERVISOR_MAX_TIMER_DELAY_MS) {\n throw new Error(\n `Supervisor reconnect jittered delay must not exceed ${SUPERVISOR_MAX_TIMER_DELAY_MS}.`\n );\n }\n if (!isRecord3(value.harness) || value.harness.adapter !== "pi-sdk") {\n throw new Error(\'Supervisor config harness.adapter must be "pi-sdk".\');\n }\n if (value.harness.adapterVersion !== 1) {\n throw new Error("Supervisor config harness.adapterVersion must be 1.");\n }\n if (!isNonEmptyString2(value.harness.moduleSpecifier)) {\n throw new Error(\n "Supervisor config harness.moduleSpecifier must be a non-empty string."\n );\n }\n if (!isNonEmptyString2(value.harness.expectedVersion)) {\n throw new Error(\n "Supervisor config harness.expectedVersion must be a non-empty string."\n );\n }\n if (!isNonEmptyString2(value.harness.sessionPath)) {\n throw new Error(\n "Supervisor config harness.sessionPath must be a non-empty string."\n );\n }\n assertCanonicalSandboxPath(\n "Supervisor config harness.sessionPath",\n value.harness.sessionPath\n );\n if (value.harness.sessionPath === value.stateDir || !sandboxPathIsEqualToOrBelow(\n value.stateDir,\n value.harness.sessionPath\n )) {\n throw new Error(\n "Supervisor config harness.sessionPath must be strictly below stateDir."\n );\n }\n if (value.harness.agentDir !== void 0 && !isNonEmptyString2(value.harness.agentDir)) {\n throw new Error(\n "Supervisor config harness.agentDir must be a non-empty string when set."\n );\n }\n if (value.harness.agentDir !== void 0) {\n assertCanonicalSandboxPath(\n "Supervisor config harness.agentDir",\n value.harness.agentDir\n );\n if (value.harness.agentDir === value.stateDir || !sandboxPathIsEqualToOrBelow(\n value.stateDir,\n value.harness.agentDir\n )) {\n throw new Error(\n "Supervisor config harness.agentDir must be strictly below stateDir."\n );\n }\n }\n assertSupervisorHarnessPathOwnership(\n value.stateDir,\n value.harness.sessionPath,\n value.harness.agentDir\n );\n if (value.harness.provider !== void 0 && !isNonEmptyString2(value.harness.provider)) {\n throw new Error(\n "Supervisor config harness.provider must be a non-empty string when set."\n );\n }\n if (value.harness.model !== void 0 && !isNonEmptyString2(value.harness.model)) {\n throw new Error(\n "Supervisor config harness.model must be a non-empty string when set."\n );\n }\n if (value.harness.provider === void 0 !== (value.harness.model === void 0)) {\n throw new Error(\n "Supervisor config harness.provider and harness.model must be set together."\n );\n }\n if (value.harness.providerCredentialEnv !== void 0 && (!isNonEmptyString2(value.harness.providerCredentialEnv) || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(value.harness.providerCredentialEnv))) {\n throw new Error(\n "Supervisor config harness.providerCredentialEnv must be a valid environment variable name when set."\n );\n }\n if (value.harness.provider === void 0 !== (value.harness.providerCredentialEnv === void 0)) {\n throw new Error(\n "Supervisor config harness.providerCredentialEnv must be set with provider and model."\n );\n }\n if (value.harness.providerCredentialEnv === value.credentialEnv) {\n throw new Error(\n "Supervisor and provider credentials must use different environment variables."\n );\n }\n if (value.harness.thinking !== void 0 && !PI_THINKING_LEVELS.includes(value.harness.thinking)) {\n throw new Error("Supervisor config harness.thinking is invalid.");\n }\n if (!isTimerDelay(value.harness.stopGraceMs)) {\n throw new Error(\n `Supervisor config harness.stopGraceMs must be a positive integer no greater than ${SUPERVISOR_MAX_TIMER_DELAY_MS}.`\n );\n }\n return {\n ...value,\n attachments: {\n maxBytesPerAttachment: attachments.maxBytesPerAttachment,\n maxBytesPerCommand: attachments.maxBytesPerCommand,\n maxFilesPerAttempt,\n maxBytesPerAttempt,\n downloadTimeoutMs: attachments.downloadTimeoutMs\n }\n };\n}\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((resolve2, 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(() => resolve2(value)),\n (error) => settle(() => reject(error))\n );\n });\n}\nfunction withTimeout(task, timeoutMs, message) {\n return settleOperation(() => task, {\n timeout: {\n timeoutMs,\n createError: () => new Error(message)\n }\n });\n}\n\n// src/supervisor/attachments.ts\nimport { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";\nimport { constants as fsConstants2 } from "node:fs";\nimport { opendir } from "node:fs/promises";\nimport { dirname, join as join2 } from "node:path";\n\n// src/supervisor/durable-fs.ts\nimport { randomUUID } from "node:crypto";\nimport { constants as fsConstants } from "node:fs";\nimport { link, mkdir, open, rename, unlink } from "node:fs/promises";\nimport { isAbsolute, join, relative, sep } from "node:path";\nvar SUPERVISOR_ATTEMPT_POINTER_ROOT = "attempts";\nvar SUPERVISOR_ATTEMPT_DATA_ROOT = `attempt-data-v${SUPERVISOR_RUNTIME_VERSION}`;\nvar SUPERVISOR_ATTEMPT_DIRECTORY_MODE = 448;\nvar SUPERVISOR_ATTEMPT_POINTER_MODE = 384;\nvar DEFAULT_DIRECTORY_DEPENDENCIES = {};\nvar SAFE_DIRECTORY_OPEN_FLAGS = fsConstants.O_RDONLY | fsConstants.O_DIRECTORY | fsConstants.O_NOFOLLOW;\nvar SAFE_LEAF_OPEN_FLAGS = fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK;\nvar BOUNDED_READ_CHUNK_BYTES = 64 * 1024;\nfunction descriptorBoundDirectoryPath(directory) {\n return `/proc/${process.pid}/fd/${directory.handle.fd}`;\n}\nfunction descriptorBoundEntryPath(directory, name) {\n assertSafePathSegment("Descriptor-bound directory entry", name);\n return join(descriptorBoundDirectoryPath(directory), name);\n}\nfunction descriptorBoundFilesystemEntryPath(directory, name) {\n if (!name || name === "." || name === ".." || name.includes("/") || name.includes("\\0")) {\n throw new Error("Descriptor-bound filesystem entry must be one POSIX path segment.");\n }\n return join(descriptorBoundDirectoryPath(directory), name);\n}\nfunction directoryIdentity(stats) {\n return { device: stats.dev, inode: stats.ino };\n}\nfunction matchesDirectoryIdentity(stats, expected) {\n return stats.dev === expected.device && stats.ino === expected.inode;\n}\nasync function openBoundDirectoryHandle(path, displayPath, expectedIdentity) {\n let handle = null;\n try {\n handle = await open(path, SAFE_DIRECTORY_OPEN_FLAGS);\n const stats = await handle.stat({ bigint: true });\n if (!stats.isDirectory() || expectedIdentity !== void 0 && !matchesDirectoryIdentity(stats, expectedIdentity)) {\n throw new Error(`${displayPath} must continue to identify its original directory.`);\n }\n return {\n handle,\n displayPath,\n identity: directoryIdentity(stats)\n };\n } catch (error) {\n await handle?.close().catch(() => void 0);\n const code = error.code;\n if (code === "ELOOP" || code === "ENOTDIR") {\n throw new Error(`${displayPath} must be a directory.`, { cause: error });\n }\n throw error;\n }\n}\nasync function openDescriptorBoundDirectory(path, expectedIdentity) {\n return openBoundDirectoryHandle(path, path, expectedIdentity);\n}\nasync function openDescriptorBoundDirectoryAt(parent, name, expectedIdentity) {\n const displayPath = join(parent.displayPath, name);\n return openBoundDirectoryHandle(\n descriptorBoundEntryPath(parent, name),\n displayPath,\n expectedIdentity\n );\n}\nasync function openDescriptorBoundFilesystemDirectoryAt(parent, name, expectedIdentity) {\n const displayPath = join(parent.displayPath, name);\n return openBoundDirectoryHandle(\n descriptorBoundFilesystemEntryPath(parent, name),\n displayPath,\n expectedIdentity\n );\n}\nfunction relativeDirectorySegments(anchor, path) {\n const relativePath = relative(anchor, path);\n if (isAbsolute(relativePath) || relativePath === ".." || relativePath.startsWith(`..${sep}`)) {\n throw new Error(`${path} must be equal to or below durability anchor ${anchor}.`);\n }\n if (!relativePath) return [];\n const segments = relativePath.split(sep);\n for (const segment of segments) {\n assertSafePathSegment("Durable directory path edge", segment);\n }\n return segments;\n}\nasync function verifyBoundDirectoryEntry(parent, child, name) {\n let current = null;\n try {\n current = await openDescriptorBoundDirectoryAt(parent, name, child.identity);\n } catch (error) {\n throw new Error(`${child.displayPath} must continue to identify its original directory.`, {\n cause: error\n });\n } finally {\n await current?.handle.close().catch(() => void 0);\n }\n}\nasync function syncDescriptorBoundDirectory(directory) {\n try {\n await directory.handle.sync();\n } catch (error) {\n const code = error.code;\n if (code !== "EINVAL" && code !== "ENOTSUP" && code !== "EBADF") throw error;\n }\n}\nasync function ensureDescriptorBoundDirectoryAt(parent, name, mode = SUPERVISOR_ATTEMPT_DIRECTORY_MODE, dependencies = DEFAULT_DIRECTORY_DEPENDENCIES) {\n const path = descriptorBoundEntryPath(parent, name);\n let child;\n try {\n try {\n child = await openDescriptorBoundDirectoryAt(parent, name);\n } catch (error) {\n if (error.code !== "ENOENT") throw error;\n try {\n await mkdir(path, { mode });\n } catch (mkdirError) {\n if (mkdirError.code !== "EEXIST") {\n throw mkdirError;\n }\n }\n child = await openDescriptorBoundDirectoryAt(parent, name);\n }\n await (dependencies.syncDirectory?.(parent) ?? syncDescriptorBoundDirectory(parent));\n const boundChild = child;\n await dependencies.afterDirectoryBound?.(boundChild.displayPath);\n await verifyBoundDirectoryEntry(parent, boundChild, name);\n return boundChild;\n } catch (error) {\n await child?.handle.close().catch(() => void 0);\n throw error;\n }\n}\nasync function bindDescriptorBoundDirectory(anchor, path, expectedIdentity, dependencies = DEFAULT_DIRECTORY_DEPENDENCIES) {\n const segments = relativeDirectorySegments(anchor, path);\n let current = await openDescriptorBoundDirectory(anchor);\n try {\n for (const [index, segment] of segments.entries()) {\n const next = await openDescriptorBoundDirectoryAt(\n current,\n segment,\n index === segments.length - 1 ? expectedIdentity : void 0\n );\n await dependencies.afterDirectoryBound?.(next.displayPath);\n await current.handle.close();\n current = next;\n }\n if (!segments.length && expectedIdentity !== void 0) {\n const stats = await current.handle.stat({ bigint: true });\n if (!matchesDirectoryIdentity(stats, expectedIdentity)) {\n throw new Error(`${path} must continue to identify its original directory.`);\n }\n }\n return current;\n } catch (error) {\n await current.handle.close().catch(() => void 0);\n throw error;\n }\n}\nasync function ensureDescriptorBoundDirectory(anchor, path, mode = SUPERVISOR_ATTEMPT_DIRECTORY_MODE, dependencies = DEFAULT_DIRECTORY_DEPENDENCIES) {\n const segments = relativeDirectorySegments(anchor, path);\n let current = await openDescriptorBoundDirectory(anchor);\n try {\n for (const segment of segments) {\n const next = await ensureDescriptorBoundDirectoryAt(current, segment, mode, dependencies);\n await current.handle.close();\n current = next;\n }\n return current;\n } catch (error) {\n await current.handle.close().catch(() => void 0);\n throw error;\n }\n}\nasync function openRegularFileAt(parent, name, flags, description, mode) {\n return openRegularLeafFile(descriptorBoundEntryPath(parent, name), flags, description, mode);\n}\nasync function openRegularFilesystemEntryAt(parent, name, flags, description, mode) {\n return openRegularLeafFile(\n descriptorBoundFilesystemEntryPath(parent, name),\n flags,\n description,\n mode\n );\n}\nasync function openRegularLeafFile(path, flags, name, mode) {\n const handle = await open(path, flags | SAFE_LEAF_OPEN_FLAGS, mode);\n try {\n const stats = await handle.stat();\n if (!stats.isFile()) throw new Error(`${name} must be a regular file.`);\n return handle;\n } catch (error) {\n await handle.close();\n throw error;\n }\n}\nasync function retainedRegularFileStats(retained, current) {\n return Promise.all([\n retained.stat({ bigint: true }),\n current.stat({ bigint: true })\n ]);\n}\nasync function matchesRetainedRegularFileIdentity(retained, current) {\n const [retainedStats, currentStats] = await retainedRegularFileStats(retained, current);\n return retainedStats.isFile() && currentStats.isFile() && retainedStats.dev === currentStats.dev && retainedStats.ino === currentStats.ino;\n}\nasync function withRevalidatedPrivateRegularFile(retained, openCurrent, operation, options = {}) {\n const { maximumBytes } = options;\n if (maximumBytes !== void 0 && (!Number.isSafeInteger(maximumBytes) || maximumBytes < 0)) {\n throw new Error("Retained private regular file has an invalid size limit.");\n }\n const current = await openCurrent();\n try {\n const [retainedStats, currentStats] = await retainedRegularFileStats(retained, current);\n const expectedUid = typeof process.getuid === "function" ? BigInt(process.getuid()) : null;\n const maximumSize = maximumBytes === void 0 ? null : BigInt(maximumBytes);\n if (!retainedStats.isFile() || !currentStats.isFile() || retainedStats.dev !== currentStats.dev || retainedStats.ino !== currentStats.ino || retainedStats.nlink !== 1n || currentStats.nlink !== 1n || (retainedStats.mode & 0o777n) !== 0o600n || (currentStats.mode & 0o777n) !== 0o600n || maximumSize !== null && (retainedStats.size > maximumSize || currentStats.size > maximumSize) || expectedUid !== null && (retainedStats.uid !== expectedUid || currentStats.uid !== expectedUid)) {\n throw new Error(\n options.failureMessage ?? "Retained private regular file no longer satisfies its descriptor binding."\n );\n }\n return operation();\n } finally {\n await current.close().catch(() => void 0);\n }\n}\nasync function readBoundedRegularTextHandle(handle, maximumBytes, capacityName, options = {}) {\n if (!Number.isSafeInteger(maximumBytes) || maximumBytes < 0) {\n throw new Error(`${capacityName} has an invalid read capacity.`);\n }\n if (options.expectedBytes !== void 0 && (!Number.isSafeInteger(options.expectedBytes) || options.expectedBytes < 0 || options.expectedBytes > maximumBytes)) {\n throw new Error(`${capacityName} has an invalid expected byte length.`);\n }\n const stats = await handle.stat();\n if (!Number.isSafeInteger(stats.size) || stats.size < 0 || stats.size > maximumBytes) {\n throw new Error(`${capacityName} exceeds its bounded on-disk capacity.`);\n }\n const chunks = [];\n let totalBytes = 0;\n const readLimit = options.expectedBytes ?? maximumBytes + 1;\n while (totalBytes < readLimit) {\n const remaining = readLimit - totalBytes;\n const chunk = Buffer.allocUnsafe(Math.min(BOUNDED_READ_CHUNK_BYTES, remaining));\n const { bytesRead } = await handle.read(chunk, 0, chunk.length, totalBytes);\n if (bytesRead === 0) {\n if (options.expectedBytes !== void 0) {\n throw options.prematureEofError?.() ?? new Error(`${capacityName} ended before its expected byte length.`);\n }\n break;\n }\n chunks.push(chunk.subarray(0, bytesRead));\n totalBytes += bytesRead;\n }\n if (totalBytes > maximumBytes) {\n throw new Error(`${capacityName} exceeds its bounded on-disk capacity.`);\n }\n try {\n return new TextDecoder("utf-8", {\n fatal: true,\n ignoreBOM: options.ignoreBOM ?? true\n }).decode(Buffer.concat(chunks, totalBytes));\n } catch (error) {\n if (options.invalidUtf8Error !== void 0) throw options.invalidUtf8Error();\n throw error;\n }\n}\nasync function readBoundedRegularTextFileAt(parent, name, maximumBytes, capacityName) {\n const handle = await openRegularFileAt(parent, name, fsConstants.O_RDONLY, capacityName);\n try {\n return await readBoundedRegularTextHandle(handle, maximumBytes, capacityName);\n } finally {\n await handle.close();\n }\n}\nasync function linkDescriptorBoundEntry(sourceParent, sourceName, destinationParent, destinationName) {\n await link(\n descriptorBoundEntryPath(sourceParent, sourceName),\n descriptorBoundEntryPath(destinationParent, destinationName)\n );\n}\nasync function renameDescriptorBoundEntry(sourceParent, sourceName, destinationParent, destinationName) {\n await rename(\n descriptorBoundEntryPath(sourceParent, sourceName),\n descriptorBoundEntryPath(destinationParent, destinationName)\n );\n}\nasync function unlinkDescriptorBoundEntry(parent, name) {\n await unlink(descriptorBoundEntryPath(parent, name));\n}\nasync function unlinkDescriptorBoundEntryIfPresent(parent, name) {\n try {\n await unlinkDescriptorBoundEntry(parent, name);\n return true;\n } catch (error) {\n if (error.code === "ENOENT") return false;\n throw error;\n }\n}\nfunction supervisorAttemptDataDirectory(config) {\n return join(config.stateDir, SUPERVISOR_ATTEMPT_DATA_ROOT, config.attemptId);\n}\nfunction supervisorAttemptPointer(config) {\n return `${JSON.stringify({\n revision: SUPERVISOR_RUNTIME_VERSION,\n dataDirectory: `${SUPERVISOR_ATTEMPT_DATA_ROOT}/${config.attemptId}`\n })}\n`;\n}\nasync function readAndValidateAttemptPointerAt(pointerParent, name, expected, attemptId) {\n let actual;\n try {\n actual = await readBoundedRegularTextFileAt(\n pointerParent,\n name,\n SUPERVISOR_MAX_ATTEMPT_POINTER_BYTES,\n `Supervisor attempt ${attemptId} storage revision pointer`\n );\n } catch (error) {\n let directory = null;\n try {\n directory = await openDescriptorBoundDirectoryAt(pointerParent, name);\n throw new Error(\n `Supervisor attempt ${attemptId} uses a pre-revision storage layout and cannot be upgraded in place; launch a replacement attempt.`\n );\n } catch (directoryError) {\n if (directoryError instanceof Error && directoryError.message.includes("uses a pre-revision storage layout")) {\n throw directoryError;\n }\n } finally {\n await directory?.handle.close().catch(() => void 0);\n }\n throw error;\n }\n if (actual !== expected) {\n throw new Error(`Supervisor attempt ${attemptId} has an unsupported storage revision pointer.`);\n }\n}\nasync function publishAttemptPointerAt(pointerParent, name, expected, attemptId) {\n const temporaryName = `.${process.pid}.${randomUUID()}.revision.tmp`;\n let temporaryExists = false;\n try {\n const handle = await openRegularFileAt(\n pointerParent,\n temporaryName,\n fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL,\n `Supervisor attempt ${attemptId} temporary storage revision pointer`,\n SUPERVISOR_ATTEMPT_POINTER_MODE\n );\n temporaryExists = true;\n try {\n await handle.writeFile(expected, "utf8");\n await handle.sync();\n } finally {\n await handle.close();\n }\n try {\n await linkDescriptorBoundEntry(pointerParent, temporaryName, pointerParent, name);\n } catch (error) {\n if (error.code !== "EEXIST") throw error;\n }\n await readAndValidateAttemptPointerAt(pointerParent, name, expected, attemptId);\n await syncDescriptorBoundDirectory(pointerParent);\n } finally {\n if (temporaryExists) {\n const removed = await unlinkDescriptorBoundEntryIfPresent(\n pointerParent,\n temporaryName\n );\n if (removed) await syncDescriptorBoundDirectory(pointerParent);\n }\n }\n}\nasync function openSupervisorAttemptStorage(config) {\n const state = await ensureDescriptorBoundDirectory(config.stateDurabilityAnchor, config.stateDir);\n let pointerParent = null;\n let dataParent = null;\n try {\n pointerParent = await ensureDescriptorBoundDirectoryAt(state, SUPERVISOR_ATTEMPT_POINTER_ROOT);\n const expectedPointer = supervisorAttemptPointer(config);\n try {\n await readAndValidateAttemptPointerAt(\n pointerParent,\n config.attemptId,\n expectedPointer,\n config.attemptId\n );\n await syncDescriptorBoundDirectory(pointerParent);\n } catch (error) {\n if (error.code !== "ENOENT") throw error;\n await publishAttemptPointerAt(\n pointerParent,\n config.attemptId,\n expectedPointer,\n config.attemptId\n );\n }\n dataParent = await ensureDescriptorBoundDirectoryAt(state, SUPERVISOR_ATTEMPT_DATA_ROOT);\n return await ensureDescriptorBoundDirectoryAt(dataParent, config.attemptId);\n } finally {\n await dataParent?.handle.close().catch(() => void 0);\n await pointerParent?.handle.close().catch(() => void 0);\n await state.handle.close().catch(() => void 0);\n }\n}\n\n// src/supervisor/attachments.ts\nvar MAX_ATTACHMENTS_PER_COMMAND = 100;\nvar ATTACHMENT_TARGET_SUFFIX_BYTES = 108;\nvar ATTACHMENT_READ_CHUNK_BYTES = 64 * 1024;\nvar ATTACHMENT_BATCH_MARKER_MAX_BYTES = 64 * 1024;\nvar IMMUTABLE_ATTACHMENT_FILENAME_PATTERN = /^[a-f0-9]{64}-[a-f0-9]{64}-[a-f0-9]{16}-.+$/u;\nvar ATTACHMENT_BATCH_MARKER_PATTERN = /^\\.batch-([a-f0-9]{64})\\.(pending|committed)$/u;\nvar DEFAULT_DEPENDENCIES = {\n fetch: globalThis.fetch,\n randomId: randomUUID2\n};\nvar AttachmentMaterializationError = class extends Error {\n name = "AttachmentMaterializationError";\n};\nfunction safeError(attachment, message) {\n const id = typeof attachment.id === "string" ? truncateUtf8(attachment.id, SUPERVISOR_MAX_ATTACHMENT_ID_LENGTH) : "unknown";\n return new AttachmentMaterializationError(`Attachment ${id} ${message}`);\n}\nfunction validateFilename(attachment) {\n try {\n assertSafePathSegment("Attachment path", attachment.path);\n } catch {\n throw safeError(attachment, "path must be a safe single filename.");\n }\n}\nfunction validateSourceUrl(attachment) {\n let url;\n try {\n url = new URL(attachment.url);\n } catch {\n throw safeError(attachment, "download URL is invalid.");\n }\n if (url.protocol !== "https:" || url.username || url.password) {\n throw safeError(attachment, "download URL must use HTTPS without embedded credentials.");\n }\n return url;\n}\nfunction attachmentDirectory(config) {\n return join2(supervisorAttemptDataDirectory(config), "attachments");\n}\nfunction commandDirectoryName(commandId) {\n return createHash2("sha256").update(commandId, "utf8").digest("hex");\n}\nfunction truncateUtf8(value, maximumBytes) {\n let result = "";\n let bytes = 0;\n for (const character of value) {\n const characterBytes = Buffer.byteLength(character, "utf8");\n if (bytes + characterBytes > maximumBytes) break;\n result += character;\n bytes += characterBytes;\n }\n return result;\n}\nfunction immutableAttachmentFilename(commandId, attachment) {\n const commandHash = commandDirectoryName(commandId);\n const nameHash = createHash2("sha256").update(attachment.path, "utf8").digest("hex").slice(0, 16);\n return `${commandHash}-${attachment.sha256.toLowerCase()}-${nameHash}-${truncateUtf8(\n attachment.path,\n ATTACHMENT_TARGET_SUFFIX_BYTES\n )}`;\n}\nfunction throwIfAborted(signal) {\n if (!signal?.aborted) return;\n if (signal.reason instanceof Error) throw signal.reason;\n throw new Error("Attachment materialization was aborted.");\n}\nasync function writeChunk(handle, chunk) {\n let offset = 0;\n while (offset < chunk.byteLength) {\n const { bytesWritten } = await handle.write(chunk, offset, chunk.byteLength - offset, null);\n if (bytesWritten <= 0) throw new Error("Attachment file write made no progress.");\n offset += bytesWritten;\n }\n}\nfunction attachmentBatchMarkerName(commandHash, state) {\n return `.batch-${commandHash}.${state}`;\n}\nfunction isRecord4(value) {\n return typeof value === "object" && value !== null && !Array.isArray(value);\n}\nfunction validatePrivateAttachmentStats(stats, maximumBytes) {\n const expectedUid = typeof process.getuid === "function" ? BigInt(process.getuid()) : null;\n if (!stats.isFile() || stats.nlink !== 1n || (stats.mode & 0o777n) !== 0o600n || stats.size < 0n || stats.size > BigInt(maximumBytes) || expectedUid !== null && stats.uid !== expectedUid) {\n throw new AttachmentMaterializationError(\n "Attempt attachment storage contains an invalid published file."\n );\n }\n return Number(stats.size);\n}\nasync function attachmentDigest(handle, sizeBytes) {\n const hash = createHash2("sha256");\n let offset = 0;\n while (offset < sizeBytes) {\n const chunk = Buffer.allocUnsafe(Math.min(ATTACHMENT_READ_CHUNK_BYTES, sizeBytes - offset));\n const { bytesRead } = await handle.read(chunk, 0, chunk.byteLength, offset);\n if (bytesRead <= 0) {\n throw new AttachmentMaterializationError(\n "Attempt attachment storage contains a truncated published file."\n );\n }\n hash.update(chunk.subarray(0, bytesRead));\n offset += bytesRead;\n }\n return hash.digest("hex");\n}\nvar SupervisorAttachmentMaterializer = class {\n constructor(config, dependencies = {}) {\n this.config = config;\n this.directory = attachmentDirectory(config);\n this.dependencies = { ...DEFAULT_DEPENDENCIES, ...dependencies };\n this.maxFilesPerAttempt = config.attachments.maxFilesPerAttempt ?? DEFAULT_SUPERVISOR_ATTACHMENT_CONFIG.maxFilesPerAttempt;\n this.maxBytesPerAttempt = config.attachments.maxBytesPerAttempt ?? config.attachments.maxBytesPerCommand;\n }\n config;\n directory;\n dependencies;\n maxFilesPerAttempt;\n maxBytesPerAttempt;\n attachmentDirectoryPromise = null;\n activeMaterializations = /* @__PURE__ */ new Set();\n materializationTail = Promise.resolve();\n closed = false;\n closePromise = null;\n materialize(commandId, attachments, signal) {\n if (this.closed) {\n return Promise.reject(new Error("Supervisor attachment materializer is closed."));\n }\n const materializing = this.materializationTail.then(\n () => this.materializeBound(commandId, attachments, signal)\n );\n this.materializationTail = materializing.then(\n () => void 0,\n () => void 0\n );\n this.activeMaterializations.add(materializing);\n void materializing.then(\n () => this.activeMaterializations.delete(materializing),\n () => this.activeMaterializations.delete(materializing)\n );\n return materializing;\n }\n async close() {\n if (this.closePromise !== null) return this.closePromise;\n this.closed = true;\n const closing = (async () => {\n await Promise.allSettled([...this.activeMaterializations]);\n const directoryPromise = this.attachmentDirectoryPromise;\n this.attachmentDirectoryPromise = null;\n const directory = await directoryPromise?.catch(() => null);\n await directory?.handle.close();\n })();\n this.closePromise = closing;\n return closing;\n }\n async materializeBound(commandId, attachments, signal) {\n throwIfAborted(signal);\n if (!attachments?.length) return void 0;\n if (attachments.length > MAX_ATTACHMENTS_PER_COMMAND) {\n throw new AttachmentMaterializationError(\n `A command may contain at most ${MAX_ATTACHMENTS_PER_COMMAND} attachments.`\n );\n }\n let declaredTotal = 0;\n const ids = /* @__PURE__ */ new Set();\n const paths = /* @__PURE__ */ new Set();\n const sources = /* @__PURE__ */ new Map();\n for (const attachment of attachments) {\n validateFilename(attachment);\n if (!/^[a-fA-F0-9]{64}$/.test(attachment.sha256)) {\n throw safeError(attachment, "SHA-256 must contain exactly 64 hexadecimal characters.");\n }\n if (!Number.isSafeInteger(attachment.sizeBytes) || attachment.sizeBytes < 0) {\n throw safeError(attachment, "sizeBytes must be a nonnegative safe integer.");\n }\n if (attachment.sizeBytes > this.config.attachments.maxBytesPerAttachment) {\n throw safeError(attachment, "exceeds the per-attachment byte limit.");\n }\n declaredTotal += attachment.sizeBytes;\n if (!Number.isSafeInteger(declaredTotal) || declaredTotal > this.config.attachments.maxBytesPerCommand) {\n throw new AttachmentMaterializationError(\n "Command attachments exceed the aggregate byte limit."\n );\n }\n if (ids.has(attachment.id)) throw safeError(attachment, "ID is duplicated.");\n if (paths.has(attachment.path)) throw safeError(attachment, "path is duplicated.");\n ids.add(attachment.id);\n paths.add(attachment.path);\n sources.set(attachment, validateSourceUrl(attachment));\n }\n const attachmentDirectory2 = await this.getAttachmentDirectory();\n throwIfAborted(signal);\n const usage = await this.recoverAttachmentUsage(attachmentDirectory2);\n const targetNames = /* @__PURE__ */ new Map();\n const requestedTargets = /* @__PURE__ */ new Set();\n let reservedFiles = 0;\n let reservedBytes = 0;\n for (const attachment of attachments) {\n const targetName = immutableAttachmentFilename(commandId, attachment);\n if (requestedTargets.has(targetName)) {\n throw safeError(attachment, "resolves to a duplicate immutable target.");\n }\n requestedTargets.add(targetName);\n targetNames.set(attachment, targetName);\n const existing = usage.files.get(targetName);\n if (existing) {\n if (existing.sizeBytes !== attachment.sizeBytes) {\n throw safeError(attachment, "does not match its existing immutable target.");\n }\n } else {\n reservedFiles += 1;\n reservedBytes += attachment.sizeBytes;\n }\n }\n if (usage.files.size + reservedFiles > this.maxFilesPerAttempt) {\n throw new AttachmentMaterializationError(\n "Attempt attachments exceed the persistent file limit."\n );\n }\n const reservedTotalBytes = usage.bytes + reservedBytes;\n if (!Number.isSafeInteger(reservedBytes) || !Number.isSafeInteger(reservedTotalBytes) || reservedTotalBytes > this.maxBytesPerAttempt) {\n throw new AttachmentMaterializationError(\n "Attempt attachments exceed the persistent byte limit."\n );\n }\n const rollbackTargets = attachments.map((attachment) => targetNames.get(attachment)).filter(\n (targetName) => targetName !== void 0 && !usage.files.has(targetName)\n );\n const batchMarkerName = rollbackTargets.length === 0 ? null : await this.beginAttachmentBatch(\n attachmentDirectory2,\n commandDirectoryName(commandId),\n rollbackTargets\n );\n const materialized = [];\n try {\n for (const attachment of attachments) {\n throwIfAborted(signal);\n const source = sources.get(attachment);\n const targetName = targetNames.get(attachment);\n if (!source || !targetName) {\n throw safeError(attachment, "validated materialization metadata was lost.");\n }\n let path;\n if (usage.files.has(targetName)) {\n path = await this.reuseExisting(\n attachmentDirectory2,\n targetName,\n attachment\n );\n } else {\n const downloaded = await this.download(\n attachmentDirectory2,\n targetName,\n attachment,\n source,\n signal\n );\n path = downloaded.path;\n }\n materialized.push({\n id: attachment.id,\n path,\n ...attachment.mimeType === void 0 ? {} : { mimeType: attachment.mimeType }\n });\n }\n if (batchMarkerName !== null) {\n await this.commitAttachmentBatch(attachmentDirectory2, batchMarkerName);\n }\n return materialized;\n } catch (error) {\n try {\n await this.rollbackBatch(\n attachmentDirectory2,\n rollbackTargets,\n batchMarkerName\n );\n } catch {\n throw new AttachmentMaterializationError(\n "Attachment batch rollback could not be durably completed."\n );\n }\n throw error;\n }\n }\n /**\n * The published files are the durable quota ledger. A restarted supervisor\n * reconstructs exact usage through its retained directory descriptor and\n * removes only crash-left temporary names from the reserved namespace.\n */\n async recoverAttachmentUsage(attachmentDirectory2) {\n await this.removeCrashLeftPartials(attachmentDirectory2);\n await this.recoverAttachmentBatches(attachmentDirectory2);\n const publishedNames = [];\n let unexpectedEntry = false;\n let tooManyFiles = false;\n let removedPartial = false;\n const scanner = await opendir(descriptorBoundDirectoryPath(attachmentDirectory2));\n try {\n while (true) {\n const entry = await scanner.read();\n if (entry === null) break;\n if (entry.name.startsWith(".") && entry.name.endsWith(".partial")) {\n const removed = await unlinkDescriptorBoundEntryIfPresent(\n attachmentDirectory2,\n entry.name\n );\n removedPartial ||= removed;\n continue;\n }\n if (!IMMUTABLE_ATTACHMENT_FILENAME_PATTERN.test(entry.name)) {\n unexpectedEntry = true;\n continue;\n }\n if (publishedNames.length >= this.maxFilesPerAttempt) {\n tooManyFiles = true;\n continue;\n }\n publishedNames.push(entry.name);\n }\n } finally {\n await scanner.close().catch((error) => {\n if (error.code !== "ERR_DIR_CLOSED") throw error;\n });\n if (removedPartial) await syncDescriptorBoundDirectory(attachmentDirectory2);\n }\n if (unexpectedEntry) {\n throw new AttachmentMaterializationError(\n "Attempt attachment storage contains an unexpected entry."\n );\n }\n if (tooManyFiles) {\n throw new AttachmentMaterializationError(\n "Attempt attachment storage exceeds its persistent budget."\n );\n }\n const files = /* @__PURE__ */ new Map();\n let bytes = 0;\n for (const name of publishedNames) {\n const handle = await openRegularFilesystemEntryAt(\n attachmentDirectory2,\n name,\n fsConstants2.O_RDONLY,\n "Supervisor persisted attachment"\n );\n try {\n const sizeBytes = validatePrivateAttachmentStats(\n await handle.stat({ bigint: true }),\n this.config.attachments.maxBytesPerAttachment\n );\n files.set(name, { sizeBytes });\n bytes += sizeBytes;\n if (!Number.isSafeInteger(bytes) || bytes > this.maxBytesPerAttempt) {\n throw new AttachmentMaterializationError(\n "Attempt attachment storage exceeds its persistent budget."\n );\n }\n } finally {\n await handle.close().catch(() => void 0);\n }\n }\n return { files, bytes };\n }\n async removeCrashLeftPartials(attachmentDirectory2) {\n let removed = false;\n const scanner = await opendir(descriptorBoundDirectoryPath(attachmentDirectory2));\n try {\n while (true) {\n const entry = await scanner.read();\n if (entry === null) break;\n if (!entry.name.startsWith(".") || !entry.name.endsWith(".partial")) continue;\n const didRemove = await unlinkDescriptorBoundEntryIfPresent(\n attachmentDirectory2,\n entry.name\n );\n removed ||= didRemove;\n }\n } finally {\n await scanner.close().catch((error) => {\n if (error.code !== "ERR_DIR_CLOSED") throw error;\n });\n }\n if (removed) await syncDescriptorBoundDirectory(attachmentDirectory2);\n }\n async readAttachmentBatchMarker(attachmentDirectory2, markerName, expectedCommandHash) {\n const handle = await openRegularFilesystemEntryAt(\n attachmentDirectory2,\n markerName,\n fsConstants2.O_RDONLY,\n "Supervisor attachment batch marker"\n );\n try {\n const stats = await handle.stat({ bigint: true });\n const expectedUid = typeof process.getuid === "function" ? BigInt(process.getuid()) : null;\n if (!stats.isFile() || stats.nlink !== 1n || (stats.mode & 0o777n) !== 0o600n || stats.size <= 0n || stats.size > BigInt(ATTACHMENT_BATCH_MARKER_MAX_BYTES) || expectedUid !== null && stats.uid !== expectedUid) {\n throw new AttachmentMaterializationError(\n "Attempt attachment storage contains an invalid batch marker."\n );\n }\n const size = Number(stats.size);\n const text = await readBoundedRegularTextHandle(\n handle,\n ATTACHMENT_BATCH_MARKER_MAX_BYTES,\n "Supervisor attachment batch marker",\n {\n expectedBytes: size,\n ignoreBOM: false,\n prematureEofError: () => new AttachmentMaterializationError(\n "Attempt attachment storage contains a truncated batch marker."\n ),\n invalidUtf8Error: () => new AttachmentMaterializationError(\n "Attempt attachment storage contains an invalid batch marker."\n )\n }\n );\n let value;\n try {\n value = JSON.parse(text);\n } catch {\n throw new AttachmentMaterializationError(\n "Attempt attachment storage contains an invalid batch marker."\n );\n }\n if (!isRecord4(value) || value.version !== 1 || value.commandHash !== expectedCommandHash || !Array.isArray(value.targets) || value.targets.length === 0 || value.targets.length > MAX_ATTACHMENTS_PER_COMMAND || Object.keys(value).length !== 3) {\n throw new AttachmentMaterializationError(\n "Attempt attachment storage contains an invalid batch marker."\n );\n }\n const targets = /* @__PURE__ */ new Set();\n for (const target of value.targets) {\n if (typeof target !== "string" || !IMMUTABLE_ATTACHMENT_FILENAME_PATTERN.test(target) || !target.startsWith(`${expectedCommandHash}-`) || targets.has(target)) {\n throw new AttachmentMaterializationError(\n "Attempt attachment storage contains an invalid batch marker."\n );\n }\n targets.add(target);\n }\n return {\n version: 1,\n commandHash: expectedCommandHash,\n targets: [...targets]\n };\n } finally {\n await handle.close().catch(() => void 0);\n }\n }\n async recoverAttachmentBatches(attachmentDirectory2) {\n const markers = /* @__PURE__ */ new Map();\n const scanner = await opendir(descriptorBoundDirectoryPath(attachmentDirectory2));\n try {\n while (true) {\n const entry = await scanner.read();\n if (entry === null) break;\n const match = ATTACHMENT_BATCH_MARKER_PATTERN.exec(entry.name);\n if (!match) continue;\n const commandHash = match[1];\n const state = match[2];\n const existing = markers.get(commandHash) ?? {};\n existing[state] = entry.name;\n markers.set(commandHash, existing);\n }\n } finally {\n await scanner.close().catch((error) => {\n if (error.code !== "ERR_DIR_CLOSED") throw error;\n });\n }\n for (const [commandHash, markerNames] of markers) {\n if (markerNames.pending && markerNames.committed) {\n throw new AttachmentMaterializationError(\n "Attempt attachment storage contains conflicting batch markers."\n );\n }\n const markerName = markerNames.pending ?? markerNames.committed;\n if (!markerName) continue;\n const marker = await this.readAttachmentBatchMarker(\n attachmentDirectory2,\n markerName,\n commandHash\n );\n let changed = false;\n if (markerNames.pending) {\n for (const targetName of marker.targets) {\n const removed = await unlinkDescriptorBoundEntryIfPresent(\n attachmentDirectory2,\n targetName\n );\n changed ||= removed;\n }\n if (changed) await syncDescriptorBoundDirectory(attachmentDirectory2);\n }\n await unlinkDescriptorBoundEntry(attachmentDirectory2, markerName);\n await syncDescriptorBoundDirectory(attachmentDirectory2);\n }\n }\n async beginAttachmentBatch(attachmentDirectory2, commandHash, targets) {\n const markerName = attachmentBatchMarkerName(commandHash, "pending");\n const marker = { version: 1, commandHash, targets };\n const encoded = Buffer.from(`${JSON.stringify(marker)}\n`, "utf8");\n if (encoded.byteLength > ATTACHMENT_BATCH_MARKER_MAX_BYTES) {\n throw new AttachmentMaterializationError(\n "Attachment batch marker exceeds its bounded capacity."\n );\n }\n const temporaryName = `.batch-${commandHash}-${randomUUID2()}.partial`;\n let handle = null;\n let temporaryExists = false;\n let markerPublished = false;\n try {\n handle = await openRegularFileAt(\n attachmentDirectory2,\n temporaryName,\n fsConstants2.O_WRONLY | fsConstants2.O_CREAT | fsConstants2.O_EXCL,\n "Supervisor attachment batch marker temporary file",\n 384\n );\n temporaryExists = true;\n await writeChunk(handle, encoded);\n await handle.chmod(384);\n await handle.sync();\n await linkDescriptorBoundEntry(\n attachmentDirectory2,\n temporaryName,\n attachmentDirectory2,\n markerName\n );\n markerPublished = true;\n await unlinkDescriptorBoundEntry(attachmentDirectory2, temporaryName);\n temporaryExists = false;\n await syncDescriptorBoundDirectory(attachmentDirectory2);\n return markerName;\n } catch (error) {\n if (markerPublished) {\n await unlinkDescriptorBoundEntry(attachmentDirectory2, markerName).catch(() => void 0);\n }\n if (temporaryExists) {\n await unlinkDescriptorBoundEntry(attachmentDirectory2, temporaryName).catch(() => void 0);\n }\n if (markerPublished || temporaryExists) {\n await syncDescriptorBoundDirectory(attachmentDirectory2).catch(() => void 0);\n }\n throw error;\n } finally {\n await handle?.close().catch(() => void 0);\n }\n }\n async commitAttachmentBatch(attachmentDirectory2, pendingMarkerName) {\n const committedMarkerName = pendingMarkerName.replace(/\\.pending$/u, ".committed");\n await renameDescriptorBoundEntry(\n attachmentDirectory2,\n pendingMarkerName,\n attachmentDirectory2,\n committedMarkerName\n );\n await syncDescriptorBoundDirectory(attachmentDirectory2);\n await unlinkDescriptorBoundEntry(attachmentDirectory2, committedMarkerName).then(\n async () => syncDescriptorBoundDirectory(attachmentDirectory2),\n () => void 0\n );\n }\n async reuseExisting(attachmentDirectory2, targetName, attachment) {\n let handle = null;\n try {\n handle = await openRegularFileAt(\n attachmentDirectory2,\n targetName,\n fsConstants2.O_RDONLY,\n "Supervisor existing attachment"\n );\n const before = await handle.stat({ bigint: true });\n const sizeBytes = validatePrivateAttachmentStats(\n before,\n this.config.attachments.maxBytesPerAttachment\n );\n if (sizeBytes !== attachment.sizeBytes) {\n throw safeError(attachment, "does not match its existing immutable target.");\n }\n const digest = await attachmentDigest(handle, sizeBytes);\n const after = await handle.stat({ bigint: true });\n validatePrivateAttachmentStats(after, this.config.attachments.maxBytesPerAttachment);\n if (before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || digest !== attachment.sha256.toLowerCase()) {\n throw safeError(attachment, "does not match its existing immutable target.");\n }\n return await this.canonicalAttachmentPath(attachmentDirectory2, targetName, handle);\n } catch (error) {\n if (error instanceof AttachmentMaterializationError) throw error;\n throw safeError(attachment, "existing immutable target failed validation.");\n } finally {\n await handle?.close().catch(() => void 0);\n }\n }\n async canonicalAttachmentPath(attachmentDirectory2, targetName, handle) {\n const stablePath = join2(attachmentDirectory2.displayPath, targetName);\n await this.dependencies.beforeAttachmentPathPublished?.(stablePath);\n const canonicalDirectory = await bindDescriptorBoundDirectory(\n this.config.stateDurabilityAnchor,\n attachmentDirectory2.displayPath,\n attachmentDirectory2.identity\n );\n let path;\n try {\n await this.dependencies.afterCanonicalAttachmentDirectoryBound?.(\n canonicalDirectory.displayPath\n );\n path = await withRevalidatedPrivateRegularFile(\n handle,\n () => openRegularFileAt(\n canonicalDirectory,\n targetName,\n fsConstants2.O_RDONLY,\n "Supervisor attachment canonical file"\n ),\n () => stablePath,\n {\n maximumBytes: this.config.attachments.maxBytesPerAttachment,\n failureMessage: "Supervisor attachment canonical path no longer identifies the materialized file."\n }\n );\n } finally {\n await canonicalDirectory.handle.close().catch(() => void 0);\n }\n const finalCanonicalDirectory = await bindDescriptorBoundDirectory(\n this.config.stateDurabilityAnchor,\n attachmentDirectory2.displayPath,\n attachmentDirectory2.identity\n );\n try {\n await withRevalidatedPrivateRegularFile(\n handle,\n () => openRegularFileAt(\n finalCanonicalDirectory,\n targetName,\n fsConstants2.O_RDONLY,\n "Supervisor attachment final canonical file"\n ),\n () => void 0,\n {\n maximumBytes: this.config.attachments.maxBytesPerAttachment,\n failureMessage: "Supervisor attachment canonical path no longer identifies the materialized file."\n }\n );\n } finally {\n await finalCanonicalDirectory.handle.close().catch(() => void 0);\n }\n return path;\n }\n async rollbackBatch(attachmentDirectory2, targetNames, pendingMarkerName) {\n let removed = false;\n let failure;\n for (const targetName of [...targetNames].reverse()) {\n try {\n const didRemove = await unlinkDescriptorBoundEntryIfPresent(\n attachmentDirectory2,\n targetName\n );\n removed ||= didRemove;\n } catch (error) {\n failure ??= error;\n }\n }\n if (removed) {\n try {\n await syncDescriptorBoundDirectory(attachmentDirectory2);\n } catch (error) {\n failure ??= error;\n }\n }\n if (failure !== void 0) throw failure;\n if (pendingMarkerName !== null) {\n const committedMarkerName = pendingMarkerName.replace(/\\.pending$/u, ".committed");\n for (const markerName of [pendingMarkerName, committedMarkerName]) {\n try {\n const didRemove = await unlinkDescriptorBoundEntryIfPresent(\n attachmentDirectory2,\n markerName\n );\n if (didRemove) await syncDescriptorBoundDirectory(attachmentDirectory2);\n } catch (error) {\n failure ??= error;\n }\n }\n }\n if (failure !== void 0) throw failure;\n }\n getAttachmentDirectory() {\n if (this.attachmentDirectoryPromise !== null) {\n return this.attachmentDirectoryPromise;\n }\n const opening = this.openAttachmentDirectory();\n this.attachmentDirectoryPromise = opening;\n void opening.catch(() => {\n if (this.attachmentDirectoryPromise === opening) {\n this.attachmentDirectoryPromise = null;\n }\n });\n return opening;\n }\n async openAttachmentDirectory() {\n const attemptDirectory = await openSupervisorAttemptStorage(this.config);\n let attachmentDirectory2 = null;\n let retained = false;\n try {\n if (dirname(this.directory) !== attemptDirectory.displayPath) {\n throw new Error("Supervisor attachment storage resolved to an unexpected directory.");\n }\n attachmentDirectory2 = await ensureDescriptorBoundDirectoryAt(attemptDirectory, "attachments");\n await attachmentDirectory2.handle.chmod(448);\n await this.dependencies.afterAttachmentDirectoryBound?.(attachmentDirectory2.displayPath);\n retained = true;\n return attachmentDirectory2;\n } finally {\n if (!retained) await attachmentDirectory2?.handle.close().catch(() => void 0);\n await attemptDirectory.handle.close().catch(() => void 0);\n }\n }\n async download(attachmentDirectory2, targetName, attachment, source, externalSignal) {\n const temporaryName = `.${this.dependencies.randomId()}.partial`;\n const abortController = new AbortController();\n const abortFromExternalSignal = () => abortController.abort(externalSignal?.reason);\n if (externalSignal?.aborted) abortFromExternalSignal();\n else\n externalSignal?.addEventListener("abort", abortFromExternalSignal, {\n once: true\n });\n const timeout = setTimeout(\n () => abortController.abort(new Error("Attachment download timed out.")),\n this.config.attachments.downloadTimeoutMs\n );\n let handle = null;\n let temporaryExists = false;\n let targetPublished = false;\n let published = false;\n try {\n throwIfAborted(abortController.signal);\n handle = await openRegularFileAt(\n attachmentDirectory2,\n temporaryName,\n fsConstants2.O_WRONLY | fsConstants2.O_CREAT | fsConstants2.O_EXCL,\n "Supervisor attachment temporary file",\n 384\n );\n temporaryExists = true;\n let response;\n try {\n response = await this.dependencies.fetch(source, {\n redirect: "error",\n signal: abortController.signal\n });\n } catch {\n throw safeError(attachment, "download failed.");\n }\n if (!response.ok) {\n throw safeError(attachment, `download returned HTTP ${response.status}.`);\n }\n if (!response.body && attachment.sizeBytes !== 0) {\n throw safeError(attachment, "download returned an empty body.");\n }\n const hash = createHash2("sha256");\n let receivedBytes = 0;\n if (response.body) {\n const reader = response.body.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n throwIfAborted(abortController.signal);\n receivedBytes += value.byteLength;\n if (receivedBytes > attachment.sizeBytes) {\n throw safeError(attachment, "download exceeded its declared size.");\n }\n hash.update(value);\n await writeChunk(handle, value);\n }\n } finally {\n reader.releaseLock();\n }\n }\n if (receivedBytes !== attachment.sizeBytes) {\n throw safeError(\n attachment,\n `download size did not match the declared ${attachment.sizeBytes} bytes.`\n );\n }\n if (hash.digest("hex") !== attachment.sha256.toLowerCase()) {\n throw safeError(attachment, "download did not match its declared SHA-256.");\n }\n await handle.chmod(384);\n await handle.sync();\n throwIfAborted(abortController.signal);\n await linkDescriptorBoundEntry(\n attachmentDirectory2,\n temporaryName,\n attachmentDirectory2,\n targetName\n );\n targetPublished = true;\n await unlinkDescriptorBoundEntry(attachmentDirectory2, temporaryName);\n temporaryExists = false;\n await syncDescriptorBoundDirectory(attachmentDirectory2);\n const path = await this.canonicalAttachmentPath(\n attachmentDirectory2,\n targetName,\n handle\n );\n published = true;\n return { path, targetName };\n } catch (error) {\n abortController.abort();\n if (error instanceof AttachmentMaterializationError) throw error;\n throw safeError(attachment, "could not be materialized.");\n } finally {\n clearTimeout(timeout);\n externalSignal?.removeEventListener("abort", abortFromExternalSignal);\n await handle?.close().catch(() => void 0);\n let removed = false;\n let cleanupFailure;\n if (!published) {\n if (targetPublished) {\n removed = await unlinkDescriptorBoundEntryIfPresent(\n attachmentDirectory2,\n targetName\n ).catch((error) => {\n cleanupFailure ??= error;\n return false;\n });\n }\n if (temporaryExists) {\n const removedTemporary = await unlinkDescriptorBoundEntryIfPresent(\n attachmentDirectory2,\n temporaryName\n ).catch((error) => {\n cleanupFailure ??= error;\n return false;\n });\n removed ||= removedTemporary;\n }\n if (removed) {\n await syncDescriptorBoundDirectory(attachmentDirectory2).catch((error) => {\n cleanupFailure ??= error;\n });\n }\n if (cleanupFailure !== void 0) {\n throw new AttachmentMaterializationError(\n "Attachment cleanup could not be durably completed."\n );\n }\n }\n }\n }\n};\n\n// src/supervisor/execution-gate.ts\nvar SupervisorExecutionClosedError = class extends Error {\n constructor(kind, reason, options = {}) {\n super(`Supervisor execution is closed: ${reason}`, options);\n this.kind = kind;\n this.reason = reason;\n }\n kind;\n reason;\n name = "SupervisorExecutionClosedError";\n};\nvar SupervisorExecutionGate = class {\n controller = new AbortController();\n closureValue = null;\n get signal() {\n return this.controller.signal;\n }\n get closure() {\n return this.closureValue;\n }\n get isClosed() {\n return this.closureValue !== null;\n }\n close(kind, reason, cause) {\n if (this.closureValue) return false;\n const error = new SupervisorExecutionClosedError(kind, reason, { cause });\n this.closureValue = { kind, reason, error };\n this.controller.abort(error);\n return true;\n }\n throwIfClosed() {\n if (this.closureValue) throw this.closureValue.error;\n }\n};\n\n// src/sensitive-value-redactor.ts\nvar DEFAULT_MINIMUM_CAPTURE_LENGTH = 8;\nvar DEFAULT_CREDENTIAL_ENV_NAME_PATTERN = /(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)/iu;\nfunction defaultEnvironmentValueIsSensitive(name, value) {\n return value.length >= DEFAULT_MINIMUM_CAPTURE_LENGTH && DEFAULT_CREDENTIAL_ENV_NAME_PATTERN.test(name);\n}\nvar SensitiveValueRedactor = class {\n secrets = /* @__PURE__ */ new Set();\n minimumCaptureLength;\n environment;\n isEnvironmentValueSensitive;\n constructor(values = [], options = {}) {\n this.minimumCaptureLength = options.minimumCaptureLength ?? DEFAULT_MINIMUM_CAPTURE_LENGTH;\n const environment = options.environment;\n this.environment = typeof environment === "function" ? environment : () => environment ?? process.env;\n this.isEnvironmentValueSensitive = options.isEnvironmentValueSensitive ?? defaultEnvironmentValueIsSensitive;\n this.captureAll(values);\n }\n capture(value) {\n if (value) this.secrets.add(value);\n }\n captureAll(values) {\n for (const value of values) {\n if (value.length >= this.minimumCaptureLength) this.capture(value);\n }\n }\n redact(value) {\n const environmentSecrets = Object.entries(this.environment()).filter(\n (entry) => Boolean(entry[1]) && this.isEnvironmentValueSensitive(entry[0], entry[1])\n ).map(([, secret]) => secret);\n const orderedSecrets = [.../* @__PURE__ */ new Set([...this.secrets, ...environmentSecrets])].sort(\n (left, right) => {\n const lengthDifference = right.length - left.length;\n if (lengthDifference !== 0) return lengthDifference;\n return left < right ? -1 : left > right ? 1 : 0;\n }\n );\n let redacted = value;\n for (const secret of orderedSecrets) {\n redacted = redacted.split(secret).join("[REDACTED]");\n }\n return redacted;\n }\n serialize(error) {\n const serialized = serializeError(error);\n return {\n ...serialized.name === void 0 ? {} : { name: this.redact(serialized.name) },\n message: this.redact(serialized.message),\n ...serialized.stack === void 0 ? {} : { stack: this.redact(serialized.stack) }\n };\n }\n};\n\n// src/supervisor/runtime-support.ts\nfunction isRecord5(value) {\n return typeof value === "object" && value !== null && !Array.isArray(value);\n}\nfunction errorFromUnknown(error) {\n return error instanceof Error ? error : new Error(String(error));\n}\n\n// src/supervisor/gateway-transport.ts\nvar WEBSOCKET_OPEN = 1;\nvar MAX_WEBSOCKET_BUFFERED_BYTES = 1024 * 1024;\nvar MAX_OUTBOUND_BATCH_BYTES = 1024 * 1024;\nvar MAX_OUTBOUND_IN_FLIGHT_BYTES = 8 * 1024 * 1024;\nvar SUPERVISOR_MAX_PENDING_INBOUND_FRAMES = SUPERVISOR_MAX_PENDING_COMMANDS * 2 + 4;\nvar SUPERVISOR_MAX_PENDING_INBOUND_BYTES = SUPERVISOR_MAX_PENDING_COMMAND_BYTES + SUPERVISOR_MAX_FRAME_BYTES * 2;\nvar DEFAULT_GATEWAY_TRANSPORT_DEPENDENCIES = {\n createWebSocket(url) {\n const WebSocketConstructor = globalThis.WebSocket;\n if (!WebSocketConstructor) {\n throw new Error("The supervisor runtime requires a Node.js version with global WebSocket.");\n }\n return new WebSocketConstructor(url);\n },\n random: Math.random,\n now: Date.now\n};\nvar SupervisorInboundFrameTooLargeError = class extends Error {\n name = "SupervisorInboundFrameTooLargeError";\n};\nfunction decodeGatewayMessage(data) {\n let text;\n let byteLength;\n if (typeof data === "string") {\n byteLength = Buffer.byteLength(data, "utf8");\n if (byteLength >= SUPERVISOR_MAX_FRAME_BYTES) {\n throw new SupervisorInboundFrameTooLargeError(\n `Gateway frame exceeds the ${SUPERVISOR_MAX_FRAME_BYTES}-byte limit.`\n );\n }\n text = data;\n } else if (data instanceof ArrayBuffer) {\n byteLength = data.byteLength;\n if (byteLength >= SUPERVISOR_MAX_FRAME_BYTES) {\n throw new SupervisorInboundFrameTooLargeError(\n `Gateway frame exceeds the ${SUPERVISOR_MAX_FRAME_BYTES}-byte limit.`\n );\n }\n try {\n text = new TextDecoder("utf-8", { fatal: true }).decode(data);\n } catch {\n return {\n decoded: { ok: false, error: "Gateway sent invalid UTF-8." },\n byteLength\n };\n }\n } else if (ArrayBuffer.isView(data)) {\n const view = data;\n byteLength = view.byteLength;\n if (byteLength >= SUPERVISOR_MAX_FRAME_BYTES) {\n throw new SupervisorInboundFrameTooLargeError(\n `Gateway frame exceeds the ${SUPERVISOR_MAX_FRAME_BYTES}-byte limit.`\n );\n }\n try {\n text = new TextDecoder("utf-8", { fatal: true }).decode(\n new Uint8Array(view.buffer, view.byteOffset, view.byteLength)\n );\n } catch {\n return {\n decoded: { ok: false, error: "Gateway sent invalid UTF-8." },\n byteLength\n };\n }\n } else {\n return {\n decoded: { ok: false, error: "Gateway sent a non-text frame." },\n byteLength: 0\n };\n }\n let raw;\n try {\n raw = JSON.parse(text);\n } catch {\n return {\n decoded: { ok: false, error: "Gateway sent malformed JSON." },\n byteLength\n };\n }\n const frame = parseGatewayToSupervisorFrame(raw);\n return {\n decoded: frame ? { ok: true, frame } : { ok: false, error: "Gateway sent an invalid frame." },\n byteLength\n };\n}\nvar SupervisorGatewayTransport = class {\n constructor(config, store, harness, commands, executionGate, redactor, callbacks, dependencies = DEFAULT_GATEWAY_TRANSPORT_DEPENDENCIES) {\n this.config = config;\n this.store = store;\n this.harness = harness;\n this.commands = commands;\n this.executionGate = executionGate;\n this.redactor = redactor;\n this.callbacks = callbacks;\n this.dependencies = dependencies;\n }\n config;\n store;\n harness;\n commands;\n executionGate;\n redactor;\n callbacks;\n dependencies;\n connection = null;\n nextConnectionGeneration = 1;\n reconnectAttempt = 0;\n reconnectTimer = null;\n stopping = false;\n // Old socket generations can retain their queued closures while a durable\n // handler is blocked. Account across the transport lifetime so reconnects\n // cannot each allocate another full generation-local inbound window.\n pendingInboundFrames = 0;\n pendingInboundBytes = 0;\n start() {\n this.connect();\n }\n beginShutdown() {\n this.stopping = true;\n if (this.reconnectTimer) clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n this.clearConnectionTimers(this.connection);\n }\n finishShutdown(options) {\n const connection = this.connection;\n if (!options.fatal) this.flushOutbox(connection);\n if (this.isActiveConnection(connection)) {\n connection.socket.close(\n 1e3,\n options.superseded ? "attempt superseded" : "supervisor stopped"\n );\n this.connection = null;\n }\n }\n failActiveConnection() {\n const connection = this.connection;\n this.clearConnectionTimers(connection);\n if (!this.isActiveConnection(connection)) return;\n connection.failed = true;\n connection.socket.close(1011, "durable supervisor failure");\n }\n flushOutbox(connection = this.connection) {\n if (!this.isActiveConnection(connection) || connection.failed || !connection.resumed || connection.socket.readyState !== WEBSOCKET_OPEN || connection.socket.bufferedAmount > MAX_WEBSOCKET_BUFFERED_BYTES) {\n return;\n }\n const acknowledged = this.store.lastAcknowledgedEventSequence;\n const inFlight = Math.max(0, connection.transmittedEventSequence - acknowledged);\n const allowance = Math.max(0, this.config.maxInFlightEvents - inFlight);\n if (!allowance) return;\n let inFlightBytes = 0;\n for (const frame of this.store.listEventsAfter(acknowledged, inFlight)) {\n inFlightBytes += Buffer.byteLength(JSON.stringify(frame), "utf8");\n }\n if (inFlightBytes >= MAX_OUTBOUND_IN_FLIGHT_BYTES) return;\n let batchBytes = 0;\n const events = this.store.listEventsAfter(connection.transmittedEventSequence, allowance);\n for (const event of events) {\n if (!this.isActiveConnection(connection) || connection.failed || connection.socket.readyState !== WEBSOCKET_OPEN || connection.socket.bufferedAmount > MAX_WEBSOCKET_BUFFERED_BYTES) {\n break;\n }\n const serialized = JSON.stringify(event);\n const frameBytes = Buffer.byteLength(serialized, "utf8");\n if (frameBytes >= SUPERVISOR_MAX_FRAME_BYTES) {\n this.callbacks.failRuntime(\n new Error(\n `Durable event ${event.eventId} exceeds the supervisor WebSocket frame limit.`\n )\n );\n break;\n }\n if (batchBytes > 0 && batchBytes + frameBytes > MAX_OUTBOUND_BATCH_BYTES) break;\n if (inFlightBytes > 0 && inFlightBytes + frameBytes > MAX_OUTBOUND_IN_FLIGHT_BYTES) break;\n try {\n connection.socket.send(serialized);\n } catch {\n connection.socket.close(1011, "event send failed");\n break;\n }\n connection.transmittedEventSequence = event.attemptSequence;\n batchBytes += frameBytes;\n inFlightBytes += frameBytes;\n if (batchBytes >= MAX_OUTBOUND_BATCH_BYTES || inFlightBytes >= MAX_OUTBOUND_IN_FLIGHT_BYTES || connection.socket.bufferedAmount > MAX_WEBSOCKET_BUFFERED_BYTES) {\n break;\n }\n }\n }\n connect() {\n if (this.stopping || this.executionGate.isClosed) return;\n const socket = this.dependencies.createWebSocket(this.config.gatewayUrl);\n socket.binaryType = "arraybuffer";\n if (this.stopping || this.executionGate.isClosed) {\n socket.close(1e3, "supervisor stopped");\n return;\n }\n const connection = {\n generation: this.nextConnectionGeneration,\n socket,\n resumed: false,\n failed: false,\n transmittedEventSequence: 0,\n lastGatewayActivityAt: this.dependencies.now(),\n pendingInboundFrames: 0,\n pendingInboundBytes: 0,\n inboundTail: Promise.resolve(),\n handshakeTimer: null,\n heartbeatTimer: null\n };\n this.nextConnectionGeneration += 1;\n this.connection = connection;\n socket.addEventListener("open", () => {\n if (!this.isActiveConnection(connection) || this.stopping) return;\n const credential = this.callbacks.getCredential();\n if (!credential) {\n void this.callbacks.emitEvent({\n kind: "protocol_error",\n message: `Missing required credential environment variable ${this.config.credentialEnv}.`\n }).then(\n () => connection.socket.close(1008, "missing credential"),\n () => connection.socket.close(1008, "missing credential")\n );\n return;\n }\n const resume = {\n type: "resume",\n protocolVersion: SUPERVISOR_PROTOCOL_VERSION,\n runtimeVersion: SUPERVISOR_RUNTIME_VERSION,\n provider: "daytona",\n providerVersion: DAYTONA_SUPERVISOR_PROVIDER_VERSION,\n sessionId: this.config.sessionId,\n runId: this.config.runId,\n attemptId: this.config.attemptId,\n credential,\n lastAcknowledgedEventSequence: this.store.lastAcknowledgedEventSequence,\n lastAppliedCommandSequence: this.store.lastAppliedCommandSequence\n };\n try {\n connection.socket.send(JSON.stringify(resume));\n } catch {\n connection.failed = true;\n connection.socket.close(1011, "resume send failed");\n return;\n }\n connection.handshakeTimer = setTimeout(\n () => connection.socket.close(4e3, "resume handshake timeout"),\n this.config.handshakeTimeoutMs\n );\n });\n socket.addEventListener("message", (message) => {\n if (!this.isActiveConnection(connection) || this.stopping || connection.failed) {\n return;\n }\n connection.lastGatewayActivityAt = this.dependencies.now();\n let envelope;\n try {\n envelope = decodeGatewayMessage(message.data);\n } catch (error) {\n if (error instanceof SupervisorInboundFrameTooLargeError) {\n if (this.isActiveConnection(connection)) {\n connection.failed = true;\n connection.socket.close(1009, "gateway frame too large");\n }\n return;\n }\n throw error;\n }\n const { decoded, byteLength } = envelope;\n if (decoded.ok && decoded.frame.type === "attempt_superseded" && hasMatchingAttempt(this.config, decoded.frame)) {\n this.callbacks.acceptSupersession(decoded.frame.reason ?? "attempt_superseded");\n return;\n }\n if (connection.pendingInboundFrames + 1 > SUPERVISOR_MAX_PENDING_INBOUND_FRAMES || connection.pendingInboundBytes + byteLength > SUPERVISOR_MAX_PENDING_INBOUND_BYTES || this.pendingInboundFrames + 1 > SUPERVISOR_MAX_PENDING_INBOUND_FRAMES || this.pendingInboundBytes + byteLength > SUPERVISOR_MAX_PENDING_INBOUND_BYTES) {\n connection.failed = true;\n connection.socket.close(1013, "gateway inbound backpressure");\n return;\n }\n connection.pendingInboundFrames += 1;\n connection.pendingInboundBytes += byteLength;\n this.pendingInboundFrames += 1;\n this.pendingInboundBytes += byteLength;\n const handling = connection.inboundTail.then(() => this.handleGatewayMessage(connection, decoded)).then(() => void 0).catch((error) => {\n connection.failed = true;\n this.handleFrameFailure(connection, errorFromUnknown(error));\n }).finally(() => {\n connection.pendingInboundFrames -= 1;\n connection.pendingInboundBytes -= byteLength;\n this.pendingInboundFrames -= 1;\n this.pendingInboundBytes -= byteLength;\n });\n connection.inboundTail = handling;\n });\n socket.addEventListener("error", () => {\n if (this.isActiveConnection(connection)) {\n connection.socket.close(1011, "transport error");\n }\n });\n socket.addEventListener("close", () => {\n if (!this.isActiveConnection(connection)) return;\n this.clearConnectionTimers(connection);\n this.connection = null;\n this.scheduleReconnect();\n });\n }\n async handleGatewayMessage(connection, decoded) {\n if (!this.isActiveConnection(connection) || this.stopping || connection.failed) return;\n if (!decoded.ok) {\n await this.callbacks.emitEvent({ kind: "protocol_error", message: decoded.error });\n return;\n }\n const frame = decoded.frame;\n if (!hasMatchingAttempt(this.config, frame)) {\n connection.failed = true;\n connection.socket.close(1008, "attempt fence mismatch");\n return;\n }\n await this.handleGatewayFrame(connection, frame);\n }\n async handleGatewayFrame(connection, frame) {\n if (frame.type === "resume_ok") {\n if (connection.resumed) {\n this.rejectGatewayCursor(connection);\n return;\n }\n if (frame.acknowledgedEventSequence > this.store.lastEventSequence || frame.acknowledgedEventSequence < this.store.lastAcknowledgedEventSequence) {\n this.rejectGatewayCursor(connection);\n return;\n }\n const pendingCommands = [...frame.pendingCommands].sort(\n (left, right) => left.commandSequence - right.commandSequence\n );\n const resumeBatchToken = await this.commands.prepareResumeBatch(\n pendingCommands,\n frame.lastAppliedCommandSequence\n );\n let committed = false;\n try {\n if (!this.isActiveConnection(connection) || this.executionGate.isClosed) return;\n await this.store.acknowledgeEvents(frame.acknowledgedEventSequence);\n if (!this.isActiveConnection(connection) || this.executionGate.isClosed) return;\n await this.store.advanceCommandCursor(frame.lastAppliedCommandSequence);\n if (!this.isActiveConnection(connection) || this.executionGate.isClosed) return;\n committed = await this.commands.commitResumeBatch(\n resumeBatchToken,\n () => this.isActiveConnection(connection) && !this.executionGate.isClosed\n );\n } finally {\n if (!committed) await this.commands.abortResumeBatch(resumeBatchToken);\n }\n if (!committed || !this.isActiveConnection(connection) || this.executionGate.isClosed) {\n return;\n }\n if (connection.handshakeTimer) clearTimeout(connection.handshakeTimer);\n connection.handshakeTimer = null;\n connection.resumed = true;\n connection.transmittedEventSequence = frame.acknowledgedEventSequence;\n this.reconnectAttempt = 0;\n this.startHeartbeat(connection);\n this.flushOutbox(connection);\n return;\n }\n if (frame.type === "event_ack") {\n if (!connection.resumed || frame.acknowledgedEventSequence > connection.transmittedEventSequence) {\n this.rejectGatewayCursor(connection);\n return;\n }\n await this.store.acknowledgeEvents(frame.acknowledgedEventSequence);\n if (this.isActiveConnection(connection)) this.flushOutbox(connection);\n return;\n }\n if (frame.type === "command") {\n if (!connection.resumed) {\n await this.callbacks.emitEvent({\n kind: "protocol_error",\n message: "Gateway delivered a command before resume_ok."\n });\n return;\n }\n await this.commands.enqueue(frame);\n return;\n }\n if (frame.type === "attempt_superseded") {\n this.callbacks.acceptSupersession(frame.reason ?? "attempt_superseded");\n }\n }\n handleFrameFailure(connection, error) {\n if (!this.isActiveConnection(connection)) return;\n if (this.executionGate.isClosed) {\n connection.socket.close(1008, "supervisor execution closed");\n return;\n }\n void this.callbacks.emitEvent({\n kind: "protocol_error",\n message: this.redactor.redact(\n `Failed to process gateway frame: ${serializeSupervisorError(error).message}`\n )\n }).then(\n () => connection.socket.close(1011, "frame processing failed"),\n () => connection.socket.close(1011, "frame processing failed")\n );\n }\n rejectGatewayCursor(connection) {\n connection.failed = true;\n if (this.isActiveConnection(connection)) {\n connection.socket.close(1008, "invalid event cursor");\n }\n }\n startHeartbeat(connection) {\n if (connection.heartbeatTimer) clearInterval(connection.heartbeatTimer);\n this.sendHeartbeat(connection);\n connection.heartbeatTimer = setInterval(() => {\n if (!this.isActiveConnection(connection)) return;\n if (this.dependencies.now() - connection.lastGatewayActivityAt > this.config.heartbeatIntervalMs * 3) {\n connection.socket.close(4001, "gateway heartbeat stale");\n return;\n }\n this.sendHeartbeat(connection);\n this.flushOutbox(connection);\n }, this.config.heartbeatIntervalMs);\n }\n sendHeartbeat(connection) {\n if (!this.isActiveConnection(connection) || connection.failed || !connection.resumed || connection.socket.readyState !== WEBSOCKET_OPEN || connection.socket.bufferedAmount > MAX_WEBSOCKET_BUFFERED_BYTES) {\n return;\n }\n const heartbeat = {\n type: "heartbeat",\n protocolVersion: SUPERVISOR_PROTOCOL_VERSION,\n runtimeVersion: SUPERVISOR_RUNTIME_VERSION,\n sessionId: this.config.sessionId,\n runId: this.config.runId,\n attemptId: this.config.attemptId,\n sentAt: (/* @__PURE__ */ new Date()).toISOString(),\n harnessState: this.harness.state,\n outboxDepth: this.store.outboxDepth,\n lastAcknowledgedEventSequence: this.store.lastAcknowledgedEventSequence,\n lastAppliedCommandSequence: this.store.lastAppliedCommandSequence\n };\n try {\n connection.socket.send(JSON.stringify(heartbeat));\n } catch {\n connection.socket.close(1011, "heartbeat send failed");\n }\n }\n clearConnectionTimers(connection) {\n if (!connection) return;\n if (connection.handshakeTimer) clearTimeout(connection.handshakeTimer);\n if (connection.heartbeatTimer) clearInterval(connection.heartbeatTimer);\n connection.handshakeTimer = null;\n connection.heartbeatTimer = null;\n }\n isActiveConnection(connection) {\n return connection !== null && this.connection === connection && this.connection.generation === connection.generation;\n }\n scheduleReconnect() {\n if (this.stopping || this.executionGate.isClosed || this.reconnectTimer) return;\n const exponential = this.config.reconnect.initialDelayMs * this.config.reconnect.multiplier ** this.reconnectAttempt;\n const capped = Math.min(exponential, this.config.reconnect.maximumDelayMs);\n const jitter = capped * this.config.reconnect.jitterRatio;\n const delayMs = Math.max(\n 0,\n Math.round(capped - jitter + this.dependencies.random() * jitter * 2)\n );\n this.reconnectAttempt += 1;\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = null;\n try {\n this.connect();\n } catch (error) {\n if (this.stopping || this.executionGate.isClosed) return;\n this.callbacks.failTransport(errorFromUnknown(error));\n }\n }, delayMs);\n }\n};\n\n// src/supervisor/pi-sdk-harness.ts\nimport {\n constants as constants2,\n fstatSync,\n readSync,\n writeSync\n} from "node:fs";\nimport {\n lstat,\n mkdir as mkdir3,\n realpath as realpath2\n} from "node:fs/promises";\nimport { basename, dirname as dirname3, join as join4 } from "node:path";\nimport { types as nodeUtilTypes } from "node:util";\n\n// src/supervisor/pi-resource-snapshot-manager.ts\nimport { randomUUID as randomUUID3 } from "node:crypto";\nimport { constants } from "node:fs";\nimport {\n mkdir as mkdir2,\n opendir as opendir2,\n realpath,\n rm\n} from "node:fs/promises";\nimport { dirname as dirname2, join as join3 } from "node:path";\nvar DEFAULT_PI_RESOURCE_SNAPSHOT_LIMITS = {\n maximumFileBytes: 16 * 1024 * 1024,\n maximumTreeBytes: 64 * 1024 * 1024,\n maximumFiles: 4096,\n maximumDirectories: 1024,\n maximumDepth: 32,\n maximumRetainedGenerations: 8\n};\nvar DEFAULT_RESOURCE_SNAPSHOT_DEPENDENCIES = {};\nvar PI_RESOURCE_SNAPSHOT_ROOT = ".neckbeard-resource-snapshots";\nfunction resolvePiResourceSnapshotLimits(overrides) {\n const limits = { ...DEFAULT_PI_RESOURCE_SNAPSHOT_LIMITS, ...overrides };\n for (const [name, value] of Object.entries(limits)) {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw new Error(\n `Pi resource snapshot ${name} must be a positive integer.`\n );\n }\n }\n return limits;\n}\nfunction capturePiResourceSnapshotIdentity(stats) {\n return {\n device: stats.dev,\n inode: stats.ino,\n mode: stats.mode,\n uid: stats.uid,\n gid: stats.gid,\n linkCount: stats.nlink,\n size: stats.size,\n modifiedAt: stats.mtimeNs,\n changedAt: stats.ctimeNs\n };\n}\nfunction matchesPiResourceSnapshotIdentity(stats, identity) {\n return stats.dev === identity.device && stats.ino === identity.inode && stats.mode === identity.mode && stats.uid === identity.uid && stats.gid === identity.gid && stats.nlink === identity.linkCount && stats.size === identity.size && stats.mtimeNs === identity.modifiedAt && stats.ctimeNs === identity.changedAt;\n}\nasync function openPiResourceDirectory(parent, name, displayPath, expectedIdentity) {\n try {\n const directory = await openDescriptorBoundFilesystemDirectoryAt(\n { handle: parent, displayPath: dirname2(displayPath) },\n name,\n expectedIdentity\n );\n return directory.handle;\n } catch (error) {\n if (error.message.startsWith("Pi agent resource ")) throw error;\n throw new Error(\n `Pi agent resource ${displayPath} must be a real directory.`,\n {\n cause: error\n }\n );\n }\n}\nasync function assertPiResourceDirectoryEntryUnchanged(parent, name, expected, displayPath) {\n let current = null;\n try {\n const expectedStats = await expected.stat({ bigint: true });\n current = await openPiResourceDirectory(parent, name, displayPath, {\n device: expectedStats.dev,\n inode: expectedStats.ino\n });\n } catch (error) {\n throw new Error(\n `Pi resource snapshot directory ${displayPath} changed while it was being created.`,\n { cause: error }\n );\n } finally {\n await current?.close();\n }\n}\nasync function assertPiResourceFileEntryUnchanged(parent, name, expected, displayPath) {\n let current = null;\n try {\n current = await openRegularFilesystemEntryAt(\n { handle: parent },\n name,\n constants.O_RDONLY,\n `Pi resource snapshot file ${displayPath}`\n );\n if (!await matchesRetainedRegularFileIdentity(expected, current)) {\n throw new Error("file identity changed");\n }\n } catch (error) {\n throw new Error(\n `Pi resource snapshot file ${displayPath} changed while it was being created.`,\n { cause: error }\n );\n } finally {\n await current?.close();\n }\n}\nasync function assertPiResourceSnapshotNamespace(directory, manifest, displayPath) {\n try {\n const before = await directory.stat({ bigint: true });\n if (!before.isDirectory() || !matchesPiResourceSnapshotIdentity(before, manifest.identity)) {\n throw new Error("directory identity changed");\n }\n const seen = /* @__PURE__ */ new Set();\n const entries = await opendir2(descriptorBoundDirectoryPath({ handle: directory }));\n for await (const entry of entries) {\n const expected = manifest.entries.get(entry.name);\n if (expected === void 0 || seen.has(entry.name)) {\n throw new Error("directory contains an unvalidated entry");\n }\n seen.add(entry.name);\n const entryPath = join3(displayPath, entry.name);\n if (expected.kind === "directory") {\n const child = await openPiResourceDirectory(\n directory,\n entry.name,\n entryPath\n );\n try {\n await assertPiResourceSnapshotNamespace(\n child,\n expected.manifest,\n entryPath\n );\n } finally {\n await child.close();\n }\n } else {\n const child = await openRegularFilesystemEntryAt(\n { handle: directory },\n entry.name,\n constants.O_RDONLY,\n `Pi resource snapshot file ${entryPath}`\n );\n try {\n const stats = await child.stat({ bigint: true });\n if (!stats.isFile() || !matchesPiResourceSnapshotIdentity(stats, expected.identity)) {\n throw new Error("file identity changed");\n }\n } finally {\n await child.close();\n }\n }\n }\n if (seen.size !== manifest.entries.size) {\n throw new Error("directory is missing a validated entry");\n }\n const after = await directory.stat({ bigint: true });\n if (!after.isDirectory() || !matchesPiResourceSnapshotIdentity(after, manifest.identity)) {\n throw new Error("directory changed during validation");\n }\n } catch (error) {\n if (error instanceof Error && error.message.startsWith("Pi resource snapshot directory ") && error.message.endsWith(" changed while it was being created.")) {\n throw error;\n }\n throw new Error(\n `Pi resource snapshot directory ${displayPath} changed while it was being created.`,\n { cause: error }\n );\n }\n}\nasync function copyPiResourceDirectory(source, sourcePath, destination, destinationPath, dependencies, budget, depth) {\n if (depth >= budget.limits.maximumDepth) {\n throw new Error(\n `Pi agent resource directory ${sourcePath} exceeds the ${budget.limits.maximumDepth}-directory depth limit.`\n );\n }\n const sourceBefore = await source.stat({ bigint: true });\n const destinationEntries = /* @__PURE__ */ new Map();\n const entries = await opendir2(descriptorBoundDirectoryPath({ handle: source }));\n for await (const entry of entries) {\n const sourceEntryPath = join3(sourcePath, entry.name);\n const destinationEntryPath = join3(destinationPath, entry.name);\n if (entry.isSymbolicLink()) {\n throw new Error(\n `Pi agent resource ${sourceEntryPath} must not be a symbolic link.`\n );\n }\n if (entry.isDirectory()) {\n budget.directories += 1;\n if (budget.directories > budget.limits.maximumDirectories) {\n throw new Error(\n `Pi agent resource tree exceeds the ${budget.limits.maximumDirectories}-directory limit.`\n );\n }\n const child = await openPiResourceDirectory(\n source,\n entry.name,\n sourceEntryPath\n );\n let destinationChild = null;\n try {\n await dependencies.afterSourceDirectoryOpened?.(sourceEntryPath);\n await mkdir2(descriptorBoundFilesystemEntryPath({ handle: destination }, entry.name), {\n mode: 448\n });\n destinationChild = await openPiResourceDirectory(\n destination,\n entry.name,\n destinationEntryPath\n );\n await dependencies.afterDestinationDirectoryOpened?.(\n sourceEntryPath,\n destinationEntryPath\n );\n const childEntries = await copyPiResourceDirectory(\n child,\n sourceEntryPath,\n destinationChild,\n destinationEntryPath,\n dependencies,\n budget,\n depth + 1\n );\n await destinationChild.chmod(320);\n await assertPiResourceDirectoryEntryUnchanged(\n destination,\n entry.name,\n destinationChild,\n destinationEntryPath\n );\n destinationEntries.set(entry.name, {\n kind: "directory",\n manifest: {\n identity: capturePiResourceSnapshotIdentity(\n await destinationChild.stat({ bigint: true })\n ),\n entries: childEntries\n }\n });\n } finally {\n await destinationChild?.close();\n await child.close();\n }\n continue;\n }\n if (!entry.isFile()) {\n throw new Error(\n `Pi agent resource ${sourceEntryPath} must be a regular file or directory.`\n );\n }\n budget.files += 1;\n if (budget.files > budget.limits.maximumFiles) {\n throw new Error(\n `Pi agent resource tree exceeds the ${budget.limits.maximumFiles}-file limit.`\n );\n }\n const input = await openRegularFilesystemEntryAt(\n { handle: source },\n entry.name,\n constants.O_RDONLY,\n `Pi agent resource ${sourceEntryPath}`\n );\n try {\n const inputBefore = await input.stat({ bigint: true });\n if (inputBefore.size > BigInt(budget.limits.maximumFileBytes)) {\n throw new Error(\n `Pi agent resource ${sourceEntryPath} exceeds the ${budget.limits.maximumFileBytes}-byte per-file limit.`\n );\n }\n const declaredSizeBytes = Number(inputBefore.size);\n if (budget.bytes + declaredSizeBytes > budget.limits.maximumTreeBytes) {\n throw new Error(\n `Pi agent resource tree exceeds the ${budget.limits.maximumTreeBytes}-byte limit.`\n );\n }\n budget.bytes += declaredSizeBytes;\n await dependencies.afterSourceFileStat?.(\n sourceEntryPath,\n declaredSizeBytes\n );\n const output = await openRegularFilesystemEntryAt(\n { handle: destination },\n entry.name,\n constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY,\n `Pi resource snapshot file ${destinationEntryPath}`,\n 384\n );\n try {\n let position = 0;\n const buffer = Buffer.allocUnsafe(64 * 1024);\n while (position <= declaredSizeBytes) {\n const remaining = declaredSizeBytes + 1 - position;\n const { bytesRead } = await input.read(\n buffer,\n 0,\n Math.min(buffer.length, remaining),\n null\n );\n if (bytesRead === 0) break;\n if (position + bytesRead > declaredSizeBytes) {\n throw new Error(\n `Pi agent resource ${sourceEntryPath} changed while it was being snapshotted.`\n );\n }\n let written = 0;\n while (written < bytesRead) {\n const result = await output.write(\n buffer,\n written,\n bytesRead - written,\n position\n );\n if (result.bytesWritten <= 0) {\n throw new Error(\n `Pi agent resource ${sourceEntryPath} could not be copied.`\n );\n }\n written += result.bytesWritten;\n position += result.bytesWritten;\n }\n }\n if (position !== declaredSizeBytes) {\n throw new Error(\n `Pi agent resource ${sourceEntryPath} changed while it was being snapshotted.`\n );\n }\n await output.sync();\n const snapshotMode = (inputBefore.mode & 0o111n) === 0n ? 256 : 320;\n await output.chmod(snapshotMode);\n await assertPiResourceFileEntryUnchanged(\n destination,\n entry.name,\n output,\n destinationEntryPath\n );\n const inputAfter = await input.stat({ bigint: true });\n if (inputBefore.dev !== inputAfter.dev || inputBefore.ino !== inputAfter.ino || inputBefore.size !== inputAfter.size || inputBefore.mtimeNs !== inputAfter.mtimeNs || inputBefore.ctimeNs !== inputAfter.ctimeNs) {\n throw new Error(\n `Pi agent resource ${sourceEntryPath} changed while it was being snapshotted.`\n );\n }\n destinationEntries.set(entry.name, {\n kind: "file",\n identity: capturePiResourceSnapshotIdentity(\n await output.stat({ bigint: true })\n )\n });\n } finally {\n await output.close();\n }\n } finally {\n await input.close();\n }\n }\n const sourceAfter = await source.stat({ bigint: true });\n if (sourceBefore.dev !== sourceAfter.dev || sourceBefore.ino !== sourceAfter.ino || sourceBefore.mtimeNs !== sourceAfter.mtimeNs || sourceBefore.ctimeNs !== sourceAfter.ctimeNs) {\n throw new Error(\n `Pi agent resource directory ${sourcePath} changed while it was being snapshotted.`\n );\n }\n return destinationEntries;\n}\nasync function bindAgentResourceRoot(agentDir, expectedIdentity) {\n let root;\n try {\n root = await openDescriptorBoundDirectory(\n agentDir,\n expectedIdentity === void 0 ? void 0 : {\n device: expectedIdentity.device,\n inode: expectedIdentity.inode\n }\n );\n } catch (error) {\n if (expectedIdentity !== void 0 && error instanceof Error && error.message === `${agentDir} must continue to identify its original directory.`) {\n throw new Error(\n `Pi agent resource root ${agentDir} must continue to identify its original directory.`,\n { cause: error }\n );\n }\n throw new Error(\n `Pi agent resource root ${agentDir} must be a real directory.`,\n {\n cause: error\n }\n );\n }\n let identity;\n let retainRootHandle = false;\n try {\n const physicalPath = await realpath(descriptorBoundDirectoryPath(root));\n identity = {\n physicalPath,\n device: root.identity.device,\n inode: root.identity.inode,\n handle: root.handle,\n authHandle: null\n };\n if (expectedIdentity !== void 0 && physicalPath !== expectedIdentity.physicalPath) {\n throw new Error(\n `Pi agent resource root ${agentDir} must continue to identify its original directory.`\n );\n }\n if (expectedIdentity === void 0) retainRootHandle = true;\n return expectedIdentity ?? identity;\n } finally {\n if (!retainRootHandle) {\n await root.handle.close();\n }\n }\n}\nasync function adoptAgentResourceRoot(agentDir, directory) {\n try {\n const stats = await directory.handle.stat({ bigint: true });\n const expectedUid = typeof process.getuid === "function" ? BigInt(process.getuid()) : null;\n if (!stats.isDirectory() || expectedUid !== null && BigInt(stats.uid) !== expectedUid) {\n throw new Error(\n `Pi agent resource root ${agentDir} must be a process-owned real directory.`\n );\n }\n await directory.handle.chmod(448);\n await directory.handle.sync();\n const privateStats = await directory.handle.stat({ bigint: true });\n if (!privateStats.isDirectory() || (privateStats.mode & 0o777n) !== 0o700n || privateStats.dev !== stats.dev || privateStats.ino !== stats.ino || expectedUid !== null && privateStats.uid !== expectedUid) {\n throw new Error(\n `Pi agent resource root ${agentDir} must remain a process-owned private writable directory.`\n );\n }\n return {\n physicalPath: await realpath(descriptorBoundDirectoryPath(directory)),\n device: stats.dev,\n inode: stats.ino,\n handle: directory.handle,\n authHandle: null\n };\n } catch (error) {\n await directory.handle.close().catch(() => void 0);\n throw error;\n }\n}\nasync function openPiResourceSnapshotRoot(stateDurabilityAnchor, stateDir, attemptId, dependencies) {\n const parentPath = join3(stateDir, PI_RESOURCE_SNAPSHOT_ROOT);\n let parentDirectory;\n try {\n parentDirectory = await ensureDescriptorBoundDirectory(\n stateDurabilityAnchor,\n parentPath,\n 448\n );\n } catch (error) {\n throw new Error(\n `Pi resource snapshot parent ${parentPath} must be a real directory.`,\n { cause: error }\n );\n }\n const parentHandle = parentDirectory.handle;\n const path = descriptorBoundEntryPath(parentDirectory, attemptId);\n let handle = null;\n try {\n await dependencies.afterSnapshotParentBound?.(parentPath);\n const parentStats = await parentHandle.stat();\n if (!parentStats.isDirectory()) {\n throw new Error(\n `Pi resource snapshot parent ${parentPath} must be a real directory.`\n );\n }\n await parentHandle.chmod(448);\n const staleDirectory = await openDescriptorBoundDirectoryAt(\n parentDirectory,\n attemptId\n ).catch((error) => {\n if (error.code === "ENOENT") return null;\n throw error;\n });\n if (staleDirectory !== null) {\n try {\n await makePiResourceSnapshotRemovable(staleDirectory.handle);\n } finally {\n await staleDirectory.handle.close();\n }\n await rm(path, { recursive: true, force: true });\n }\n await mkdir2(path, { mode: 448 });\n handle = (await openDescriptorBoundDirectoryAt(parentDirectory, attemptId)).handle;\n await handle.chmod(448);\n return { entryName: attemptId, handle, parentHandle };\n } catch (error) {\n await handle?.close().catch(() => void 0);\n await parentHandle.close();\n throw error;\n }\n}\nasync function preparePiRuntimeAuth(agentRoot, dependencies, maximumBytes) {\n const displayPath = join3(agentRoot.physicalPath, "auth.json");\n let sourceHandle = null;\n let retained = false;\n try {\n let created = false;\n try {\n sourceHandle = await openRegularFileAt(\n { handle: agentRoot.handle },\n "auth.json",\n constants.O_RDWR | constants.O_CREAT | constants.O_EXCL,\n "Pi auth path",\n 384\n );\n created = true;\n } catch (error) {\n if (error.code !== "EEXIST") {\n throw new Error(\n `Pi auth path ${displayPath} must be a process-owned single-link regular file.`,\n { cause: error }\n );\n }\n try {\n sourceHandle = await openRegularFileAt(\n { handle: agentRoot.handle },\n "auth.json",\n constants.O_RDWR,\n "Pi auth path"\n );\n } catch (openError) {\n throw new Error(\n `Pi auth path ${displayPath} must be a process-owned single-link regular file.`,\n { cause: openError }\n );\n }\n }\n const before = await sourceHandle.stat({ bigint: true });\n const expectedUid = typeof process.getuid === "function" ? BigInt(process.getuid()) : null;\n if (!before.isFile() || before.nlink !== 1n || before.size > BigInt(maximumBytes) || expectedUid !== null && before.uid !== expectedUid) {\n throw new Error(\n `Pi auth path ${displayPath} must be a process-owned single-link regular file within the configured size limit.`\n );\n }\n if (created) await sourceHandle.writeFile("{}\\n", "utf8");\n await sourceHandle.chmod(384);\n await sourceHandle.sync();\n await agentRoot.handle.sync();\n await dependencies.afterAuthSourceOpened?.(displayPath);\n try {\n await withRevalidatedPrivateRegularFile(\n sourceHandle,\n () => openRegularFileAt(\n { handle: agentRoot.handle },\n "auth.json",\n constants.O_RDONLY,\n "Pi auth path"\n ),\n () => void 0,\n { maximumBytes, failureMessage: "auth file identity changed" }\n );\n } catch (error) {\n throw new Error(\n `Pi auth path ${displayPath} changed while its descriptor binding was created.`,\n { cause: error }\n );\n }\n agentRoot.authHandle = sourceHandle;\n sourceHandle = null;\n retained = true;\n } finally {\n if (!retained) {\n await sourceHandle?.close().catch(() => void 0);\n }\n }\n}\nasync function assertPiRuntimeAuthReady(agentRoot, maximumBytes) {\n const retained = agentRoot.authHandle;\n if (retained === null) {\n throw new Error("Pi runtime auth has not been prepared.");\n }\n try {\n await withRevalidatedPrivateRegularFile(\n retained,\n () => openRegularFileAt(\n { handle: agentRoot.handle },\n "auth.json",\n constants.O_RDONLY,\n "Pi auth path"\n ),\n () => void 0,\n { maximumBytes, failureMessage: "auth file identity changed" }\n );\n } catch (error) {\n throw new Error(\n `Pi auth path ${join3(agentRoot.physicalPath, "auth.json")} changed before SDK use.`,\n { cause: error }\n );\n }\n}\nasync function createPiResourceSnapshot(agentDir, rootIdentity, snapshotRoot, dependencies, limits) {\n const source = await bindAgentResourceRoot(agentDir, rootIdentity);\n const generation = randomUUID3();\n const snapshotPath = descriptorBoundEntryPath({ handle: snapshotRoot.handle }, generation);\n let snapshotHandle = null;\n await snapshotRoot.handle.chmod(448);\n try {\n await mkdir2(snapshotPath, { mode: 448 });\n snapshotHandle = await openPiResourceDirectory(\n snapshotRoot.handle,\n generation,\n snapshotPath\n );\n const entries = await copyPiResourceDirectory(\n source.handle,\n agentDir,\n snapshotHandle,\n snapshotPath,\n dependencies,\n { limits, files: 0, directories: 1, bytes: 0 },\n 0\n );\n await snapshotHandle.chmod(320);\n const manifest = {\n identity: capturePiResourceSnapshotIdentity(\n await snapshotHandle.stat({ bigint: true })\n ),\n entries\n };\n await assertPiResourceDirectoryEntryUnchanged(\n snapshotRoot.handle,\n generation,\n snapshotHandle,\n snapshotPath\n );\n await assertPiResourceSnapshotNamespace(\n snapshotHandle,\n manifest,\n snapshotPath\n );\n await assertPiResourceDirectoryEntryUnchanged(\n snapshotRoot.handle,\n generation,\n snapshotHandle,\n snapshotPath\n );\n await snapshotRoot.handle.chmod(320);\n return { entryName: generation, handle: snapshotHandle, manifest };\n } catch (error) {\n if (snapshotHandle !== null) {\n await makePiResourceSnapshotRemovable(snapshotHandle).catch(\n () => void 0\n );\n await snapshotHandle.close().catch(() => void 0);\n }\n await rm(snapshotPath, { recursive: true, force: true }).catch(\n () => void 0\n );\n await snapshotRoot.handle.chmod(320).catch(() => void 0);\n throw error;\n }\n}\nasync function makePiResourceSnapshotRemovable(handle) {\n const entries = await opendir2(descriptorBoundDirectoryPath({ handle }));\n for await (const entry of entries) {\n if (!entry.isDirectory() || entry.isSymbolicLink()) continue;\n const child = await openPiResourceDirectory(\n handle,\n entry.name,\n descriptorBoundFilesystemEntryPath({ handle }, entry.name)\n );\n try {\n await makePiResourceSnapshotRemovable(child);\n await child.chmod(448);\n } finally {\n await child.close();\n }\n }\n await handle.chmod(448);\n}\nasync function removePiResourceSnapshot(snapshotRoot, snapshot) {\n await snapshotRoot.handle.chmod(448);\n let failure;\n await makePiResourceSnapshotRemovable(snapshot.handle).catch(\n (error) => {\n failure ??= error;\n }\n );\n await snapshot.handle.close().catch((error) => {\n failure ??= error;\n });\n await rm(descriptorBoundEntryPath({ handle: snapshotRoot.handle }, snapshot.entryName), {\n recursive: true,\n force: true\n }).catch((error) => {\n failure ??= error;\n });\n await snapshotRoot.handle.chmod(320).catch((error) => {\n failure ??= error;\n });\n if (failure !== void 0) throw failure;\n}\nvar piResourceReloadTail = Promise.resolve();\nasync function withContainedPiResourceHome(agentDir, rootIdentity, snapshotRoot, retainedSnapshots, dependencies, limits, lifecycle, operation, preparedSnapshot) {\n const run = async () => {\n if (lifecycle.closed) {\n throw new Error("Pi resource snapshot manager is closed.");\n }\n let snapshot = preparedSnapshot;\n let createdSnapshot = false;\n if (snapshot === void 0) {\n if (retainedSnapshots.length >= limits.maximumRetainedGenerations) {\n throw new Error(\n `Pi resource reload exceeds the ${limits.maximumRetainedGenerations}-generation retention limit.`\n );\n }\n snapshot = await createPiResourceSnapshot(\n agentDir,\n rootIdentity,\n snapshotRoot,\n dependencies,\n limits\n );\n createdSnapshot = true;\n }\n const previousHome = process.env.HOME;\n const snapshotPath = descriptorBoundDirectoryPath({ handle: snapshot.handle });\n try {\n await dependencies.beforeSnapshotUse?.(snapshotPath);\n await assertPiResourceSnapshotNamespace(\n snapshot.handle,\n snapshot.manifest,\n snapshotPath\n );\n if (lifecycle.closed) {\n throw new Error("Pi resource snapshot manager is closed.");\n }\n process.env.HOME = snapshotPath;\n const result2 = await operation(snapshotPath);\n if (createdSnapshot) retainedSnapshots.push(snapshot);\n return result2;\n } catch (error) {\n if (createdSnapshot) {\n await removePiResourceSnapshot(snapshotRoot, snapshot).catch(\n () => void 0\n );\n }\n throw error;\n } finally {\n if (previousHome === void 0) delete process.env.HOME;\n else process.env.HOME = previousHome;\n }\n };\n const result = piResourceReloadTail.then(run, run);\n piResourceReloadTail = result.then(\n () => void 0,\n () => void 0\n );\n return result;\n}\nvar PI_RESOURCE_LOADER_METHODS = [\n "getExtensions",\n "getSkills",\n "getPrompts",\n "getThemes",\n "getAgentsFiles",\n "getSystemPrompt",\n "getSystemPromptSource",\n "getAppendSystemPrompt",\n "getAppendSystemPromptSources",\n "extendResources"\n];\nfunction containPiResourceLoader(createResourceLoader, agentDir, rootIdentity, snapshotRoot, retainedSnapshots, dependencies, limits, initialSnapshot, lifecycle) {\n let current = null;\n let preparedSnapshot = initialSnapshot;\n const wrapper = {\n reload: (...args) => {\n if (lifecycle.closed) {\n return Promise.reject(\n new Error("Pi resource snapshot manager is closed.")\n );\n }\n const snapshot = preparedSnapshot;\n preparedSnapshot = void 0;\n const reloading = withContainedPiResourceHome(\n agentDir,\n rootIdentity,\n snapshotRoot,\n retainedSnapshots,\n dependencies,\n limits,\n lifecycle,\n async (snapshotPath) => {\n const candidate = createResourceLoader(snapshotPath);\n await candidate.reload(...args);\n current = candidate;\n },\n snapshot\n );\n lifecycle.tail = Promise.allSettled([lifecycle.tail, reloading]).then(\n () => void 0\n );\n return reloading;\n }\n };\n for (const method of PI_RESOURCE_LOADER_METHODS) {\n wrapper[method] = (...args) => {\n if (current === null) {\n throw new Error(\n "Pi resource loader has not completed its initial reload."\n );\n }\n const candidate = current;\n const implementation = candidate[method];\n if (typeof implementation !== "function") {\n throw new Error(`Pi resource loader does not expose ${method}().`);\n }\n return Reflect.apply(implementation, current, args);\n };\n }\n return wrapper;\n}\nvar PiResourceSnapshotManager = class {\n constructor(options, dependencies = DEFAULT_RESOURCE_SNAPSHOT_DEPENDENCIES) {\n this.dependencies = dependencies;\n this.agentDir = options.agentDir;\n this.authPath = join3(options.agentDir, "auth.json");\n this.stateDir = options.stateDir;\n this.stateDurabilityAnchor = options.stateDurabilityAnchor;\n this.attemptId = options.attemptId;\n this.limits = resolvePiResourceSnapshotLimits(dependencies.limits);\n }\n dependencies;\n agentDir;\n authPath;\n stateDir;\n stateDurabilityAnchor;\n attemptId;\n limits;\n rootIdentity = null;\n snapshotRoot = null;\n retainedSnapshots = [];\n preparedSnapshot = null;\n loaderCreated = false;\n reloadLifecycle = {\n closed: false,\n tail: Promise.resolve()\n };\n closePromise = null;\n get runtimeAgentDir() {\n const snapshot = this.retainedSnapshots[0];\n if (snapshot === void 0) {\n throw new Error("Pi resource snapshot manager has not been prepared.");\n }\n return descriptorBoundDirectoryPath({ handle: snapshot.handle });\n }\n get runtimeAuthPath() {\n const identity = this.rootIdentity;\n if (identity?.authHandle === null || identity === null) {\n throw new Error("Pi resource snapshot manager has not been prepared.");\n }\n return descriptorBoundEntryPath({ handle: identity.handle }, "auth.json");\n }\n async validateRuntimeAuth() {\n const identity = this.rootIdentity;\n if (identity === null) {\n throw new Error("Pi resource snapshot manager has not been prepared.");\n }\n await assertPiRuntimeAuthReady(identity, this.limits.maximumFileBytes);\n }\n async prepare() {\n if (this.reloadLifecycle.closed || this.rootIdentity !== null || this.snapshotRoot !== null || this.preparedSnapshot !== null) {\n throw new Error("Pi resource snapshot manager is already prepared.");\n }\n const snapshotParent = join3(this.stateDir, PI_RESOURCE_SNAPSHOT_ROOT);\n if (sandboxPathsOverlap(this.agentDir, snapshotParent)) {\n throw new Error(\n "Pi agent resource directory must not overlap its snapshot directory."\n );\n }\n const agentDirectory = await ensureDescriptorBoundDirectory(\n this.stateDurabilityAnchor,\n this.agentDir\n );\n let rootIdentity;\n try {\n await this.dependencies.afterAgentRootBound?.(this.agentDir);\n rootIdentity = await adoptAgentResourceRoot(\n this.agentDir,\n agentDirectory\n );\n } catch (error) {\n await agentDirectory.handle.close().catch(() => void 0);\n throw error;\n }\n this.rootIdentity = rootIdentity;\n const snapshotRoot = await openPiResourceSnapshotRoot(\n this.stateDurabilityAnchor,\n this.stateDir,\n this.attemptId,\n this.dependencies\n );\n this.snapshotRoot = snapshotRoot;\n await preparePiRuntimeAuth(\n rootIdentity,\n this.dependencies,\n this.limits.maximumFileBytes\n );\n const initialSnapshot = await createPiResourceSnapshot(\n this.agentDir,\n rootIdentity,\n snapshotRoot,\n this.dependencies,\n this.limits\n );\n this.retainedSnapshots.push(initialSnapshot);\n this.preparedSnapshot = initialSnapshot;\n }\n createResourceLoader(createResourceLoader) {\n if (this.loaderCreated) {\n throw new Error("Pi resource loader has already been created.");\n }\n const rootIdentity = this.rootIdentity;\n const snapshotRoot = this.snapshotRoot;\n const initialSnapshot = this.preparedSnapshot;\n if (rootIdentity === null || snapshotRoot === null || initialSnapshot === null) {\n throw new Error("Pi resource snapshot manager has not been prepared.");\n }\n this.loaderCreated = true;\n this.preparedSnapshot = null;\n return containPiResourceLoader(\n createResourceLoader,\n this.agentDir,\n rootIdentity,\n snapshotRoot,\n this.retainedSnapshots,\n this.dependencies,\n this.limits,\n initialSnapshot,\n this.reloadLifecycle\n );\n }\n async close() {\n if (this.closePromise !== null) return this.closePromise;\n this.reloadLifecycle.closed = true;\n const closing = this.closePreparedState();\n this.closePromise = closing;\n return closing;\n }\n async closePreparedState() {\n await this.reloadLifecycle.tail;\n const identity = this.rootIdentity;\n this.rootIdentity = null;\n const snapshotRoot = this.snapshotRoot;\n this.snapshotRoot = null;\n this.preparedSnapshot = null;\n const snapshots = this.retainedSnapshots.splice(0);\n let failure;\n for (const snapshot of snapshots) {\n try {\n await snapshot.handle.close();\n } catch (error) {\n failure ??= error;\n await snapshot.handle.close().catch(() => void 0);\n }\n }\n if (snapshotRoot !== null) {\n await makePiResourceSnapshotRemovable(snapshotRoot.handle).catch(\n (error) => {\n failure ??= error;\n }\n );\n await snapshotRoot.handle.close().catch((error) => {\n failure ??= error;\n });\n await rm(\n descriptorBoundEntryPath(\n { handle: snapshotRoot.parentHandle },\n snapshotRoot.entryName\n ),\n { recursive: true, force: true }\n ).catch((error) => {\n failure ??= error;\n });\n await snapshotRoot.parentHandle.close().catch((error) => {\n failure ??= error;\n });\n }\n if (identity?.authHandle !== null && identity !== null) {\n await identity.authHandle.sync().catch((error) => {\n failure ??= error;\n });\n await identity.authHandle.close().catch((error) => {\n failure ??= error;\n });\n identity.authHandle = null;\n await identity.handle.sync().catch((error) => {\n failure ??= error;\n });\n }\n await identity?.handle.close().catch((error) => {\n failure ??= error;\n });\n if (failure !== void 0) throw failure;\n }\n};\n\n// src/supervisor/pi-sdk-harness.ts\nvar MAX_PERSISTED_PI_EVENT_PAYLOAD_BYTES = 512 * 1024;\nvar MAX_TRUNCATED_PI_EVENT_PAYLOAD_BYTES = 32 * 1024;\nvar MAX_PI_EVENT_METADATA_STRING_LENGTH = 256;\nvar MAX_PI_EVENT_LIFECYCLE_STRING_LENGTH = 8 * 1024;\nvar MAX_PI_EVENT_LIFECYCLE_MESSAGE_SCAN = 4 * 1024;\nvar MAX_PI_EVENT_TRAVERSAL_DEPTH = 64;\nvar MAX_PI_EVENT_TRAVERSAL_NODES = MAX_PERSISTED_PI_EVENT_PAYLOAD_BYTES;\nvar MAX_PENDING_HARNESS_EVENTS = 256;\nvar MAX_PENDING_HARNESS_EVENT_BYTES = 8 * 1024 * 1024;\nvar PI_EVENT_SCALAR_METADATA_KEYS = [\n "type",\n "id",\n "eventId",\n "messageId",\n "toolCallId",\n "toolName",\n "role",\n "stopReason",\n "provider",\n "model",\n "timestamp",\n "contentIndex",\n "isError"\n];\nvar PI_EVENT_NESTED_METADATA_KEYS = [\n "assistantMessageEvent",\n "message",\n "usage",\n "result"\n];\nvar PI_EVENT_ARRAY_METADATA_KEYS = [\n "messages",\n "toolResults",\n "content"\n];\nvar SESSION_FILE_CREATE_FLAGS = constants2.O_RDWR | constants2.O_CREAT;\nvar PI_SESSION_FORMAT_VERSION = 3;\nvar MAX_PI_SESSION_HEADER_BYTES = 64 * 1024;\nfunction piSessionHistoryLimitError(limitBytes, context) {\n return new Error(\n `Pi session history ${context} the ${limitBytes}-byte per-attempt limit; start a replacement attempt.`\n );\n}\nfunction assertPiSessionHistorySize(stats, limitBytes, comparison, context) {\n const limit = BigInt(limitBytes);\n const exceeded = comparison === "at_or_above" ? stats.size >= limit : stats.size > limit;\n if (exceeded) throw piSessionHistoryLimitError(limitBytes, context);\n}\nfunction assertPiSessionHistoryReadyForSdkOpen(handle, displayPath) {\n const stats = fstatSync(handle.fd, { bigint: true });\n assertPiSessionHistorySize(\n stats,\n SUPERVISOR_MAX_PI_SESSION_HISTORY_BYTES,\n "above",\n "exceeds"\n );\n if (stats.size === 0n) return;\n const scanBytes = Math.min(\n Number(stats.size),\n MAX_PI_SESSION_HEADER_BYTES + 1\n );\n const buffer = Buffer.allocUnsafe(scanBytes);\n let offset = 0;\n while (offset < scanBytes) {\n const bytesRead = readSync(\n handle.fd,\n buffer,\n offset,\n scanBytes - offset,\n offset\n );\n if (bytesRead === 0) {\n throw new Error(\n `Pi session path ${displayPath} changed while its header was validated.`\n );\n }\n offset += bytesRead;\n }\n const newline = buffer.indexOf(10, 0);\n const headerBytes = newline === -1 ? offset : newline;\n if (headerBytes > MAX_PI_SESSION_HEADER_BYTES || newline === -1 && stats.size > BigInt(MAX_PI_SESSION_HEADER_BYTES)) {\n throw new Error(\n `Pi session path ${displayPath} has an oversized session header.`\n );\n }\n let source;\n try {\n source = new TextDecoder("utf-8", { fatal: true }).decode(\n buffer.subarray(0, headerBytes)\n );\n } catch (error) {\n throw new Error(\n `Pi session path ${displayPath} has an invalid session header.`,\n { cause: error }\n );\n }\n if (source.endsWith("\\r")) source = source.slice(0, -1);\n let header;\n try {\n header = JSON.parse(source);\n } catch (error) {\n throw new Error(\n `Pi session path ${displayPath} has an invalid session header.`,\n { cause: error }\n );\n }\n if (!isRecord5(header) || header.type !== "session" || header.version !== PI_SESSION_FORMAT_VERSION) {\n throw new Error(\n `Pi session path ${displayPath} must use current Pi session format version ${PI_SESSION_FORMAT_VERSION}; start a replacement attempt for legacy history.`\n );\n }\n}\nasync function openPiSessionFile(directory, name, displayPath, flags, mode) {\n try {\n return await openRegularFileAt(\n directory,\n name,\n flags,\n `Pi session path ${displayPath}`,\n mode\n );\n } catch (error) {\n if (error.code === "ELOOP") {\n throw new Error(\n `Pi session path ${displayPath} must not be a symbolic link.`,\n { cause: error }\n );\n }\n throw error;\n }\n}\nasync function preparePiSessionFile(directory, name, displayPath) {\n const handle = await openPiSessionFile(\n directory,\n name,\n displayPath,\n SESSION_FILE_CREATE_FLAGS,\n 384\n );\n try {\n const before = await handle.stat({ bigint: true });\n const expectedUid = typeof process.getuid === "function" ? BigInt(process.getuid()) : null;\n if (!before.isFile() || before.nlink !== 1n || expectedUid !== null && before.uid !== expectedUid) {\n throw new Error(\n `Pi session path ${displayPath} must be a process-owned single-link regular file.`\n );\n }\n assertPiSessionHistorySize(\n before,\n SUPERVISOR_MAX_PI_SESSION_HISTORY_BYTES,\n "above",\n "exceeds"\n );\n await handle.chmod(384);\n const after = await handle.stat({ bigint: true });\n if (!after.isFile() || after.dev !== before.dev || after.ino !== before.ino || after.nlink !== 1n || expectedUid !== null && after.uid !== expectedUid) {\n throw new Error(\n `Pi session path ${displayPath} must remain a process-owned single-link regular file.`\n );\n }\n assertPiSessionHistorySize(\n after,\n SUPERVISOR_MAX_PI_SESSION_HISTORY_BYTES,\n "above",\n "exceeds"\n );\n await handle.sync();\n await syncDescriptorBoundDirectory(directory);\n return handle;\n } catch (error) {\n await handle.close();\n throw error;\n }\n}\nasync function withPiSessionFileReady(directory, name, handle, displayPath, operation) {\n return withRevalidatedPrivateRegularFile(\n handle,\n () => openPiSessionFile(\n directory,\n name,\n displayPath,\n constants2.O_RDONLY\n ),\n // The helper keeps the matching path descriptor open and invokes this\n // synchronous SDK open without yielding after its final identity checks.\n operation,\n {\n maximumBytes: SUPERVISOR_MAX_PI_SESSION_HISTORY_BYTES,\n failureMessage: `Pi session path ${displayPath} must remain the process-owned single-link private regular file bound at startup.`\n }\n );\n}\nasync function assertWorkspaceIsolated(workspaceDir, stateDir) {\n const workspaceStats = await lstat(workspaceDir);\n if (workspaceStats.isSymbolicLink() || !workspaceStats.isDirectory()) {\n throw new Error(\n `Pi workspace path ${workspaceDir} must be a real directory.`\n );\n }\n const [physicalWorkspace, physicalState] = await Promise.all([\n realpath2(workspaceDir),\n realpath2(stateDir)\n ]);\n if (sandboxPathsOverlap(physicalWorkspace, physicalState)) {\n throw new Error(\n "Pi workspace and supervisor state directories must not physically overlap."\n );\n }\n}\nfunction hasCallableProperty(value, property) {\n if ((typeof value !== "object" || value === null || Array.isArray(value)) && typeof value !== "function") {\n return false;\n }\n return typeof value[property] === "function";\n}\nfunction attachFilesToMessage(input) {\n if (!input.attachments?.length) return input.message;\n const files = input.attachments.map((attachment) => `- ${attachment.path}`).join("\\n");\n return `${input.message}\n\nFiles available in the sandbox:\n${files}`;\n}\nfunction isCoalescedPiEvent(value) {\n if (typeof value !== "object" || value === null || nodeUtilTypes.isProxy(value)) {\n return false;\n }\n const event = value;\n if (readPiLifecycleProperty(event, "type") !== "message_update") return false;\n const assistantEvent = readPiLifecycleProperty(\n event,\n "assistantMessageEvent"\n );\n if (!isRecord5(assistantEvent) || nodeUtilTypes.isProxy(assistantEvent)) {\n return false;\n }\n const assistantEventType = readPiLifecycleProperty(assistantEvent, "type");\n return typeof assistantEventType === "string" && assistantEventType.endsWith("_delta");\n}\nfunction assertPiSdkModule(value) {\n if (!isRecord5(value) || !hasCallableProperty(value.ModelRuntime, "create") || !hasCallableProperty(value.SessionManager, "open") || !hasCallableProperty(value.SettingsManager, "inMemory") || typeof value.DefaultResourceLoader !== "function" || typeof value.createAgentSession !== "function") {\n throw new Error(\n "The configured Pi SDK module does not expose the required session API."\n );\n }\n}\nfunction assertPiSdkSession(value) {\n if (!isRecord5(value) || typeof value.sessionId !== "string" || typeof value.prompt !== "function" || typeof value.steer !== "function" || typeof value.abort !== "function" || typeof value.dispose !== "function" || typeof value.subscribe !== "function") {\n throw new Error("Pi createAgentSession returned an invalid session.");\n }\n}\nfunction assertPiSdkSessionManager(value) {\n const flushed = isRecord5(value) ? Object.getOwnPropertyDescriptor(value, "flushed") : void 0;\n if (!isRecord5(value) || flushed?.value !== true || typeof value._persist !== "function" || typeof value.getSessionFile !== "function") {\n throw new Error(\n "The configured Pi SDK SessionManager does not expose the pinned persistent-session API."\n );\n }\n}\nfunction boundedMetadataString(value) {\n if (value.length <= MAX_PI_EVENT_METADATA_STRING_LENGTH) return value;\n return `${value.slice(0, MAX_PI_EVENT_METADATA_STRING_LENGTH - 3)}...`;\n}\nfunction copyPiEventScalarMetadata(source, target) {\n if (nodeUtilTypes.isProxy(source)) return;\n for (const key of PI_EVENT_SCALAR_METADATA_KEYS) {\n const item = source[key];\n if (typeof item === "string") {\n target[key] = boundedMetadataString(item);\n } else if (item === null || typeof item === "boolean" || typeof item === "number" && Number.isFinite(item)) {\n target[key] = item;\n }\n }\n}\nfunction summarizePiEventMetadata(value) {\n if (!isRecord5(value) || nodeUtilTypes.isProxy(value)) return {};\n const summary = /* @__PURE__ */ Object.create(null);\n copyPiEventScalarMetadata(value, summary);\n for (const key of PI_EVENT_NESTED_METADATA_KEYS) {\n const item = value[key];\n if (!isRecord5(item) || nodeUtilTypes.isProxy(item)) continue;\n const nested = /* @__PURE__ */ Object.create(null);\n copyPiEventScalarMetadata(item, nested);\n if (Object.keys(nested).length > 0) summary[key] = nested;\n }\n for (const key of PI_EVENT_ARRAY_METADATA_KEYS) {\n const item = value[key];\n if (Array.isArray(item) && !nodeUtilTypes.isProxy(item)) {\n summary[`${key}Count`] = item.length;\n }\n }\n return summary;\n}\nfunction truncatedPiEvent(event, reason, redactor, originalPayloadBytes) {\n let metadata;\n try {\n metadata = redactJsonStrings(\n summarizePiEventMetadata(event),\n redactor\n );\n } catch {\n metadata = {};\n }\n const truncation = {\n truncated: true,\n reason,\n maxPayloadBytes: MAX_PERSISTED_PI_EVENT_PAYLOAD_BYTES,\n ...originalPayloadBytes === void 0 ? {} : { originalPayloadBytes }\n };\n const candidate = {\n ...metadata,\n neckbeardTruncation: truncation\n };\n if (Buffer.byteLength(JSON.stringify(candidate), "utf8") <= MAX_TRUNCATED_PI_EVENT_PAYLOAD_BYTES) {\n return candidate;\n }\n return {\n ...typeof metadata.type === "string" ? { type: metadata.type } : {},\n neckbeardTruncation: truncation\n };\n}\nfunction redactJsonStrings(value, redactor) {\n if (typeof value === "string") return redactor.redact(value);\n if (typeof value === "object" && value !== null && nodeUtilTypes.isProxy(value)) {\n return void 0;\n }\n if (Array.isArray(value))\n return value.map((item) => redactJsonStrings(item, redactor));\n if (!isRecord5(value)) return value;\n const redacted = /* @__PURE__ */ Object.create(null);\n for (const [key, item] of Object.entries(value)) {\n redacted[redactor.redact(key)] = redactJsonStrings(item, redactor);\n }\n return redacted;\n}\nvar PiEventTraversalLimitError = class extends Error {\n};\nvar PiEventSerializationError = class extends Error {\n};\nfunction consumePiEventTraversalNode(writer) {\n writer.visitedNodes += 1;\n if (writer.visitedNodes > MAX_PI_EVENT_TRAVERSAL_NODES) {\n throw new PiEventTraversalLimitError();\n }\n}\nfunction appendPiEventJson(writer, chunk) {\n const remainingBytes = MAX_PERSISTED_PI_EVENT_PAYLOAD_BYTES - writer.sizeBytes;\n if (chunk.length > remainingBytes) throw new PiEventTraversalLimitError();\n const chunkBytes = Buffer.byteLength(chunk, "utf8");\n if (chunkBytes > remainingBytes) throw new PiEventTraversalLimitError();\n writer.chunks.push(chunk);\n writer.sizeBytes += chunkBytes;\n}\nfunction appendRedactedPiEventString(writer, value) {\n const remainingBytes = MAX_PERSISTED_PI_EVENT_PAYLOAD_BYTES - writer.sizeBytes;\n if (value.length + 2 > remainingBytes)\n throw new PiEventTraversalLimitError();\n const redacted = writer.redactor.redact(value);\n if (redacted.length + 2 > remainingBytes)\n throw new PiEventTraversalLimitError();\n appendPiEventJson(writer, JSON.stringify(redacted));\n}\nfunction readPiEventProperty(value, key) {\n try {\n return Reflect.get(value, key);\n } catch {\n throw new PiEventSerializationError();\n }\n}\nfunction writePiEventJsonValue(writer, value, key, depth, applyToJson = true) {\n consumePiEventTraversalNode(writer);\n if (value === null) {\n appendPiEventJson(writer, "null");\n return true;\n }\n if (typeof value === "string") {\n appendRedactedPiEventString(writer, value);\n return true;\n }\n if (typeof value === "boolean") {\n appendPiEventJson(writer, value ? "true" : "false");\n return true;\n }\n if (typeof value === "number") {\n appendPiEventJson(writer, Number.isFinite(value) ? JSON.stringify(value) : "null");\n return true;\n }\n if (value === void 0 || typeof value === "function" || typeof value === "symbol") {\n return false;\n }\n if (typeof value === "bigint") {\n const boxed = Object(value);\n const toJSON = readPiEventProperty(boxed, "toJSON");\n if (typeof toJSON !== "function") throw new PiEventSerializationError();\n let normalized;\n try {\n normalized = Reflect.apply(toJSON, value, [key]);\n } catch {\n throw new PiEventSerializationError();\n }\n return writePiEventJsonValue(writer, normalized, key, depth, false);\n }\n if (typeof value !== "object") throw new PiEventSerializationError();\n if (depth > MAX_PI_EVENT_TRAVERSAL_DEPTH)\n throw new PiEventTraversalLimitError();\n if (nodeUtilTypes.isProxy(value)) throw new PiEventSerializationError();\n if (applyToJson) {\n const toJSON = readPiEventProperty(value, "toJSON");\n if (typeof toJSON === "function") {\n let normalized;\n try {\n normalized = Reflect.apply(toJSON, value, [key]);\n } catch {\n throw new PiEventSerializationError();\n }\n return writePiEventJsonValue(writer, normalized, key, depth, false);\n }\n }\n if (nodeUtilTypes.isNumberObject(value)) {\n return writePiEventJsonValue(writer, Number(value), key, depth, false);\n }\n if (nodeUtilTypes.isStringObject(value)) {\n return writePiEventJsonValue(writer, String(value), key, depth, false);\n }\n if (nodeUtilTypes.isBooleanObject(value)) {\n return writePiEventJsonValue(writer, Boolean(value.valueOf()), key, depth, false);\n }\n if (nodeUtilTypes.isBigIntObject(value)) {\n throw new PiEventSerializationError();\n }\n if (writer.activeObjects.has(value)) throw new PiEventSerializationError();\n writer.activeObjects.add(value);\n try {\n if (Array.isArray(value)) {\n appendPiEventJson(writer, "[");\n for (let index = 0; index < value.length; index += 1) {\n consumePiEventTraversalNode(writer);\n if (index > 0) appendPiEventJson(writer, ",");\n const item = readPiEventProperty(value, String(index));\n if (!writePiEventJsonValue(writer, item, String(index), depth + 1)) {\n appendPiEventJson(writer, "null");\n }\n }\n appendPiEventJson(writer, "]");\n return true;\n }\n appendPiEventJson(writer, "{");\n let wroteProperty = false;\n try {\n for (const property in value) {\n consumePiEventTraversalNode(writer);\n if (!Object.hasOwn(value, property)) continue;\n const item = readPiEventProperty(value, property);\n const checkpointChunks = writer.chunks.length;\n const checkpointBytes = writer.sizeBytes;\n if (wroteProperty) appendPiEventJson(writer, ",");\n appendRedactedPiEventString(writer, property);\n appendPiEventJson(writer, ":");\n if (writePiEventJsonValue(writer, item, property, depth + 1)) {\n wroteProperty = true;\n } else {\n writer.chunks.length = checkpointChunks;\n writer.sizeBytes = checkpointBytes;\n }\n }\n } catch (error) {\n if (error instanceof PiEventTraversalLimitError || error instanceof PiEventSerializationError) {\n throw error;\n }\n throw new PiEventSerializationError();\n }\n appendPiEventJson(writer, "}");\n return true;\n } finally {\n writer.activeObjects.delete(value);\n }\n}\nfunction serializeBoundedPiEvent(event, redactor) {\n const writer = {\n chunks: [],\n activeObjects: /* @__PURE__ */ new WeakSet(),\n redactor,\n sizeBytes: 0,\n visitedNodes: 0\n };\n if (!writePiEventJsonValue(writer, event, "", 0)) {\n throw new PiEventSerializationError();\n }\n return writer.chunks.join("");\n}\nfunction jsonSafePiEvent(event, redactor) {\n try {\n return JSON.parse(serializeBoundedPiEvent(event, redactor));\n } catch (error) {\n if (error instanceof PiEventTraversalLimitError) {\n return truncatedPiEvent(event, "payload_exceeded_limit", redactor);\n }\n return truncatedPiEvent(event, "payload_not_json_serializable", redactor);\n }\n}\nfunction finiteNonnegative(value) {\n return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;\n}\nfunction nonnegativeInteger(value) {\n return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0;\n}\nfunction usageFromAssistantMessage(message) {\n if (!message || !isRecord5(message.usage)) return void 0;\n const usage = message.usage;\n const inputTokens = nonnegativeInteger(usage.input);\n const outputTokens = nonnegativeInteger(usage.output);\n const cacheReadTokens = nonnegativeInteger(usage.cacheRead);\n const cacheWriteTokens = nonnegativeInteger(usage.cacheWrite);\n const reportedTotal = nonnegativeInteger(usage.totalTokens);\n const calculatedTotal = inputTokens + outputTokens + cacheReadTokens + cacheWriteTokens;\n const totalTokens = reportedTotal || (Number.isSafeInteger(calculatedTotal) ? calculatedTotal : Number.MAX_SAFE_INTEGER);\n const totalCost = isRecord5(usage.cost) ? finiteNonnegative(usage.cost.total) : 0;\n return {\n inputTokens,\n outputTokens,\n cacheReadTokens,\n cacheWriteTokens,\n totalTokens,\n ...totalCost === 0 ? {} : { costUsd: totalCost }\n };\n}\nfunction lastAssistantMessage(messages) {\n if (!Array.isArray(messages) || nodeUtilTypes.isProxy(messages)) return null;\n const minimumIndex = Math.max(\n 0,\n messages.length - MAX_PI_EVENT_LIFECYCLE_MESSAGE_SCAN\n );\n for (let index = messages.length - 1; index >= minimumIndex; index -= 1) {\n const message = boundedAssistantMessage(\n readPiLifecycleProperty(messages, String(index))\n );\n if (message?.role === "assistant") return message;\n }\n return null;\n}\nfunction boundedLifecycleString(value) {\n return value.length <= MAX_PI_EVENT_LIFECYCLE_STRING_LENGTH ? value : `${value.slice(0, MAX_PI_EVENT_LIFECYCLE_STRING_LENGTH - 3)}...`;\n}\nfunction readPiLifecycleProperty(value, property) {\n try {\n let current = value;\n for (let depth = 0; current !== null && depth < 4; depth += 1) {\n if (nodeUtilTypes.isProxy(current)) return void 0;\n const descriptor = Object.getOwnPropertyDescriptor(current, property);\n if (descriptor) {\n return "value" in descriptor ? descriptor.value : void 0;\n }\n current = Object.getPrototypeOf(current);\n }\n return void 0;\n } catch {\n return void 0;\n }\n}\nfunction boundedAssistantMessage(value) {\n if (!isRecord5(value) || nodeUtilTypes.isProxy(value)) return null;\n const bounded = /* @__PURE__ */ Object.create(null);\n for (const property of ["role", "stopReason", "errorMessage"]) {\n const item = readPiLifecycleProperty(value, property);\n if (typeof item === "string") bounded[property] = boundedLifecycleString(item);\n }\n const usage = readPiLifecycleProperty(value, "usage");\n if (isRecord5(usage) && !nodeUtilTypes.isProxy(usage)) {\n const boundedUsage = /* @__PURE__ */ Object.create(null);\n for (const property of [\n "input",\n "output",\n "cacheRead",\n "cacheWrite",\n "totalTokens"\n ]) {\n const item = readPiLifecycleProperty(usage, property);\n if (typeof item === "number" && Number.isFinite(item)) {\n boundedUsage[property] = item;\n }\n }\n const cost = readPiLifecycleProperty(usage, "cost");\n if (isRecord5(cost) && !nodeUtilTypes.isProxy(cost)) {\n const total = readPiLifecycleProperty(cost, "total");\n if (typeof total === "number" && Number.isFinite(total)) {\n boundedUsage.cost = { total };\n }\n }\n bounded.usage = boundedUsage;\n }\n return bounded;\n}\nfunction boundedLifecycleFailure(value) {\n let isError = false;\n try {\n isError = value instanceof Error;\n } catch {\n return new Error("Pi turn failed.");\n }\n if (isError && typeof value === "object" && value !== null) {\n const record = value;\n const message = readPiLifecycleProperty(record, "message");\n const name = readPiLifecycleProperty(record, "name");\n const stack = readPiLifecycleProperty(record, "stack");\n const bounded = new Error(\n typeof message === "string" ? boundedLifecycleString(message) : "Pi turn failed."\n );\n if (typeof name === "string") {\n bounded.name = boundedLifecycleString(name);\n }\n if (typeof stack === "string") {\n bounded.stack = boundedLifecycleString(stack);\n }\n return bounded;\n }\n if (typeof value === "string") return boundedLifecycleString(value);\n return new Error("Pi turn failed.");\n}\nvar PiSdkHarnessAdapter = class {\n constructor(config, executionGate = new SupervisorExecutionGate(), redactor = new SensitiveValueRedactor(), dependencies = {}) {\n this.config = config;\n this.executionGate = executionGate;\n this.redactor = redactor;\n this.dependencies = dependencies;\n assertSupervisorHarnessPathOwnership(\n config.stateDir,\n config.harness.sessionPath,\n config.harness.agentDir\n );\n this.resourceSnapshotManager = new PiResourceSnapshotManager(\n {\n agentDir: config.harness.agentDir ?? join4(config.stateDir, "pi/agent"),\n stateDir: config.stateDir,\n stateDurabilityAnchor: config.stateDurabilityAnchor,\n attemptId: config.attemptId\n },\n dependencies\n );\n }\n config;\n executionGate;\n redactor;\n dependencies;\n name = "pi-sdk";\n state = "idle";\n listeners = /* @__PURE__ */ new Set();\n session = null;\n unsubscribe = null;\n startPromise = null;\n stopPromise = null;\n activeTurn = null;\n eventQueue = [];\n eventQueueBytes = 0;\n eventPump = null;\n eventFailure = null;\n commandApplied = /* @__PURE__ */ new Set();\n commandAppliedWaiters = /* @__PURE__ */ new Map();\n resourceSnapshotManager;\n sessionDirectory = null;\n sessionFile = null;\n sessionHistoryFailure = null;\n subscribe(listener) {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n async start() {\n this.executionGate.throwIfClosed();\n if (this.state === "running") return;\n if (this.startPromise) return this.startPromise;\n if (this.state !== "idle") {\n throw new Error(`Pi cannot start while harness state is ${this.state}.`);\n }\n const starting = this.startSession();\n this.startPromise = starting;\n try {\n await starting;\n } finally {\n if (this.startPromise === starting) this.startPromise = null;\n }\n }\n async prompt(input) {\n this.executionGate.throwIfClosed();\n await this.start();\n this.executionGate.throwIfClosed();\n const session = this.session;\n if (!session) throw new Error("Pi SDK session is unavailable.");\n if (this.activeTurn || session.isStreaming) {\n throw new Error(\n "Pi already has an active turn; use a steer command instead."\n );\n }\n await this.assertSessionHistoryPromptCapacity();\n this.executionGate.throwIfClosed();\n const turn = {\n commandId: input.commandId,\n run: null,\n terminalTask: null,\n terminalClaim: null,\n terminalFinalized: false,\n started: false,\n latestAssistantMessage: null\n };\n this.activeTurn = turn;\n let preflightSettled = false;\n let preflightAccepted = false;\n let resolvePreflight;\n let rejectPreflight;\n const preflight = new Promise((resolveAccepted, rejectAccepted) => {\n resolvePreflight = resolveAccepted;\n rejectPreflight = rejectAccepted;\n });\n let run;\n try {\n this.assertSessionHistoryPromptCapacitySync();\n this.executionGate.throwIfClosed();\n run = session.prompt(attachFilesToMessage(input), {\n preflightResult: (disposition) => {\n if (preflightSettled) return;\n preflightSettled = true;\n if (disposition !== false) {\n preflightAccepted = true;\n resolvePreflight();\n } else {\n rejectPreflight(\n new Error("Pi rejected the prompt before acceptance.")\n );\n }\n }\n });\n } catch (error) {\n if (this.activeTurn === turn) this.activeTurn = null;\n throw error;\n }\n const tracked = run.then(\n async () => {\n if (!preflightSettled) {\n preflightSettled = true;\n rejectPreflight(\n new Error("Pi completed before reporting prompt preflight.")\n );\n }\n if (preflightAccepted) await this.finishTurn(turn);\n },\n async (error) => {\n if (!preflightSettled) {\n preflightSettled = true;\n rejectPreflight(errorFromUnknown(error));\n }\n if (preflightAccepted) await this.finishTurn(turn, error);\n }\n ).finally(() => {\n if (!preflightAccepted || turn.terminalFinalized || turn.terminalClaim === "shutdown") {\n this.releaseTurn(turn);\n }\n });\n turn.run = tracked;\n void tracked.catch(() => void 0);\n await preflight;\n }\n async steer(input) {\n this.executionGate.throwIfClosed();\n const session = this.session;\n const turn = this.activeTurn;\n if (!session || !turn?.run || !session.isStreaming) {\n throw new Error(\n "Pi is not running an active turn; steering cannot be queued."\n );\n }\n await this.assertSessionHistoryPromptCapacity();\n this.assertSessionHistoryPromptCapacitySync();\n this.executionGate.throwIfClosed();\n await session.steer(attachFilesToMessage(input));\n }\n async cancel(reason, commandId) {\n await this.cancelForCommand(reason, commandId);\n }\n async cancelForCommand(reason, commandId) {\n if (!this.claimStop()) return false;\n await this.abortClaimedStop(reason, commandId);\n return true;\n }\n claimStop() {\n this.executionGate.throwIfClosed();\n const session = this.session;\n const turn = this.activeTurn;\n if (!session || !turn?.run) return false;\n return this.claimTerminal(turn, "stopped");\n }\n async abortClaimedStop(reason, commandId) {\n const session = this.session;\n const turn = this.activeTurn;\n if (!session || !turn?.run || turn.terminalClaim !== "stopped") {\n throw new Error(\n "Pi stop must be claimed before aborting the active turn."\n );\n }\n let abort;\n try {\n this.executionGate.throwIfClosed();\n abort = session.abort();\n } catch (error) {\n this.failHarness("Pi failed to abort the active turn.", error);\n throw error;\n }\n const safeReason = reason === void 0 ? void 0 : sanitizeSupervisorReason(this.redactor.redact(reason));\n const terminalTask = abort.then(async () => {\n await turn.run?.catch(() => void 0);\n await this.drainEvents();\n await this.syncSessionHistory();\n if (commandId) await this.waitForCommandApplied(commandId);\n const usage = usageFromAssistantMessage(turn.latestAssistantMessage);\n await this.enqueueEvent({\n type: "lifecycle",\n event: {\n kind: "turn_stopped",\n commandId: turn.commandId,\n ...safeReason === void 0 ? {} : { reason: safeReason },\n ...usage === void 0 ? {} : { usage }\n }\n });\n }).catch((error) => {\n if (!this.executionGate.isClosed && !this.eventFailure) {\n this.failHarness("Pi cancellation could not be finalized.", error);\n }\n throw error;\n }).finally(() => {\n turn.terminalFinalized = true;\n this.forgetCommandApplication(turn.commandId);\n this.forgetCommandApplication(commandId);\n this.releaseTurn(turn);\n });\n turn.terminalTask = terminalTask;\n void terminalTask.catch(() => void 0);\n await abort;\n }\n confirmCommandApplied(commandId) {\n if (this.executionGate.closure) {\n this.commandAppliedWaiters.get(commandId)?.reject(this.executionGate.closure.error);\n this.commandAppliedWaiters.delete(commandId);\n return;\n }\n this.commandApplied.add(commandId);\n this.commandAppliedWaiters.get(commandId)?.resolve();\n this.commandAppliedWaiters.delete(commandId);\n }\n stop(reason = "supervisor_shutdown") {\n const safeReason = sanitizeSupervisorReason(this.redactor.redact(reason));\n this.executionGate.close("shutdown", safeReason);\n if (this.stopPromise) return this.stopPromise;\n const stopping = this.stopSession();\n this.stopPromise = stopping;\n return stopping;\n }\n async startSession() {\n this.state = "starting";\n let candidateSession = null;\n let candidateUnsubscribe = null;\n try {\n const sessionDirectory = await ensureDescriptorBoundDirectory(\n this.config.stateDurabilityAnchor,\n dirname3(this.config.harness.sessionPath)\n );\n this.sessionDirectory = sessionDirectory;\n await this.dependencies.afterSessionDirectoryBound?.(\n dirname3(this.config.harness.sessionPath)\n );\n this.sessionFile = await preparePiSessionFile(\n sessionDirectory,\n basename(this.config.harness.sessionPath),\n this.config.harness.sessionPath\n );\n this.executionGate.throwIfClosed();\n await mkdir3(this.config.workspaceDir, { recursive: true });\n await assertWorkspaceIsolated(\n this.config.workspaceDir,\n this.config.stateDir\n );\n this.executionGate.throwIfClosed();\n await this.resourceSnapshotManager.prepare();\n const agentDir = this.resourceSnapshotManager.runtimeAgentDir;\n const authPath = this.resourceSnapshotManager.runtimeAuthPath;\n this.executionGate.throwIfClosed();\n const provider = this.config.harness.provider;\n const providerCredentialEnv = this.config.harness.providerCredentialEnv;\n const providerCredential = providerCredentialEnv === void 0 ? void 0 : process.env[providerCredentialEnv];\n if (providerCredentialEnv !== void 0 && !providerCredential?.trim()) {\n throw new Error(\n `Pi provider credential ${providerCredentialEnv} must be non-empty.`\n );\n }\n if (providerCredentialEnv !== void 0)\n delete process.env[providerCredentialEnv];\n this.redactor.capture(providerCredential);\n const sdk = await import(this.config.harness.moduleSpecifier);\n this.executionGate.throwIfClosed();\n assertPiSdkModule(sdk);\n if (sdk.VERSION !== this.config.harness.expectedVersion) {\n throw new Error(\n `Pi SDK version mismatch: expected ${this.config.harness.expectedVersion}, received ${String(\n sdk.VERSION\n )}.`\n );\n }\n await this.resourceSnapshotManager.validateRuntimeAuth();\n this.executionGate.throwIfClosed();\n await this.dependencies.beforeModelRuntimeCreate?.(authPath);\n await this.resourceSnapshotManager.validateRuntimeAuth();\n this.executionGate.throwIfClosed();\n const modelRuntime = await sdk.ModelRuntime.create({\n authPath,\n modelsPath: null\n });\n this.executionGate.throwIfClosed();\n if (provider && providerCredential) {\n await modelRuntime.setRuntimeApiKey(provider, providerCredential, {\n allowNetwork: false\n });\n this.executionGate.throwIfClosed();\n }\n this.executionGate.throwIfClosed();\n const sessionFile = this.sessionFile;\n if (sessionFile === null) {\n throw new Error("Pi session storage is not descriptor-bound.");\n }\n const sessionManager = await withPiSessionFileReady(\n sessionDirectory,\n basename(this.config.harness.sessionPath),\n sessionFile,\n this.config.harness.sessionPath,\n () => {\n this.executionGate.throwIfClosed();\n assertPiSessionHistoryReadyForSdkOpen(\n sessionFile,\n this.config.harness.sessionPath\n );\n return sdk.SessionManager.open(\n this.boundSessionFilePath(),\n descriptorBoundDirectoryPath(sessionDirectory),\n this.config.workspaceDir\n );\n }\n );\n assertPiSdkSessionManager(sessionManager);\n this.installSessionHistoryWriteGuard(sessionManager);\n await this.syncSessionHistory();\n const model = provider && this.config.harness.model ? modelRuntime.getModel(provider, this.config.harness.model) : void 0;\n if (this.config.harness.provider && this.config.harness.model && !model) {\n throw new Error(\n `Pi model ${this.config.harness.provider}/${this.config.harness.model} was not found.`\n );\n }\n const settingsManager = sdk.SettingsManager.inMemory(\n {},\n { projectTrusted: false }\n );\n const createResourceLoader = (snapshotAgentDir) => new sdk.DefaultResourceLoader({\n cwd: this.config.workspaceDir,\n agentDir: snapshotAgentDir,\n settingsManager\n });\n const resourceLoader = this.resourceSnapshotManager.createResourceLoader(\n createResourceLoader\n );\n await resourceLoader.reload();\n this.executionGate.throwIfClosed();\n const result = await sdk.createAgentSession({\n cwd: this.config.workspaceDir,\n agentDir,\n modelRuntime,\n resourceLoader,\n settingsManager,\n sessionManager,\n ...model === void 0 ? {} : { model },\n ...this.config.harness.thinking === void 0 ? {} : { thinkingLevel: this.config.harness.thinking }\n });\n assertPiSdkSession(result.session);\n candidateSession = result.session;\n await this.syncSessionHistory();\n this.executionGate.throwIfClosed();\n candidateUnsubscribe = candidateSession.subscribe(\n (event) => this.onPiEvent(event)\n );\n this.executionGate.throwIfClosed();\n this.session = candidateSession;\n this.unsubscribe = candidateUnsubscribe;\n candidateSession = null;\n candidateUnsubscribe = null;\n this.state = "running";\n await this.enqueueEvent({ type: "started" });\n this.executionGate.throwIfClosed();\n } catch (error) {\n candidateUnsubscribe?.();\n candidateSession?.dispose();\n this.disposePublishedSession();\n await this.resourceSnapshotManager.close().catch(() => void 0);\n await this.closeSessionStorage().catch(() => void 0);\n if (this.state !== "stopping")\n this.state = "exited";\n if (!this.executionGate.isClosed) {\n this.executionGate.close(\n "startup_failed",\n "Pi SDK session initialization failed.",\n error\n );\n }\n throw error;\n }\n }\n async stopSession() {\n if (this.state !== "exited") this.state = "stopping";\n const closureError = this.executionGate.closure?.error ?? new Error("Supervisor execution was stopped.");\n const turn = this.activeTurn;\n if (turn) this.claimTerminal(turn, "shutdown");\n this.rejectCommandAppliedWaiters(closureError);\n let failure = null;\n try {\n await withTimeout(\n this.settleHarnessForStop(),\n this.config.harness.stopGraceMs,\n "Timed out while stopping the Pi SDK session."\n );\n } catch (error) {\n failure = errorFromUnknown(error);\n }\n try {\n this.disposePublishedSession();\n } catch (error) {\n failure ??= errorFromUnknown(error);\n }\n const closingSnapshots = this.resourceSnapshotManager.close();\n void closingSnapshots.catch(() => void 0);\n try {\n await withTimeout(\n closingSnapshots,\n this.config.harness.stopGraceMs,\n "Timed out while releasing Pi resource snapshots."\n );\n } catch (error) {\n failure ??= errorFromUnknown(error);\n }\n try {\n await this.closeSessionStorage();\n } catch (error) {\n failure ??= errorFromUnknown(error);\n }\n this.activeTurn = null;\n this.commandApplied.clear();\n this.commandAppliedWaiters.clear();\n this.state = "exited";\n try {\n await withTimeout(\n (async () => {\n await this.drainEvents();\n if (!this.eventFailure) {\n await this.enqueueEvent({\n type: "exit",\n result: { exitCode: 0, signal: null }\n });\n }\n })(),\n this.config.harness.stopGraceMs,\n "Timed out while draining Pi SDK lifecycle events."\n );\n } catch (error) {\n failure ??= errorFromUnknown(error);\n }\n if (this.eventFailure) failure ??= this.eventFailure;\n if (failure) throw failure;\n }\n async settleHarnessForStop() {\n await this.startPromise?.catch(() => void 0);\n const session = this.session;\n const turn = this.activeTurn;\n if (!session || !turn?.run) return;\n this.claimTerminal(turn, "shutdown");\n await session.abort();\n await turn.run.catch(() => void 0);\n await turn.terminalTask?.catch(() => void 0);\n await this.syncSessionHistory();\n }\n onPiEvent(event) {\n const turn = this.activeTurn;\n const boundedEvent = isRecord5(event) && !nodeUtilTypes.isProxy(event) ? event : null;\n const eventType = boundedEvent === null ? void 0 : readPiLifecycleProperty(boundedEvent, "type");\n if (turn && boundedEvent) {\n if (eventType === "turn_end") {\n turn.latestAssistantMessage = boundedAssistantMessage(\n readPiLifecycleProperty(boundedEvent, "message")\n ) ?? turn.latestAssistantMessage;\n } else if (eventType === "agent_end") {\n turn.latestAssistantMessage = lastAssistantMessage(\n readPiLifecycleProperty(boundedEvent, "messages")\n ) ?? turn.latestAssistantMessage;\n }\n }\n const safeEvent = jsonSafePiEvent(event, this.redactor);\n this.queueEvent(\n { type: "event", payload: safeEvent },\n isCoalescedPiEvent(safeEvent)\n );\n if (turn && eventType === "agent_start" && !turn.started) {\n turn.started = true;\n this.queueEvent({\n type: "lifecycle",\n event: { kind: "turn_started", commandId: turn.commandId }\n });\n }\n }\n async finishTurn(turn, failure) {\n if (!this.claimTerminal(turn, "natural")) return;\n try {\n await this.waitForCommandApplied(turn.commandId);\n await this.drainEvents();\n await this.syncSessionHistory();\n if (!turn.started) {\n turn.started = true;\n await this.enqueueEvent({\n type: "lifecycle",\n event: { kind: "turn_started", commandId: turn.commandId }\n });\n }\n const message = turn.latestAssistantMessage;\n const rawStopReason = message && typeof message.stopReason === "string" ? message.stopReason : void 0;\n const stopReason = rawStopReason === void 0 ? void 0 : sanitizeSupervisorReason(\n this.redactor.redact(boundedLifecycleString(rawStopReason))\n );\n const usage = usageFromAssistantMessage(message);\n const errorMessage = message && typeof message.errorMessage === "string" ? message.errorMessage : void 0;\n if (failure !== void 0 || rawStopReason === "error" || rawStopReason === "aborted") {\n await this.enqueueEvent({\n type: "lifecycle",\n event: {\n kind: "turn_failed",\n commandId: turn.commandId,\n ...stopReason === void 0 ? {} : { stopReason },\n error: this.redactor.serialize(\n boundedLifecycleFailure(\n failure ?? errorMessage ?? `Pi turn ended with stop reason ${String(stopReason)}.`\n )\n ),\n ...usage === void 0 ? {} : { usage }\n }\n });\n } else {\n await this.enqueueEvent({\n type: "lifecycle",\n event: {\n kind: "turn_completed",\n commandId: turn.commandId,\n ...stopReason === void 0 ? {} : { stopReason },\n ...usage === void 0 ? {} : { usage }\n }\n });\n }\n } finally {\n turn.terminalFinalized = true;\n this.forgetCommandApplication(turn.commandId);\n this.releaseTurn(turn);\n }\n }\n forgetCommandApplication(commandId) {\n if (commandId === void 0) return;\n this.commandApplied.delete(commandId);\n this.commandAppliedWaiters.delete(commandId);\n }\n claimTerminal(turn, claim) {\n if (this.activeTurn !== turn || turn.terminalClaim) return false;\n turn.terminalClaim = claim;\n return true;\n }\n releaseTurn(turn) {\n if (this.activeTurn === turn) this.activeTurn = null;\n }\n waitForCommandApplied(commandId) {\n if (this.commandApplied.has(commandId)) return Promise.resolve();\n if (this.executionGate.closure)\n return Promise.reject(this.executionGate.closure.error);\n const existing = this.commandAppliedWaiters.get(commandId);\n if (existing) return existing.promise;\n let resolveApplied;\n let rejectApplied;\n const promise = new Promise((resolve2, reject) => {\n resolveApplied = resolve2;\n rejectApplied = reject;\n });\n this.commandAppliedWaiters.set(commandId, {\n promise,\n resolve: resolveApplied,\n reject: rejectApplied\n });\n return promise;\n }\n rejectCommandAppliedWaiters(error) {\n for (const waiter of this.commandAppliedWaiters.values())\n waiter.reject(error);\n this.commandAppliedWaiters.clear();\n }\n async syncSessionHistory() {\n try {\n const file = this.sessionFile;\n const directory = this.sessionDirectory;\n if (file === null || directory === null) {\n throw new Error("Pi session storage is not descriptor-bound.");\n }\n if (this.sessionHistoryFailure) throw this.sessionHistoryFailure;\n await this.revalidateSessionHistoryFile();\n await file.sync();\n await syncDescriptorBoundDirectory(directory);\n await this.dependencies.afterSessionHistoryDurabilitySync?.(\n this.config.harness.sessionPath\n );\n const stats = await this.revalidateSessionHistoryFile();\n if (this.sessionHistoryFailure) throw this.sessionHistoryFailure;\n assertPiSessionHistorySize(\n stats,\n SUPERVISOR_MAX_PI_SESSION_HISTORY_BYTES,\n "above",\n "exceeds"\n );\n } catch (error) {\n this.failHarness("Pi session history could not be made durable.", error);\n throw error;\n }\n }\n async assertSessionHistoryPromptCapacity() {\n const stats = await this.revalidateSessionHistoryFile();\n assertPiSessionHistorySize(\n stats,\n SUPERVISOR_PI_SESSION_HISTORY_PROMPT_LIMIT_BYTES,\n "at_or_above",\n "has reached"\n );\n await this.dependencies.afterSessionHistoryAdmissionRevalidation?.(\n this.config.harness.sessionPath\n );\n }\n assertSessionHistoryPromptCapacitySync() {\n const file = this.sessionFile;\n if (file === null) {\n throw new Error("Pi session storage is not descriptor-bound.");\n }\n assertPiSessionHistorySize(\n fstatSync(file.fd, { bigint: true }),\n SUPERVISOR_PI_SESSION_HISTORY_PROMPT_LIMIT_BYTES,\n "at_or_above",\n "has reached"\n );\n }\n async revalidateSessionHistoryFile() {\n const file = this.sessionFile;\n const directory = this.sessionDirectory;\n if (file === null || directory === null) {\n throw new Error("Pi session storage is not descriptor-bound.");\n }\n let stats = null;\n await withRevalidatedPrivateRegularFile(\n file,\n () => openPiSessionFile(\n directory,\n basename(this.config.harness.sessionPath),\n this.config.harness.sessionPath,\n constants2.O_RDONLY\n ),\n () => {\n stats = fstatSync(file.fd, { bigint: true });\n },\n {\n failureMessage: `Pi session path ${this.config.harness.sessionPath} must remain the process-owned single-link private regular file bound at startup.`\n }\n );\n if (stats === null) {\n throw new Error("Pi session storage could not be revalidated.");\n }\n return stats;\n }\n installSessionHistoryWriteGuard(sessionManager) {\n this.assertSessionManagerUsesBoundHistory(sessionManager);\n this.assertSessionManagerIsAppendOnly(sessionManager);\n const adapter = this;\n sessionManager._persist = function guardedPiSessionPersist(entry) {\n try {\n adapter.assertSessionManagerUsesBoundHistory(sessionManager);\n adapter.assertSessionManagerIsAppendOnly(sessionManager);\n const serialized = JSON.stringify(entry);\n if (typeof serialized !== "string") {\n throw new Error("Pi attempted to persist a non-JSON session entry.");\n }\n adapter.assertSessionManagerUsesBoundHistory(sessionManager);\n adapter.assertSessionManagerIsAppendOnly(sessionManager);\n const line = Buffer.from(`${serialized}\n`, "utf8");\n const beforeBytes = adapter.assertSessionHistoryWriteCapacity(\n line.byteLength\n );\n adapter.appendSessionHistoryLine(line, beforeBytes);\n adapter.dependencies.afterSessionHistoryAppend?.(\n adapter.config.harness.sessionPath\n );\n adapter.assertSessionManagerUsesBoundHistory(sessionManager);\n adapter.assertSessionManagerIsAppendOnly(sessionManager);\n const afterBytes = adapter.assertSessionHistoryWriteCapacity(0);\n if (afterBytes !== beforeBytes + BigInt(line.byteLength)) {\n throw new Error(\n "Pi session history append did not produce its exact expected size."\n );\n }\n } catch (error) {\n throw adapter.failSessionHistoryPersistence(error);\n }\n };\n }\n assertSessionManagerUsesBoundHistory(sessionManager) {\n if (sessionManager.getSessionFile() !== this.boundSessionFilePath()) {\n throw new Error(\n "Pi SessionManager must keep using the descriptor-bound session history path."\n );\n }\n }\n assertSessionManagerIsAppendOnly(sessionManager) {\n if (Object.getOwnPropertyDescriptor(sessionManager, "flushed")?.value !== true) {\n throw new Error(\n "Pi SessionManager left its pinned append-only persistence state."\n );\n }\n }\n assertSessionHistoryWriteCapacity(entryBytes) {\n const file = this.sessionFile;\n if (file === null) {\n throw new Error("Pi session storage is not descriptor-bound.");\n }\n const stats = fstatSync(file.fd, { bigint: true });\n const maximumBytes = BigInt(SUPERVISOR_MAX_PI_SESSION_HISTORY_BYTES);\n if (stats.size + BigInt(entryBytes) > maximumBytes) {\n throw piSessionHistoryLimitError(\n SUPERVISOR_MAX_PI_SESSION_HISTORY_BYTES,\n "would exceed"\n );\n }\n return stats.size;\n }\n appendSessionHistoryLine(line, start) {\n const file = this.sessionFile;\n if (file === null) {\n throw new Error("Pi session storage is not descriptor-bound.");\n }\n const position = Number(start);\n let written = 0;\n while (written < line.byteLength) {\n const bytesWritten = writeSync(\n file.fd,\n line,\n written,\n line.byteLength - written,\n position + written\n );\n if (bytesWritten <= 0) {\n throw new Error("Pi session history append made no forward progress.");\n }\n written += bytesWritten;\n }\n }\n failSessionHistoryPersistence(error) {\n const failure = errorFromUnknown(error);\n this.sessionHistoryFailure ??= failure;\n this.failHarness("Pi session history persistence failed.", failure);\n return failure;\n }\n boundSessionFilePath() {\n const file = this.sessionFile;\n if (file === null) {\n throw new Error("Pi session storage is not descriptor-bound.");\n }\n return descriptorBoundDirectoryPath({ handle: file });\n }\n async closeSessionStorage() {\n const file = this.sessionFile;\n const directory = this.sessionDirectory;\n this.sessionFile = null;\n this.sessionDirectory = null;\n let failure;\n await file?.close().catch((error) => {\n failure ??= error;\n });\n await directory?.handle.close().catch((error) => {\n failure ??= error;\n });\n if (failure !== void 0) throw failure;\n }\n queueEvent(event, coalescible = false) {\n if (this.eventFailure) return;\n try {\n this.stageEvent({\n event,\n sizeBytes: Buffer.byteLength(JSON.stringify(event), "utf8"),\n coalescible\n });\n } catch (error) {\n this.latchEventFailure(errorFromUnknown(error));\n }\n }\n enqueueEvent(event) {\n if (this.eventFailure) return Promise.reject(this.eventFailure);\n const sizeBytes = Buffer.byteLength(JSON.stringify(event), "utf8");\n const persisted = new Promise((resolvePersisted, rejectPersisted) => {\n try {\n this.stageEvent({\n event,\n sizeBytes,\n coalescible: false,\n resolve: resolvePersisted,\n reject: rejectPersisted\n });\n } catch (error) {\n rejectPersisted(errorFromUnknown(error));\n }\n });\n void persisted.catch(() => void 0);\n return persisted;\n }\n stageEvent(entry) {\n if (this.eventFailure) throw this.eventFailure;\n const last = this.eventQueue.at(-1);\n if (entry.coalescible && last?.coalescible && !last.inFlight) {\n this.eventQueueBytes += entry.sizeBytes - last.sizeBytes;\n last.event = entry.event;\n last.sizeBytes = entry.sizeBytes;\n } else {\n this.eventQueue.push(entry);\n this.eventQueueBytes += entry.sizeBytes;\n }\n if (this.eventQueue.length > MAX_PENDING_HARNESS_EVENTS || this.eventQueueBytes > MAX_PENDING_HARNESS_EVENT_BYTES) {\n const failure = new Error(\n "Pi event delivery exceeded its bounded pending queue."\n );\n this.latchEventFailure(failure);\n throw failure;\n }\n this.startEventPump();\n }\n startEventPump() {\n if (this.eventPump || this.eventFailure || this.eventQueue.length === 0)\n return;\n const pumping = this.pumpEvents();\n this.eventPump = pumping;\n void pumping.catch((error) => {\n this.latchEventFailure(errorFromUnknown(error));\n }).finally(() => {\n if (this.eventPump === pumping) this.eventPump = null;\n if (!this.eventFailure && this.eventQueue.length > 0)\n this.startEventPump();\n });\n }\n async pumpEvents() {\n while (this.eventQueue.length > 0) {\n if (this.eventFailure) throw this.eventFailure;\n const entry = this.eventQueue[0];\n if (!entry) return;\n entry.inFlight = true;\n try {\n await this.emit(entry.event);\n entry.resolve?.();\n } catch (error) {\n const failure = errorFromUnknown(error);\n entry.reject?.(failure);\n throw failure;\n } finally {\n if (!this.eventFailure && this.eventQueue[0] === entry) {\n this.eventQueue.shift();\n this.eventQueueBytes -= entry.sizeBytes;\n }\n }\n }\n }\n async drainEvents() {\n while (true) {\n if (this.eventFailure) throw this.eventFailure;\n const pumping = this.eventPump;\n if (pumping) await pumping.catch(() => void 0);\n if (this.eventFailure) throw this.eventFailure;\n if (!this.eventPump && this.eventQueue.length === 0) return;\n this.startEventPump();\n }\n }\n latchEventFailure(error) {\n if (this.eventFailure) return;\n this.eventFailure = error;\n const pending = this.eventQueue.splice(0);\n this.eventQueueBytes = 0;\n for (const entry of pending) entry.reject?.(error);\n this.executionGate.close(\n "persistence_failed",\n "A harness event listener failed; durable event delivery cannot continue.",\n error\n );\n this.rejectCommandAppliedWaiters(error);\n queueMicrotask(() => {\n void this.stop("harness_event_persistence_failed").catch(() => void 0);\n });\n }\n failHarness(reason, error) {\n const failure = errorFromUnknown(error);\n this.executionGate.close("harness_failed", reason, failure);\n this.rejectCommandAppliedWaiters(failure);\n queueMicrotask(() => {\n void this.stop(reason).catch(() => void 0);\n });\n }\n disposePublishedSession() {\n const unsubscribe = this.unsubscribe;\n const session = this.session;\n this.unsubscribe = null;\n this.session = null;\n unsubscribe?.();\n session?.dispose();\n }\n async emit(event) {\n for (const listener of this.listeners) await listener(event);\n }\n};\n\n// src/supervisor/runtime-store.ts\nimport { randomUUID as randomUUID4 } from "node:crypto";\nimport { constants as fsConstants3 } from "node:fs";\nvar STORE_DISK_FORMAT_VERSION = 2;\nvar LEGACY_SUPERVISOR_RUNTIME_VERSION = 1;\nvar OUTBOX_COMPACTION_MIN_RECLAIMED_EVENTS = 64;\nvar OUTBOX_COMPACTION_MIN_RECLAIMED_BYTES = 4 * 1024 * 1024;\nvar METADATA_FILE = "metadata.json";\nvar OUTBOX_FILE = "outbox.jsonl";\nvar COMMAND_LEDGER_FILE = "commands.jsonl";\nvar ACTIVE_TURN_FILE = "active-turn.json";\nvar DEFAULT_OUTBOX_CAPACITY = {\n maximumEvents: 8192,\n maximumBytes: 32 * 1024 * 1024,\n recoveryReserveEvents: 64,\n recoveryReserveBytes: 8 * 1024 * 1024\n};\nvar DEFAULT_COMMAND_LEDGER_CAPACITY = {\n maximumBytes: SUPERVISOR_MAX_COMMAND_LEDGER_BYTES,\n maximumRecords: SUPERVISOR_MAX_COMMAND_LEDGER_RECORDS,\n maximumDistinctCommands: SUPERVISOR_MAX_DISTINCT_COMMANDS,\n recoveryReserveBytes: SUPERVISOR_COMMAND_LEDGER_RECOVERY_BYTES,\n recoveryReserveRecords: SUPERVISOR_COMMAND_LEDGER_RECOVERY_RECORDS\n};\nfunction sanitizeStoredEvent(event) {\n if ((event.kind === "turn_completed" || event.kind === "turn_failed") && typeof event.stopReason === "string") {\n return { ...event, stopReason: sanitizeSupervisorReason(event.stopReason) };\n }\n if ((event.kind === "turn_stopped" || event.kind === "interrupted" || event.kind === "supervisor_stopping") && typeof event.reason === "string") {\n return { ...event, reason: sanitizeSupervisorReason(event.reason) };\n }\n return event;\n}\nfunction createSupervisorCommandIdentity(command) {\n return {\n commandId: command.commandId,\n commandSequence: command.commandSequence,\n commandKind: command.payload.kind,\n attemptId: command.attemptId,\n commandFingerprint: createSupervisorCommandFingerprint(command)\n };\n}\nfunction compareSupervisorCommandIdentity(left, right) {\n if (left.commandId !== right.commandId || left.commandSequence !== right.commandSequence || left.commandKind !== right.commandKind || left.attemptId !== right.attemptId) {\n return "mismatch";\n }\n if (left.commandFingerprint === void 0 || right.commandFingerprint === void 0) {\n return "unverifiable";\n }\n return left.commandFingerprint === right.commandFingerprint ? "match" : "mismatch";\n}\nvar DEFAULT_METADATA = {\n nextEventSequence: 1,\n lastAcknowledgedEventSequence: 0,\n lastAppliedCommandSequence: 0\n};\nvar StoreMutationConflictError = class extends Error {\n name = "StoreMutationConflictError";\n};\nfunction isRecord6(value) {\n return typeof value === "object" && value !== null && !Array.isArray(value);\n}\nfunction isNonNegativeInteger2(value) {\n return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;\n}\nfunction isPositiveInteger3(value) {\n return typeof value === "number" && Number.isSafeInteger(value) && value > 0;\n}\nfunction isStoredCommandId(value) {\n return isBoundedUtf8Identifier(value, SUPERVISOR_MAX_COMMAND_ID_LENGTH);\n}\nfunction isCanonicalTimestamp(value) {\n return typeof value === "string" && Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;\n}\nfunction parseStoredEvent(value) {\n if (isRecord6(value) && isRecord6(value.event)) {\n const sanitizedEvent = sanitizeStoredEvent(value.event);\n if (sanitizedEvent !== value.event) value = { ...value, event: sanitizedEvent };\n }\n if (!isRecord6(value) || value.type !== "event" || value.protocolVersion !== SUPERVISOR_PROTOCOL_VERSION || value.runtimeVersion !== LEGACY_SUPERVISOR_RUNTIME_VERSION && value.runtimeVersion !== SUPERVISOR_RUNTIME_VERSION || typeof value.sessionId !== "string" || value.sessionId.length === 0 || typeof value.runId !== "string" || value.runId.length === 0 || typeof value.attemptId !== "string" || value.attemptId.length === 0 || typeof value.eventId !== "string" || value.eventId.length === 0 || !isPositiveInteger3(value.attemptSequence) || !isCanonicalTimestamp(value.occurredAt) || value.durability !== "durable" && value.durability !== "coalesced" || !isSupervisorEvent(value.event)) {\n return null;\n }\n const frame = {\n ...value,\n runtimeVersion: SUPERVISOR_RUNTIME_VERSION\n };\n if (serializedFrameBytes(frame) >= SUPERVISOR_MAX_FRAME_BYTES) return null;\n return frame;\n}\nfunction parseStoredCommand(value) {\n if (!isRecord6(value) || !isStoredCommandId(value.commandId) || !isPositiveInteger3(value.commandSequence) || value.commandKind !== "prompt" && value.commandKind !== "steer" && value.commandKind !== "stop" || typeof value.attemptId !== "string" || value.attemptId.length === 0 || value.status !== "received" && value.status !== "applied" && value.status !== "failed" || !isCanonicalTimestamp(value.recordedAt) || value.commandFingerprint !== void 0 && !isSupervisorCommandFingerprint(value.commandFingerprint)) {\n return null;\n }\n return value;\n}\nfunction parseActiveTurn(value) {\n if (!isRecord6(value) || !isStoredCommandId(value.commandId) || typeof value.attemptId !== "string" || value.attemptId.length === 0 || typeof value.startedAt !== "string" || !isCanonicalTimestamp(value.startedAt) || value.stop !== void 0 && (!isRecord6(value.stop) || !isStoredCommandId(value.stop.commandId) || value.stop.reason !== void 0 && typeof value.stop.reason !== "string")) {\n return null;\n }\n return {\n commandId: value.commandId,\n attemptId: value.attemptId,\n startedAt: value.startedAt,\n ...value.stop === void 0 ? {} : {\n stop: {\n commandId: value.stop.commandId,\n ...value.stop.reason === void 0 ? {} : {\n reason: sanitizeSupervisorReason(value.stop.reason)\n }\n }\n }\n };\n}\nfunction parseOutboxCheckpoint(value) {\n if (!isRecord6(value) || value.recordType !== "outbox_checkpoint" || value.diskFormatVersion !== STORE_DISK_FORMAT_VERSION || typeof value.sessionId !== "string" || typeof value.runId !== "string" || typeof value.attemptId !== "string" || !isNonNegativeInteger2(value.acknowledgedEventSequence) || !isPositiveInteger3(value.nextEventSequence) || value.acknowledgedEventSequence >= value.nextEventSequence) {\n return null;\n }\n const recoveryFacts = value.recoveryFacts === void 0 ? void 0 : parseStoredRecoveryFacts(value.recoveryFacts, {\n allowMissingCommandApplications: true\n });\n if (recoveryFacts === null) return null;\n return {\n recordType: "outbox_checkpoint",\n diskFormatVersion: STORE_DISK_FORMAT_VERSION,\n sessionId: value.sessionId,\n runId: value.runId,\n attemptId: value.attemptId,\n acknowledgedEventSequence: value.acknowledgedEventSequence,\n nextEventSequence: value.nextEventSequence,\n ...recoveryFacts === void 0 ? {} : {\n recoveryFacts\n }\n };\n}\nfunction parseCommandOutcomeFact(value) {\n if (!isRecord6(value) || !isStoredCommandId(value.commandId) || !isPositiveInteger3(value.commandSequence) || !isPositiveInteger3(value.eventSequence)) {\n return null;\n }\n return value;\n}\nfunction parseTurnTerminalFact(value) {\n if (!isRecord6(value) || !isStoredCommandId(value.commandId) || !isPositiveInteger3(value.eventSequence) || value.kind !== "turn_completed" && value.kind !== "turn_failed" && value.kind !== "turn_stopped" || value.stopReason !== void 0 && typeof value.stopReason !== "string") {\n return null;\n }\n return {\n commandId: value.commandId,\n eventSequence: value.eventSequence,\n kind: value.kind,\n ...value.stopReason === void 0 ? {} : { stopReason: sanitizeSupervisorReason(value.stopReason) }\n };\n}\nfunction parseStoredRecoveryFacts(value, {\n allowMissingCommandApplications\n}) {\n if (!isRecord6(value)) return null;\n const commandApplicationCandidates = value.commandApplications === void 0 && allowMissingCommandApplications ? [] : value.commandApplications;\n if (!Array.isArray(commandApplicationCandidates) || !Array.isArray(value.commandFailures) || !Array.isArray(value.turnTerminals)) {\n return null;\n }\n const recoveryFacts = {\n commandApplications: [],\n commandFailures: [],\n turnTerminals: []\n };\n for (const candidate of commandApplicationCandidates) {\n const fact = parseCommandOutcomeFact(candidate);\n if (!fact) return null;\n recoveryFacts.commandApplications.push(fact);\n }\n for (const candidate of value.commandFailures) {\n const fact = parseCommandOutcomeFact(candidate);\n if (!fact) return null;\n recoveryFacts.commandFailures.push(fact);\n }\n for (const candidate of value.turnTerminals) {\n const fact = parseTurnTerminalFact(candidate);\n if (!fact) return null;\n recoveryFacts.turnTerminals.push(fact);\n }\n return recoveryFacts;\n}\nfunction sameCommandOutcomeFact(left, right) {\n return left.commandId === right.commandId && left.commandSequence === right.commandSequence && left.eventSequence === right.eventSequence;\n}\nfunction sameTurnTerminalFact(left, right) {\n return left.commandId === right.commandId && left.eventSequence === right.eventSequence && left.kind === right.kind && left.stopReason === right.stopReason;\n}\nfunction commandOutcomeFactKey(fact) {\n return JSON.stringify([fact.commandId, fact.commandSequence, fact.eventSequence]);\n}\nfunction turnTerminalFactKey(fact) {\n return JSON.stringify([\n fact.commandId,\n fact.eventSequence,\n fact.kind,\n fact.stopReason ?? null\n ]);\n}\nfunction parseAppendOnlyJsonLines(raw, name) {\n const values = [];\n const lines = raw.split("\\n");\n const finalLineMayBePartial = !raw.endsWith("\\n");\n for (let index = 0; index < lines.length; index += 1) {\n const line = lines[index];\n if (!line) continue;\n try {\n values.push(JSON.parse(line));\n } catch {\n if (finalLineMayBePartial && index === lines.length - 1) continue;\n throw new Error(`${name} contains malformed JSON before its crash-safe suffix.`);\n }\n }\n return values;\n}\nasync function readTextIfPresent(directory, name, maximumBytes, capacityName) {\n try {\n return await readBoundedRegularTextFileAt(directory, name, maximumBytes, capacityName);\n } catch (error) {\n if (error.code === "ENOENT") return null;\n throw error;\n }\n}\nasync function appendDurably(directory, name, value) {\n const handle = await openRegularFileAt(\n directory,\n name,\n fsConstants3.O_WRONLY | fsConstants3.O_APPEND | fsConstants3.O_CREAT,\n "Supervisor append-only journal",\n 384\n );\n try {\n await assertMutableJournalHandle(handle);\n await handle.writeFile(`${JSON.stringify(value)}\n`, "utf8");\n await handle.sync();\n } finally {\n await handle.close();\n }\n await syncDescriptorBoundDirectory(directory);\n}\nasync function repairPartialJsonLine(directory, name, raw) {\n if (!raw || raw.endsWith("\\n")) return;\n const finalLineStart = raw.lastIndexOf("\\n") + 1;\n const finalLineStartBytes = Buffer.byteLength(raw.slice(0, finalLineStart), "utf8");\n const finalLine = raw.slice(finalLineStart);\n let finalLineIsValid = false;\n try {\n JSON.parse(finalLine);\n finalLineIsValid = true;\n } catch {\n }\n const handle = await openRegularFileAt(\n directory,\n name,\n finalLineIsValid ? fsConstants3.O_WRONLY | fsConstants3.O_APPEND : fsConstants3.O_RDWR,\n "Supervisor append-only journal"\n );\n try {\n await assertMutableJournalHandle(handle);\n if (finalLineIsValid) await handle.writeFile("\\n", "utf8");\n else await handle.truncate(finalLineStartBytes);\n await handle.sync();\n } finally {\n await handle.close();\n }\n}\nasync function assertMutableJournalHandle(handle) {\n const processUid = typeof process.getuid === "function" ? BigInt(process.getuid()) : null;\n const stats = await handle.stat({ bigint: true });\n if (!stats.isFile() || processUid === null || stats.uid !== processUid || stats.nlink !== 1n) {\n throw new Error(\n "Supervisor append-only journal must be a process-owned single-link regular file."\n );\n }\n}\nasync function writeTextAtomically(directory, name, value) {\n const temporaryName = `${name}.${process.pid}.${randomUUID4()}.tmp`;\n let renamed = false;\n try {\n const handle = await openRegularFileAt(\n directory,\n temporaryName,\n fsConstants3.O_WRONLY | fsConstants3.O_CREAT | fsConstants3.O_EXCL,\n "Supervisor atomic-write temporary file",\n 384\n );\n try {\n await handle.writeFile(value, "utf8");\n await handle.sync();\n } finally {\n await handle.close();\n }\n await renameDescriptorBoundEntry(directory, temporaryName, directory, name);\n renamed = true;\n await syncDescriptorBoundDirectory(directory);\n } finally {\n if (!renamed) {\n await unlinkDescriptorBoundEntry(directory, temporaryName).catch(() => void 0);\n }\n }\n}\nasync function writeJsonAtomically(directory, name, value, maximumBytes, capacityName) {\n const serialized = `${JSON.stringify(value)}\n`;\n if (Buffer.byteLength(serialized, "utf8") > maximumBytes) {\n throw new Error(`${capacityName} exceeds its bounded on-disk capacity.`);\n }\n await writeTextAtomically(directory, name, serialized);\n}\nasync function unlinkDurably(directory, name) {\n const removed = await unlinkDescriptorBoundEntryIfPresent(directory, name);\n if (removed) await syncDescriptorBoundDirectory(directory);\n return removed;\n}\nfunction serializedFrameBytes(frame) {\n return Buffer.byteLength(`${JSON.stringify(frame)}\n`, "utf8");\n}\nfunction serializedRecordBytes(record) {\n return Buffer.byteLength(`${JSON.stringify(record)}\n`, "utf8");\n}\nfunction usesRecoveryOutboxReserve(event) {\n return event.kind === "supervisor_started" || event.kind === "command_applied" || event.kind === "command_failed" || event.kind === "turn_completed" || event.kind === "turn_failed" || event.kind === "turn_stopped" || event.kind === "interrupted" || event.kind === "supervisor_stopping";\n}\nfunction cloneActiveTurn(activeTurn) {\n if (!activeTurn) return null;\n return {\n ...activeTurn,\n ...activeTurn.stop === void 0 ? {} : { stop: { ...activeTurn.stop } }\n };\n}\nvar DiskSupervisorStore = class {\n constructor(config, outboxCapacity = DEFAULT_OUTBOX_CAPACITY, commandLedgerCapacity = DEFAULT_COMMAND_LEDGER_CAPACITY) {\n this.config = config;\n this.outboxCapacity = outboxCapacity;\n this.commandLedgerCapacity = commandLedgerCapacity;\n this.attemptDir = supervisorAttemptDataDirectory(config);\n }\n config;\n outboxCapacity;\n commandLedgerCapacity;\n attemptDir;\n attemptDirectoryIdentity = null;\n currentAttemptDirectory = null;\n metadata = { ...DEFAULT_METADATA };\n /** Contains only frames above the durable acknowledgement cursor. */\n events = [];\n commandsById = /* @__PURE__ */ new Map();\n commandIdsBySequence = /* @__PURE__ */ new Map();\n commandApplicationFacts = /* @__PURE__ */ new Map();\n commandFailureFacts = /* @__PURE__ */ new Map();\n turnTerminalFacts = /* @__PURE__ */ new Map();\n activeTurn = null;\n reclaimedEventCount = 0;\n reclaimedEventBytes = 0;\n requiresOutboxMigration = false;\n unacknowledgedEventBytes = 0;\n commandLedgerBytes = 0;\n commandLedgerRecords = 0;\n initialized = false;\n mutationFailure = null;\n mutationTail = Promise.resolve();\n async initialize() {\n await this.mutate(async () => {\n if (this.initialized) return;\n const attemptDirectory = this.requireCurrentAttemptDirectory();\n if (attemptDirectory.displayPath !== this.attemptDir) {\n throw new Error("Supervisor attempt storage resolved to an unexpected directory.");\n }\n const metadataRaw = await readTextIfPresent(\n attemptDirectory,\n METADATA_FILE,\n SUPERVISOR_MAX_STORE_METADATA_BYTES,\n "Supervisor metadata"\n );\n const metadataRecoveryFacts = this.loadMetadata(metadataRaw);\n const commandRaw = await readTextIfPresent(\n attemptDirectory,\n COMMAND_LEDGER_FILE,\n this.commandLedgerCapacity.maximumBytes + this.commandLedgerCapacity.recoveryReserveBytes,\n "Supervisor command ledger"\n );\n if (commandRaw) {\n this.loadCommandLedger(commandRaw);\n await repairPartialJsonLine(attemptDirectory, COMMAND_LEDGER_FILE, commandRaw);\n const ledgerHandle = await openRegularFileAt(\n attemptDirectory,\n COMMAND_LEDGER_FILE,\n fsConstants3.O_RDONLY,\n "Supervisor command ledger"\n );\n try {\n this.commandLedgerBytes = (await ledgerHandle.stat()).size;\n } finally {\n await ledgerHandle.close();\n }\n }\n const activeTurnRaw = await readTextIfPresent(\n attemptDirectory,\n ACTIVE_TURN_FILE,\n SUPERVISOR_MAX_ACTIVE_TURN_BYTES,\n "Supervisor active-turn marker"\n );\n if (activeTurnRaw !== null) {\n let activeTurn;\n try {\n activeTurn = parseActiveTurn(JSON.parse(activeTurnRaw));\n } catch {\n activeTurn = null;\n }\n if (!activeTurn || activeTurn.attemptId !== this.config.attemptId) {\n throw new Error(\n "Supervisor active-turn marker is malformed or belongs to another attempt."\n );\n }\n this.activeTurn = activeTurn;\n }\n const maximumJournalBytes = this.outboxCapacity.maximumBytes + this.outboxCapacity.recoveryReserveBytes + OUTBOX_COMPACTION_MIN_RECLAIMED_BYTES + SUPERVISOR_MAX_FRAME_BYTES;\n const outboxRaw = await readTextIfPresent(\n attemptDirectory,\n OUTBOX_FILE,\n maximumJournalBytes,\n "Supervisor outbox"\n );\n let loadedOutbox = { checkpoint: null, allEvents: [] };\n if (outboxRaw) {\n loadedOutbox = this.loadOutbox(outboxRaw);\n await repairPartialJsonLine(attemptDirectory, OUTBOX_FILE, outboxRaw);\n } else if (this.metadata.lastAcknowledgedEventSequence > 0 || this.metadata.nextEventSequence > 1) {\n throw new Error("Supervisor metadata references event history but its outbox is missing.");\n }\n this.rebuildAndBoundRecoveryFacts(metadataRecoveryFacts, loadedOutbox);\n this.initialized = true;\n await this.persistMetadata();\n await this.maybeCompactOutbox();\n }, true);\n }\n get lastAcknowledgedEventSequence() {\n return this.metadata.lastAcknowledgedEventSequence;\n }\n get lastAppliedCommandSequence() {\n return this.metadata.lastAppliedCommandSequence;\n }\n get lastEventSequence() {\n return this.metadata.nextEventSequence - 1;\n }\n get outboxDepth() {\n return this.events.length;\n }\n async appendEvent(event, durability = "durable") {\n return this.mutate(async () => {\n this.requireInitialized();\n const attemptSequence = this.metadata.nextEventSequence;\n const boundedEvent = sanitizeStoredEvent(event);\n const frame = {\n type: "event",\n protocolVersion: SUPERVISOR_PROTOCOL_VERSION,\n runtimeVersion: SUPERVISOR_RUNTIME_VERSION,\n sessionId: this.config.sessionId,\n runId: this.config.runId,\n attemptId: this.config.attemptId,\n eventId: createSupervisorEventId(this.config.attemptId, attemptSequence),\n attemptSequence,\n occurredAt: (/* @__PURE__ */ new Date()).toISOString(),\n durability,\n event: boundedEvent\n };\n const frameBytes = serializedFrameBytes(frame);\n if (frameBytes >= SUPERVISOR_MAX_FRAME_BYTES) {\n throw new Error(\n `Supervisor event frame exceeds the ${SUPERVISOR_MAX_FRAME_BYTES}-byte transport limit.`\n );\n }\n const usesReserve = usesRecoveryOutboxReserve(boundedEvent);\n const maximumEvents = this.outboxCapacity.maximumEvents + (usesReserve ? this.outboxCapacity.recoveryReserveEvents : 0);\n const maximumBytes = this.outboxCapacity.maximumBytes + (usesReserve ? this.outboxCapacity.recoveryReserveBytes : 0);\n if (this.events.length + 1 > maximumEvents || this.unacknowledgedEventBytes + frameBytes > maximumBytes) {\n throw new Error(\n "Supervisor unacknowledged outbox exceeded bounded capacity; gateway acknowledgement is required."\n );\n }\n await appendDurably(this.requireCurrentAttemptDirectory(), OUTBOX_FILE, frame);\n this.events.push(frame);\n this.unacknowledgedEventBytes += frameBytes;\n this.metadata.nextEventSequence += 1;\n this.noteRecoveryFact(frame);\n await this.persistMetadata();\n return frame;\n });\n }\n listEventsAfter(sequence, limit = Number.POSITIVE_INFINITY) {\n return this.events.filter((event) => event.attemptSequence > sequence).slice(0, Number.isFinite(limit) ? limit : void 0);\n }\n async acknowledgeEvents(sequence) {\n await this.mutate(async () => {\n this.requireInitialized();\n if (!isNonNegativeInteger2(sequence)) {\n throw new StoreMutationConflictError(\n "Event acknowledgement must be a nonnegative integer."\n );\n }\n const boundedSequence = Math.min(sequence, this.lastEventSequence);\n if (boundedSequence <= this.metadata.lastAcknowledgedEventSequence) return;\n const acknowledgedMetadata = {\n ...this.metadata,\n lastAcknowledgedEventSequence: boundedSequence\n };\n await this.persistMetadata(acknowledgedMetadata);\n this.metadata = acknowledgedMetadata;\n const retained = [];\n for (const frame of this.events) {\n if (frame.attemptSequence <= boundedSequence) {\n this.reclaimedEventCount += 1;\n const frameBytes = serializedFrameBytes(frame);\n this.reclaimedEventBytes += frameBytes;\n this.unacknowledgedEventBytes -= frameBytes;\n } else {\n retained.push(frame);\n }\n }\n this.events = retained;\n await this.maybeCompactOutbox();\n });\n }\n getCommand(commandId) {\n return this.commandsById.get(commandId);\n }\n getUnfinishedCommands() {\n return [...this.commandsById.values()].filter((command) => command.status === "received");\n }\n hasCommandFailureEvent(commandId) {\n return this.commandFailureFacts.has(commandId);\n }\n hasCommandApplicationEvent(commandId) {\n return this.commandApplicationFacts.has(commandId);\n }\n hasRecoveryTurnFailureEvent(commandId, stopReason) {\n const fact = this.turnTerminalFacts.get(commandId);\n return fact?.kind === "turn_failed" && fact.stopReason === stopReason;\n }\n hasTurnTerminalEvent(commandId) {\n return this.turnTerminalFacts.has(commandId);\n }\n async readActiveTurn() {\n await this.mutationTail;\n if (this.mutationFailure) throw this.mutationFailure;\n return cloneActiveTurn(this.activeTurn);\n }\n async recordActiveTurn(commandId) {\n await this.mutate(async () => {\n this.requireInitialized();\n if (this.activeTurn && this.activeTurn.commandId !== commandId) {\n throw new StoreMutationConflictError(\n `Active turn ${this.activeTurn.commandId} must finish before starting ${commandId}.`\n );\n }\n if (this.activeTurn) return;\n const activeTurn = {\n commandId,\n attemptId: this.config.attemptId,\n startedAt: (/* @__PURE__ */ new Date()).toISOString()\n };\n await writeJsonAtomically(\n this.requireCurrentAttemptDirectory(),\n ACTIVE_TURN_FILE,\n activeTurn,\n SUPERVISOR_MAX_ACTIVE_TURN_BYTES,\n "Supervisor active-turn marker"\n );\n this.activeTurn = activeTurn;\n });\n }\n async recordActiveTurnStop(commandId, reason) {\n await this.mutate(async () => {\n this.requireInitialized();\n const boundedReason = reason === void 0 ? void 0 : sanitizeSupervisorReason(reason);\n if (!this.activeTurn) return;\n if (this.activeTurn.stop) {\n if (this.activeTurn.stop.commandId === commandId && this.activeTurn.stop.reason === boundedReason) {\n return;\n }\n throw new StoreMutationConflictError(\n `Active turn stop is already owned by command ${this.activeTurn.stop.commandId}.`\n );\n }\n const activeTurn = {\n ...this.activeTurn,\n stop: {\n commandId,\n ...boundedReason === void 0 ? {} : { reason: boundedReason }\n }\n };\n await writeJsonAtomically(\n this.requireCurrentAttemptDirectory(),\n ACTIVE_TURN_FILE,\n activeTurn,\n SUPERVISOR_MAX_ACTIVE_TURN_BYTES,\n "Supervisor active-turn marker"\n );\n this.activeTurn = activeTurn;\n });\n }\n async clearActiveTurn(expectedCommandId) {\n await this.mutate(async () => {\n this.requireInitialized();\n if (expectedCommandId !== void 0 && this.activeTurn !== null && this.activeTurn.commandId !== expectedCommandId) {\n return;\n }\n const commandId = expectedCommandId ?? this.activeTurn?.commandId;\n await unlinkDurably(this.requireCurrentAttemptDirectory(), ACTIVE_TURN_FILE);\n this.activeTurn = null;\n if (commandId && this.turnTerminalFacts.delete(commandId)) await this.persistMetadata();\n });\n }\n async recordCommandReceived(command) {\n return this.mutate(async () => {\n this.requireInitialized();\n const { commandIdentity, existing } = this.validateCommandReplay(command);\n if (existing) return existing;\n const record = {\n ...commandIdentity,\n status: "received",\n recordedAt: (/* @__PURE__ */ new Date()).toISOString()\n };\n this.assertCommandLedgerCapacity(record, false, true);\n await appendDurably(this.requireCurrentAttemptDirectory(), COMMAND_LEDGER_FILE, record);\n this.commandLedgerBytes += serializedRecordBytes(record);\n this.commandLedgerRecords += 1;\n this.commandsById.set(record.commandId, record);\n this.commandIdsBySequence.set(record.commandSequence, record.commandId);\n return record;\n });\n }\n async completeCommand(command, status, error) {\n return this.mutate(async () => {\n this.requireInitialized();\n const { existing } = this.validateCommandReplay(command);\n if (!existing) {\n throw new StoreMutationConflictError(\n `Command ${command.commandId} must be durably received before completion.`\n );\n }\n return this.completeStoredCommandWithinMutation(existing, status, error);\n });\n }\n async completeStoredCommand(command, status, error) {\n return this.mutate(async () => {\n this.requireInitialized();\n const existing = this.commandsById.get(command.commandId);\n if (!existing) {\n throw new StoreMutationConflictError(`Command ${command.commandId} is not in the ledger.`);\n }\n this.assertMatchingStoredCommand(existing, command);\n return this.completeStoredCommandWithinMutation(existing, status, error);\n });\n }\n validateCommandReplay(command, options = {}) {\n this.requireInitialized();\n const commandIdentity = createSupervisorCommandIdentity(command);\n const existing = this.commandsById.get(command.commandId);\n if (existing) {\n this.assertMatchingCommandFrame(existing, commandIdentity, options.deferLegacyUnfinished);\n }\n const sequenceOwner = this.commandIdsBySequence.get(command.commandSequence);\n if (sequenceOwner && sequenceOwner !== command.commandId) {\n throw new StoreMutationConflictError(\n `Command sequence ${command.commandSequence} is already owned by ${sequenceOwner}.`\n );\n }\n return { commandIdentity, existing };\n }\n async advanceCommandCursor(sequence) {\n await this.mutate(async () => {\n this.requireInitialized();\n if (!isNonNegativeInteger2(sequence)) {\n throw new StoreMutationConflictError("Command cursor must be a nonnegative integer.");\n }\n if (sequence <= this.metadata.lastAppliedCommandSequence) return;\n const conflicting = [...this.commandsById.values()].find(\n (command) => command.status === "received" && command.commandSequence <= sequence\n );\n if (conflicting) {\n throw new StoreMutationConflictError(\n `Cannot advance the command cursor to ${sequence}; command ${conflicting.commandId} at sequence ${conflicting.commandSequence} is unfinished.`\n );\n }\n const advancedMetadata = {\n ...this.metadata,\n lastAppliedCommandSequence: sequence\n };\n await this.persistMetadata(advancedMetadata);\n this.metadata = advancedMetadata;\n });\n }\n mutate(operation, initializeStorage = false) {\n const mutation = this.mutationTail.then(async () => {\n if (this.mutationFailure) throw this.mutationFailure;\n let attemptDirectory = null;\n let operationFailed = false;\n try {\n if (initializeStorage && this.attemptDirectoryIdentity === null) {\n attemptDirectory = await openSupervisorAttemptStorage(this.config);\n this.attemptDirectoryIdentity = attemptDirectory.identity;\n } else if (this.attemptDirectoryIdentity !== null) {\n attemptDirectory = await bindDescriptorBoundDirectory(\n this.config.stateDurabilityAnchor,\n this.attemptDir,\n this.attemptDirectoryIdentity\n );\n }\n this.currentAttemptDirectory = attemptDirectory;\n return await operation();\n } catch (error) {\n operationFailed = true;\n if (!(error instanceof StoreMutationConflictError)) this.mutationFailure = error;\n throw error;\n } finally {\n this.currentAttemptDirectory = null;\n try {\n await attemptDirectory?.handle.close();\n } catch (error) {\n if (!operationFailed) {\n this.mutationFailure ??= error;\n throw error;\n }\n }\n }\n });\n this.mutationTail = mutation.then(\n () => void 0,\n () => void 0\n );\n return mutation;\n }\n requireCurrentAttemptDirectory() {\n if (this.currentAttemptDirectory === null) {\n throw new Error("Supervisor attempt storage is not descriptor-bound.");\n }\n return this.currentAttemptDirectory;\n }\n requireInitialized() {\n if (!this.initialized) {\n throw new StoreMutationConflictError("Supervisor store must be initialized before use.");\n }\n }\n loadMetadata(raw) {\n if (!raw) return null;\n let value;\n try {\n value = JSON.parse(raw);\n } catch {\n return null;\n }\n if (!isRecord6(value)) return null;\n const hasDiskFormatVersion = Object.hasOwn(value, "diskFormatVersion");\n if (hasDiskFormatVersion && value.diskFormatVersion !== STORE_DISK_FORMAT_VERSION) {\n throw new Error("Supervisor metadata uses an unsupported disk format version.");\n }\n const recoveryFacts = hasDiskFormatVersion ? parseStoredRecoveryFacts(value.recoveryFacts, {\n allowMissingCommandApplications: false\n }) : null;\n if (hasDiskFormatVersion && recoveryFacts === null) {\n throw new Error("Supervisor metadata contains invalid recovery facts.");\n }\n this.metadata = {\n nextEventSequence: isPositiveInteger3(value.nextEventSequence) ? value.nextEventSequence : DEFAULT_METADATA.nextEventSequence,\n lastAcknowledgedEventSequence: isNonNegativeInteger2(value.lastAcknowledgedEventSequence) ? value.lastAcknowledgedEventSequence : DEFAULT_METADATA.lastAcknowledgedEventSequence,\n lastAppliedCommandSequence: isNonNegativeInteger2(value.lastAppliedCommandSequence) ? value.lastAppliedCommandSequence : DEFAULT_METADATA.lastAppliedCommandSequence\n };\n if (!hasDiskFormatVersion) return null;\n return recoveryFacts;\n }\n loadCommandLedger(raw) {\n for (const value of parseAppendOnlyJsonLines(raw, "Supervisor command ledger")) {\n const command = parseStoredCommand(value);\n if (!command || command.attemptId !== this.config.attemptId) {\n throw new Error("Supervisor command ledger contains an invalid record.");\n }\n const sequenceOwner = this.commandIdsBySequence.get(command.commandSequence);\n if (sequenceOwner && sequenceOwner !== command.commandId) {\n throw new Error(\n `Supervisor command sequence ${command.commandSequence} has multiple owners.`\n );\n }\n const previous = this.commandsById.get(command.commandId);\n if (previous) {\n this.assertMatchingStoredCommand(previous, command, "disk");\n const validTransition = previous.status === "received" ? command.status !== "received" : command.status === previous.status;\n if (!validTransition) {\n throw new Error(\n `Supervisor command ${command.commandId} has an invalid on-disk status transition.`\n );\n }\n } else if (command.status !== "received") {\n throw new Error(\n `Supervisor command ${command.commandId} has an invalid on-disk status transition.`\n );\n }\n this.commandIdsBySequence.set(command.commandSequence, command.commandId);\n this.commandsById.set(command.commandId, command);\n this.commandLedgerRecords += 1;\n if (this.commandLedgerRecords > this.commandLedgerCapacity.maximumRecords + this.commandLedgerCapacity.recoveryReserveRecords) {\n throw new Error("Supervisor command ledger exceeds its bounded record capacity.");\n }\n }\n if (this.commandsById.size > this.commandLedgerCapacity.maximumDistinctCommands) {\n throw new Error("Supervisor command ledger exceeds its distinct-command capacity.");\n }\n let contiguousTerminalSequence = this.metadata.lastAppliedCommandSequence;\n while (contiguousTerminalSequence < Number.MAX_SAFE_INTEGER) {\n const commandId = this.commandIdsBySequence.get(contiguousTerminalSequence + 1);\n const command = commandId ? this.commandsById.get(commandId) : void 0;\n if (!command || command.status === "received") break;\n contiguousTerminalSequence += 1;\n }\n this.metadata.lastAppliedCommandSequence = contiguousTerminalSequence;\n }\n loadOutbox(raw) {\n let checkpoint = null;\n let journalRuntimeVersion = null;\n const allEvents = [];\n let sawEvent = false;\n let previousSequence = 0;\n for (const value of parseAppendOnlyJsonLines(raw, "Supervisor outbox")) {\n const candidateCheckpoint = parseOutboxCheckpoint(value);\n if (candidateCheckpoint) {\n if (checkpoint || sawEvent || !this.hasMatchingIdentity(candidateCheckpoint)) {\n throw new Error("Supervisor outbox contains an invalid compaction checkpoint.");\n }\n checkpoint = candidateCheckpoint;\n journalRuntimeVersion = SUPERVISOR_RUNTIME_VERSION;\n continue;\n }\n const event = parseStoredEvent(value);\n const storedRuntimeVersion = isRecord6(value) && (value.runtimeVersion === LEGACY_SUPERVISOR_RUNTIME_VERSION || value.runtimeVersion === SUPERVISOR_RUNTIME_VERSION) ? value.runtimeVersion : null;\n if (!event || storedRuntimeVersion === null || journalRuntimeVersion !== null && storedRuntimeVersion !== journalRuntimeVersion || !this.hasMatchingIdentity(event) || event.eventId !== createSupervisorEventId(this.config.attemptId, event.attemptSequence) || event.attemptSequence <= previousSequence) {\n throw new Error("Supervisor outbox contains an invalid or out-of-order event record.");\n }\n journalRuntimeVersion = storedRuntimeVersion;\n if (storedRuntimeVersion === LEGACY_SUPERVISOR_RUNTIME_VERSION) {\n this.requiresOutboxMigration = true;\n }\n if (checkpoint && event.attemptSequence <= checkpoint.acknowledgedEventSequence) {\n throw new Error("Supervisor compacted outbox retained an acknowledged event record.");\n }\n sawEvent = true;\n previousSequence = event.attemptSequence;\n allEvents.push(event);\n }\n const checkpointAcknowledgement = checkpoint?.acknowledgedEventSequence ?? 0;\n let expectedJournalSequence = checkpointAcknowledgement + 1;\n for (const event of allEvents) {\n if (event.attemptSequence !== expectedJournalSequence) {\n throw new Error(\n `Supervisor outbox is missing unacknowledged event sequence ${expectedJournalSequence}.`\n );\n }\n expectedJournalSequence += 1;\n }\n const lastJournalSequence = allEvents.at(-1)?.attemptSequence ?? 0;\n const checkpointNextSequence = checkpoint?.nextEventSequence ?? 1;\n const acknowledged = Math.max(\n this.metadata.lastAcknowledgedEventSequence,\n checkpointAcknowledgement\n );\n const nextSequence = Math.max(\n this.metadata.nextEventSequence,\n checkpointNextSequence,\n lastJournalSequence + 1,\n acknowledged + 1\n );\n if (!checkpoint && acknowledged > lastJournalSequence) {\n throw new Error("Supervisor metadata acknowledgement is beyond its legacy outbox history.");\n }\n if (checkpoint && acknowledged > checkpointAcknowledgement && acknowledged > lastJournalSequence) {\n throw new Error("Supervisor metadata acknowledgement is beyond its compacted outbox history.");\n }\n const retained = allEvents.filter((event) => event.attemptSequence > acknowledged);\n let expectedSequence = acknowledged + 1;\n for (const event of retained) {\n if (event.attemptSequence !== expectedSequence) {\n throw new Error(\n `Supervisor outbox is missing unacknowledged event sequence ${expectedSequence}.`\n );\n }\n expectedSequence += 1;\n }\n if (expectedSequence !== nextSequence) {\n throw new Error(\n `Supervisor outbox is missing unacknowledged event sequence ${expectedSequence}.`\n );\n }\n this.metadata.nextEventSequence = nextSequence;\n this.metadata.lastAcknowledgedEventSequence = acknowledged;\n this.events = retained;\n this.unacknowledgedEventBytes = retained.reduce(\n (total, event) => total + serializedFrameBytes(event),\n 0\n );\n const hardMaximumEvents = this.outboxCapacity.maximumEvents + this.outboxCapacity.recoveryReserveEvents;\n const hardMaximumBytes = this.outboxCapacity.maximumBytes + this.outboxCapacity.recoveryReserveBytes;\n if (this.events.length > hardMaximumEvents || this.unacknowledgedEventBytes > hardMaximumBytes) {\n throw new Error("Supervisor outbox exceeds its bounded unacknowledged capacity.");\n }\n const reclaimed = allEvents.filter((event) => event.attemptSequence <= acknowledged);\n this.reclaimedEventCount = reclaimed.length;\n this.reclaimedEventBytes = reclaimed.reduce(\n (total, event) => total + serializedFrameBytes(event),\n 0\n );\n return { checkpoint, allEvents };\n }\n rebuildAndBoundRecoveryFacts(metadataRecoveryFacts, loadedOutbox) {\n const { checkpoint, allEvents } = loadedOutbox;\n const eventsBySequence = new Map(\n allEvents.map((frame) => [frame.attemptSequence, frame])\n );\n const checkpointFacts = checkpoint?.recoveryFacts;\n const checkpointCommandApplicationKeys = new Set(\n checkpointFacts?.commandApplications.map(commandOutcomeFactKey)\n );\n const checkpointCommandFailureKeys = new Set(\n checkpointFacts?.commandFailures.map(commandOutcomeFactKey)\n );\n const checkpointTurnTerminalKeys = new Set(\n checkpointFacts?.turnTerminals.map(turnTerminalFactKey)\n );\n const metadataCommandApplicationKeys = new Set(\n metadataRecoveryFacts?.commandApplications.map(commandOutcomeFactKey)\n );\n const metadataCommandFailureKeys = new Set(\n metadataRecoveryFacts?.commandFailures.map(commandOutcomeFactKey)\n );\n const metadataTurnTerminalKeys = new Set(\n metadataRecoveryFacts?.turnTerminals.map(turnTerminalFactKey)\n );\n const invalidRecoveryFacts = () => {\n throw new Error(\n "Supervisor recovery facts do not match the durable ledger, cursors, and outbox history."\n );\n };\n const assertFactEvent = (eventSequence, matchesEvent, retainedByCheckpoint, retainedByMetadata) => {\n if (eventSequence >= this.metadata.nextEventSequence) invalidRecoveryFacts();\n const frame = eventsBySequence.get(eventSequence);\n if (frame) {\n if (!matchesEvent(frame)) invalidRecoveryFacts();\n return;\n }\n if (!checkpoint || eventSequence > checkpoint.acknowledgedEventSequence || !retainedByCheckpoint || metadataRecoveryFacts !== null && !retainedByMetadata) {\n invalidRecoveryFacts();\n }\n };\n const commandOutcomes = /* @__PURE__ */ new Map();\n const turnTerminals = /* @__PURE__ */ new Map();\n const factOwnersByEventSequence = /* @__PURE__ */ new Map();\n const assertUniqueEventOwner = (eventSequence, owner) => {\n const existing = factOwnersByEventSequence.get(eventSequence);\n if (existing !== void 0 && existing !== owner) invalidRecoveryFacts();\n factOwnersByEventSequence.set(eventSequence, owner);\n };\n const recordCommandOutcome = (kind, fact) => {\n const owner = `${kind}:${fact.commandId}:${fact.commandSequence}`;\n assertUniqueEventOwner(fact.eventSequence, owner);\n const existing = commandOutcomes.get(fact.commandId);\n if (existing && (existing.kind !== kind || !sameCommandOutcomeFact(existing.fact, fact))) {\n invalidRecoveryFacts();\n }\n commandOutcomes.set(fact.commandId, { kind, fact });\n };\n const acceptCommandOutcome = (kind, fact) => {\n const command = this.commandsById.get(fact.commandId);\n if (!command) return invalidRecoveryFacts();\n if (command.commandSequence !== fact.commandSequence) return invalidRecoveryFacts();\n if (command.status === "received" && command.commandSequence <= this.metadata.lastAppliedCommandSequence) {\n invalidRecoveryFacts();\n }\n if (command.status !== "received") return;\n const checkpointKeys = kind === "command_applied" ? checkpointCommandApplicationKeys : checkpointCommandFailureKeys;\n const metadataKeys = kind === "command_applied" ? metadataCommandApplicationKeys : metadataCommandFailureKeys;\n const factKey = commandOutcomeFactKey(fact);\n assertFactEvent(\n fact.eventSequence,\n (frame) => {\n const event = frame.event;\n return event.kind === kind && event.commandId === command.commandId && event.commandSequence === command.commandSequence && event.commandKind === command.commandKind;\n },\n checkpointKeys.has(factKey),\n metadataKeys.has(factKey)\n );\n recordCommandOutcome(kind, fact);\n };\n const acceptPhysicalCommandOutcome = (kind, fact, commandKind) => {\n const command = this.commandsById.get(fact.commandId);\n const matchingTerminalStatus = kind === "command_applied" ? "applied" : "failed";\n if (!command || command.commandSequence !== fact.commandSequence || command.commandKind !== commandKind || command.status !== "received" && command.status !== matchingTerminalStatus) {\n invalidRecoveryFacts();\n }\n recordCommandOutcome(kind, fact);\n };\n const acceptTurnTerminal = (fact) => {\n const command = this.commandsById.get(fact.commandId);\n if (!command) {\n if (this.activeTurn?.commandId === fact.commandId) return invalidRecoveryFacts();\n return;\n }\n if (command.commandKind !== "prompt") return invalidRecoveryFacts();\n if (command.status === "received" && command.commandSequence <= this.metadata.lastAppliedCommandSequence) {\n invalidRecoveryFacts();\n }\n const commandUnfinished = command.status === "received";\n const turnStillActive = this.activeTurn?.commandId === fact.commandId;\n if (!commandUnfinished && !turnStillActive) return;\n assertFactEvent(\n fact.eventSequence,\n (frame) => {\n const event = frame.event;\n return event.kind === fact.kind && event.commandId === command.commandId && (event.kind !== "turn_failed" || event.stopReason === fact.stopReason);\n },\n checkpointTurnTerminalKeys.has(turnTerminalFactKey(fact)),\n metadataTurnTerminalKeys.has(turnTerminalFactKey(fact))\n );\n const owner = `${fact.kind}:${fact.commandId}`;\n assertUniqueEventOwner(fact.eventSequence, owner);\n const existing = turnTerminals.get(fact.commandId);\n if (existing && !sameTurnTerminalFact(existing, fact)) invalidRecoveryFacts();\n turnTerminals.set(fact.commandId, fact);\n };\n for (const recoveryFacts of [metadataRecoveryFacts, checkpointFacts]) {\n if (!recoveryFacts) continue;\n for (const fact of recoveryFacts.commandApplications) {\n acceptCommandOutcome("command_applied", fact);\n }\n for (const fact of recoveryFacts.commandFailures) {\n acceptCommandOutcome("command_failed", fact);\n }\n for (const fact of recoveryFacts.turnTerminals) acceptTurnTerminal(fact);\n }\n for (const frame of allEvents) {\n const event = frame.event;\n if (event.kind === "command_applied" || event.kind === "command_failed") {\n acceptPhysicalCommandOutcome(\n event.kind,\n {\n commandId: event.commandId,\n commandSequence: event.commandSequence,\n eventSequence: frame.attemptSequence\n },\n event.commandKind\n );\n } else if ((event.kind === "turn_completed" || event.kind === "turn_failed" || event.kind === "turn_stopped") && event.commandId) {\n acceptTurnTerminal({\n commandId: event.commandId,\n eventSequence: frame.attemptSequence,\n kind: event.kind,\n ...event.kind === "turn_failed" && event.stopReason !== void 0 ? { stopReason: event.stopReason } : {}\n });\n }\n }\n this.commandApplicationFacts.clear();\n this.commandFailureFacts.clear();\n this.turnTerminalFacts.clear();\n for (const { kind, fact } of commandOutcomes.values()) {\n if (this.commandsById.get(fact.commandId)?.status !== "received") continue;\n if (kind === "command_applied") this.commandApplicationFacts.set(fact.commandId, fact);\n else this.commandFailureFacts.set(fact.commandId, fact);\n }\n for (const fact of turnTerminals.values()) {\n const commandUnfinished = this.commandsById.get(fact.commandId)?.status === "received";\n const turnStillActive = this.activeTurn?.commandId === fact.commandId;\n if (commandUnfinished || turnStillActive) this.turnTerminalFacts.set(fact.commandId, fact);\n }\n }\n noteRecoveryFact(frame) {\n const event = frame.event;\n if (event.kind === "command_applied" || event.kind === "command_failed") {\n const commandOutcomeFacts = event.kind === "command_applied" ? this.commandApplicationFacts : this.commandFailureFacts;\n if (this.commandsById.get(event.commandId)?.status === "received") {\n const existing = commandOutcomeFacts.get(event.commandId);\n if (!existing || frame.attemptSequence < existing.eventSequence) {\n commandOutcomeFacts.set(event.commandId, {\n commandId: event.commandId,\n commandSequence: event.commandSequence,\n eventSequence: frame.attemptSequence\n });\n }\n }\n return;\n }\n if ((event.kind === "turn_completed" || event.kind === "turn_failed" || event.kind === "turn_stopped") && event.commandId) {\n const commandUnfinished = this.commandsById.get(event.commandId)?.status === "received";\n const turnStillActive = this.activeTurn?.commandId === event.commandId;\n if (!commandUnfinished && !turnStillActive) return;\n const existing = this.turnTerminalFacts.get(event.commandId);\n if (!existing || frame.attemptSequence < existing.eventSequence) {\n this.turnTerminalFacts.set(event.commandId, {\n commandId: event.commandId,\n eventSequence: frame.attemptSequence,\n kind: event.kind,\n ...event.kind === "turn_failed" && event.stopReason !== void 0 ? { stopReason: event.stopReason } : {}\n });\n }\n }\n }\n assertMatchingCommandFrame(existing, commandIdentity, deferLegacyUnfinished = false) {\n const comparison = compareSupervisorCommandIdentity(existing, commandIdentity);\n if (comparison === "mismatch") {\n throw new StoreMutationConflictError(\n `Command ${commandIdentity.commandId} was replayed with different semantic content.`\n );\n }\n if (comparison === "unverifiable" && existing.status === "received" && !deferLegacyUnfinished) {\n throw new StoreMutationConflictError(\n `Legacy unfinished command ${commandIdentity.commandId} cannot be safely replayed.`\n );\n }\n }\n assertMatchingStoredCommand(existing, command, context = "completion") {\n const comparison = compareSupervisorCommandIdentity(existing, command);\n const mixedFingerprintPresence = existing.commandFingerprint === void 0 !== (command.commandFingerprint === void 0);\n if (comparison !== "mismatch" && !mixedFingerprintPresence) return;\n if (context === "disk") {\n throw new Error(`Supervisor command ${command.commandId} changed identity on disk.`);\n }\n throw new StoreMutationConflictError(\n `Command ${command.commandId} completion metadata does not match its receipt.`\n );\n }\n async completeStoredCommandWithinMutation(command, status, error) {\n if (command.status !== "received") {\n if (command.status === status) return command;\n throw new StoreMutationConflictError(\n `Command ${command.commandId} already has the ${command.status} outcome.`\n );\n }\n const record = {\n commandId: command.commandId,\n commandSequence: command.commandSequence,\n commandKind: command.commandKind,\n attemptId: command.attemptId,\n status,\n recordedAt: (/* @__PURE__ */ new Date()).toISOString(),\n ...command.commandFingerprint === void 0 ? {} : { commandFingerprint: command.commandFingerprint },\n ...error === void 0 ? {} : { error }\n };\n this.assertCommandLedgerCapacity(record, true, false);\n await appendDurably(this.requireCurrentAttemptDirectory(), COMMAND_LEDGER_FILE, record);\n this.commandLedgerBytes += serializedRecordBytes(record);\n this.commandLedgerRecords += 1;\n this.commandsById.set(record.commandId, record);\n this.commandIdsBySequence.set(record.commandSequence, record.commandId);\n if (record.commandSequence === this.metadata.lastAppliedCommandSequence + 1) {\n this.metadata.lastAppliedCommandSequence = record.commandSequence;\n while (true) {\n const nextId = this.commandIdsBySequence.get(this.metadata.lastAppliedCommandSequence + 1);\n const next = nextId ? this.commandsById.get(nextId) : void 0;\n if (!next || next.status === "received") break;\n this.metadata.lastAppliedCommandSequence += 1;\n }\n }\n this.commandApplicationFacts.delete(record.commandId);\n this.commandFailureFacts.delete(record.commandId);\n if (this.activeTurn?.commandId !== record.commandId) {\n this.turnTerminalFacts.delete(record.commandId);\n }\n await this.persistMetadata();\n return record;\n }\n assertCommandLedgerCapacity(record, usesRecoveryReserve, addsDistinctCommand) {\n const recordBytes = serializedRecordBytes(record);\n const maximumBytes = this.commandLedgerCapacity.maximumBytes + (usesRecoveryReserve ? this.commandLedgerCapacity.recoveryReserveBytes : 0);\n const maximumRecords = this.commandLedgerCapacity.maximumRecords + (usesRecoveryReserve ? this.commandLedgerCapacity.recoveryReserveRecords : 0);\n if (this.commandLedgerBytes + recordBytes > maximumBytes || this.commandLedgerRecords + 1 > maximumRecords || addsDistinctCommand && this.commandsById.size + 1 > this.commandLedgerCapacity.maximumDistinctCommands) {\n throw new Error("Supervisor command ledger exceeded bounded capacity.");\n }\n }\n hasMatchingIdentity(value) {\n return hasMatchingAttempt(this.config, value);\n }\n metadataForPersistence(metadata = this.metadata) {\n return {\n diskFormatVersion: STORE_DISK_FORMAT_VERSION,\n ...metadata,\n recoveryFacts: {\n commandApplications: [...this.commandApplicationFacts.values()].sort(\n (left, right) => left.eventSequence - right.eventSequence\n ),\n commandFailures: [...this.commandFailureFacts.values()].sort(\n (left, right) => left.eventSequence - right.eventSequence\n ),\n turnTerminals: [...this.turnTerminalFacts.values()].sort(\n (left, right) => left.eventSequence - right.eventSequence\n )\n }\n };\n }\n async persistMetadata(metadata = this.metadata) {\n await writeJsonAtomically(\n this.requireCurrentAttemptDirectory(),\n METADATA_FILE,\n this.metadataForPersistence(metadata),\n SUPERVISOR_MAX_STORE_METADATA_BYTES,\n "Supervisor metadata"\n );\n }\n shouldCompactOutbox() {\n if (this.requiresOutboxMigration) return true;\n if (this.metadata.lastAcknowledgedEventSequence === 0) return false;\n if (this.events.length === 0 && this.metadata.lastAcknowledgedEventSequence === this.lastEventSequence) {\n return true;\n }\n return this.reclaimedEventCount >= OUTBOX_COMPACTION_MIN_RECLAIMED_EVENTS || this.reclaimedEventBytes >= OUTBOX_COMPACTION_MIN_RECLAIMED_BYTES;\n }\n async maybeCompactOutbox() {\n if (!this.shouldCompactOutbox()) return;\n const checkpoint = {\n recordType: "outbox_checkpoint",\n diskFormatVersion: STORE_DISK_FORMAT_VERSION,\n sessionId: this.config.sessionId,\n runId: this.config.runId,\n attemptId: this.config.attemptId,\n acknowledgedEventSequence: this.metadata.lastAcknowledgedEventSequence,\n nextEventSequence: this.metadata.nextEventSequence,\n recoveryFacts: this.metadataForPersistence().recoveryFacts\n };\n const lines = [checkpoint, ...this.events].map((value) => JSON.stringify(value));\n await writeTextAtomically(\n this.requireCurrentAttemptDirectory(),\n OUTBOX_FILE,\n `${lines.join("\\n")}\n`\n );\n this.requiresOutboxMigration = false;\n this.reclaimedEventCount = 0;\n this.reclaimedEventBytes = 0;\n }\n};\n\n// src/supervisor/runtime.ts\nvar SUPERVISOR_SHUTDOWN_STOP_REASON = "supervisor_shutdown";\nfunction serializedCommandBytes(command) {\n return Buffer.byteLength(JSON.stringify(command), "utf8");\n}\nvar DEFAULT_DEPENDENCIES2 = {\n ...DEFAULT_GATEWAY_TRANSPORT_DEPENDENCIES\n};\nvar SupervisorCommandProcessor = class {\n constructor(config, store, harness, attachments, emit, executionGate, onFailure, redactor) {\n this.config = config;\n this.store = store;\n this.harness = harness;\n this.attachments = attachments;\n this.emit = emit;\n this.executionGate = executionGate;\n this.onFailure = onFailure;\n this.redactor = redactor;\n executionGate.signal.addEventListener(\n "abort",\n () => {\n this.clearPendingCommands();\n this.preparedResumeBatch = null;\n },\n { once: true }\n );\n }\n config;\n store;\n harness;\n attachments;\n emit;\n executionGate;\n onFailure;\n redactor;\n pending = /* @__PURE__ */ new Map();\n pendingByteLengths = /* @__PURE__ */ new Map();\n pendingBytes = 0;\n applying = /* @__PURE__ */ new Map();\n intakeTail = Promise.resolve();\n drainTask = null;\n nextResumeBatchToken = 1;\n preparedResumeBatch = null;\n async recoverUnfinishedCommands() {\n await this.finalizeInterruptedCommands({\n stopReason: SUPERVISOR_RECOVERY_STOP_REASON,\n message: "Supervisor restarted while Pi work was in flight; side-effect state is indeterminate."\n });\n }\n async finalizeGracefulShutdown() {\n await this.waitForQuiescence();\n await this.finalizeInterruptedCommands({\n stopReason: SUPERVISOR_SHUTDOWN_STOP_REASON,\n message: "Supervisor shut down while Pi work was in flight."\n });\n }\n async finalizeInterruptedCommands(options) {\n const unfinished = this.store.getUnfinishedCommands();\n const activeTurn = await this.store.readActiveTurn();\n const error = {\n name: "InterruptedCommandError",\n message: options.message\n };\n for (const command of unfinished) {\n const appliedByStopMarker = activeTurn?.stop?.commandId === command.commandId;\n if (appliedByStopMarker && !this.store.hasCommandApplicationEvent(command.commandId)) {\n await this.emit({\n kind: "command_applied",\n commandId: command.commandId,\n commandSequence: command.commandSequence,\n commandKind: command.commandKind\n });\n }\n if (!appliedByStopMarker && !this.store.hasCommandApplicationEvent(command.commandId) && !this.store.hasCommandFailureEvent(command.commandId)) {\n await this.emit({\n kind: "command_failed",\n commandId: command.commandId,\n commandSequence: command.commandSequence,\n commandKind: command.commandKind,\n error\n });\n }\n }\n if (activeTurn && !this.store.hasTurnTerminalEvent(activeTurn.commandId)) {\n if (activeTurn.stop) {\n await this.emit({\n kind: "turn_stopped",\n adapter: this.harness.name,\n commandId: activeTurn.commandId,\n ...activeTurn.stop.reason === void 0 ? {} : { reason: activeTurn.stop.reason }\n });\n } else {\n await this.emit({\n kind: "turn_failed",\n adapter: this.harness.name,\n commandId: activeTurn.commandId,\n stopReason: options.stopReason,\n error\n });\n }\n }\n for (const command of unfinished) {\n if (command.commandKind === "prompt" && command.commandId !== activeTurn?.commandId && !this.store.hasTurnTerminalEvent(command.commandId)) {\n await this.emit({\n kind: "turn_failed",\n adapter: this.harness.name,\n commandId: command.commandId,\n stopReason: options.stopReason,\n error\n });\n }\n if (this.store.hasCommandApplicationEvent(command.commandId) || activeTurn?.stop?.commandId === command.commandId) {\n await this.store.completeStoredCommand(command, "applied");\n } else {\n await this.store.completeStoredCommand(command, "failed", error);\n }\n }\n if (activeTurn) await this.store.clearActiveTurn(activeTurn.commandId);\n }\n async enqueue(command) {\n const intake = this.intakeTail.then(() => {\n const staged = this.snapshotPendingCommands();\n this.validateAndStage(command, staged);\n this.commitStagedCommands(staged);\n this.scheduleDrain();\n });\n this.intakeTail = intake.catch(() => void 0);\n await intake;\n }\n async prepareResumeBatch(commands, lastAppliedCommandSequence) {\n const intake = this.intakeTail.then(() => {\n this.preparedResumeBatch = null;\n const staged = {\n commands: /* @__PURE__ */ new Map(),\n byteLengths: /* @__PURE__ */ new Map(),\n totalBytes: 0\n };\n const effectiveCommandCursor = Math.max(\n lastAppliedCommandSequence,\n this.store.lastAppliedCommandSequence\n );\n try {\n for (const command of commands) {\n this.validateAndStage(command, staged, effectiveCommandCursor);\n }\n } catch (error) {\n this.scheduleDrain();\n throw error;\n }\n const token = this.nextResumeBatchToken;\n this.nextResumeBatchToken += 1;\n this.preparedResumeBatch = { token, staged };\n return token;\n });\n this.intakeTail = intake.then(() => void 0, () => void 0);\n return intake;\n }\n async commitResumeBatch(token, canCommit) {\n const intake = this.intakeTail.then(() => {\n const prepared = this.preparedResumeBatch;\n if (!prepared || prepared.token !== token || !canCommit()) return false;\n const durableCursor = this.store.lastAppliedCommandSequence;\n for (const sequence of prepared.staged.commands.keys()) {\n if (sequence > durableCursor) continue;\n const commandBytes = prepared.staged.byteLengths.get(sequence);\n if (commandBytes === void 0 || commandBytes > prepared.staged.totalBytes) {\n throw new Error("Prepared command byte accounting is inconsistent.");\n }\n prepared.staged.commands.delete(sequence);\n prepared.staged.byteLengths.delete(sequence);\n prepared.staged.totalBytes -= commandBytes;\n }\n this.preparedResumeBatch = null;\n this.commitStagedCommands(prepared.staged);\n this.scheduleDrain();\n return true;\n });\n this.intakeTail = intake.then(() => void 0, () => void 0);\n return intake;\n }\n async abortResumeBatch(token) {\n const intake = this.intakeTail.then(() => {\n if (this.preparedResumeBatch?.token !== token) return;\n this.preparedResumeBatch = null;\n this.scheduleDrain();\n });\n this.intakeTail = intake.catch(() => void 0);\n await intake;\n }\n close() {\n this.clearPendingCommands();\n this.preparedResumeBatch = null;\n }\n async waitForQuiescence() {\n while (true) {\n await this.intakeTail;\n const draining = this.drainTask;\n if (!draining) return;\n await draining.catch(() => void 0);\n if (this.drainTask === null) return;\n }\n }\n validateAndStage(command, staged, lastAppliedCommandSequence = this.store.lastAppliedCommandSequence) {\n const pendingCommands = staged.commands;\n this.executionGate.throwIfClosed();\n if (!hasMatchingAttempt(this.config, command)) {\n throw new Error("Command attempt identity does not match this supervisor.");\n }\n const commandIdentity = createSupervisorCommandIdentity(command);\n const applying = this.applying.get(command.commandId);\n if (applying) {\n if (compareSupervisorCommandIdentity(applying, commandIdentity) !== "match") {\n throw new Error(`Applying command ${command.commandId} was replayed with different metadata.`);\n }\n return;\n }\n for (const [applyingId, applyingCommand] of this.applying) {\n if (applyingCommand.commandSequence === command.commandSequence && applyingId !== command.commandId) {\n throw new Error(\n `Command sequence ${command.commandSequence} conflicts with applying command ${applyingId}.`\n );\n }\n }\n const { existing } = this.store.validateCommandReplay(command, {\n // Preserve the legacy recovery boundary: intake may stage an otherwise\n // matching v1 receipt, but the serialized record mutation still rejects\n // it before any attachment or harness side effect.\n deferLegacyUnfinished: true\n });\n if (existing?.status !== void 0 && existing.status !== "received") return;\n if (command.commandSequence <= lastAppliedCommandSequence) return;\n if (command.commandSequence - lastAppliedCommandSequence > SUPERVISOR_PENDING_COMMAND_SEQUENCE_WINDOW) {\n throw new Error(\n `Command sequence ${command.commandSequence} exceeds the pending sequence window.`\n );\n }\n const pendingAtSequence = pendingCommands.get(command.commandSequence);\n if (pendingAtSequence) {\n if (pendingAtSequence.commandId !== command.commandId) {\n throw new Error(\n `Pending command sequence ${command.commandSequence} conflicts with command ${pendingAtSequence.commandId}.`\n );\n }\n if (compareSupervisorCommandIdentity(\n createSupervisorCommandIdentity(pendingAtSequence),\n commandIdentity\n ) !== "match") {\n throw new Error(\n `Pending command ${command.commandId} was replayed with different metadata.`\n );\n }\n }\n for (const pending of pendingCommands.values()) {\n if (pending.commandId === command.commandId && compareSupervisorCommandIdentity(createSupervisorCommandIdentity(pending), commandIdentity) !== "match") {\n throw new Error(`Pending command ${command.commandId} was replayed with different metadata.`);\n }\n }\n const nextCount = pendingCommands.size + (pendingAtSequence ? 0 : 1);\n if (nextCount > SUPERVISOR_MAX_PENDING_COMMANDS) {\n throw new Error(\n `Pending command count exceeds the ${SUPERVISOR_MAX_PENDING_COMMANDS}-command limit.`\n );\n }\n const commandBytes = serializedCommandBytes(command);\n const previousBytes = pendingAtSequence ? staged.byteLengths.get(command.commandSequence) ?? serializedCommandBytes(pendingAtSequence) : 0;\n const nextBytes = staged.totalBytes - previousBytes + commandBytes;\n if (nextBytes > SUPERVISOR_MAX_PENDING_COMMAND_BYTES) {\n throw new Error(\n `Pending commands exceed the ${SUPERVISOR_MAX_PENDING_COMMAND_BYTES}-byte limit.`\n );\n }\n pendingCommands.set(command.commandSequence, command);\n staged.byteLengths.set(command.commandSequence, commandBytes);\n staged.totalBytes = nextBytes;\n }\n snapshotPendingCommands() {\n return {\n commands: new Map(this.pending),\n byteLengths: new Map(this.pendingByteLengths),\n totalBytes: this.pendingBytes\n };\n }\n commitStagedCommands(staged) {\n this.clearPendingCommands();\n for (const [sequence, command] of staged.commands) this.pending.set(sequence, command);\n for (const [sequence, byteLength] of staged.byteLengths) {\n this.pendingByteLengths.set(sequence, byteLength);\n }\n this.pendingBytes = staged.totalBytes;\n }\n clearPendingCommands() {\n this.pending.clear();\n this.pendingByteLengths.clear();\n this.pendingBytes = 0;\n }\n scheduleDrain() {\n if (this.drainTask || this.preparedResumeBatch || this.executionGate.isClosed) return;\n const draining = this.drain();\n this.drainTask = draining;\n void draining.catch((error) => {\n const closure = this.executionGate.closure;\n if (closure?.kind === "shutdown" || closure?.kind === "superseded") return;\n this.onFailure(errorFromUnknown(error));\n }).finally(() => {\n if (this.drainTask === draining) this.drainTask = null;\n if (!this.executionGate.isClosed && this.pending.has(this.store.lastAppliedCommandSequence + 1)) {\n this.scheduleDrain();\n }\n });\n }\n async drain() {\n while (true) {\n this.executionGate.throwIfClosed();\n if (this.preparedResumeBatch) return;\n const sequence = this.store.lastAppliedCommandSequence + 1;\n const command = this.pending.get(sequence);\n if (!command) return;\n const commandBytes = this.pendingByteLengths.get(sequence);\n if (commandBytes === void 0 || commandBytes > this.pendingBytes) {\n throw new Error("Pending command byte accounting is inconsistent.");\n }\n this.pending.delete(sequence);\n this.pendingByteLengths.delete(sequence);\n this.pendingBytes -= commandBytes;\n await this.apply(command);\n }\n }\n async apply(command) {\n if (this.applying.has(command.commandId)) return;\n this.applying.set(command.commandId, createSupervisorCommandIdentity(command));\n const existing = await this.store.recordCommandReceived(command);\n let stopClaimed = false;\n let stopFailure = null;\n try {\n if (existing.status !== "received") return;\n await this.emit({\n kind: "command_received",\n commandId: command.commandId,\n commandSequence: command.commandSequence,\n commandKind: command.payload.kind\n });\n this.executionGate.throwIfClosed();\n if (command.payload.kind === "prompt") {\n const attachments = await this.attachments.materialize(\n command.commandId,\n command.payload.attachments,\n this.executionGate.signal\n );\n this.executionGate.throwIfClosed();\n await this.store.recordActiveTurn(command.commandId);\n this.executionGate.throwIfClosed();\n this.executionGate.throwIfClosed();\n await this.harness.prompt({\n commandId: command.commandId,\n message: command.payload.message,\n attachments\n });\n } else if (command.payload.kind === "steer") {\n const attachments = await this.attachments.materialize(\n command.commandId,\n command.payload.attachments,\n this.executionGate.signal\n );\n this.executionGate.throwIfClosed();\n await this.harness.steer({\n commandId: command.commandId,\n message: command.payload.message,\n attachments\n });\n } else {\n const stopReason = command.payload.reason === void 0 ? void 0 : this.redactor.redact(command.payload.reason);\n stopClaimed = this.harness.claimStop();\n if (stopClaimed) {\n await this.store.recordActiveTurnStop(command.commandId, stopReason);\n try {\n this.executionGate.throwIfClosed();\n await this.harness.abortClaimedStop(stopReason, command.commandId);\n } catch (error) {\n stopFailure = errorFromUnknown(error);\n }\n }\n }\n await this.emit({\n kind: "command_applied",\n commandId: command.commandId,\n commandSequence: command.commandSequence,\n commandKind: command.payload.kind\n });\n await this.store.completeCommand(command, "applied");\n if (command.payload.kind === "prompt" || stopClaimed) {\n this.harness.confirmCommandApplied(command.commandId);\n }\n if (stopFailure) {\n const closure = this.executionGate.closure;\n if (closure?.kind !== "shutdown" && closure?.kind !== "superseded") {\n this.onFailure(stopFailure);\n }\n return;\n }\n } catch (error) {\n const closure = this.executionGate.closure;\n if (closure?.kind === "shutdown" || closure?.kind === "superseded") return;\n if (closure?.kind === "persistence_failed") throw closure.error;\n if (this.store.hasCommandApplicationEvent(command.commandId)) throw error;\n const serialized = this.redactor.serialize(error);\n await this.emit({\n kind: "command_failed",\n commandId: command.commandId,\n commandSequence: command.commandSequence,\n commandKind: command.payload.kind,\n error: serialized\n });\n if (command.payload.kind === "prompt" && !this.store.hasTurnTerminalEvent(command.commandId)) {\n await this.emit({\n kind: "turn_failed",\n adapter: this.harness.name,\n commandId: command.commandId,\n stopReason: "prompt_not_accepted",\n error: serialized\n });\n }\n await this.store.completeCommand(command, "failed", serialized);\n if (command.payload.kind === "prompt") {\n await this.store.clearActiveTurn(command.commandId);\n }\n if (closure) this.onFailure(closure.error);\n } finally {\n this.applying.delete(command.commandId);\n }\n }\n};\nvar SupervisorRuntime = class {\n constructor(config, dependencies = DEFAULT_DEPENDENCIES2, handoffEnvironment = {}) {\n this.config = config;\n this.redactor = new SensitiveValueRedactor(Object.values(handoffEnvironment));\n this.completion = new Promise((resolveCompletion, rejectCompletion) => {\n this.resolveCompletion = resolveCompletion;\n this.rejectCompletion = rejectCompletion;\n });\n void this.completion.catch(() => void 0);\n this.store = new DiskSupervisorStore(config);\n this.harness = new PiSdkHarnessAdapter(config, this.executionGate, this.redactor);\n this.attachments = new SupervisorAttachmentMaterializer(config, {\n ...dependencies.fetch === void 0 ? {} : { fetch: dependencies.fetch }\n });\n this.commands = new SupervisorCommandProcessor(\n config,\n this.store,\n this.harness,\n this.attachments,\n (event, durability) => this.emitEvent(event, durability),\n this.executionGate,\n (error) => this.failRuntime(error),\n this.redactor\n );\n this.transport = new SupervisorGatewayTransport(\n config,\n this.store,\n this.harness,\n this.commands,\n this.executionGate,\n this.redactor,\n {\n getCredential: () => this.credential,\n emitEvent: (event, durability) => this.emitEvent(event, durability),\n acceptSupersession: (reason) => this.acceptSupersession(reason),\n failRuntime: (error) => this.failRuntime(error),\n failTransport: (error) => this.failTransport(error)\n },\n dependencies\n );\n this.executionGate.signal.addEventListener(\n "abort",\n () => this.handleExecutionClosure(),\n { once: true }\n );\n }\n config;\n executionGate = new SupervisorExecutionGate();\n redactor;\n store;\n harness;\n attachments;\n commands;\n transport;\n completion;\n resolveCompletion;\n rejectCompletion;\n credential = null;\n stopped = false;\n superseded = false;\n stopPromise = null;\n fatalError = null;\n completionSettled = false;\n async start() {\n const credential = process.env[this.config.credentialEnv];\n if (!isSupervisorAttemptCredential(credential)) {\n throw new Error(\n `Supervisor credential ${this.config.credentialEnv} must be the canonical unpadded base64url encoding of ${SUPERVISOR_CREDENTIAL_BYTE_LENGTH} cryptographically random bytes (${SUPERVISOR_CREDENTIAL_ENCODED_LENGTH} characters).`\n );\n }\n this.credential = credential;\n this.redactor.capture(credential);\n delete process.env[this.config.credentialEnv];\n try {\n await this.store.initialize();\n await this.commands.recoverUnfinishedCommands();\n this.harness.subscribe(async (event) => {\n try {\n if (event.type === "started") {\n await this.emitEvent({\n kind: "harness_started",\n adapter: this.harness.name,\n pid: event.pid\n });\n } else if (event.type === "event") {\n await this.emitEvent(\n { kind: "harness_event", adapter: this.harness.name, payload: event.payload },\n isCoalescedPiEvent(event.payload) ? "coalesced" : "durable"\n );\n } else if (event.type === "lifecycle") {\n await this.emitEvent({\n ...event.event,\n adapter: this.harness.name\n });\n if ((event.event.kind === "turn_completed" || event.event.kind === "turn_failed" || event.event.kind === "turn_stopped") && event.event.commandId) {\n await this.store.clearActiveTurn(event.event.commandId);\n }\n } else if (event.type === "stderr") {\n await this.emitEvent({\n kind: "harness_stderr",\n adapter: this.harness.name,\n data: this.redactor.redact(event.data)\n });\n } else {\n await this.emitEvent({\n kind: "harness_exited",\n adapter: this.harness.name,\n exitCode: event.result.exitCode,\n signal: event.result.signal\n });\n }\n } catch (error) {\n const failure = errorFromUnknown(error);\n this.failRuntime(failure);\n throw failure;\n }\n });\n await this.emitEvent({\n kind: "supervisor_started",\n recovered: this.store.lastEventSequence > 0\n });\n this.transport.start();\n } catch (error) {\n const failure = errorFromUnknown(error);\n this.executionGate.close("startup_failed", "Supervisor startup failed.", failure);\n await this.attachments.close().catch(() => void 0);\n this.credential = null;\n throw failure;\n }\n }\n waitUntilStopped() {\n return this.completion;\n }\n serializeErrorForLog(error) {\n return this.redactor.serialize(error);\n }\n stop(reason = "supervisor_shutdown") {\n const safeReason = sanitizeSupervisorReason(this.redactor.redact(reason));\n this.executionGate.close(this.superseded ? "superseded" : "shutdown", safeReason);\n this.commands.close();\n if (this.stopPromise) return this.stopPromise;\n this.stopped = true;\n const stopping = this.stopRuntime(safeReason);\n this.stopPromise = stopping;\n void stopping.then(\n () => this.settleCompletion(),\n (error) => {\n this.fatalError ??= errorFromUnknown(error);\n this.settleCompletion();\n }\n );\n return stopping;\n }\n async stopRuntime(reason) {\n this.transport.beginShutdown();\n const stopEvent = this.fatalError ? Promise.resolve() : withTimeout(\n this.emitEvent({ kind: "supervisor_stopping", reason }),\n this.config.harness.stopGraceMs,\n "Timed out while persisting the supervisor shutdown event."\n );\n const harnessStop = this.harness.stop(reason);\n const commandQuiescence = withTimeout(\n this.commands.waitForQuiescence(),\n this.config.harness.stopGraceMs,\n "Timed out while waiting for supervisor commands to quiesce."\n );\n const results = await Promise.allSettled([stopEvent, harnessStop, commandQuiescence]);\n let rejected = results.find(\n (result) => result.status === "rejected"\n );\n if (!rejected && !this.fatalError && !this.superseded) {\n try {\n await withTimeout(\n this.commands.finalizeGracefulShutdown(),\n this.config.harness.stopGraceMs,\n "Timed out while finalizing interrupted supervisor commands."\n );\n } catch (error) {\n rejected = {\n status: "rejected",\n reason: error\n };\n }\n }\n try {\n await withTimeout(\n this.attachments.close(),\n this.config.harness.stopGraceMs,\n "Timed out while releasing descriptor-bound attachment storage."\n );\n } catch (error) {\n rejected ??= {\n status: "rejected",\n reason: error\n };\n }\n this.transport.finishShutdown({\n fatal: this.fatalError !== null,\n superseded: this.superseded\n });\n this.credential = null;\n if (this.fatalError) throw this.fatalError;\n if (rejected) throw errorFromUnknown(rejected.reason);\n }\n settleCompletion() {\n if (this.completionSettled) return;\n this.completionSettled = true;\n if (this.fatalError) this.rejectCompletion(this.fatalError);\n else this.resolveCompletion();\n }\n async emitEvent(event, durability = "durable") {\n try {\n await this.store.appendEvent(event, durability);\n this.transport.flushOutbox();\n } catch (error) {\n const failure = errorFromUnknown(error);\n this.failRuntime(failure);\n throw failure;\n }\n }\n failRuntime(error) {\n this.transitionToFatal(\n error,\n "persistence_failed",\n "Durable supervisor state could not be persisted.",\n true\n );\n }\n failTransport(error) {\n this.transitionToFatal(\n error,\n "runtime_failed",\n "Supervisor WebSocket construction failed.",\n false\n );\n }\n transitionToFatal(error, gateKind, gateMessage, failActiveConnection) {\n if (this.fatalError) return;\n this.fatalError = error;\n this.executionGate.close(gateKind, gateMessage, error);\n this.commands.close();\n if (failActiveConnection) this.transport.failActiveConnection();\n queueMicrotask(() => {\n void this.stop("fatal_supervisor_error").catch(() => void 0);\n });\n }\n handleExecutionClosure() {\n const closure = this.executionGate.closure;\n if (!closure || closure.kind === "shutdown" || closure.kind === "superseded" || closure.kind === "startup_failed" || this.fatalError) {\n return;\n }\n const cause = closure.error.cause;\n const failure = cause instanceof Error ? cause : closure.error;\n queueMicrotask(() => this.failRuntime(failure));\n }\n acceptSupersession(reason) {\n if (this.superseded || this.stopped) return;\n const safeReason = sanitizeSupervisorReason(this.redactor.redact(reason));\n this.superseded = true;\n this.executionGate.close("superseded", safeReason);\n this.commands.close();\n void this.stop(safeReason).catch(() => void 0);\n }\n};\n\n// src/supervisor/runtime-entry.ts\nvar INVALID_HANDOFF_ERROR = "Supervisor environment handoff is invalid.";\nvar DEFAULT_HANDOFF_DEPENDENCIES = {\n fstat: (fd) => fstatSync2(fd),\n read: (fd, buffer, offset, length, position) => readSync2(fd, buffer, offset, length, position),\n close: (fd) => closeSync(fd),\n truncate: (fd, length) => ftruncateSync(fd, length)\n};\nfunction parseSupervisorEnvironmentHandoff(source) {\n const handoff = deserializeSupervisorEnvironmentHandoff(source);\n if (!handoff.ok) throw new Error(INVALID_HANDOFF_ERROR);\n return handoff.environment;\n}\nfunction readSupervisorEnvironmentHandoff(dependencies) {\n const stats = dependencies.fstat(SUPERVISOR_ENVIRONMENT_FD);\n if (!stats.isFile() || !Number.isSafeInteger(stats.size) || stats.size <= 0 || stats.size > SUPERVISOR_ENVIRONMENT_MAX_BYTES) {\n throw new Error(INVALID_HANDOFF_ERROR);\n }\n const buffer = Buffer.alloc(SUPERVISOR_ENVIRONMENT_MAX_BYTES + 1);\n let offset = 0;\n while (offset < buffer.length) {\n const bytesRead = dependencies.read(\n SUPERVISOR_ENVIRONMENT_FD,\n buffer,\n offset,\n buffer.length - offset,\n null\n );\n if (!Number.isSafeInteger(bytesRead) || bytesRead < 0 || bytesRead > buffer.length - offset) {\n throw new Error(INVALID_HANDOFF_ERROR);\n }\n if (bytesRead === 0) break;\n offset += bytesRead;\n }\n if (offset === 0 || offset > SUPERVISOR_ENVIRONMENT_MAX_BYTES) {\n throw new Error(INVALID_HANDOFF_ERROR);\n }\n try {\n return new TextDecoder("utf-8", { fatal: true }).decode(buffer.subarray(0, offset));\n } catch {\n throw new Error(INVALID_HANDOFF_ERROR);\n }\n}\nfunction hydrateSupervisorEnvironmentFromHandoff(environment = process.env, dependencies = DEFAULT_HANDOFF_DEPENDENCIES, required = false) {\n const indicator = environment[SUPERVISOR_ENVIRONMENT_FD_ENV];\n if (indicator === void 0) {\n if (!required && environment[SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV] === void 0) {\n return /* @__PURE__ */ Object.create(null);\n }\n delete environment[SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV];\n throw new Error(INVALID_HANDOFF_ERROR);\n }\n delete environment[SUPERVISOR_ENVIRONMENT_FD_ENV];\n let hydrated;\n let failed = false;\n try {\n if (indicator !== String(SUPERVISOR_ENVIRONMENT_FD) || environment[SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV] !== void 0) {\n throw new Error(INVALID_HANDOFF_ERROR);\n }\n hydrated = parseSupervisorEnvironmentHandoff(\n readSupervisorEnvironmentHandoff(dependencies)\n );\n } catch {\n failed = true;\n } finally {\n delete environment[SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV];\n try {\n dependencies.truncate(SUPERVISOR_ENVIRONMENT_FD, 0);\n } catch {\n failed = true;\n }\n try {\n dependencies.close(SUPERVISOR_ENVIRONMENT_FD);\n } catch {\n failed = true;\n }\n }\n if (failed || hydrated === void 0) throw new Error(INVALID_HANDOFF_ERROR);\n for (const [name, value] of Object.entries(hydrated)) environment[name] = value;\n return hydrated;\n}\nasync function loadConfig(path) {\n await access(path, fsConstants4.R_OK);\n const raw = await readFile(path, "utf8");\n return parseSupervisorRuntimeConfig(JSON.parse(raw));\n}\nvar processRuntime = null;\nvar processRedactor = new SensitiveValueRedactor();\nasync function main() {\n const handoffEnvironment = hydrateSupervisorEnvironmentFromHandoff(\n process.env,\n DEFAULT_HANDOFF_DEPENDENCIES,\n true\n );\n processRedactor.captureAll(Object.values(handoffEnvironment));\n const configPath = resolve(process.argv[2] ?? "neckbeard-supervisor.json");\n const config = await loadConfig(configPath);\n const runtime = new SupervisorRuntime(config, void 0, handoffEnvironment);\n processRuntime = runtime;\n await runtime.start();\n let shuttingDown = false;\n const shutdown = (signal) => {\n if (shuttingDown) return;\n shuttingDown = true;\n void runtime.stop(signal).catch(() => void 0);\n };\n process.on("SIGTERM", () => shutdown("SIGTERM"));\n process.on("SIGINT", () => shutdown("SIGINT"));\n await runtime.waitUntilStopped();\n}\nvar isMain = process.argv[1] ? pathToFileURL(resolve(process.argv[1])).href === import.meta.url : false;\nif (isMain) {\n main().catch((error) => {\n console.error(\n "[neckbeard-supervisor] failed to start",\n processRuntime?.serializeErrorForLog(error) ?? processRedactor.serialize(error)\n );\n process.exit(1);\n });\n}\nexport {\n PiSdkHarnessAdapter,\n SupervisorRuntime,\n hydrateSupervisorEnvironmentFromHandoff,\n parseSupervisorEnvironmentHandoff\n};\n';
23
-
24
- // src/supervisor/default-pi-package-lock.json
25
- var default_pi_package_lock_default = {
26
- name: "neckbeard-supervisor-runtime",
27
- lockfileVersion: 3,
28
- requires: true,
29
- packages: {
30
- "": {
31
- name: "neckbeard-supervisor-runtime",
32
- dependencies: {
33
- "@earendil-works/pi-coding-agent": "1.3.0"
34
- }
35
- },
36
- "node_modules/@anthropic-ai/sdk": {
37
- version: "0.129.0",
38
- resolved: "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.129.0.tgz",
39
- integrity: "sha512-MH7LB20kNpGLUpPTe2OG5XvL/KhX8HUO9XyBaFjgFk6TLS4Xjt0VPIuMKywe7POKKPslX+QxSlVok9e+8kG5Nw==",
40
- license: "MIT",
41
- dependencies: {
42
- "json-schema-to-ts": "^3.1.1",
43
- standardwebhooks: "^1.0.0"
44
- },
45
- bin: {
46
- "anthropic-ai-sdk": "bin/cli"
47
- },
48
- peerDependencies: {
49
- zod: "^3.25.0 || ^4.0.0"
50
- },
51
- peerDependenciesMeta: {
52
- zod: {
53
- optional: true
54
- }
55
- }
56
- },
57
- "node_modules/@aws-sdk/client-bedrock-runtime": {
58
- version: "3.1127.0",
59
- resolved: "https://registry.npmjs.org/@aws-sdk/client-bedrock-runtime/-/client-bedrock-runtime-3.1127.0.tgz",
60
- integrity: "sha512-IDl/lrPb90aH+pZFHGNDmgH9nAUQj5PlZH1sJ3w7RikctyjHSnY3oNjZhrLoaBoQn/rNK0zsP6OHEqEhj2tdLA==",
61
- license: "Apache-2.0",
62
- dependencies: {
63
- "@aws-sdk/core": "^3.977.9",
64
- "@aws-sdk/credential-provider-node": "^3.972.82",
65
- "@aws-sdk/eventstream-handler-node": "^3.972.34",
66
- "@aws-sdk/middleware-eventstream": "^3.972.29",
67
- "@aws-sdk/middleware-websocket": "^3.972.52",
68
- "@aws-sdk/token-providers": "3.1127.0",
69
- "@aws-sdk/types": "^3.974.5",
70
- "@smithy/core": "^3.33.3",
71
- "@smithy/fetch-http-handler": "^5.7.2",
72
- "@smithy/node-http-handler": "^4.11.3",
73
- "@smithy/types": "^4.17.2",
74
- tslib: "^2.6.2"
75
- },
76
- engines: {
77
- node: ">=20.0.0"
78
- }
79
- },
80
- "node_modules/@aws-sdk/core": {
81
- version: "3.978.3",
82
- resolved: "https://registry.npmjs.org/@aws-sdk/core/-/core-3.978.3.tgz",
83
- integrity: "sha512-nslpzUCTI9b2IQMWSd6mSAXldBexPc8rr0d3dXUutXYFLFaTdsHa2GD7sJdsn3PhyjK0O5K8ypd6zi+RXXPVlg==",
84
- license: "Apache-2.0",
85
- dependencies: {
86
- "@aws-sdk/types": "^3.974.6",
87
- "@aws-sdk/xml-builder": "^3.972.41",
88
- "@aws/lambda-invoke-store": "^0.3.0",
89
- "@smithy/core": "^3.35.2",
90
- "@smithy/signature-v4": "^5.7.4",
91
- "@smithy/types": "^4.19.0",
92
- bowser: "^2.11.0",
93
- tslib: "^2.6.2"
94
- },
95
- engines: {
96
- node: ">=20.0.0"
97
- }
98
- },
99
- "node_modules/@aws-sdk/credential-provider-env": {
100
- version: "3.972.74",
101
- resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.972.74.tgz",
102
- integrity: "sha512-rsRJcW2iFUhCgclyD6OSbMEaPl8Eu0qSeRZb2uuCK1ViZ66hl5wOe/p6Vr6MO3b+ydyKgFeqza2p6tZThvILlw==",
103
- license: "Apache-2.0",
104
- dependencies: {
105
- "@aws-sdk/core": "^3.978.3",
106
- "@aws-sdk/types": "^3.974.6",
107
- "@smithy/core": "^3.35.2",
108
- "@smithy/types": "^4.19.0",
109
- tslib: "^2.6.2"
110
- },
111
- engines: {
112
- node: ">=20.0.0"
113
- }
114
- },
115
- "node_modules/@aws-sdk/credential-provider-http": {
116
- version: "3.972.76",
117
- resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.972.76.tgz",
118
- integrity: "sha512-pnKdh0Br7OJPj+7qKjzgTfDTFW0RhEMKXNDR2jv9CAM4oHuG/4z3hRh8KtutLfpmItuRtDbKBmwWkDqHwwAWXw==",
119
- license: "Apache-2.0",
120
- dependencies: {
121
- "@aws-sdk/core": "^3.978.3",
122
- "@aws-sdk/types": "^3.974.6",
123
- "@smithy/core": "^3.35.2",
124
- "@smithy/fetch-http-handler": "^5.8.0",
125
- "@smithy/node-http-handler": "^4.12.1",
126
- "@smithy/types": "^4.19.0",
127
- tslib: "^2.6.2"
128
- },
129
- engines: {
130
- node: ">=20.0.0"
131
- }
132
- },
133
- "node_modules/@aws-sdk/credential-provider-ini": {
134
- version: "3.973.19",
135
- resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.973.19.tgz",
136
- integrity: "sha512-kcjvAxqQEV8yuwkX58RelNn3ne65o7JgRWf3Z/gVvbi7Xuw1qSDLJlatrLD76+40cmRxmNkLxBoyp/vAQChQ5g==",
137
- license: "Apache-2.0",
138
- dependencies: {
139
- "@aws-sdk/core": "^3.978.3",
140
- "@aws-sdk/credential-provider-env": "^3.972.74",
141
- "@aws-sdk/credential-provider-http": "^3.972.76",
142
- "@aws-sdk/credential-provider-login": "^3.972.81",
143
- "@aws-sdk/credential-provider-process": "^3.972.74",
144
- "@aws-sdk/credential-provider-sso": "^3.973.18",
145
- "@aws-sdk/credential-provider-web-identity": "^3.972.80",
146
- "@aws-sdk/nested-clients": "^3.997.48",
147
- "@aws-sdk/types": "^3.974.6",
148
- "@smithy/core": "^3.35.2",
149
- "@smithy/credential-provider-imds": "^4.5.2",
150
- "@smithy/types": "^4.19.0",
151
- tslib: "^2.6.2"
152
- },
153
- engines: {
154
- node: ">=20.0.0"
155
- }
156
- },
157
- "node_modules/@aws-sdk/credential-provider-login": {
158
- version: "3.972.81",
159
- resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-login/-/credential-provider-login-3.972.81.tgz",
160
- integrity: "sha512-CeQHSbE2CnVdaHIJ/NayRaCecIER+Pm9faUPkmRATO54rCoMTEPSbVieGHzEwvm1dZM2HIs6qQZCznhayNTWJQ==",
161
- license: "Apache-2.0",
162
- dependencies: {
163
- "@aws-sdk/core": "^3.978.3",
164
- "@aws-sdk/nested-clients": "^3.997.48",
165
- "@aws-sdk/types": "^3.974.6",
166
- "@smithy/core": "^3.35.2",
167
- "@smithy/types": "^4.19.0",
168
- tslib: "^2.6.2"
169
- },
170
- engines: {
171
- node: ">=20.0.0"
172
- }
173
- },
174
- "node_modules/@aws-sdk/credential-provider-node": {
175
- version: "3.972.86",
176
- resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.972.86.tgz",
177
- integrity: "sha512-WNttSyr6e8innPtBSty//CdnqJcgZN6eAbtw3v/CR2IObz6MYZEo8eusdtuCHJ2ujwFqC2bSPHVyhXGHx8HruQ==",
178
- license: "Apache-2.0",
179
- dependencies: {
180
- "@aws-sdk/credential-provider-env": "^3.972.74",
181
- "@aws-sdk/credential-provider-http": "^3.972.76",
182
- "@aws-sdk/credential-provider-ini": "^3.973.19",
183
- "@aws-sdk/credential-provider-process": "^3.972.74",
184
- "@aws-sdk/credential-provider-sso": "^3.973.18",
185
- "@aws-sdk/credential-provider-web-identity": "^3.972.80",
186
- "@aws-sdk/types": "^3.974.6",
187
- "@smithy/core": "^3.35.2",
188
- "@smithy/credential-provider-imds": "^4.5.2",
189
- "@smithy/types": "^4.19.0",
190
- tslib: "^2.6.2"
191
- },
192
- engines: {
193
- node: ">=20.0.0"
194
- }
195
- },
196
- "node_modules/@aws-sdk/credential-provider-process": {
197
- version: "3.972.74",
198
- resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.972.74.tgz",
199
- integrity: "sha512-Yj6kZFJQdbR+PygTkqdVLPHHpdDpOS9GCYVcDCuweCRRig9LF24ELQBMfyUw1vspvrZJUfnOGVyMjhaL094ahw==",
200
- license: "Apache-2.0",
201
- dependencies: {
202
- "@aws-sdk/core": "^3.978.3",
203
- "@aws-sdk/types": "^3.974.6",
204
- "@smithy/core": "^3.35.2",
205
- "@smithy/types": "^4.19.0",
206
- tslib: "^2.6.2"
207
- },
208
- engines: {
209
- node: ">=20.0.0"
210
- }
211
- },
212
- "node_modules/@aws-sdk/credential-provider-sso": {
213
- version: "3.973.18",
214
- resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.973.18.tgz",
215
- integrity: "sha512-FnpPhdY4qUGtX/8X6eKxh+uD+9Y19i9FYibgk4SBe0M935s9vocHkHzaxaMNk+YkHmvzgdu8cHA5SCoeU+kkew==",
216
- license: "Apache-2.0",
217
- dependencies: {
218
- "@aws-sdk/core": "^3.978.3",
219
- "@aws-sdk/nested-clients": "^3.997.48",
220
- "@aws-sdk/token-providers": "3.1150.0",
221
- "@aws-sdk/types": "^3.974.6",
222
- "@smithy/core": "^3.35.2",
223
- "@smithy/types": "^4.19.0",
224
- tslib: "^2.6.2"
225
- },
226
- engines: {
227
- node: ">=20.0.0"
228
- }
229
- },
230
- "node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers": {
231
- version: "3.1150.0",
232
- resolved: "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1150.0.tgz",
233
- integrity: "sha512-wDU36ofhabZYu+d2KSriyDbwzxNoaOp+4dG0p3qkabk7HeALR5nIWyQbjoyJZLn3iqWkv/xNdyUfbfevDVDzzg==",
234
- license: "Apache-2.0",
235
- dependencies: {
236
- "@aws-sdk/core": "^3.978.3",
237
- "@aws-sdk/nested-clients": "^3.997.48",
238
- "@aws-sdk/types": "^3.974.6",
239
- "@smithy/core": "^3.35.2",
240
- "@smithy/types": "^4.19.0",
241
- tslib: "^2.6.2"
242
- },
243
- engines: {
244
- node: ">=20.0.0"
245
- }
246
- },
247
- "node_modules/@aws-sdk/credential-provider-web-identity": {
248
- version: "3.972.80",
249
- resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.972.80.tgz",
250
- integrity: "sha512-TJF25Ndwy2HxcVj6oxMgp8qVlJAawlExHYBXqhuC6Zt2m+A7WpdkjBD6QglNbiArlteYljZHEY3R7KKmno6ISA==",
251
- license: "Apache-2.0",
252
- dependencies: {
253
- "@aws-sdk/core": "^3.978.3",
254
- "@aws-sdk/nested-clients": "^3.997.48",
255
- "@aws-sdk/types": "^3.974.6",
256
- "@smithy/core": "^3.35.2",
257
- "@smithy/types": "^4.19.0",
258
- tslib: "^2.6.2"
259
- },
260
- engines: {
261
- node: ">=20.0.0"
262
- }
263
- },
264
- "node_modules/@aws-sdk/eventstream-handler-node": {
265
- version: "3.972.36",
266
- resolved: "https://registry.npmjs.org/@aws-sdk/eventstream-handler-node/-/eventstream-handler-node-3.972.36.tgz",
267
- integrity: "sha512-HFaKXA6ugPVvpR7W/3UT3hylWIPndqGMwduwNVrmGsRT5+OESHN8/ven4eeofraQF5Kxp8A8QgGVrv7iQsTRKQ==",
268
- license: "Apache-2.0",
269
- dependencies: {
270
- "@aws-sdk/types": "^3.974.6",
271
- "@smithy/core": "^3.35.2",
272
- "@smithy/types": "^4.19.0",
273
- tslib: "^2.6.2"
274
- },
275
- engines: {
276
- node: ">=20.0.0"
277
- }
278
- },
279
- "node_modules/@aws-sdk/middleware-eventstream": {
280
- version: "3.972.31",
281
- resolved: "https://registry.npmjs.org/@aws-sdk/middleware-eventstream/-/middleware-eventstream-3.972.31.tgz",
282
- integrity: "sha512-4yvdTVwPGKCnrwuwlYEmwLqQXKwk0unx3f/FvBi4FA9ruK/WGoPJyqfK7hOYurheIyQL44FR0ovgOHqvkfdpAQ==",
283
- license: "Apache-2.0",
284
- dependencies: {
285
- "@aws-sdk/types": "^3.974.6",
286
- "@smithy/core": "^3.35.2",
287
- "@smithy/types": "^4.19.0",
288
- tslib: "^2.6.2"
289
- },
290
- engines: {
291
- node: ">=20.0.0"
292
- }
293
- },
294
- "node_modules/@aws-sdk/middleware-websocket": {
295
- version: "3.972.56",
296
- resolved: "https://registry.npmjs.org/@aws-sdk/middleware-websocket/-/middleware-websocket-3.972.56.tgz",
297
- integrity: "sha512-32d9EnnNM5UMwjVp/qnL0K4XYiZv+YlSbULI3BaoBdJvebAS6cD0bKfPJ7lzovN0qrelvmSh5jo/3tk0KoTuGQ==",
298
- license: "Apache-2.0",
299
- dependencies: {
300
- "@aws-sdk/core": "^3.978.3",
301
- "@aws-sdk/types": "^3.974.6",
302
- "@smithy/core": "^3.35.2",
303
- "@smithy/fetch-http-handler": "^5.8.0",
304
- "@smithy/signature-v4": "^5.7.4",
305
- "@smithy/types": "^4.19.0",
306
- tslib: "^2.6.2"
307
- },
308
- engines: {
309
- node: ">= 14.0.0"
310
- }
311
- },
312
- "node_modules/@aws-sdk/nested-clients": {
313
- version: "3.997.48",
314
- resolved: "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.997.48.tgz",
315
- integrity: "sha512-B01jdXJtAW/XOiUzGdI2mz67WyEHbGEc9X6Euzw3bjLAa+txTqdZDER4X2FsIEcXzV2ABqudVZ5thali8tCCzQ==",
316
- license: "Apache-2.0",
317
- dependencies: {
318
- "@aws-sdk/core": "^3.978.3",
319
- "@aws-sdk/signature-v4-multi-region": "^3.996.48",
320
- "@aws-sdk/types": "^3.974.6",
321
- "@smithy/core": "^3.35.2",
322
- "@smithy/fetch-http-handler": "^5.8.0",
323
- "@smithy/node-http-handler": "^4.12.1",
324
- "@smithy/types": "^4.19.0",
325
- tslib: "^2.6.2"
326
- },
327
- engines: {
328
- node: ">=20.0.0"
329
- }
330
- },
331
- "node_modules/@aws-sdk/signature-v4-multi-region": {
332
- version: "3.996.48",
333
- resolved: "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.996.48.tgz",
334
- integrity: "sha512-cFDXfEbXaGwbnpvR/DyqfxfjxpjXVRVthQLgkwvcfDS5u3+8G9WSj1X1Ag/pTRg/QOeOno1Tq3ycEdrKsCUcOA==",
335
- license: "Apache-2.0",
336
- dependencies: {
337
- "@aws-sdk/types": "^3.974.6",
338
- "@smithy/signature-v4": "^5.7.4",
339
- "@smithy/types": "^4.19.0",
340
- tslib: "^2.6.2"
341
- },
342
- engines: {
343
- node: ">=20.0.0"
344
- }
345
- },
346
- "node_modules/@aws-sdk/token-providers": {
347
- version: "3.1127.0",
348
- resolved: "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1127.0.tgz",
349
- integrity: "sha512-Dv2TMWBshJ+tF6ahs2Sy5bh4Iabsd4GAQqVvE9XZmYmnoaVbpS2QKIKE/HRacc7bTtbjEEvP+laGzHvHlf1CiQ==",
350
- license: "Apache-2.0",
351
- dependencies: {
352
- "@aws-sdk/core": "^3.977.9",
353
- "@aws-sdk/nested-clients": "^3.997.44",
354
- "@aws-sdk/types": "^3.974.5",
355
- "@smithy/core": "^3.33.3",
356
- "@smithy/types": "^4.17.2",
357
- tslib: "^2.6.2"
358
- },
359
- engines: {
360
- node: ">=20.0.0"
361
- }
362
- },
363
- "node_modules/@aws-sdk/types": {
364
- version: "3.974.6",
365
- resolved: "https://registry.npmjs.org/@aws-sdk/types/-/types-3.974.6.tgz",
366
- integrity: "sha512-v/clNZzZnDxGyvpHMOGpJKVXFAExJzUNAAjaWGdcx8QAcXLGwTaOkw33p5SHAi0YAioK32xB3hWwOekRVfmfKg==",
367
- license: "Apache-2.0",
368
- dependencies: {
369
- "@smithy/types": "^4.19.0",
370
- tslib: "^2.6.2"
371
- },
372
- engines: {
373
- node: ">=20.0.0"
374
- }
375
- },
376
- "node_modules/@aws-sdk/xml-builder": {
377
- version: "3.972.41",
378
- resolved: "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.972.41.tgz",
379
- integrity: "sha512-ctjVSyCMegrWfXlx6VqzSBFI6UqmQ5ZlnfMhdLIiWmhoH8UAQxSCP5N3OpG7X3k4LnS7ou74C4mt20+bfTW2aQ==",
380
- license: "Apache-2.0",
381
- dependencies: {
382
- "@smithy/types": "^4.19.0",
383
- tslib: "^2.6.2"
384
- },
385
- engines: {
386
- node: ">=20.0.0"
387
- }
388
- },
389
- "node_modules/@aws/lambda-invoke-store": {
390
- version: "0.3.0",
391
- resolved: "https://registry.npmjs.org/@aws/lambda-invoke-store/-/lambda-invoke-store-0.3.0.tgz",
392
- integrity: "sha512-sl4Bm6yiMNYrZKkqqDFWN0UfnWhlS8ivKxrYl+6t0gCLrqr8y3B2IqZZbFRkfaVVp7C/baApyh71P+LeE1A2sQ==",
393
- license: "Apache-2.0",
394
- engines: {
395
- node: ">=18.0.0"
396
- }
397
- },
398
- "node_modules/@babel/runtime": {
399
- version: "7.29.10",
400
- resolved: "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.10.tgz",
401
- integrity: "sha512-NpugTzbKgGrNe45Ui32cN8vCFFMxVtP/9rtfwv0nP5FRDAjvYBxJcLVpYA9mr1jxP6cnIT7x9LUzuDTbWYYNRA==",
402
- license: "MIT",
403
- engines: {
404
- node: ">=6.9.0"
405
- }
406
- },
407
- "node_modules/@earendil-works/pi-agent-core": {
408
- version: "1.3.0",
409
- resolved: "https://registry.npmjs.org/@earendil-works/pi-agent-core/-/pi-agent-core-1.3.0.tgz",
410
- integrity: "sha512-2jvpxZs47PFD5mSQb/yK0pGHJ5yO7Nu22u9mFjHbSLRgu62vZ9rupimDSIp4arnqOadyv0AWvYHtCSpFoJV7ag==",
411
- license: "MIT",
412
- dependencies: {
413
- "@earendil-works/pi-ai": "1.3.0",
414
- typebox: "1.3.27"
415
- },
416
- engines: {
417
- node: ">=22.19.0"
418
- }
419
- },
420
- "node_modules/@earendil-works/pi-ai": {
421
- version: "1.3.0",
422
- resolved: "https://registry.npmjs.org/@earendil-works/pi-ai/-/pi-ai-1.3.0.tgz",
423
- integrity: "sha512-KaBI8x7q7sPoFUXICNGD9efHzDG+oRNwVvkA9jdIsSQWH1RjFssOlEGsbLtewUPPgCrvmz0l2KTgSLXTyj3acw==",
424
- license: "MIT",
425
- dependencies: {
426
- "@anthropic-ai/sdk": "0.129.0",
427
- "@aws-sdk/client-bedrock-runtime": "3.1127.0",
428
- "@earendil-works/pi-telemetry": "1.3.0",
429
- "@google/genai": "2.21.0",
430
- "@smithy/node-http-handler": "4.12.1",
431
- "http-proxy-agent": "9.1.0",
432
- "https-proxy-agent": "9.1.0",
433
- openai: "7.19.0",
434
- "partial-json": "0.1.7",
435
- typebox: "1.3.27"
436
- },
437
- bin: {
438
- "pi-ai": "dist/cli.js"
439
- },
440
- engines: {
441
- node: ">=22.19.0"
442
- }
443
- },
444
- "node_modules/@earendil-works/pi-codemode": {
445
- version: "1.3.0",
446
- resolved: "https://registry.npmjs.org/@earendil-works/pi-codemode/-/pi-codemode-1.3.0.tgz",
447
- integrity: "sha512-2G9tmbsPhgzwfz7cmzJpbLSLqOx3eu22Gbzm+Wc3HqeZMjLQS4F3KfAabozVhv7uEjq3k2O1dZTHmhhWr2xbfQ==",
448
- license: "MIT",
449
- dependencies: {
450
- "quickjs-wasi": "3.6.2"
451
- },
452
- engines: {
453
- node: ">=22.19.0"
454
- }
455
- },
456
- "node_modules/@earendil-works/pi-coding-agent": {
457
- version: "1.3.0",
458
- resolved: "https://registry.npmjs.org/@earendil-works/pi-coding-agent/-/pi-coding-agent-1.3.0.tgz",
459
- integrity: "sha512-V/WoCjA2hQSe3QLWIUB24cTRdtEdeLiIzkDqU5RMXV6VWuD+KGZnzVBMhglwdnQTySkehZsjt8a3g6Jd2g4nnw==",
460
- license: "MIT",
461
- dependencies: {
462
- "@earendil-works/pi-agent-core": "1.3.0",
463
- "@earendil-works/pi-ai": "1.3.0",
464
- "@earendil-works/pi-codemode": "1.3.0",
465
- "@earendil-works/pi-mcp": "1.3.0",
466
- "@earendil-works/pi-tui": "1.3.0",
467
- "@silvia-odwyer/photon-node": "0.3.4",
468
- "brace-expansion": "5.0.12",
469
- chalk: "6.0.0",
470
- "cross-spawn": "7.0.6",
471
- diff: "8.0.4",
472
- "grok-mermaid": "0.2.3",
473
- "highlight.js": "10.7.3",
474
- "hosted-git-info": "9.0.3",
475
- ignore: "7.0.8",
476
- jiti: "2.7.0",
477
- minimatch: "10.2.6",
478
- "proper-lockfile": "4.1.2",
479
- "quickjs-wasi": "3.6.2",
480
- semver: "7.8.5",
481
- typebox: "1.3.27",
482
- undici: "8.10.2",
483
- yaml: "2.9.0"
484
- },
485
- bin: {
486
- pi: "dist/bundle/cli.js"
487
- },
488
- engines: {
489
- node: ">=22.19.0"
490
- }
491
- },
492
- "node_modules/@earendil-works/pi-mcp": {
493
- version: "1.3.0",
494
- resolved: "https://registry.npmjs.org/@earendil-works/pi-mcp/-/pi-mcp-1.3.0.tgz",
495
- integrity: "sha512-lbktLplmdGamM2t460Q0ziNEfpUEHDTVNf79g/AialJ3XZ+SHgNqa/OJXRR+fU+GV/l+gBhRPcyP8XkQlv8Avw==",
496
- license: "MIT",
497
- dependencies: {
498
- "cross-spawn": "7.0.6"
499
- },
500
- engines: {
501
- node: ">=22.19.0"
502
- }
503
- },
504
- "node_modules/@earendil-works/pi-telemetry": {
505
- version: "1.3.0",
506
- resolved: "https://registry.npmjs.org/@earendil-works/pi-telemetry/-/pi-telemetry-1.3.0.tgz",
507
- integrity: "sha512-ERGZr+aXjNJzoUbB7ZzHVH3g5otzMHjHLs2Fyizm12By5X+gBEhod9cJXFOk13S7M8a29Am+Mq21zm73mRJFLg==",
508
- license: "MIT",
509
- engines: {
510
- node: ">=22.19.0"
511
- }
512
- },
513
- "node_modules/@earendil-works/pi-tui": {
514
- version: "1.3.0",
515
- resolved: "https://registry.npmjs.org/@earendil-works/pi-tui/-/pi-tui-1.3.0.tgz",
516
- integrity: "sha512-AlKvEwEWyVtnuw7SVb4N/mUhlfIohyFslUNWarZVdLHHSdt3ca5EhMLwTzblBpDpaofSz+f+tAHie6CfxVrWKA==",
517
- license: "MIT",
518
- dependencies: {
519
- "get-east-asian-width": "1.6.0",
520
- marked: "18.0.11"
521
- },
522
- engines: {
523
- node: ">=22.19.0"
524
- }
525
- },
526
- "node_modules/@google/genai": {
527
- version: "2.21.0",
528
- resolved: "https://registry.npmjs.org/@google/genai/-/genai-2.21.0.tgz",
529
- integrity: "sha512-+PDtco2/Z0ONdzCGekCoCT+O1VJS9xJQNN4XzQpXG/t3El/SWWMkCWlFRO1KmivOHPa4Q0VjUYu1HBKCZ/v33Q==",
530
- hasInstallScript: true,
531
- license: "Apache-2.0",
532
- dependencies: {
533
- "google-auth-library": "^10.3.0",
534
- "p-retry": "^4.6.2",
535
- protobufjs: "^7.5.4",
536
- ws: "^8.18.0"
537
- },
538
- engines: {
539
- node: ">=20.0.0"
540
- },
541
- peerDependencies: {
542
- "@modelcontextprotocol/sdk": "^1.25.2"
543
- },
544
- peerDependenciesMeta: {
545
- "@modelcontextprotocol/sdk": {
546
- optional: true
547
- }
548
- }
549
- },
550
- "node_modules/@protobufjs/aspromise": {
551
- version: "1.1.2",
552
- resolved: "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz",
553
- integrity: "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==",
554
- license: "BSD-3-Clause"
555
- },
556
- "node_modules/@protobufjs/base64": {
557
- version: "1.1.2",
558
- resolved: "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz",
559
- integrity: "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==",
560
- license: "BSD-3-Clause"
561
- },
562
- "node_modules/@protobufjs/codegen": {
563
- version: "2.0.5",
564
- resolved: "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz",
565
- integrity: "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==",
566
- license: "BSD-3-Clause"
567
- },
568
- "node_modules/@protobufjs/eventemitter": {
569
- version: "1.1.1",
570
- resolved: "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz",
571
- integrity: "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==",
572
- license: "BSD-3-Clause"
573
- },
574
- "node_modules/@protobufjs/fetch": {
575
- version: "1.1.1",
576
- resolved: "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz",
577
- integrity: "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==",
578
- license: "BSD-3-Clause",
579
- dependencies: {
580
- "@protobufjs/aspromise": "^1.1.1"
581
- }
582
- },
583
- "node_modules/@protobufjs/float": {
584
- version: "1.0.2",
585
- resolved: "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz",
586
- integrity: "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==",
587
- license: "BSD-3-Clause"
588
- },
589
- "node_modules/@protobufjs/path": {
590
- version: "1.1.2",
591
- resolved: "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz",
592
- integrity: "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==",
593
- license: "BSD-3-Clause"
594
- },
595
- "node_modules/@protobufjs/pool": {
596
- version: "1.1.0",
597
- resolved: "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz",
598
- integrity: "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==",
599
- license: "BSD-3-Clause"
600
- },
601
- "node_modules/@protobufjs/utf8": {
602
- version: "1.1.2",
603
- resolved: "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.2.tgz",
604
- integrity: "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==",
605
- license: "BSD-3-Clause"
606
- },
607
- "node_modules/@silvia-odwyer/photon-node": {
608
- version: "0.3.4",
609
- resolved: "https://registry.npmjs.org/@silvia-odwyer/photon-node/-/photon-node-0.3.4.tgz",
610
- integrity: "sha512-bnly4BKB3KDTFxrUIcgCLbaeVVS8lrAkri1pEzskpmxu9MdfGQTy8b8EgcD83ywD3RPMsIulY8xJH5Awa+t9fA==",
611
- license: "Apache-2.0"
612
- },
613
- "node_modules/@smithy/core": {
614
- version: "3.36.0",
615
- resolved: "https://registry.npmjs.org/@smithy/core/-/core-3.36.0.tgz",
616
- integrity: "sha512-3hJiwG1F5t1SoXqp/yOCmYXziyx7ZVqF63S5W6YU201e/qwVaHPex+E/3vvyY9a3ORq/b+BydeNZpP2saQ9X2g==",
617
- license: "Apache-2.0",
618
- dependencies: {
619
- "@smithy/types": "^4.19.0",
620
- tslib: "^2.6.2"
621
- },
622
- engines: {
623
- node: ">=18.0.0"
624
- }
625
- },
626
- "node_modules/@smithy/credential-provider-imds": {
627
- version: "4.5.2",
628
- resolved: "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.5.2.tgz",
629
- integrity: "sha512-A9uSdn72ozbRUSit0eib0TW7nXuNPlaeM0zcGkJ+nE6tFcSDbnmtwoxbTCFBukVQcszDAyvsd7+rTduPTXpygg==",
630
- license: "Apache-2.0",
631
- dependencies: {
632
- "@smithy/core": "^3.33.2",
633
- "@smithy/types": "^4.17.2",
634
- tslib: "^2.6.2"
635
- },
636
- engines: {
637
- node: ">=18.0.0"
638
- }
639
- },
640
- "node_modules/@smithy/fetch-http-handler": {
641
- version: "5.8.0",
642
- resolved: "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.8.0.tgz",
643
- integrity: "sha512-ycSJu3tFAQ4v04CBB0agqFMVsSQ1iG3yw+SpgxRqKfaURpQD4CZ8Wn0zPMmSnOuTpTh65Vz+EA0rMrw089wvkA==",
644
- license: "Apache-2.0",
645
- dependencies: {
646
- "@smithy/core": "^3.33.3",
647
- "@smithy/types": "^4.18.0",
648
- tslib: "^2.6.2"
649
- },
650
- engines: {
651
- node: ">=18.0.0"
652
- }
653
- },
654
- "node_modules/@smithy/node-http-handler": {
655
- version: "4.12.1",
656
- resolved: "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.12.1.tgz",
657
- integrity: "sha512-ThMkboGeONWXAelq9FvGsuJC4rOi+qyC4/zhUF58xYpxUg5sQKx2VXZYJmtNjr4dSuBJ1HeJXETQILCz3wOHvw==",
658
- license: "Apache-2.0",
659
- dependencies: {
660
- "@smithy/core": "^3.33.3",
661
- "@smithy/types": "^4.18.0",
662
- tslib: "^2.6.2"
663
- },
664
- engines: {
665
- node: ">=18.0.0"
666
- }
667
- },
668
- "node_modules/@smithy/signature-v4": {
669
- version: "5.7.4",
670
- resolved: "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.7.4.tgz",
671
- integrity: "sha512-tHy0K0VtqNd5Y7Y41h0a0Lhh0L1GzC08dTWg0F7vRJWFtTENg7IZikf3wQkanYIRdb7ngoIPMTmqgUi401fEeQ==",
672
- license: "Apache-2.0",
673
- dependencies: {
674
- "@smithy/core": "^3.35.0",
675
- "@smithy/types": "^4.19.0",
676
- tslib: "^2.6.2"
677
- },
678
- engines: {
679
- node: ">=18.0.0"
680
- }
681
- },
682
- "node_modules/@smithy/types": {
683
- version: "4.19.0",
684
- resolved: "https://registry.npmjs.org/@smithy/types/-/types-4.19.0.tgz",
685
- integrity: "sha512-r7jh49VJxGerfAcTQA6gXcKc+98zOp/tqRwzYjgOE+iSQsP6cEU1hq2QzbuipmP68QtYdY9wKEhiCQZIzHgZ4Q==",
686
- license: "Apache-2.0",
687
- dependencies: {
688
- tslib: "^2.6.2"
689
- },
690
- engines: {
691
- node: ">=18.0.0"
692
- }
693
- },
694
- "node_modules/@stablelib/base64": {
695
- version: "1.0.1",
696
- resolved: "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz",
697
- integrity: "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==",
698
- license: "MIT"
699
- },
700
- "node_modules/@types/node": {
701
- version: "26.6.5",
702
- resolved: "https://registry.npmjs.org/@types/node/-/node-26.6.5.tgz",
703
- integrity: "sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==",
704
- license: "MIT",
705
- dependencies: {
706
- "undici-types": "~8.9.0"
707
- }
708
- },
709
- "node_modules/@types/retry": {
710
- version: "0.12.0",
711
- resolved: "https://registry.npmjs.org/@types/retry/-/retry-0.12.0.tgz",
712
- integrity: "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==",
713
- license: "MIT"
714
- },
715
- "node_modules/agent-base": {
716
- version: "9.0.0",
717
- resolved: "https://registry.npmjs.org/agent-base/-/agent-base-9.0.0.tgz",
718
- integrity: "sha512-TQf59BsZnytt8GdJKLPfUZ54g/iaUL2OWDSFCCvMOhsHduDQxO8xC4PNeyIkVcA5KwL2phPSv0douC0fgWzmnA==",
719
- license: "MIT",
720
- engines: {
721
- node: ">= 20"
722
- }
723
- },
724
- "node_modules/balanced-match": {
725
- version: "4.0.4",
726
- resolved: "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",
727
- integrity: "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",
728
- license: "MIT",
729
- engines: {
730
- node: "18 || 20 || >=22"
731
- }
732
- },
733
- "node_modules/base64-js": {
734
- version: "1.5.1",
735
- resolved: "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
736
- integrity: "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
737
- funding: [
738
- {
739
- type: "github",
740
- url: "https://github.com/sponsors/feross"
741
- },
742
- {
743
- type: "patreon",
744
- url: "https://www.patreon.com/feross"
745
- },
746
- {
747
- type: "consulting",
748
- url: "https://feross.org/support"
749
- }
750
- ],
751
- license: "MIT"
752
- },
753
- "node_modules/bignumber.js": {
754
- version: "9.3.1",
755
- resolved: "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.3.1.tgz",
756
- integrity: "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==",
757
- license: "MIT",
758
- engines: {
759
- node: "*"
760
- }
761
- },
762
- "node_modules/bowser": {
763
- version: "2.14.1",
764
- resolved: "https://registry.npmjs.org/bowser/-/bowser-2.14.1.tgz",
765
- integrity: "sha512-tzPjzCxygAKWFOJP011oxFHs57HzIhOEracIgAePE4pqB3LikALKnSzUyU4MGs9/iCEUuHlAJTjTc5M+u7YEGg==",
766
- license: "MIT"
767
- },
768
- "node_modules/brace-expansion": {
769
- version: "5.0.12",
770
- resolved: "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz",
771
- integrity: "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==",
772
- license: "MIT",
773
- dependencies: {
774
- "balanced-match": "^4.0.2"
775
- },
776
- engines: {
777
- node: "20 || >=22"
778
- }
779
- },
780
- "node_modules/buffer-equal-constant-time": {
781
- version: "1.0.1",
782
- resolved: "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
783
- integrity: "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",
784
- license: "BSD-3-Clause"
785
- },
786
- "node_modules/chalk": {
787
- version: "6.0.0",
788
- resolved: "https://registry.npmjs.org/chalk/-/chalk-6.0.0.tgz",
789
- integrity: "sha512-2uNTXIuTTxk7ciZgAU1BQcgnchcG0xXnrs6jzkQfj9SsRa9M2s5zE8WT96hS6KmG4MzWHSrvH43DF1m4XRkrFg==",
790
- license: "MIT",
791
- engines: {
792
- node: ">=22"
793
- },
794
- funding: {
795
- url: "https://github.com/chalk/chalk"
796
- }
797
- },
798
- "node_modules/cross-spawn": {
799
- version: "7.0.6",
800
- resolved: "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
801
- integrity: "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
802
- license: "MIT",
803
- dependencies: {
804
- "path-key": "^3.1.0",
805
- "shebang-command": "^2.0.0",
806
- which: "^2.0.1"
807
- },
808
- engines: {
809
- node: ">= 8"
810
- }
811
- },
812
- "node_modules/data-uri-to-buffer": {
813
- version: "4.0.1",
814
- resolved: "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz",
815
- integrity: "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==",
816
- license: "MIT",
817
- engines: {
818
- node: ">= 12"
819
- }
820
- },
821
- "node_modules/debug": {
822
- version: "4.4.3",
823
- resolved: "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
824
- integrity: "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
825
- license: "MIT",
826
- dependencies: {
827
- ms: "^2.1.3"
828
- },
829
- engines: {
830
- node: ">=6.0"
831
- },
832
- peerDependenciesMeta: {
833
- "supports-color": {
834
- optional: true
835
- }
836
- }
837
- },
838
- "node_modules/diff": {
839
- version: "8.0.4",
840
- resolved: "https://registry.npmjs.org/diff/-/diff-8.0.4.tgz",
841
- integrity: "sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw==",
842
- license: "BSD-3-Clause",
843
- engines: {
844
- node: ">=0.3.1"
845
- }
846
- },
847
- "node_modules/ecdsa-sig-formatter": {
848
- version: "1.0.11",
849
- resolved: "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
850
- integrity: "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",
851
- license: "Apache-2.0",
852
- dependencies: {
853
- "safe-buffer": "^5.0.1"
854
- }
855
- },
856
- "node_modules/extend": {
857
- version: "3.0.2",
858
- resolved: "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",
859
- integrity: "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",
860
- license: "MIT"
861
- },
862
- "node_modules/fast-sha256": {
863
- version: "1.3.0",
864
- resolved: "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz",
865
- integrity: "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==",
866
- license: "Unlicense"
867
- },
868
- "node_modules/fetch-blob": {
869
- version: "3.2.0",
870
- resolved: "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz",
871
- integrity: "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==",
872
- funding: [
873
- {
874
- type: "github",
875
- url: "https://github.com/sponsors/jimmywarting"
876
- },
877
- {
878
- type: "paypal",
879
- url: "https://paypal.me/jimmywarting"
880
- }
881
- ],
882
- license: "MIT",
883
- dependencies: {
884
- "node-domexception": "^1.0.0",
885
- "web-streams-polyfill": "^3.0.3"
886
- },
887
- engines: {
888
- node: "^12.20 || >= 14.13"
889
- }
890
- },
891
- "node_modules/formdata-polyfill": {
892
- version: "4.0.10",
893
- resolved: "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz",
894
- integrity: "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==",
895
- license: "MIT",
896
- dependencies: {
897
- "fetch-blob": "^3.1.2"
898
- },
899
- engines: {
900
- node: ">=12.20.0"
901
- }
902
- },
903
- "node_modules/gaxios": {
904
- version: "7.3.1",
905
- resolved: "https://registry.npmjs.org/gaxios/-/gaxios-7.3.1.tgz",
906
- integrity: "sha512-kB3rzJV7d9juLZh8/56QTXCwQfxyhdOMdyYk1HdQKFtF8TJTDTZQJtixWIwXdE9Jji91mC41DUNpjleo4L4eAQ==",
907
- license: "Apache-2.0",
908
- dependencies: {
909
- extend: "^3.0.2",
910
- "https-proxy-agent": "^7.0.1",
911
- "node-fetch": "^3.3.2"
912
- },
913
- engines: {
914
- node: ">=18"
915
- }
916
- },
917
- "node_modules/gaxios/node_modules/agent-base": {
918
- version: "7.1.4",
919
- resolved: "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
920
- integrity: "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",
921
- license: "MIT",
922
- engines: {
923
- node: ">= 14"
924
- }
925
- },
926
- "node_modules/gaxios/node_modules/https-proxy-agent": {
927
- version: "7.0.6",
928
- resolved: "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
929
- integrity: "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
930
- license: "MIT",
931
- dependencies: {
932
- "agent-base": "^7.1.2",
933
- debug: "4"
934
- },
935
- engines: {
936
- node: ">= 14"
937
- }
938
- },
939
- "node_modules/gcp-metadata": {
940
- version: "8.1.2",
941
- resolved: "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-8.1.2.tgz",
942
- integrity: "sha512-zV/5HKTfCeKWnxG0Dmrw51hEWFGfcF2xiXqcA3+J90WDuP0SvoiSO5ORvcBsifmx/FoIjgQN3oNOGaQ5PhLFkg==",
943
- license: "Apache-2.0",
944
- dependencies: {
945
- gaxios: "^7.0.0",
946
- "google-logging-utils": "^1.0.0",
947
- "json-bigint": "^1.0.0"
948
- },
949
- engines: {
950
- node: ">=18"
951
- }
952
- },
953
- "node_modules/get-east-asian-width": {
954
- version: "1.6.0",
955
- resolved: "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.6.0.tgz",
956
- integrity: "sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA==",
957
- license: "MIT",
958
- engines: {
959
- node: ">=18"
960
- },
961
- funding: {
962
- url: "https://github.com/sponsors/sindresorhus"
963
- }
964
- },
965
- "node_modules/google-auth-library": {
966
- version: "10.9.1",
967
- resolved: "https://registry.npmjs.org/google-auth-library/-/google-auth-library-10.9.1.tgz",
968
- integrity: "sha512-i1ydyHrqcIxXkWh/uBmVkzCvIuq5yiK2ATndIe5XxKholrG/MTYP9xGYka4sQhrbIAgGjL2B6NOE7rFaiF3fXw==",
969
- license: "Apache-2.0",
970
- dependencies: {
971
- "base64-js": "^1.3.0",
972
- "ecdsa-sig-formatter": "^1.0.11",
973
- gaxios: "^7.1.4",
974
- "gcp-metadata": "8.1.2",
975
- "google-logging-utils": "1.1.3",
976
- jws: "^4.0.0"
977
- },
978
- engines: {
979
- node: ">=18"
980
- }
981
- },
982
- "node_modules/google-logging-utils": {
983
- version: "1.1.3",
984
- resolved: "https://registry.npmjs.org/google-logging-utils/-/google-logging-utils-1.1.3.tgz",
985
- integrity: "sha512-eAmLkjDjAFCVXg7A1unxHsLf961m6y17QFqXqAXGj/gVkKFrEICfStRfwUlGNfeCEjNRa32JEWOUTlYXPyyKvA==",
986
- license: "Apache-2.0",
987
- engines: {
988
- node: ">=14"
989
- }
990
- },
991
- "node_modules/graceful-fs": {
992
- version: "4.2.11",
993
- resolved: "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
994
- integrity: "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
995
- license: "ISC"
996
- },
997
- "node_modules/grok-mermaid": {
998
- version: "0.2.3",
999
- resolved: "https://registry.npmjs.org/grok-mermaid/-/grok-mermaid-0.2.3.tgz",
1000
- integrity: "sha512-/4KopAbsjvuRP9MdPtlDjOHUmUVEohOX73JNcsWpzAtFxh+bq5+Dhb6gzvRieLDwIPQIR3/vy8V1NNTuz4Zsmg==",
1001
- license: "Apache-2.0",
1002
- engines: {
1003
- node: ">=18"
1004
- }
1005
- },
1006
- "node_modules/highlight.js": {
1007
- version: "10.7.3",
1008
- resolved: "https://registry.npmjs.org/highlight.js/-/highlight.js-10.7.3.tgz",
1009
- integrity: "sha512-tzcUFauisWKNHaRkN4Wjl/ZA07gENAjFl3J/c480dprkGTg5EQstgaNFqBfUqCq54kZRIEcreTsAgF/m2quD7A==",
1010
- license: "BSD-3-Clause",
1011
- engines: {
1012
- node: "*"
1013
- }
1014
- },
1015
- "node_modules/hosted-git-info": {
1016
- version: "9.0.3",
1017
- resolved: "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-9.0.3.tgz",
1018
- integrity: "sha512-Hc+ghLoSt6QaYZUv0WBiIvmMDZuZZ7oaDvdH8MbfOO4lOsxdXLEvuC6ePoGs9H1X9oCLyq6+NVN0MKqD+ydxyg==",
1019
- license: "ISC",
1020
- dependencies: {
1021
- "lru-cache": "^11.1.0"
1022
- },
1023
- engines: {
1024
- node: "^20.17.0 || >=22.9.0"
1025
- }
1026
- },
1027
- "node_modules/http-proxy-agent": {
1028
- version: "9.1.0",
1029
- resolved: "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-9.1.0.tgz",
1030
- integrity: "sha512-2NxoveTT58mjYT4n3RPTEfCZGLMbidoO8XEieXfpSYxu+PQJ1qpx4ypwH6N+uF9twBPIvRRgvkvW5HUTYWENig==",
1031
- license: "MIT",
1032
- dependencies: {
1033
- "agent-base": "9.0.0",
1034
- debug: "^4.3.4",
1035
- "proxy-agent-negotiate": "1.1.0"
1036
- },
1037
- engines: {
1038
- node: ">= 20"
1039
- }
1040
- },
1041
- "node_modules/https-proxy-agent": {
1042
- version: "9.1.0",
1043
- resolved: "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-9.1.0.tgz",
1044
- integrity: "sha512-ag87y7cJJ9/3+GxFr8Oy4O5faDsGRGnBGsJj/YjOSsSx/5eadKLYTMPlzuR6obgoCDDm0abAAZitXXQkMOPSpA==",
1045
- license: "MIT",
1046
- dependencies: {
1047
- "agent-base": "9.0.0",
1048
- debug: "^4.3.4",
1049
- "proxy-agent-negotiate": "1.1.0"
1050
- },
1051
- engines: {
1052
- node: ">= 20"
1053
- }
1054
- },
1055
- "node_modules/ignore": {
1056
- version: "7.0.8",
1057
- resolved: "https://registry.npmjs.org/ignore/-/ignore-7.0.8.tgz",
1058
- integrity: "sha512-YYNsSlXBjMk92SKnkwvB5LOVSa6OznlFUGcsvrFgNJbJCd0M1XKeFVRc8ZByeCqz32FivYNHJVooLmdqrmvp/Q==",
1059
- license: "MIT",
1060
- engines: {
1061
- node: ">= 4"
1062
- }
1063
- },
1064
- "node_modules/isexe": {
1065
- version: "2.0.0",
1066
- resolved: "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
1067
- integrity: "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
1068
- license: "ISC"
1069
- },
1070
- "node_modules/jiti": {
1071
- version: "2.7.0",
1072
- resolved: "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz",
1073
- integrity: "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==",
1074
- license: "MIT",
1075
- bin: {
1076
- jiti: "lib/jiti-cli.mjs"
1077
- }
1078
- },
1079
- "node_modules/json-bigint": {
1080
- version: "1.0.0",
1081
- resolved: "https://registry.npmjs.org/json-bigint/-/json-bigint-1.0.0.tgz",
1082
- integrity: "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==",
1083
- license: "MIT",
1084
- dependencies: {
1085
- "bignumber.js": "^9.0.0"
1086
- }
1087
- },
1088
- "node_modules/json-schema-to-ts": {
1089
- version: "3.1.1",
1090
- resolved: "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz",
1091
- integrity: "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==",
1092
- license: "MIT",
1093
- dependencies: {
1094
- "@babel/runtime": "^7.18.3",
1095
- "ts-algebra": "^2.0.0"
1096
- },
1097
- engines: {
1098
- node: ">=16"
1099
- }
1100
- },
1101
- "node_modules/jwa": {
1102
- version: "2.0.1",
1103
- resolved: "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz",
1104
- integrity: "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==",
1105
- license: "MIT",
1106
- dependencies: {
1107
- "buffer-equal-constant-time": "^1.0.1",
1108
- "ecdsa-sig-formatter": "1.0.11",
1109
- "safe-buffer": "^5.0.1"
1110
- }
1111
- },
1112
- "node_modules/jws": {
1113
- version: "4.0.1",
1114
- resolved: "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz",
1115
- integrity: "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==",
1116
- license: "MIT",
1117
- dependencies: {
1118
- jwa: "^2.0.1",
1119
- "safe-buffer": "^5.0.1"
1120
- }
1121
- },
1122
- "node_modules/long": {
1123
- version: "5.3.2",
1124
- resolved: "https://registry.npmjs.org/long/-/long-5.3.2.tgz",
1125
- integrity: "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==",
1126
- license: "Apache-2.0"
1127
- },
1128
- "node_modules/lru-cache": {
1129
- version: "11.5.3",
1130
- resolved: "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz",
1131
- integrity: "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==",
1132
- license: "BlueOak-1.0.0",
1133
- engines: {
1134
- node: "20 || >=22"
1135
- }
1136
- },
1137
- "node_modules/marked": {
1138
- version: "18.0.11",
1139
- resolved: "https://registry.npmjs.org/marked/-/marked-18.0.11.tgz",
1140
- integrity: "sha512-HnslJfsZkRPBDJRHvVtAaWlZHEpSu7u8LgQuJCELjRKuWR+hpq4A7sLq3p8HaI9ypVoXDXxV34CsQJEe1+J5Aw==",
1141
- license: "MIT",
1142
- bin: {
1143
- marked: "bin/marked.js"
1144
- },
1145
- engines: {
1146
- node: ">= 20"
1147
- }
1148
- },
1149
- "node_modules/minimatch": {
1150
- version: "10.2.6",
1151
- resolved: "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz",
1152
- integrity: "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==",
1153
- license: "BlueOak-1.0.0",
1154
- dependencies: {
1155
- "brace-expansion": "^5.0.8"
1156
- },
1157
- engines: {
1158
- node: "18 || 20 || >=22"
1159
- },
1160
- funding: {
1161
- url: "https://github.com/sponsors/isaacs"
1162
- }
1163
- },
1164
- "node_modules/ms": {
1165
- version: "2.1.3",
1166
- resolved: "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
1167
- integrity: "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
1168
- license: "MIT"
1169
- },
1170
- "node_modules/node-domexception": {
1171
- version: "1.0.0",
1172
- resolved: "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz",
1173
- integrity: "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==",
1174
- deprecated: "Use your platform's native DOMException instead",
1175
- funding: [
1176
- {
1177
- type: "github",
1178
- url: "https://github.com/sponsors/jimmywarting"
1179
- },
1180
- {
1181
- type: "github",
1182
- url: "https://paypal.me/jimmywarting"
1183
- }
1184
- ],
1185
- license: "MIT",
1186
- engines: {
1187
- node: ">=10.5.0"
1188
- }
1189
- },
1190
- "node_modules/node-fetch": {
1191
- version: "3.3.2",
1192
- resolved: "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz",
1193
- integrity: "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==",
1194
- license: "MIT",
1195
- dependencies: {
1196
- "data-uri-to-buffer": "^4.0.0",
1197
- "fetch-blob": "^3.1.4",
1198
- "formdata-polyfill": "^4.0.10"
1199
- },
1200
- engines: {
1201
- node: "^12.20.0 || ^14.13.1 || >=16.0.0"
1202
- },
1203
- funding: {
1204
- type: "opencollective",
1205
- url: "https://opencollective.com/node-fetch"
1206
- }
1207
- },
1208
- "node_modules/openai": {
1209
- version: "7.19.0",
1210
- resolved: "https://registry.npmjs.org/openai/-/openai-7.19.0.tgz",
1211
- integrity: "sha512-MX2s3u2L5racTO0CC/SWpCOasJQBCJrqLKXK+l82cAhdeF8mPMBEe/gxMm0ZFa2xpKpOFLRjxv5afYEZbBXmbQ==",
1212
- license: "Apache-2.0",
1213
- engines: {
1214
- node: ">=22.0.0"
1215
- },
1216
- peerDependencies: {
1217
- "@aws-sdk/credential-provider-node": ">=3.972.0 <4",
1218
- "@smithy/hash-node": ">=4.3.0 <5",
1219
- "@smithy/signature-v4": ">=5.4.0 <6",
1220
- undici: ">=5 <9",
1221
- ws: "^8.21.0",
1222
- zod: "^3.25 || ^4.0"
1223
- },
1224
- peerDependenciesMeta: {
1225
- "@aws-sdk/credential-provider-node": {
1226
- optional: true
1227
- },
1228
- "@smithy/hash-node": {
1229
- optional: true
1230
- },
1231
- "@smithy/signature-v4": {
1232
- optional: true
1233
- },
1234
- undici: {
1235
- optional: true
1236
- },
1237
- ws: {
1238
- optional: true
1239
- },
1240
- zod: {
1241
- optional: true
1242
- }
1243
- }
1244
- },
1245
- "node_modules/p-retry": {
1246
- version: "4.6.2",
1247
- resolved: "https://registry.npmjs.org/p-retry/-/p-retry-4.6.2.tgz",
1248
- integrity: "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ==",
1249
- license: "MIT",
1250
- dependencies: {
1251
- "@types/retry": "0.12.0",
1252
- retry: "^0.13.1"
1253
- },
1254
- engines: {
1255
- node: ">=8"
1256
- }
1257
- },
1258
- "node_modules/partial-json": {
1259
- version: "0.1.7",
1260
- resolved: "https://registry.npmjs.org/partial-json/-/partial-json-0.1.7.tgz",
1261
- integrity: "sha512-Njv/59hHaokb/hRUjce3Hdv12wd60MtM9Z5Olmn+nehe0QDAsRtRbJPvJ0Z91TusF0SuZRIvnM+S4l6EIP8leA==",
1262
- license: "MIT"
1263
- },
1264
- "node_modules/path-key": {
1265
- version: "3.1.1",
1266
- resolved: "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
1267
- integrity: "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
1268
- license: "MIT",
1269
- engines: {
1270
- node: ">=8"
1271
- }
1272
- },
1273
- "node_modules/proper-lockfile": {
1274
- version: "4.1.2",
1275
- resolved: "https://registry.npmjs.org/proper-lockfile/-/proper-lockfile-4.1.2.tgz",
1276
- integrity: "sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==",
1277
- license: "MIT",
1278
- dependencies: {
1279
- "graceful-fs": "^4.2.4",
1280
- retry: "^0.12.0",
1281
- "signal-exit": "^3.0.2"
1282
- }
1283
- },
1284
- "node_modules/proper-lockfile/node_modules/retry": {
1285
- version: "0.12.0",
1286
- resolved: "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz",
1287
- integrity: "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==",
1288
- license: "MIT",
1289
- engines: {
1290
- node: ">= 4"
1291
- }
1292
- },
1293
- "node_modules/protobufjs": {
1294
- version: "7.6.6",
1295
- resolved: "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.6.tgz",
1296
- integrity: "sha512-dYDWdjSl5RNb7SgPxGQcRU+GtvP7s2fpkrY0r432PcOIaZ0/rBcxEZnQN67iJhFuQiVw754JDoPruPCNdGsbjg==",
1297
- hasInstallScript: true,
1298
- license: "BSD-3-Clause",
1299
- dependencies: {
1300
- "@protobufjs/aspromise": "^1.1.2",
1301
- "@protobufjs/base64": "^1.1.2",
1302
- "@protobufjs/codegen": "^2.0.5",
1303
- "@protobufjs/eventemitter": "^1.1.1",
1304
- "@protobufjs/fetch": "^1.1.1",
1305
- "@protobufjs/float": "^1.0.2",
1306
- "@protobufjs/path": "^1.1.2",
1307
- "@protobufjs/pool": "^1.1.0",
1308
- "@protobufjs/utf8": "^1.1.1",
1309
- "@types/node": ">=13.7.0",
1310
- long: "^5.3.2"
1311
- },
1312
- engines: {
1313
- node: ">=12.0.0"
1314
- }
1315
- },
1316
- "node_modules/proxy-agent-negotiate": {
1317
- version: "1.1.0",
1318
- resolved: "https://registry.npmjs.org/proxy-agent-negotiate/-/proxy-agent-negotiate-1.1.0.tgz",
1319
- integrity: "sha512-N8IBcM3UgCVzz2L2Lqv8DVntDnnC8/hiV4nEDUPkqq72TPUgYWjQc+bdZlBPZK9LzPAvOY//gAt0S0DApoOXWQ==",
1320
- license: "MIT",
1321
- engines: {
1322
- node: ">= 20"
1323
- },
1324
- peerDependencies: {
1325
- kerberos: "^2.0.0"
1326
- },
1327
- peerDependenciesMeta: {
1328
- kerberos: {
1329
- optional: true
1330
- }
1331
- }
1332
- },
1333
- "node_modules/quickjs-wasi": {
1334
- version: "3.6.2",
1335
- resolved: "https://registry.npmjs.org/quickjs-wasi/-/quickjs-wasi-3.6.2.tgz",
1336
- integrity: "sha512-FCqGtGOrMgzUiIrMNMA2YnsOxCNwo31dzqXvclXUC6xeT35NJLKXQJsvbeCTjvoFAwZgEAPg8U6+KAPDGXn8Mg==",
1337
- license: "MIT"
1338
- },
1339
- "node_modules/retry": {
1340
- version: "0.13.1",
1341
- resolved: "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz",
1342
- integrity: "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==",
1343
- license: "MIT",
1344
- engines: {
1345
- node: ">= 4"
1346
- }
1347
- },
1348
- "node_modules/safe-buffer": {
1349
- version: "5.2.1",
1350
- resolved: "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
1351
- integrity: "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
1352
- funding: [
1353
- {
1354
- type: "github",
1355
- url: "https://github.com/sponsors/feross"
1356
- },
1357
- {
1358
- type: "patreon",
1359
- url: "https://www.patreon.com/feross"
1360
- },
1361
- {
1362
- type: "consulting",
1363
- url: "https://feross.org/support"
1364
- }
1365
- ],
1366
- license: "MIT"
1367
- },
1368
- "node_modules/semver": {
1369
- version: "7.8.5",
1370
- resolved: "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
1371
- integrity: "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
1372
- license: "ISC",
1373
- bin: {
1374
- semver: "bin/semver.js"
1375
- },
1376
- engines: {
1377
- node: ">=10"
1378
- }
1379
- },
1380
- "node_modules/shebang-command": {
1381
- version: "2.0.0",
1382
- resolved: "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
1383
- integrity: "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
1384
- license: "MIT",
1385
- dependencies: {
1386
- "shebang-regex": "^3.0.0"
1387
- },
1388
- engines: {
1389
- node: ">=8"
1390
- }
1391
- },
1392
- "node_modules/shebang-regex": {
1393
- version: "3.0.0",
1394
- resolved: "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
1395
- integrity: "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
1396
- license: "MIT",
1397
- engines: {
1398
- node: ">=8"
1399
- }
1400
- },
1401
- "node_modules/signal-exit": {
1402
- version: "3.0.7",
1403
- resolved: "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz",
1404
- integrity: "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==",
1405
- license: "ISC"
1406
- },
1407
- "node_modules/standardwebhooks": {
1408
- version: "1.1.1",
1409
- resolved: "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.1.1.tgz",
1410
- integrity: "sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ==",
1411
- license: "MIT",
1412
- dependencies: {
1413
- "@stablelib/base64": "^1.0.0",
1414
- "fast-sha256": "^1.3.0"
1415
- }
1416
- },
1417
- "node_modules/ts-algebra": {
1418
- version: "2.0.0",
1419
- resolved: "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz",
1420
- integrity: "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==",
1421
- license: "MIT"
1422
- },
1423
- "node_modules/tslib": {
1424
- version: "2.8.1",
1425
- resolved: "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
1426
- integrity: "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
1427
- license: "0BSD"
1428
- },
1429
- "node_modules/typebox": {
1430
- version: "1.3.27",
1431
- resolved: "https://registry.npmjs.org/typebox/-/typebox-1.3.27.tgz",
1432
- integrity: "sha512-zu+jc1pcy4UiNThxikUr36f0Rybk9PEeCg/NE6adeWr/SKsdNO4EzZHYRDlv2YCVAfj3Odq3dESSo/jNyoBXzA==",
1433
- license: "MIT"
1434
- },
1435
- "node_modules/undici": {
1436
- version: "8.10.2",
1437
- resolved: "https://registry.npmjs.org/undici/-/undici-8.10.2.tgz",
1438
- integrity: "sha512-/y4/bH9YNU5hi9NIrpOuvGXFcxrj3CMrV+/AYpowAYTpHn8gX/XPFjNy766FPoYY0miQhdW977JFWKGNhBdwyQ==",
1439
- license: "MIT",
1440
- engines: {
1441
- node: ">=22.19.0"
1442
- }
1443
- },
1444
- "node_modules/undici-types": {
1445
- version: "8.9.0",
1446
- resolved: "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
1447
- integrity: "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
1448
- license: "MIT"
1449
- },
1450
- "node_modules/web-streams-polyfill": {
1451
- version: "3.3.3",
1452
- resolved: "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz",
1453
- integrity: "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==",
1454
- license: "MIT",
1455
- engines: {
1456
- node: ">= 8"
1457
- }
1458
- },
1459
- "node_modules/which": {
1460
- version: "2.0.2",
1461
- resolved: "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
1462
- integrity: "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
1463
- license: "ISC",
1464
- dependencies: {
1465
- isexe: "^2.0.0"
1466
- },
1467
- bin: {
1468
- "node-which": "bin/node-which"
1469
- },
1470
- engines: {
1471
- node: ">= 8"
1472
- }
1473
- },
1474
- "node_modules/ws": {
1475
- version: "8.22.0",
1476
- resolved: "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz",
1477
- integrity: "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==",
1478
- license: "MIT",
1479
- engines: {
1480
- node: ">=10.0.0"
1481
- },
1482
- peerDependencies: {
1483
- bufferutil: "^4.0.1",
1484
- "utf-8-validate": ">=5.0.2"
1485
- },
1486
- peerDependenciesMeta: {
1487
- bufferutil: {
1488
- optional: true
1489
- },
1490
- "utf-8-validate": {
1491
- optional: true
1492
- }
1493
- }
1494
- },
1495
- "node_modules/yaml": {
1496
- version: "2.9.0",
1497
- resolved: "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz",
1498
- integrity: "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==",
1499
- license: "ISC",
1500
- bin: {
1501
- yaml: "bin.mjs"
1502
- },
1503
- engines: {
1504
- node: ">= 14.6"
1505
- },
1506
- funding: {
1507
- url: "https://github.com/sponsors/eemeli"
1508
- }
1509
- }
1510
- }
1511
- };
1512
-
1513
- // src/supervisor/package-lock-policy.mjs
1514
- var DEFAULT_PI_SDK_MODULE = "@earendil-works/pi-coding-agent";
1515
- var DEFAULT_PI_SDK_VERSION = "1.3.0";
1516
- function createSupervisorPackageManifest(moduleSpecifier = DEFAULT_PI_SDK_MODULE, expectedVersion = DEFAULT_PI_SDK_VERSION) {
1517
- return {
1518
- name: "neckbeard-supervisor-runtime",
1519
- private: true,
1520
- type: "module",
1521
- dependencies: { [moduleSpecifier]: expectedVersion }
1522
- };
1523
- }
1524
- var SHA512_INTEGRITY = /^sha512-[A-Za-z0-9+/]{86}==$/u;
1525
- var EXACT_SEMVER = /^(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u;
1526
- var CREDENTIAL_FIELD = /^(?:_?auth(?:token)?|token|_?password|credential|username)$/iu;
1527
- function isCredentialField(key) {
1528
- if (CREDENTIAL_FIELD.test(key)) return true;
1529
- if (!key.startsWith("//")) return false;
1530
- const scopeSeparator = key.lastIndexOf(":");
1531
- return scopeSeparator >= 2 && CREDENTIAL_FIELD.test(key.slice(scopeSeparator + 1));
1532
- }
1533
- function isRecord(value) {
1534
- return typeof value === "object" && value !== null && !Array.isArray(value);
1535
- }
1536
- function isExactPackageVersion(value) {
1537
- return typeof value === "string" && EXACT_SEMVER.test(value);
1538
- }
1539
- function assertCredentialFreeLockValue(value, key) {
1540
- if (key && isCredentialField(key)) {
1541
- throw new Error("pi.packageLock must not contain credential fields.");
1542
- }
1543
- if (key === "resolved" && typeof value !== "string") {
1544
- throw new Error(
1545
- "pi.packageLock resolved URLs must use HTTPS without credentials."
1546
- );
1547
- }
1548
- if (key === "resolved" && typeof value === "string" || typeof value === "string" && value.includes("://")) {
1549
- let url;
1550
- try {
1551
- url = new URL(value);
1552
- } catch {
1553
- throw new Error("pi.packageLock contains an invalid package URL.");
1554
- }
1555
- if (url.protocol !== "https:" || url.username || url.password) {
1556
- throw new Error(
1557
- "pi.packageLock package URLs must use HTTPS without credentials."
1558
- );
1559
- }
1560
- if (url.search || url.hash) {
1561
- throw new Error(
1562
- "pi.packageLock package URLs must not contain a query or fragment."
1563
- );
1564
- }
1565
- return;
1566
- }
1567
- if (Array.isArray(value)) {
1568
- for (const entry of value) assertCredentialFreeLockValue(entry);
1569
- return;
1570
- }
1571
- if (isRecord(value)) {
1572
- for (const [entryKey, entryValue] of Object.entries(value)) {
1573
- assertCredentialFreeLockValue(entryValue, entryKey);
1574
- }
1575
- }
1576
- }
1577
- function assertFrozenPackageEntry(path, value) {
1578
- if (!isRecord(value)) {
1579
- throw new Error(`pi.packageLock package ${path} must be an object.`);
1580
- }
1581
- if (Object.hasOwn(value, "link")) {
1582
- throw new Error(
1583
- `pi.packageLock package ${path} must not be a linked dependency.`
1584
- );
1585
- }
1586
- if (!isExactPackageVersion(value.version)) {
1587
- throw new Error(
1588
- `pi.packageLock package ${path} must have an exact semantic version.`
1589
- );
1590
- }
1591
- if (typeof value.resolved !== "string") {
1592
- throw new Error(
1593
- `pi.packageLock package ${path} must have an exact HTTPS resolved URL.`
1594
- );
1595
- }
1596
- let resolved;
1597
- try {
1598
- resolved = new URL(value.resolved);
1599
- } catch {
1600
- throw new Error(
1601
- `pi.packageLock package ${path} must have an exact HTTPS resolved URL.`
1602
- );
1603
- }
1604
- if (resolved.protocol !== "https:" || !resolved.hostname || resolved.href !== value.resolved || resolved.username || resolved.password || resolved.search || resolved.hash) {
1605
- throw new Error(
1606
- `pi.packageLock package ${path} resolved URL must use HTTPS without credentials, query, or fragment.`
1607
- );
1608
- }
1609
- if (typeof value.integrity !== "string" || !SHA512_INTEGRITY.test(value.integrity)) {
1610
- throw new Error(
1611
- `pi.packageLock package ${path} must have a strict sha512 integrity.`
1612
- );
1613
- }
1614
- }
1615
- function validateSupervisorPackageLock(value, moduleSpecifier = DEFAULT_PI_SDK_MODULE, expectedVersion = DEFAULT_PI_SDK_VERSION) {
1616
- if (!isRecord(value) || value.lockfileVersion !== 3 || !isRecord(value.packages)) {
1617
- throw new Error("pi.packageLock must use npm lockfileVersion 3.");
1618
- }
1619
- assertCredentialFreeLockValue(value);
1620
- for (const [path, packageValue] of Object.entries(value.packages)) {
1621
- if (path) assertFrozenPackageEntry(path, packageValue);
1622
- }
1623
- const root = value.packages[""];
1624
- if (!isRecord(root) || !isRecord(root.dependencies)) {
1625
- throw new Error(
1626
- "pi.packageLock is missing its root dependency declaration."
1627
- );
1628
- }
1629
- const dependencyNames = Object.keys(root.dependencies);
1630
- if (dependencyNames.length !== 1 || dependencyNames[0] !== moduleSpecifier || root.dependencies[moduleSpecifier] !== expectedVersion) {
1631
- throw new Error(
1632
- `pi.packageLock must depend exactly on ${moduleSpecifier}@${expectedVersion}.`
1633
- );
1634
- }
1635
- const installed = value.packages[`node_modules/${moduleSpecifier}`];
1636
- if (!isRecord(installed) || installed.version !== expectedVersion || typeof installed.resolved !== "string" || typeof installed.integrity !== "string") {
1637
- throw new Error(
1638
- `pi.packageLock does not freeze ${moduleSpecifier}@${expectedVersion}.`
1639
- );
1640
- }
1641
- return value;
1642
- }
1643
-
1644
- // src/supervisor/protocol.ts
1645
- import { createHash } from "crypto";
1646
-
1647
- // src/supervisor/runtime-limits.ts
1648
- var SUPERVISOR_CREDENTIAL_BYTE_LENGTH = 32;
1649
- var SUPERVISOR_CREDENTIAL_ENCODED_LENGTH = 43;
1650
- var MIN_SUPERVISOR_CREDENTIAL_LENGTH = SUPERVISOR_CREDENTIAL_ENCODED_LENGTH;
1651
- function isSupervisorAttemptCredential(value) {
1652
- if (typeof value !== "string" || value.length !== SUPERVISOR_CREDENTIAL_ENCODED_LENGTH || !/^[A-Za-z0-9_-]+$/u.test(value)) {
1653
- return false;
1654
- }
1655
- const decoded = Buffer.from(value, "base64url");
1656
- return decoded.byteLength === SUPERVISOR_CREDENTIAL_BYTE_LENGTH && decoded.toString("base64url") === value;
1657
- }
1658
- var SUPERVISOR_MAX_STORE_METADATA_BYTES = 1024 * 1024;
1659
- var SUPERVISOR_MAX_ACTIVE_TURN_BYTES = 16 * 1024;
1660
- var SUPERVISOR_MAX_WIRE_ID_BYTES = 512;
1661
- function isBoundedUtf8Identifier(value, maxBytes = SUPERVISOR_MAX_WIRE_ID_BYTES) {
1662
- return typeof value === "string" && value.length > 0 && Buffer.byteLength(value, "utf8") <= maxBytes;
1663
- }
1664
- var SUPERVISOR_MAX_REASON_LENGTH = 2e3;
1665
- var SUPERVISOR_MAX_ATTACHMENT_ID_LENGTH = SUPERVISOR_MAX_WIRE_ID_BYTES;
1666
- var SUPERVISOR_MAX_COMMAND_ID_LENGTH = SUPERVISOR_MAX_WIRE_ID_BYTES;
1667
- var SUPERVISOR_MAX_COMMAND_LEDGER_BYTES = 64 * 1024 * 1024;
1668
- var SUPERVISOR_COMMAND_LEDGER_RECOVERY_BYTES = 8 * 1024 * 1024;
1669
- var SUPERVISOR_MAX_PI_SESSION_HISTORY_BYTES = 64 * 1024 * 1024;
1670
- var SUPERVISOR_PI_SESSION_HISTORY_TURN_HEADROOM_BYTES = 8 * 1024 * 1024;
1671
- var SUPERVISOR_PI_SESSION_HISTORY_PROMPT_LIMIT_BYTES = SUPERVISOR_MAX_PI_SESSION_HISTORY_BYTES - SUPERVISOR_PI_SESSION_HISTORY_TURN_HEADROOM_BYTES;
1672
- var SUPERVISOR_MAX_PENDING_COMMANDS = 256;
1673
- var SUPERVISOR_MAX_PENDING_COMMAND_BYTES = 8 * 1024 * 1024;
1674
-
1675
- // src/supervisor/protocol.ts
1676
- var SUPERVISOR_PROTOCOL_VERSION = 1;
1677
- var SUPERVISOR_RUNTIME_VERSION = 2;
1678
- var DAYTONA_SUPERVISOR_PROVIDER_VERSION = 1;
1679
- var SUPERVISOR_RECOVERY_STOP_REASON = "supervisor_restarted_during_prompt";
1680
- var SUPERVISOR_COMMAND_FINGERPRINT_VERSION = 1;
1681
- var SUPERVISOR_COMMAND_FINGERPRINT_PATTERN = new RegExp(
1682
- `^sha256-v${SUPERVISOR_COMMAND_FINGERPRINT_VERSION}:[a-f0-9]{64}$`,
1683
- "u"
1684
- );
1685
- function isRecord2(value) {
1686
- return typeof value === "object" && value !== null && !Array.isArray(value);
1687
- }
1688
- function isNonEmptyString(value) {
1689
- return typeof value === "string" && value.length > 0;
1690
- }
1691
- function isCommandId(value) {
1692
- return isBoundedUtf8Identifier(value, SUPERVISOR_MAX_COMMAND_ID_LENGTH);
1693
- }
1694
- function isNonNegativeInteger(value) {
1695
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
1696
- }
1697
- function isPositiveInteger(value) {
1698
- return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
1699
- }
1700
- function isSupervisorReason(value) {
1701
- return typeof value === "string" && value.length <= SUPERVISOR_MAX_REASON_LENGTH;
1702
- }
1703
- function hasCurrentProtocolVersion(value) {
1704
- return value.protocolVersion === SUPERVISOR_PROTOCOL_VERSION;
1705
- }
1706
- function hasAttemptIdentity(value) {
1707
- return isBoundedUtf8Identifier(value.sessionId) && isBoundedUtf8Identifier(value.runId) && isBoundedUtf8Identifier(value.attemptId);
1708
- }
1709
- function parseAttachments(value) {
1710
- if (value === void 0) return void 0;
1711
- if (!Array.isArray(value)) return void 0;
1712
- const attachments = [];
1713
- for (const attachment of value) {
1714
- if (!isRecord2(attachment) || !isBoundedUtf8Identifier(
1715
- attachment.id,
1716
- SUPERVISOR_MAX_ATTACHMENT_ID_LENGTH
1717
- ) || !isNonEmptyString(attachment.url) || !isNonEmptyString(attachment.path) || attachment.mimeType !== void 0 && typeof attachment.mimeType !== "string" || typeof attachment.sha256 !== "string" || !/^[a-fA-F0-9]{64}$/.test(attachment.sha256) || !isNonNegativeInteger(attachment.sizeBytes)) {
1718
- return void 0;
1719
- }
1720
- attachments.push({
1721
- id: attachment.id,
1722
- url: attachment.url,
1723
- path: attachment.path,
1724
- ...attachment.mimeType === void 0 ? {} : { mimeType: attachment.mimeType },
1725
- sha256: attachment.sha256.toLowerCase(),
1726
- sizeBytes: attachment.sizeBytes
1727
- });
1728
- }
1729
- return attachments;
1730
- }
1731
- function parseCommandPayload(value) {
1732
- if (!isRecord2(value) || typeof value.kind !== "string") return null;
1733
- if (value.kind === "stop") {
1734
- if (value.reason !== void 0 && !isSupervisorReason(value.reason)) return null;
1735
- return {
1736
- kind: "stop",
1737
- ...value.reason === void 0 ? {} : { reason: value.reason }
1738
- };
1739
- }
1740
- if ((value.kind === "prompt" || value.kind === "steer") && typeof value.message === "string") {
1741
- const attachments = parseAttachments(value.attachments);
1742
- if (value.attachments !== void 0 && attachments === void 0) return null;
1743
- return {
1744
- kind: value.kind,
1745
- message: value.message,
1746
- ...attachments === void 0 ? {} : { attachments }
1747
- };
1748
- }
1749
- return null;
1750
- }
1751
- function parseCommandFrame(value) {
1752
- if (!isRecord2(value) || value.type !== "command" || !hasCurrentProtocolVersion(value) || !hasAttemptIdentity(value) || !isCommandId(value.commandId) || !isPositiveInteger(value.commandSequence)) {
1753
- return null;
1754
- }
1755
- const payload = parseCommandPayload(value.payload);
1756
- if (!payload) return null;
1757
- return {
1758
- type: "command",
1759
- protocolVersion: SUPERVISOR_PROTOCOL_VERSION,
1760
- sessionId: value.sessionId,
1761
- runId: value.runId,
1762
- attemptId: value.attemptId,
1763
- commandId: value.commandId,
1764
- commandSequence: value.commandSequence,
1765
- payload
1766
- };
1767
- }
1768
- function parseGatewayToSupervisorFrame(value) {
1769
- if (!isRecord2(value) || !hasCurrentProtocolVersion(value) || !hasAttemptIdentity(value)) {
1770
- return null;
1771
- }
1772
- const identity = {
1773
- sessionId: value.sessionId,
1774
- runId: value.runId,
1775
- attemptId: value.attemptId
1776
- };
1777
- if (value.type === "command") return parseCommandFrame(value);
1778
- if (value.type === "event_ack" && isNonNegativeInteger(value.acknowledgedEventSequence)) {
1779
- return {
1780
- type: "event_ack",
1781
- protocolVersion: SUPERVISOR_PROTOCOL_VERSION,
1782
- ...identity,
1783
- acknowledgedEventSequence: value.acknowledgedEventSequence
1784
- };
1785
- }
1786
- if (value.type === "resume_ok" && isNonNegativeInteger(value.acknowledgedEventSequence) && isNonNegativeInteger(value.lastAppliedCommandSequence) && Array.isArray(value.pendingCommands) && value.pendingCommands.length <= SUPERVISOR_MAX_PENDING_COMMANDS) {
1787
- const pendingCommands = value.pendingCommands.map(parseCommandFrame);
1788
- if (pendingCommands.some((command) => command === null)) return null;
1789
- return {
1790
- type: "resume_ok",
1791
- protocolVersion: SUPERVISOR_PROTOCOL_VERSION,
1792
- ...identity,
1793
- acknowledgedEventSequence: value.acknowledgedEventSequence,
1794
- lastAppliedCommandSequence: value.lastAppliedCommandSequence,
1795
- pendingCommands
1796
- };
1797
- }
1798
- if (value.type === "attempt_superseded" && (value.reason === void 0 || isSupervisorReason(value.reason))) {
1799
- return {
1800
- type: "attempt_superseded",
1801
- protocolVersion: SUPERVISOR_PROTOCOL_VERSION,
1802
- ...identity,
1803
- ...value.reason === void 0 ? {} : { reason: value.reason }
1804
- };
1805
- }
1806
- if (value.type === "pong" && typeof value.sentAt === "string") {
1807
- return {
1808
- type: "pong",
1809
- protocolVersion: SUPERVISOR_PROTOCOL_VERSION,
1810
- ...identity,
1811
- sentAt: value.sentAt
1812
- };
1813
- }
1814
- return null;
1815
- }
1816
- function hasMatchingAttempt(identity, frame) {
1817
- return identity.sessionId === frame.sessionId && identity.runId === frame.runId && identity.attemptId === frame.attemptId;
1818
- }
1819
- function createSupervisorEventId(attemptId, attemptSequence) {
1820
- return `${attemptId}:${attemptSequence}`;
1821
- }
1822
- function serializeSupervisorError(error) {
1823
- return serializeError(error);
1824
- }
1825
-
1826
- // src/supervisor/path-policy.ts
1827
- import { posix } from "path";
1828
- function containsControlCharacter(value) {
1829
- return /[\u0000-\u001f\u007f]/u.test(value);
1830
- }
1831
- function assertCanonicalSandboxPath(name, value) {
1832
- if (!posix.isAbsolute(value) || value === "/" || value.endsWith("/") || value !== posix.normalize(value) || value.includes("\\") || containsControlCharacter(value)) {
1833
- throw new Error(
1834
- `${name} must be a canonical absolute non-root POSIX sandbox path.`
1835
- );
1836
- }
1837
- }
1838
- function sandboxPathIsEqualToOrBelow(parent, child) {
1839
- const relativePath = posix.relative(parent, child);
1840
- return !posix.isAbsolute(relativePath) && relativePath !== ".." && !relativePath.startsWith("../");
1841
- }
1842
- function sandboxPathsOverlap(left, right) {
1843
- return sandboxPathIsEqualToOrBelow(left, right) || sandboxPathIsEqualToOrBelow(right, left);
1844
- }
1845
- function assertSafePathSegment(name, value) {
1846
- if (value.length === 0 || value === "." || value === ".." || value.includes("/") || value.includes("\\") || containsControlCharacter(value) || Buffer.byteLength(value, "utf8") > 255) {
1847
- throw new Error(
1848
- `${name} must be one safe POSIX path segment of 1 to 255 bytes.`
1849
- );
1850
- }
1851
- }
1852
-
1853
- // src/supervisor/config.ts
1854
- var PI_THINKING_LEVELS = [
1855
- "off",
1856
- "minimal",
1857
- "low",
1858
- "medium",
1859
- "high",
1860
- "xhigh"
1861
- ];
1862
- var SUPERVISOR_MAX_TIMER_DELAY_MS = 2147483647;
1863
- var DEFAULT_SUPERVISOR_ATTACHMENT_CONFIG = {
1864
- maxBytesPerAttachment: 100 * 1024 * 1024,
1865
- maxBytesPerCommand: 500 * 1024 * 1024,
1866
- maxFilesPerAttempt: 100,
1867
- maxBytesPerAttempt: 500 * 1024 * 1024,
1868
- downloadTimeoutMs: 12e4
1869
- };
1870
- function assertSupervisorHarnessPathOwnership(stateDir, sessionPath, agentDir) {
1871
- const effectiveAgentDir = agentDir ?? `${stateDir}/pi/agent`;
1872
- const reservedStateRoots = [
1873
- `${stateDir}/attempts`,
1874
- `${stateDir}/attempt-data-v${SUPERVISOR_RUNTIME_VERSION}`,
1875
- `${stateDir}/.neckbeard-resource-snapshots`
1876
- ];
1877
- if (reservedStateRoots.some((path) => sandboxPathsOverlap(sessionPath, path))) {
1878
- throw new Error(
1879
- "Supervisor config harness.sessionPath must not overlap supervisor-owned state."
1880
- );
1881
- }
1882
- if (reservedStateRoots.some((path) => sandboxPathsOverlap(effectiveAgentDir, path))) {
1883
- throw new Error(
1884
- "Supervisor config harness.agentDir must not overlap supervisor-owned state."
1885
- );
1886
- }
1887
- if (sandboxPathsOverlap(sessionPath, effectiveAgentDir)) {
1888
- throw new Error(
1889
- "Supervisor config harness.sessionPath and harness.agentDir must not overlap."
1890
- );
1891
- }
1892
- }
1893
- function isRecord3(value) {
1894
- return typeof value === "object" && value !== null && !Array.isArray(value);
1895
- }
1896
- function isNonEmptyString2(value) {
1897
- return typeof value === "string" && value.length > 0;
1898
- }
1899
- function isPositiveInteger2(value) {
1900
- return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
1901
- }
1902
- function isTimerDelay(value) {
1903
- return isPositiveInteger2(value) && value <= SUPERVISOR_MAX_TIMER_DELAY_MS;
1904
- }
1905
- function isNonNegativeNumber(value) {
1906
- return typeof value === "number" && Number.isFinite(value) && value >= 0;
1907
- }
1908
- function parseSupervisorRuntimeConfig(value) {
1909
- if (!isRecord3(value)) throw new Error("Supervisor config must be an object.");
1910
- if (value.protocolVersion !== SUPERVISOR_PROTOCOL_VERSION) {
1911
- throw new Error(
1912
- `Unsupported supervisor protocol version: ${String(value.protocolVersion)}.`
1913
- );
1914
- }
1915
- if (value.runtimeVersion !== SUPERVISOR_RUNTIME_VERSION) {
1916
- throw new Error(
1917
- `Unsupported supervisor runtime version: ${String(value.runtimeVersion)}.`
1918
- );
1919
- }
1920
- if (value.provider !== "daytona") {
1921
- throw new Error('Supervisor provider must be "daytona".');
1922
- }
1923
- if (value.providerVersion !== DAYTONA_SUPERVISOR_PROVIDER_VERSION) {
1924
- throw new Error(
1925
- `Unsupported Daytona supervisor provider version: ${String(value.providerVersion)}.`
1926
- );
1927
- }
1928
- for (const field of [
1929
- "sessionId",
1930
- "runId",
1931
- "attemptId",
1932
- "gatewayUrl",
1933
- "credentialEnv",
1934
- "workspaceDir",
1935
- "stateDurabilityAnchor",
1936
- "stateDir"
1937
- ]) {
1938
- if (!isNonEmptyString2(value[field])) {
1939
- throw new Error(`Supervisor config ${field} must be a non-empty string.`);
1940
- }
1941
- }
1942
- for (const field of ["sessionId", "runId"]) {
1943
- if (!isBoundedUtf8Identifier(value[field])) {
1944
- throw new Error(
1945
- `Supervisor config ${field} must be at most ${SUPERVISOR_MAX_WIRE_ID_BYTES} UTF-8 bytes.`
1946
- );
1947
- }
1948
- }
1949
- assertSafePathSegment(
1950
- "Supervisor config attemptId",
1951
- value.attemptId
1952
- );
1953
- assertCanonicalSandboxPath(
1954
- "Supervisor config workspaceDir",
1955
- value.workspaceDir
1956
- );
1957
- assertCanonicalSandboxPath(
1958
- "Supervisor config stateDurabilityAnchor",
1959
- value.stateDurabilityAnchor
1960
- );
1961
- assertCanonicalSandboxPath(
1962
- "Supervisor config stateDir",
1963
- value.stateDir
1964
- );
1965
- if (!sandboxPathIsEqualToOrBelow(
1966
- value.stateDurabilityAnchor,
1967
- value.stateDir
1968
- )) {
1969
- throw new Error(
1970
- "Supervisor config stateDir must be equal to or below stateDurabilityAnchor."
1971
- );
1972
- }
1973
- if (sandboxPathsOverlap(value.workspaceDir, value.stateDir)) {
1974
- throw new Error(
1975
- "Supervisor config workspaceDir and stateDir must not overlap."
1976
- );
1977
- }
1978
- if (!isTimerDelay(value.heartbeatIntervalMs)) {
1979
- throw new Error(
1980
- `Supervisor config heartbeatIntervalMs must be a positive integer no greater than ${SUPERVISOR_MAX_TIMER_DELAY_MS}.`
1981
- );
1982
- }
1983
- if (!isTimerDelay(value.handshakeTimeoutMs)) {
1984
- throw new Error(
1985
- `Supervisor config handshakeTimeoutMs must be a positive integer no greater than ${SUPERVISOR_MAX_TIMER_DELAY_MS}.`
1986
- );
1987
- }
1988
- if (!isPositiveInteger2(value.maxInFlightEvents)) {
1989
- throw new Error(
1990
- "Supervisor config maxInFlightEvents must be a positive integer."
1991
- );
1992
- }
1993
- if (typeof value.allowInsecureGateway !== "boolean") {
1994
- throw new Error(
1995
- "Supervisor config allowInsecureGateway must be a boolean."
1996
- );
1997
- }
1998
- let gatewayUrl;
1999
- try {
2000
- gatewayUrl = new URL(value.gatewayUrl);
2001
- } catch {
2002
- throw new Error("Supervisor config gatewayUrl must be a valid URL.");
2003
- }
2004
- if (gatewayUrl.protocol !== "wss:" && !(value.allowInsecureGateway && gatewayUrl.protocol === "ws:")) {
2005
- throw new Error("Supervisor config gatewayUrl must use wss://.");
2006
- }
2007
- if (gatewayUrl.username || gatewayUrl.password) {
2008
- throw new Error(
2009
- "Supervisor config gatewayUrl must not contain credentials."
2010
- );
2011
- }
2012
- if (gatewayUrl.search || gatewayUrl.hash) {
2013
- throw new Error(
2014
- "Supervisor config gatewayUrl must not contain a query or fragment."
2015
- );
2016
- }
2017
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(value.credentialEnv)) {
2018
- throw new Error(
2019
- "Supervisor config credentialEnv must be a valid environment variable name."
2020
- );
2021
- }
2022
- const attachments = value.attachments === void 0 ? DEFAULT_SUPERVISOR_ATTACHMENT_CONFIG : value.attachments;
2023
- if (!isRecord3(attachments)) {
2024
- throw new Error("Supervisor config attachments must be an object.");
2025
- }
2026
- if (!isPositiveInteger2(attachments.maxBytesPerAttachment)) {
2027
- throw new Error(
2028
- "Supervisor attachments.maxBytesPerAttachment must be a positive integer."
2029
- );
2030
- }
2031
- if (!isPositiveInteger2(attachments.maxBytesPerCommand)) {
2032
- throw new Error(
2033
- "Supervisor attachments.maxBytesPerCommand must be a positive integer."
2034
- );
2035
- }
2036
- const maxFilesPerAttempt = attachments.maxFilesPerAttempt === void 0 ? DEFAULT_SUPERVISOR_ATTACHMENT_CONFIG.maxFilesPerAttempt : attachments.maxFilesPerAttempt;
2037
- if (!isPositiveInteger2(maxFilesPerAttempt)) {
2038
- throw new Error(
2039
- "Supervisor attachments.maxFilesPerAttempt must be a positive integer."
2040
- );
2041
- }
2042
- const maxBytesPerAttempt = attachments.maxBytesPerAttempt === void 0 ? attachments.maxBytesPerCommand : attachments.maxBytesPerAttempt;
2043
- if (!isPositiveInteger2(maxBytesPerAttempt)) {
2044
- throw new Error(
2045
- "Supervisor attachments.maxBytesPerAttempt must be a positive integer."
2046
- );
2047
- }
2048
- if (!isTimerDelay(attachments.downloadTimeoutMs)) {
2049
- throw new Error(
2050
- `Supervisor attachments.downloadTimeoutMs must be a positive integer no greater than ${SUPERVISOR_MAX_TIMER_DELAY_MS}.`
2051
- );
2052
- }
2053
- if (!isRecord3(value.reconnect)) {
2054
- throw new Error("Supervisor config reconnect must be an object.");
2055
- }
2056
- if (!isTimerDelay(value.reconnect.initialDelayMs)) {
2057
- throw new Error(
2058
- `Supervisor reconnect.initialDelayMs must be a positive integer no greater than ${SUPERVISOR_MAX_TIMER_DELAY_MS}.`
2059
- );
2060
- }
2061
- if (!isTimerDelay(value.reconnect.maximumDelayMs)) {
2062
- throw new Error(
2063
- `Supervisor reconnect.maximumDelayMs must be a positive integer no greater than ${SUPERVISOR_MAX_TIMER_DELAY_MS}.`
2064
- );
2065
- }
2066
- if (value.reconnect.maximumDelayMs < value.reconnect.initialDelayMs) {
2067
- throw new Error(
2068
- "Supervisor reconnect.maximumDelayMs must be >= initialDelayMs."
2069
- );
2070
- }
2071
- if (typeof value.reconnect.multiplier !== "number" || !Number.isFinite(value.reconnect.multiplier) || value.reconnect.multiplier < 1) {
2072
- throw new Error("Supervisor reconnect.multiplier must be at least 1.");
2073
- }
2074
- if (!isNonNegativeNumber(value.reconnect.jitterRatio) || value.reconnect.jitterRatio > 1) {
2075
- throw new Error(
2076
- "Supervisor reconnect.jitterRatio must be between 0 and 1."
2077
- );
2078
- }
2079
- if (value.reconnect.maximumDelayMs * (1 + value.reconnect.jitterRatio) > SUPERVISOR_MAX_TIMER_DELAY_MS) {
2080
- throw new Error(
2081
- `Supervisor reconnect jittered delay must not exceed ${SUPERVISOR_MAX_TIMER_DELAY_MS}.`
2082
- );
2083
- }
2084
- if (!isRecord3(value.harness) || value.harness.adapter !== "pi-sdk") {
2085
- throw new Error('Supervisor config harness.adapter must be "pi-sdk".');
2086
- }
2087
- if (value.harness.adapterVersion !== 1) {
2088
- throw new Error("Supervisor config harness.adapterVersion must be 1.");
2089
- }
2090
- if (!isNonEmptyString2(value.harness.moduleSpecifier)) {
2091
- throw new Error(
2092
- "Supervisor config harness.moduleSpecifier must be a non-empty string."
2093
- );
2094
- }
2095
- if (!isNonEmptyString2(value.harness.expectedVersion)) {
2096
- throw new Error(
2097
- "Supervisor config harness.expectedVersion must be a non-empty string."
2098
- );
2099
- }
2100
- if (!isNonEmptyString2(value.harness.sessionPath)) {
2101
- throw new Error(
2102
- "Supervisor config harness.sessionPath must be a non-empty string."
2103
- );
2104
- }
2105
- assertCanonicalSandboxPath(
2106
- "Supervisor config harness.sessionPath",
2107
- value.harness.sessionPath
2108
- );
2109
- if (value.harness.sessionPath === value.stateDir || !sandboxPathIsEqualToOrBelow(
2110
- value.stateDir,
2111
- value.harness.sessionPath
2112
- )) {
2113
- throw new Error(
2114
- "Supervisor config harness.sessionPath must be strictly below stateDir."
2115
- );
2116
- }
2117
- if (value.harness.agentDir !== void 0 && !isNonEmptyString2(value.harness.agentDir)) {
2118
- throw new Error(
2119
- "Supervisor config harness.agentDir must be a non-empty string when set."
2120
- );
2121
- }
2122
- if (value.harness.agentDir !== void 0) {
2123
- assertCanonicalSandboxPath(
2124
- "Supervisor config harness.agentDir",
2125
- value.harness.agentDir
2126
- );
2127
- if (value.harness.agentDir === value.stateDir || !sandboxPathIsEqualToOrBelow(
2128
- value.stateDir,
2129
- value.harness.agentDir
2130
- )) {
2131
- throw new Error(
2132
- "Supervisor config harness.agentDir must be strictly below stateDir."
2133
- );
2134
- }
2135
- }
2136
- assertSupervisorHarnessPathOwnership(
2137
- value.stateDir,
2138
- value.harness.sessionPath,
2139
- value.harness.agentDir
2140
- );
2141
- if (value.harness.provider !== void 0 && !isNonEmptyString2(value.harness.provider)) {
2142
- throw new Error(
2143
- "Supervisor config harness.provider must be a non-empty string when set."
2144
- );
2145
- }
2146
- if (value.harness.model !== void 0 && !isNonEmptyString2(value.harness.model)) {
2147
- throw new Error(
2148
- "Supervisor config harness.model must be a non-empty string when set."
2149
- );
2150
- }
2151
- if (value.harness.provider === void 0 !== (value.harness.model === void 0)) {
2152
- throw new Error(
2153
- "Supervisor config harness.provider and harness.model must be set together."
2154
- );
2155
- }
2156
- if (value.harness.providerCredentialEnv !== void 0 && (!isNonEmptyString2(value.harness.providerCredentialEnv) || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(value.harness.providerCredentialEnv))) {
2157
- throw new Error(
2158
- "Supervisor config harness.providerCredentialEnv must be a valid environment variable name when set."
2159
- );
2160
- }
2161
- if (value.harness.provider === void 0 !== (value.harness.providerCredentialEnv === void 0)) {
2162
- throw new Error(
2163
- "Supervisor config harness.providerCredentialEnv must be set with provider and model."
2164
- );
2165
- }
2166
- if (value.harness.providerCredentialEnv === value.credentialEnv) {
2167
- throw new Error(
2168
- "Supervisor and provider credentials must use different environment variables."
2169
- );
2170
- }
2171
- if (value.harness.thinking !== void 0 && !PI_THINKING_LEVELS.includes(value.harness.thinking)) {
2172
- throw new Error("Supervisor config harness.thinking is invalid.");
2173
- }
2174
- if (!isTimerDelay(value.harness.stopGraceMs)) {
2175
- throw new Error(
2176
- `Supervisor config harness.stopGraceMs must be a positive integer no greater than ${SUPERVISOR_MAX_TIMER_DELAY_MS}.`
2177
- );
2178
- }
2179
- return {
2180
- ...value,
2181
- attachments: {
2182
- maxBytesPerAttachment: attachments.maxBytesPerAttachment,
2183
- maxBytesPerCommand: attachments.maxBytesPerCommand,
2184
- maxFilesPerAttempt,
2185
- maxBytesPerAttempt,
2186
- downloadTimeoutMs: attachments.downloadTimeoutMs
2187
- }
2188
- };
2189
- }
2190
-
2191
- // src/supervisor/artifact.ts
2192
- var SUPERVISOR_RUNTIME_FILENAME = "neckbeard-supervisor.mjs";
2193
- var SUPERVISOR_CONFIG_FILENAME = "neckbeard-supervisor.json";
2194
- var SUPERVISOR_PACKAGE_FILENAME = "package.json";
2195
- var SUPERVISOR_PACKAGE_LOCK_FILENAME = "package-lock.json";
2196
- var SUPERVISOR_SHRINKWRAP_FILENAME = "npm-shrinkwrap.json";
2197
- var DEFAULT_SUPERVISOR_CREDENTIAL_ENV = "NECKBEARD_SUPERVISOR_CREDENTIAL";
2198
- var SUPERVISOR_LAUNCH_CANCELLED_CODE = "NECKBEARD_SUPERVISOR_LAUNCH_CANCELLED";
2199
- var SUPERVISOR_RELEASED_GENERATION_UNAVAILABLE_CODE = "NECKBEARD_SUPERVISOR_RELEASED_GENERATION_UNAVAILABLE";
2200
- var SupervisorLaunchCancelledError = class extends Error {
2201
- name = "SupervisorLaunchCancelledError";
2202
- code = SUPERVISOR_LAUNCH_CANCELLED_CODE;
2203
- constructor() {
2204
- super("Supervisor launch was cancelled before release.");
2205
- }
2206
- };
2207
- var SupervisorReleasedGenerationUnavailableError = class extends Error {
2208
- name = "SupervisorReleasedGenerationUnavailableError";
2209
- code = SUPERVISOR_RELEASED_GENERATION_UNAVAILABLE_CODE;
2210
- constructor() {
2211
- super("Supervisor released generation is unavailable.");
2212
- }
2213
- };
2214
- var DURABLE_SESSION_PI_HARNESS_OPTION_KEYS = [
2215
- "moduleSpecifier",
2216
- "expectedVersion",
2217
- "sessionPath",
2218
- "agentDir",
2219
- "provider",
2220
- "model",
2221
- "providerCredentialEnv",
2222
- "thinking",
2223
- "stopGraceMs"
2224
- ];
2225
- var MAX_PACKAGE_LOCK_BYTES = 4 * 1024 * 1024;
2226
- var SUPERVISOR_BOOTSTRAP_PATH = "/usr/local/share/nvm/current/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
2227
- function selectDurableSessionPiHarnessOptions(options) {
2228
- const selected = {};
2229
- if (!options) return selected;
2230
- for (const key of DURABLE_SESSION_PI_HARNESS_OPTION_KEYS) {
2231
- const value = options[key];
2232
- if (value !== void 0) Object.assign(selected, { [key]: value });
2233
- }
2234
- return selected;
2235
- }
2236
- var SUPERVISOR_INSTALL_PREPARATION_TIMEOUT_MS = 3e4;
2237
- var SUPERVISOR_INSTALL_DIRECTORY_PREPARER = [
2238
- '"use strict";',
2239
- 'const { constants, closeSync, fchmodSync, fstatSync, lstatSync, mkdirSync, openSync, realpathSync } = require("node:fs");',
2240
- 'const fail = () => { process.stderr.write("Supervisor install path is unsafe.\\n"); process.exit(5); };',
2241
- "let directoryDescriptor;",
2242
- "const fileDescriptors = [];",
2243
- "try {",
2244
- ' if (typeof constants.O_NOFOLLOW !== "number" || typeof constants.O_DIRECTORY !== "number" || typeof process.getuid !== "function") fail();',
2245
- " const installDir = process.argv[1];",
2246
- " const stagePaths = process.argv.slice(2);",
2247
- " const uid = process.getuid();",
2248
- ' let current = "";',
2249
- ' for (const component of installDir.split("/").slice(1)) {',
2250
- ' if (!component || component === "." || component === "..") fail();',
2251
- " current += `/${component}`;",
2252
- " let stats = lstatSync(current, { throwIfNoEntry: false });",
2253
- " if (stats === undefined) {",
2254
- " try { mkdirSync(current, { mode: 0o700 }); } catch {}",
2255
- " stats = lstatSync(current, { throwIfNoEntry: false });",
2256
- " }",
2257
- " if (!stats?.isDirectory() || stats.isSymbolicLink()) fail();",
2258
- " const mode = stats.mode & 0o7777;",
2259
- " if (stats.uid !== uid && stats.uid !== 0) fail();",
2260
- " if (current !== installDir && (mode & 0o022) !== 0 && (mode & 0o1000) === 0) fail();",
2261
- " }",
2262
- " if (current !== installDir || realpathSync(installDir) !== installDir) fail();",
2263
- " directoryDescriptor = openSync(installDir, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW | constants.O_NONBLOCK);",
2264
- " let directoryStats = fstatSync(directoryDescriptor);",
2265
- " if (!directoryStats.isDirectory() || directoryStats.uid !== uid) fail();",
2266
- " fchmodSync(directoryDescriptor, 0o700);",
2267
- " directoryStats = fstatSync(directoryDescriptor);",
2268
- " if ((directoryStats.mode & 0o7777) !== 0o700) fail();",
2269
- " for (const stagePath of stagePaths) {",
2270
- ' if (!stagePath.startsWith(`${installDir}/`) || stagePath.slice(installDir.length + 1).includes("/")) fail();',
2271
- " const descriptor = openSync(stagePath, constants.O_CREAT | constants.O_RDWR | constants.O_NOFOLLOW | constants.O_NONBLOCK, 0o600);",
2272
- " fileDescriptors.push(descriptor);",
2273
- " let stats = fstatSync(descriptor);",
2274
- " if (!stats.isFile() || stats.uid !== uid || stats.nlink !== 1) fail();",
2275
- " fchmodSync(descriptor, 0o600);",
2276
- " stats = fstatSync(descriptor);",
2277
- " if ((stats.mode & 0o7777) !== 0o600) fail();",
2278
- " }",
2279
- "} catch {",
2280
- " fail();",
2281
- "} finally {",
2282
- " for (const descriptor of fileDescriptors) { try { closeSync(descriptor); } catch {} }",
2283
- " if (directoryDescriptor !== undefined) { try { closeSync(directoryDescriptor); } catch {} }",
2284
- "}"
2285
- ].join("\n");
2286
- function parsePackageLock(source, moduleSpecifier, expectedVersion) {
2287
- if (Buffer2.byteLength(source, "utf8") > MAX_PACKAGE_LOCK_BYTES) {
2288
- throw new Error(
2289
- "pi.packageLock exceeds the supervisor artifact size limit."
2290
- );
2291
- }
2292
- let lock;
2293
- try {
2294
- lock = JSON.parse(source);
2295
- } catch {
2296
- throw new Error("pi.packageLock must be valid JSON.");
2297
- }
2298
- validateSupervisorPackageLock(lock, moduleSpecifier, expectedVersion);
2299
- return `${JSON.stringify(lock, null, 2)}
2300
- `;
2301
- }
2302
- function packageLockForCoordinates(moduleSpecifier, expectedVersion, suppliedLock) {
2303
- const usesDefaultCoordinates = moduleSpecifier === DEFAULT_PI_SDK_MODULE && expectedVersion === DEFAULT_PI_SDK_VERSION;
2304
- const generatedDefault = parsePackageLock(
2305
- `${JSON.stringify(default_pi_package_lock_default, null, 2)}
2306
- `,
2307
- DEFAULT_PI_SDK_MODULE,
2308
- DEFAULT_PI_SDK_VERSION
2309
- );
2310
- if (usesDefaultCoordinates) {
2311
- if (suppliedLock !== void 0 && parsePackageLock(suppliedLock, moduleSpecifier, expectedVersion) !== generatedDefault) {
2312
- throw new Error(
2313
- "The supported default Pi coordinate must use Neckbeard's generated lock."
2314
- );
2315
- }
2316
- return generatedDefault;
2317
- }
2318
- if (suppliedLock === void 0) {
2319
- throw new Error(
2320
- "Custom Pi package coordinates require pi.packageLock with the exact frozen dependency graph."
2321
- );
2322
- }
2323
- return parsePackageLock(suppliedLock, moduleSpecifier, expectedVersion);
2324
- }
2325
- var SUPERVISOR_BOOTSTRAP_MARKER = ".neckbeard-bootstrap-v2";
2326
- var SUPERVISOR_BOOTSTRAP_PENDING = ".neckbeard-bootstrap-v2.pending";
2327
- var SUPERVISOR_BOOTSTRAP_LOCK = ".neckbeard-bootstrap-v2.lock";
2328
- var SUPERVISOR_BOOTSTRAP_INSTALLED_MANIFEST = ".neckbeard-bootstrap-v2.installed.json";
2329
- var SUPERVISOR_CLEAN_ENVIRONMENT_WRAPPER = 'exec /usr/bin/env -i "$@"';
2330
- function createSupervisorBootstrapEnvironment(installDir) {
2331
- return [
2332
- `HOME=${installDir}`,
2333
- `PATH=${SUPERVISOR_BOOTSTRAP_PATH}`,
2334
- "NPM_CONFIG_GLOBALCONFIG=/dev/null",
2335
- "NPM_CONFIG_UPDATE_NOTIFIER=false",
2336
- "NO_COLOR=1"
2337
- ];
2338
- }
2339
- var SUPERVISOR_TRUSTED_BOOTSTRAP_ENTRYPOINT = ["/usr/bin/env", "-i"];
2340
- var SUPERVISOR_BOOTSTRAP_LOCK_WRAPPER = [
2341
- '"use strict";',
2342
- 'const { constants, closeSync, fstatSync, openSync } = require("node:fs");',
2343
- 'const { spawnSync } = require("node:child_process");',
2344
- "const lockPath = process.argv[1];",
2345
- "const bootstrap = process.argv[2];",
2346
- "let descriptor;",
2347
- "let exitCode = 5;",
2348
- "try {",
2349
- ' if (typeof constants.O_NOFOLLOW !== "number" || typeof process.getuid !== "function") throw new Error();',
2350
- " descriptor = openSync(lockPath, constants.O_CREAT | constants.O_RDWR | constants.O_NOFOLLOW | constants.O_NONBLOCK, 0o600);",
2351
- " const stats = fstatSync(descriptor);",
2352
- " if (!stats.isFile() || stats.uid !== process.getuid() || stats.nlink !== 1 || (stats.mode & 0o7777) !== 0o600) throw new Error();",
2353
- ' const stdio = ["ignore", "inherit", "inherit", "ignore", "ignore", "ignore", "ignore", "ignore", "ignore", descriptor];',
2354
- ' const lockedBootstrap = "flock -E 3 -w 110 9 || exit $?; exec sh -c \\"$1\\"";',
2355
- ' const result = spawnSync("sh", ["-c", lockedBootstrap, "neckbeard-bootstrap", bootstrap], { env: process.env, stdio });',
2356
- ' if (result.status === 3) process.stderr.write("Timed out waiting for supervisor dependency bootstrap.\\n");',
2357
- " exitCode = result.status ?? 5;",
2358
- "} catch {",
2359
- ' process.stderr.write("Supervisor bootstrap lock file is unsafe.\\n");',
2360
- "} finally {",
2361
- " if (descriptor !== undefined) { try { closeSync(descriptor); } catch { exitCode = 5; } }",
2362
- "}",
2363
- "process.exit(exitCode);"
2364
- ].join("\n");
2365
- var SUPERVISOR_INSTALLED_GRAPH_VERIFIER = [
2366
- '"use strict";',
2367
- 'const { lstatSync, readFileSync } = require("node:fs");',
2368
- "const fail = () => process.exit(1);",
2369
- "try {",
2370
- ' const lock = JSON.parse(readFileSync("package-lock.json", "utf8"));',
2371
- ' if (!lock || typeof lock !== "object" || !lock.packages || typeof lock.packages !== "object" || Array.isArray(lock.packages)) fail();',
2372
- " for (const [relativePath, entry] of Object.entries(lock.packages)) {",
2373
- ' if (relativePath === "") continue;',
2374
- ' if (!relativePath.startsWith("node_modules/") || !entry || typeof entry !== "object" || Array.isArray(entry) || typeof entry.version !== "string") fail();',
2375
- " const packageStats = lstatSync(relativePath, { throwIfNoEntry: false });",
2376
- " if (packageStats === undefined) {",
2377
- " if (entry.optional === true) continue;",
2378
- " fail();",
2379
- " }",
2380
- ' let currentPath = "";',
2381
- ' for (const component of relativePath.split("/")) {',
2382
- ' if (!component || component === "." || component === "..") fail();',
2383
- " currentPath = currentPath ? `${currentPath}/${component}` : component;",
2384
- " const componentStats = lstatSync(currentPath, { throwIfNoEntry: false });",
2385
- " if (!componentStats?.isDirectory() || componentStats.isSymbolicLink()) fail();",
2386
- " }",
2387
- " const manifestPath = `${relativePath}/package.json`;",
2388
- " const manifestStats = lstatSync(manifestPath, { throwIfNoEntry: false });",
2389
- " if (!manifestStats?.isFile() || manifestStats.isSymbolicLink()) fail();",
2390
- ' const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));',
2391
- ' if (!manifest || typeof manifest !== "object" || manifest.version !== entry.version) fail();',
2392
- " }",
2393
- "} catch {",
2394
- " fail();",
2395
- "}"
2396
- ].join("\n");
2397
- var SUPERVISOR_INSTALLED_TREE_MANIFEST = [
2398
- '"use strict";',
2399
- 'const { createHash, randomUUID } = require("node:crypto");',
2400
- 'const { constants, closeSync, fstatSync, fsyncSync, lstatSync, openSync, readSync, readdirSync, readlinkSync, renameSync, unlinkSync, writeSync } = require("node:fs");',
2401
- 'const { posix } = require("node:path");',
2402
- "const operation = process.argv[1];",
2403
- "const manifestPath = process.argv[2];",
2404
- "const expectedGraph = process.argv[3];",
2405
- "const MAX_ENTRIES = 250000;",
2406
- "const MAX_PATH_BYTES = 4096;",
2407
- "const MAX_SYMLINK_BYTES = 4096;",
2408
- "const MAX_TOTAL_NAME_BYTES = 64 * 1024 * 1024;",
2409
- "const MAX_FILE_BYTES = 512 * 1024 * 1024;",
2410
- "const MAX_TREE_BYTES = 2 * 1024 * 1024 * 1024;",
2411
- "const MAX_MANIFEST_BYTES = 64 * 1024 * 1024;",
2412
- "const fail = () => process.exit(1);",
2413
- "const statIdentity = (stats) => [stats.dev, stats.ino, stats.mode, stats.nlink, stats.uid, stats.gid, stats.size, stats.mtimeNs, stats.ctimeNs];",
2414
- "const sameIdentity = (left, right) => statIdentity(left).every((value, index) => value === statIdentity(right)[index]);",
2415
- "const modeBits = (stats) => Number(stats.mode & 0o7777n);",
2416
- "const descriptorPath = (descriptor, name) => name === undefined ? `/proc/self/fd/${descriptor}` : `/proc/self/fd/${descriptor}/${name}`;",
2417
- 'const utf8Decoder = new TextDecoder("utf-8", { fatal: true });',
2418
- 'const decodeUtf8 = (value) => { const decoded = utf8Decoder.decode(value); if (!Buffer.from(decoded, "utf8").equals(value)) fail(); return decoded; };',
2419
- 'const assertOwned = (stats) => { if (typeof process.getuid !== "function" || stats.uid !== BigInt(process.getuid())) fail(); };',
2420
- "const assertPathBudget = (budget, relativePath) => {",
2421
- ' const bytes = Buffer.byteLength(relativePath, "utf8");',
2422
- " if (bytes === 0 || bytes > MAX_PATH_BYTES) fail();",
2423
- " budget.nameBytes += bytes;",
2424
- " budget.entries += 1;",
2425
- " if (budget.entries > MAX_ENTRIES || budget.nameBytes > MAX_TOTAL_NAME_BYTES) fail();",
2426
- "};",
2427
- "const assertSafeSymlink = (relativePath, target, budget) => {",
2428
- ' const targetBytes = Buffer.byteLength(target, "utf8");',
2429
- ' if (targetBytes === 0 || targetBytes > MAX_SYMLINK_BYTES || target.includes("\\0") || posix.isAbsolute(target)) fail();',
2430
- " budget.nameBytes += targetBytes;",
2431
- " if (budget.nameBytes > MAX_TOTAL_NAME_BYTES) fail();",
2432
- ' const withinRoot = relativePath === "node_modules" ? "" : relativePath.slice("node_modules/".length);',
2433
- " const resolved = posix.normalize(posix.join(posix.dirname(withinRoot), target));",
2434
- ' if (resolved === ".." || resolved.startsWith("../") || posix.isAbsolute(resolved)) fail();',
2435
- "};",
2436
- "const hashRegularFile = (descriptor, expectedSize, budget, durable) => {",
2437
- " if (expectedSize < 0n || expectedSize > BigInt(MAX_FILE_BYTES)) fail();",
2438
- " const size = Number(expectedSize);",
2439
- " if (!Number.isSafeInteger(size) || budget.fileBytes + size > MAX_TREE_BYTES) fail();",
2440
- " budget.fileBytes += size;",
2441
- ' const hash = createHash("sha256");',
2442
- " const buffer = Buffer.allocUnsafe(1024 * 1024);",
2443
- " let bytesReadTotal = 0;",
2444
- " while (true) {",
2445
- " const bytesRead = readSync(descriptor, buffer, 0, buffer.length, null);",
2446
- " if (!Number.isSafeInteger(bytesRead) || bytesRead < 0 || bytesReadTotal + bytesRead > size) fail();",
2447
- " if (bytesRead === 0) break;",
2448
- " bytesReadTotal += bytesRead;",
2449
- " hash.update(buffer.subarray(0, bytesRead));",
2450
- " }",
2451
- " if (bytesReadTotal !== size) fail();",
2452
- " if (durable) fsyncSync(descriptor);",
2453
- ' return hash.digest("hex");',
2454
- "};",
2455
- "const inspectDirectory = (descriptor, relativePath, entries, budget, durable) => {",
2456
- " const before = fstatSync(descriptor, { bigint: true });",
2457
- " if (!before.isDirectory() || before.isSymbolicLink()) fail();",
2458
- " assertOwned(before);",
2459
- " assertPathBudget(budget, relativePath);",
2460
- ' entries.push({ path: relativePath, kind: "directory", mode: modeBits(before) });',
2461
- ' const names = readdirSync(descriptorPath(descriptor), { encoding: "buffer" }).sort(Buffer.compare);',
2462
- " for (const rawName of names) {",
2463
- " const name = decodeUtf8(rawName);",
2464
- ' if (!name || name === "." || name === ".." || name.includes("/") || name.includes("\\0")) fail();',
2465
- " const childRelativePath = `${relativePath}/${name}`;",
2466
- " assertPathBudget(budget, childRelativePath);",
2467
- " const childPath = descriptorPath(descriptor, name);",
2468
- " const childBefore = lstatSync(childPath, { bigint: true });",
2469
- " assertOwned(childBefore);",
2470
- " if (childBefore.isSymbolicLink()) {",
2471
- ' const target = decodeUtf8(readlinkSync(childPath, { encoding: "buffer" }));',
2472
- " assertSafeSymlink(childRelativePath, target, budget);",
2473
- " const childAfter = lstatSync(childPath, { bigint: true });",
2474
- " if (!childAfter.isSymbolicLink() || !sameIdentity(childBefore, childAfter)) fail();",
2475
- ' entries.push({ path: childRelativePath, kind: "symlink", mode: modeBits(childBefore), target });',
2476
- " continue;",
2477
- " }",
2478
- " if (childBefore.isDirectory()) {",
2479
- " let childDescriptor;",
2480
- " try {",
2481
- " childDescriptor = openSync(childPath, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW | constants.O_NONBLOCK);",
2482
- " const opened = fstatSync(childDescriptor, { bigint: true });",
2483
- " if (!opened.isDirectory() || !sameIdentity(childBefore, opened)) fail();",
2484
- " budget.entries -= 1;",
2485
- ' budget.nameBytes -= Buffer.byteLength(childRelativePath, "utf8");',
2486
- " inspectDirectory(childDescriptor, childRelativePath, entries, budget, durable);",
2487
- " } finally {",
2488
- " if (childDescriptor !== undefined) closeSync(childDescriptor);",
2489
- " }",
2490
- " const childAfter = lstatSync(childPath, { bigint: true });",
2491
- " if (!childAfter.isDirectory() || !sameIdentity(childBefore, childAfter)) fail();",
2492
- " continue;",
2493
- " }",
2494
- " if (!childBefore.isFile()) fail();",
2495
- " let childDescriptor;",
2496
- " try {",
2497
- " childDescriptor = openSync(childPath, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);",
2498
- " const opened = fstatSync(childDescriptor, { bigint: true });",
2499
- " if (!opened.isFile() || !sameIdentity(childBefore, opened)) fail();",
2500
- " const sha256 = hashRegularFile(childDescriptor, opened.size, budget, durable);",
2501
- " const after = fstatSync(childDescriptor, { bigint: true });",
2502
- " if (!after.isFile() || !sameIdentity(opened, after)) fail();",
2503
- ' entries.push({ path: childRelativePath, kind: "file", mode: modeBits(opened), size: Number(opened.size), sha256 });',
2504
- " } finally {",
2505
- " if (childDescriptor !== undefined) closeSync(childDescriptor);",
2506
- " }",
2507
- " const childAfter = lstatSync(childPath, { bigint: true });",
2508
- " if (!childAfter.isFile() || !sameIdentity(childBefore, childAfter)) fail();",
2509
- " }",
2510
- " if (durable) fsyncSync(descriptor);",
2511
- " const after = fstatSync(descriptor, { bigint: true });",
2512
- " if (!after.isDirectory() || !sameIdentity(before, after)) fail();",
2513
- "};",
2514
- "const createManifest = (installDescriptor, durable) => {",
2515
- ' const rootPath = descriptorPath(installDescriptor, "node_modules");',
2516
- " const rootBefore = lstatSync(rootPath, { bigint: true });",
2517
- " if (!rootBefore.isDirectory() || rootBefore.isSymbolicLink()) fail();",
2518
- " assertOwned(rootBefore);",
2519
- " let rootDescriptor;",
2520
- " try {",
2521
- " rootDescriptor = openSync(rootPath, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW | constants.O_NONBLOCK);",
2522
- " const opened = fstatSync(rootDescriptor, { bigint: true });",
2523
- " if (!opened.isDirectory() || !sameIdentity(rootBefore, opened)) fail();",
2524
- " const entries = [];",
2525
- ' inspectDirectory(rootDescriptor, "node_modules", entries, { entries: 0, nameBytes: 0, fileBytes: 0 }, durable);',
2526
- " const rootAfter = lstatSync(rootPath, { bigint: true });",
2527
- " if (!rootAfter.isDirectory() || !sameIdentity(rootBefore, rootAfter)) fail();",
2528
- " entries.sort((left, right) => Buffer.compare(Buffer.from(left.path), Buffer.from(right.path)));",
2529
- " const serialized = `${JSON.stringify({ version: 1, graph: expectedGraph, entries })}\\n`;",
2530
- ' if (Buffer.byteLength(serialized, "utf8") > MAX_MANIFEST_BYTES) fail();',
2531
- " return serialized;",
2532
- " } finally {",
2533
- " if (rootDescriptor !== undefined) closeSync(rootDescriptor);",
2534
- " }",
2535
- "};",
2536
- "const readManifest = (installDescriptor) => {",
2537
- " let descriptor;",
2538
- " try {",
2539
- " const canonicalPath = descriptorPath(installDescriptor, manifestPath);",
2540
- " const pathBefore = lstatSync(canonicalPath, { bigint: true });",
2541
- " if (!pathBefore.isFile() || pathBefore.isSymbolicLink()) fail();",
2542
- " descriptor = openSync(canonicalPath, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);",
2543
- " const before = fstatSync(descriptor, { bigint: true });",
2544
- " if (!before.isFile() || !sameIdentity(pathBefore, before) || before.nlink !== 1n || before.uid !== BigInt(process.getuid()) || (before.mode & 0o7777n) !== 0o600n || before.size <= 0n || before.size > BigInt(MAX_MANIFEST_BYTES)) fail();",
2545
- " const size = Number(before.size);",
2546
- " const buffer = Buffer.allocUnsafe(size + 1);",
2547
- " let offset = 0;",
2548
- " while (offset < buffer.length) {",
2549
- " const bytesRead = readSync(descriptor, buffer, offset, buffer.length - offset, null);",
2550
- " if (!Number.isSafeInteger(bytesRead) || bytesRead < 0) fail();",
2551
- " if (bytesRead === 0) break;",
2552
- " offset += bytesRead;",
2553
- " }",
2554
- " if (offset !== size) fail();",
2555
- " const after = fstatSync(descriptor, { bigint: true });",
2556
- " const pathAfter = lstatSync(canonicalPath, { bigint: true });",
2557
- " if (!pathAfter.isFile() || pathAfter.isSymbolicLink() || !sameIdentity(before, after) || !sameIdentity(after, pathAfter)) fail();",
2558
- " return decodeUtf8(buffer.subarray(0, offset));",
2559
- " } finally {",
2560
- " if (descriptor !== undefined) closeSync(descriptor);",
2561
- " }",
2562
- "};",
2563
- "const publishManifest = (installDescriptor, serialized) => {",
2564
- " const temporary = `.${manifestPath}.${process.pid}.${randomUUID()}.tmp`;",
2565
- " let descriptor;",
2566
- " let exists = false;",
2567
- " try {",
2568
- " descriptor = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW | constants.O_NONBLOCK, 0o600);",
2569
- " exists = true;",
2570
- ' const contents = Buffer.from(serialized, "utf8");',
2571
- " let offset = 0;",
2572
- " while (offset < contents.length) {",
2573
- " const bytesWritten = writeSync(descriptor, contents, offset, contents.length - offset, null);",
2574
- " if (!Number.isSafeInteger(bytesWritten) || bytesWritten <= 0) fail();",
2575
- " offset += bytesWritten;",
2576
- " }",
2577
- " fsyncSync(descriptor);",
2578
- " closeSync(descriptor);",
2579
- " descriptor = undefined;",
2580
- " renameSync(temporary, manifestPath);",
2581
- " exists = false;",
2582
- " fsyncSync(installDescriptor);",
2583
- " } finally {",
2584
- " if (descriptor !== undefined) closeSync(descriptor);",
2585
- " if (exists) { try { unlinkSync(temporary); } catch {} }",
2586
- " }",
2587
- "};",
2588
- "let installDescriptor;",
2589
- "try {",
2590
- ' if (!/^[a-f0-9]{64}$/u.test(expectedGraph) || !manifestPath || manifestPath.includes("/") || manifestPath.includes("\\0")) fail();',
2591
- ' installDescriptor = openSync(".", constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW | constants.O_NONBLOCK);',
2592
- " const installStats = fstatSync(installDescriptor, { bigint: true });",
2593
- " if (!installStats.isDirectory() || installStats.uid !== BigInt(process.getuid())) fail();",
2594
- ' if (operation === "capture") {',
2595
- " const serialized = createManifest(installDescriptor, true);",
2596
- " fsyncSync(installDescriptor);",
2597
- " publishManifest(installDescriptor, serialized);",
2598
- " if (readManifest(installDescriptor) !== serialized) fail();",
2599
- ' } else if (operation === "verify") {',
2600
- " const expected = readManifest(installDescriptor);",
2601
- " if (expected !== createManifest(installDescriptor, false)) fail();",
2602
- " } else {",
2603
- " fail();",
2604
- " }",
2605
- "} catch {",
2606
- " fail();",
2607
- "} finally {",
2608
- " if (installDescriptor !== undefined) { try { closeSync(installDescriptor); } catch { fail(); } }",
2609
- "}"
2610
- ].join("\n");
2611
- function sha256(value) {
2612
- return createHash2("sha256").update(value, "utf8").digest("hex");
2613
- }
2614
- function supervisorEnvironmentRevision(envs, credentialEnv) {
2615
- const credential = envs[credentialEnv];
2616
- if (credential === void 0) {
2617
- throw new Error(
2618
- "Supervisor environment revision requires its attempt credential."
2619
- );
2620
- }
2621
- const entries = Object.entries(envs).sort(
2622
- ([left], [right]) => left < right ? -1 : left > right ? 1 : 0
2623
- );
2624
- return createHmac("sha256", credential).update(
2625
- JSON.stringify(["supervisor-environment-revision-v1", entries]),
2626
- "utf8"
2627
- ).digest("hex");
2628
- }
2629
- function bootstrapVerifyCommands(files) {
2630
- return files.map(
2631
- (file) => `verify_file ${shellQuote(file.stageFilename)} ${shellQuote(file.sha256)}`
2632
- );
2633
- }
2634
- function finalVerifyCommands(files) {
2635
- return files.map(
2636
- (file) => `verify_file ${shellQuote(file.filename)} ${shellQuote(file.sha256)}`
2637
- );
2638
- }
2639
- function createBootstrapScript(graphFingerprint, files) {
2640
- const verifyStages = bootstrapVerifyCommands(files);
2641
- const verifyFinals = finalVerifyCommands(files);
2642
- const existingFinalChecks = files.map(
2643
- (file) => `if [ -e ${shellQuote(file.filename)} ] || [ -L ${shellQuote(file.filename)} ]; then finals_present=1; fi`
2644
- );
2645
- const publishFinals = files.map(
2646
- (file) => `publish_file ${shellQuote(file.stageFilename)} ${shellQuote(file.filename)} ${shellQuote(file.sha256)}`
2647
- );
2648
- const protectedBootstrap = [
2649
- "set -eu",
2650
- "umask 077",
2651
- `marker=${shellQuote(SUPERVISOR_BOOTSTRAP_MARKER)}`,
2652
- `pending=${shellQuote(SUPERVISOR_BOOTSTRAP_PENDING)}`,
2653
- `installed_manifest=${shellQuote(SUPERVISOR_BOOTSTRAP_INSTALLED_MANIFEST)}`,
2654
- `expected_graph=${shellQuote(graphFingerprint)}`,
2655
- "verify_file() {",
2656
- " file=$1",
2657
- " expected_hash=$2",
2658
- ' [ -f "$file" ] && [ ! -L "$file" ] || { printf "%s\\n" "Supervisor bootstrap file is missing or unsafe: $file" >&2; exit 5; }',
2659
- ' digest=$(sha256sum -- "$file") || exit 5',
2660
- " digest=${digest%% *}",
2661
- ' [ "$digest" = "$expected_hash" ] || { printf "%s\\n" "Supervisor bootstrap file hash mismatch: $file" >&2; exit 5; }',
2662
- "}",
2663
- "verify_graph_file() {",
2664
- " graph_file=$1",
2665
- ' [ -f "$graph_file" ] && [ ! -L "$graph_file" ] || return 1',
2666
- ' [ "$(wc -l < "$graph_file")" -eq 1 ] || return 1',
2667
- ' actual_graph=$(cat -- "$graph_file") || return 1',
2668
- ' [ "$actual_graph" = "$expected_graph" ]',
2669
- "}",
2670
- "publish_graph_file() {",
2671
- " graph_file=$1",
2672
- ' graph_temporary=".$graph_file.$$.tmp"',
2673
- ' printf "%s\\n" "$expected_graph" > "$graph_temporary"',
2674
- ' sync -f "$graph_temporary"',
2675
- ' mv -f -- "$graph_temporary" "$graph_file"',
2676
- " sync -f .",
2677
- "}",
2678
- "publish_file() {",
2679
- " source_file=$1",
2680
- " final_file=$2",
2681
- " expected_hash=$3",
2682
- ' final_temporary=".$final_file.$$.tmp"',
2683
- ' cp -- "$source_file" "$final_temporary"',
2684
- ' sync -f "$final_temporary"',
2685
- ' mv -f -- "$final_temporary" "$final_file"',
2686
- " sync -f .",
2687
- ' verify_file "$final_file" "$expected_hash"',
2688
- "}",
2689
- "verify_installed_graph() {",
2690
- ` node -e ${shellQuote(SUPERVISOR_INSTALLED_GRAPH_VERIFIER)} >/dev/null 2>&1`,
2691
- "}",
2692
- "verify_dependency_graph() {",
2693
- " [ -d node_modules ] && [ ! -L node_modules ] && npm ls --omit=dev --all --json --ignore-scripts >/dev/null 2>&1 && verify_installed_graph",
2694
- "}",
2695
- "verify_installed_manifest() {",
2696
- ` node -e ${shellQuote(SUPERVISOR_INSTALLED_TREE_MANIFEST)} verify "$installed_manifest" "$expected_graph" >/dev/null 2>&1`,
2697
- "}",
2698
- "capture_installed_manifest() {",
2699
- ` node -e ${shellQuote(SUPERVISOR_INSTALLED_TREE_MANIFEST)} capture "$installed_manifest" "$expected_graph" >/dev/null 2>&1`,
2700
- "}",
2701
- "verify_dependency_install() {",
2702
- " verify_dependency_graph && verify_installed_manifest",
2703
- "}",
2704
- ...verifyStages,
2705
- 'if [ -e .npmrc ] || [ -L .npmrc ]; then printf "%s\\n" "Supervisor install directory must not contain .npmrc." >&2; exit 5; fi',
2706
- 'if [ -e "$marker" ] || [ -L "$marker" ]; then',
2707
- ' verify_graph_file "$marker" || { printf "%s\\n" "Supervisor install directory belongs to another artifact graph." >&2; exit 2; }',
2708
- ...verifyFinals.map((command) => ` ${command}`),
2709
- ' if [ -e "$pending" ] || [ -L "$pending" ]; then',
2710
- ' verify_graph_file "$pending" || { printf "%s\\n" "Supervisor bootstrap pending graph is invalid." >&2; exit 2; }',
2711
- " fi",
2712
- " if verify_dependency_install; then",
2713
- ' if [ -e "$pending" ] || [ -L "$pending" ]; then',
2714
- ' rm -f -- "$pending"',
2715
- " sync -f .",
2716
- " fi",
2717
- " exit 0",
2718
- " fi",
2719
- ' if [ ! -e "$pending" ] && [ ! -L "$pending" ]; then publish_graph_file "$pending"; fi',
2720
- "fi",
2721
- 'if [ -e "$pending" ] || [ -L "$pending" ]; then',
2722
- ' verify_graph_file "$pending" || { printf "%s\\n" "Supervisor install directory has another pending artifact graph." >&2; exit 2; }',
2723
- "else",
2724
- " finals_present=0",
2725
- ...existingFinalChecks.map((command) => ` ${command}`),
2726
- ' if [ "$finals_present" -eq 1 ]; then',
2727
- ...verifyFinals.map((command) => ` ${command}`),
2728
- " fi",
2729
- ' publish_graph_file "$pending"',
2730
- "fi",
2731
- ...publishFinals,
2732
- ...verifyFinals,
2733
- "npm ci --omit=dev --no-audit --no-fund",
2734
- 'verify_dependency_graph || { printf "%s\\n" "Supervisor dependency install verification failed." >&2; exit 5; }',
2735
- 'capture_installed_manifest || { printf "%s\\n" "Supervisor dependency install durability publication failed." >&2; exit 5; }',
2736
- 'verify_installed_manifest || { printf "%s\\n" "Supervisor dependency install manifest verification failed." >&2; exit 5; }',
2737
- ...verifyFinals,
2738
- 'publish_graph_file "$marker"',
2739
- 'rm -f -- "$pending"',
2740
- "sync -f ."
2741
- ].join("\n");
2742
- return [
2743
- "set -eu",
2744
- "umask 077",
2745
- 'command -v node >/dev/null 2>&1 || { printf "%s\\n" "Supervisor bootstrap requires Node.js >=22.19.0." >&2; exit 4; }',
2746
- `node -e "const [major, minor] = process.versions.node.split('.').map(Number); process.exit(major > 22 || (major === 22 && minor >= 19) ? 0 : 1)" || { printf "%s\\n" "Supervisor bootstrap requires Node.js >=22.19.0." >&2; exit 4; }`,
2747
- 'command -v flock >/dev/null 2>&1 || { printf "%s\\n" "Supervisor bootstrap requires flock." >&2; exit 4; }',
2748
- 'command -v sha256sum >/dev/null 2>&1 || { printf "%s\\n" "Supervisor bootstrap requires sha256sum." >&2; exit 4; }',
2749
- `exec node -e ${shellQuote(SUPERVISOR_BOOTSTRAP_LOCK_WRAPPER)} ${shellQuote(SUPERVISOR_BOOTSTRAP_LOCK)} ${shellQuote(protectedBootstrap)}`
2750
- ].join("\n");
2751
- }
2752
- function createInstallPreparationCommand(artifact) {
2753
- return [
2754
- "/usr/bin/env",
2755
- "-i",
2756
- `PATH=${SUPERVISOR_BOOTSTRAP_PATH}`,
2757
- "NO_COLOR=1",
2758
- "node",
2759
- "-e",
2760
- SUPERVISOR_INSTALL_DIRECTORY_PREPARER,
2761
- artifact.installDir,
2762
- ...artifact.files.map((file) => file.path)
2763
- ].map(shellQuote).join(" ");
2764
- }
2765
- function createBootstrapArtifactPlan(installDir, finalFiles) {
2766
- const fileHashes = finalFiles.map((file) => ({
2767
- ...file,
2768
- sha256: sha256(file.content)
2769
- }));
2770
- const graphFingerprint = sha256(
2771
- JSON.stringify({
2772
- version: 2,
2773
- files: fileHashes.map(({ filename, sha256: fileSha256 }) => ({
2774
- filename,
2775
- sha256: fileSha256
2776
- }))
2777
- })
2778
- );
2779
- const files = fileHashes.map((file) => ({
2780
- ...file,
2781
- stageFilename: `.neckbeard-stage-v2-${graphFingerprint}-${file.filename}`
2782
- }));
2783
- return {
2784
- files: files.map((file) => ({
2785
- path: joinPosix(installDir, file.stageFilename),
2786
- content: file.content
2787
- })),
2788
- script: createBootstrapScript(graphFingerprint, files)
2789
- };
2790
- }
2791
- function joinPosix(base, child) {
2792
- return `${base.replace(/\/+$/, "")}/${child.replace(/^\/+/, "")}`;
2793
- }
2794
- function assertNpmPackageName(value) {
2795
- if (value.length > 214 || !/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u.test(value)) {
2796
- throw new Error("pi.moduleSpecifier must be a safe npm package name.");
2797
- }
2798
- }
2799
- function assertExactPackageVersion(value) {
2800
- if (!isExactPackageVersion(value)) {
2801
- throw new Error("pi.expectedVersion must be one exact semantic version.");
2802
- }
2803
- }
2804
- function createDurableSessionArtifact(options) {
2805
- assertCanonicalSandboxPath("installDir", options.installDir);
2806
- assertCanonicalSandboxPath("workspaceDir", options.workspaceDir);
2807
- assertCanonicalSandboxPath(
2808
- "stateDurabilityAnchor",
2809
- options.stateDurabilityAnchor
2810
- );
2811
- assertCanonicalSandboxPath("stateDir", options.stateDir);
2812
- if (sandboxPathsOverlap(options.installDir, options.stateDir)) {
2813
- throw new Error("installDir and stateDir must not overlap.");
2814
- }
2815
- if (sandboxPathsOverlap(options.installDir, options.workspaceDir)) {
2816
- throw new Error("installDir and workspaceDir must not overlap.");
2817
- }
2818
- const piHarnessOptions = selectDurableSessionPiHarnessOptions(options.pi);
2819
- const sessionPath = piHarnessOptions.sessionPath ?? joinPosix(options.stateDir, "pi/session.jsonl");
2820
- assertCanonicalSandboxPath("pi.sessionPath", sessionPath);
2821
- if (piHarnessOptions.agentDir !== void 0) {
2822
- assertCanonicalSandboxPath("pi.agentDir", piHarnessOptions.agentDir);
2823
- }
2824
- const moduleSpecifier = piHarnessOptions.moduleSpecifier ?? DEFAULT_PI_SDK_MODULE;
2825
- const expectedVersion = piHarnessOptions.expectedVersion ?? DEFAULT_PI_SDK_VERSION;
2826
- assertNpmPackageName(moduleSpecifier);
2827
- assertExactPackageVersion(expectedVersion);
2828
- const packageLock = packageLockForCoordinates(
2829
- moduleSpecifier,
2830
- expectedVersion,
2831
- options.pi?.packageLock
2832
- );
2833
- const config = parseSupervisorRuntimeConfig({
2834
- protocolVersion: SUPERVISOR_PROTOCOL_VERSION,
2835
- runtimeVersion: SUPERVISOR_RUNTIME_VERSION,
2836
- provider: "daytona",
2837
- providerVersion: DAYTONA_SUPERVISOR_PROVIDER_VERSION,
2838
- sessionId: options.sessionId,
2839
- runId: options.runId,
2840
- attemptId: options.attemptId,
2841
- gatewayUrl: options.gatewayUrl,
2842
- credentialEnv: options.credentialEnv ?? DEFAULT_SUPERVISOR_CREDENTIAL_ENV,
2843
- workspaceDir: options.workspaceDir,
2844
- stateDurabilityAnchor: options.stateDurabilityAnchor,
2845
- stateDir: options.stateDir,
2846
- heartbeatIntervalMs: options.heartbeatIntervalMs ?? 3e4,
2847
- handshakeTimeoutMs: options.handshakeTimeoutMs ?? 15e3,
2848
- maxInFlightEvents: options.maxInFlightEvents ?? 256,
2849
- allowInsecureGateway: options.allowInsecureGateway ?? false,
2850
- reconnect: {
2851
- initialDelayMs: options.reconnect?.initialDelayMs ?? 500,
2852
- maximumDelayMs: options.reconnect?.maximumDelayMs ?? 6e4,
2853
- multiplier: options.reconnect?.multiplier ?? 2,
2854
- jitterRatio: options.reconnect?.jitterRatio ?? 0.2
2855
- },
2856
- attachments: {
2857
- maxBytesPerAttachment: options.attachments?.maxBytesPerAttachment ?? DEFAULT_SUPERVISOR_ATTACHMENT_CONFIG.maxBytesPerAttachment,
2858
- maxBytesPerCommand: options.attachments?.maxBytesPerCommand ?? DEFAULT_SUPERVISOR_ATTACHMENT_CONFIG.maxBytesPerCommand,
2859
- maxFilesPerAttempt: options.attachments?.maxFilesPerAttempt ?? DEFAULT_SUPERVISOR_ATTACHMENT_CONFIG.maxFilesPerAttempt,
2860
- maxBytesPerAttempt: options.attachments?.maxBytesPerAttempt ?? options.attachments?.maxBytesPerCommand ?? DEFAULT_SUPERVISOR_ATTACHMENT_CONFIG.maxBytesPerCommand,
2861
- downloadTimeoutMs: options.attachments?.downloadTimeoutMs ?? DEFAULT_SUPERVISOR_ATTACHMENT_CONFIG.downloadTimeoutMs
2862
- },
2863
- harness: {
2864
- adapter: "pi-sdk",
2865
- adapterVersion: 1,
2866
- ...piHarnessOptions,
2867
- moduleSpecifier,
2868
- expectedVersion,
2869
- sessionPath,
2870
- stopGraceMs: piHarnessOptions.stopGraceMs ?? 1e4
2871
- }
2872
- });
2873
- const bootstrapPlan = createBootstrapArtifactPlan(options.installDir, [
2874
- {
2875
- filename: SUPERVISOR_RUNTIME_FILENAME,
2876
- content: SUPERVISOR_RUNTIME_SOURCE
2877
- },
2878
- {
2879
- filename: SUPERVISOR_CONFIG_FILENAME,
2880
- content: `${JSON.stringify(config, null, 2)}
2881
- `
2882
- },
2883
- {
2884
- filename: SUPERVISOR_PACKAGE_FILENAME,
2885
- content: `${JSON.stringify(
2886
- createSupervisorPackageManifest(moduleSpecifier, expectedVersion),
2887
- null,
2888
- 2
2889
- )}
2890
- `
2891
- },
2892
- {
2893
- filename: SUPERVISOR_PACKAGE_LOCK_FILENAME,
2894
- content: packageLock
2895
- },
2896
- {
2897
- filename: SUPERVISOR_SHRINKWRAP_FILENAME,
2898
- content: packageLock
2899
- }
2900
- ]);
2901
- return {
2902
- durability: "durable",
2903
- protocolVersion: SUPERVISOR_PROTOCOL_VERSION,
2904
- runtimeVersion: SUPERVISOR_RUNTIME_VERSION,
2905
- provider: "daytona",
2906
- providerVersion: DAYTONA_SUPERVISOR_PROVIDER_VERSION,
2907
- installDir: options.installDir,
2908
- config,
2909
- files: bootstrapPlan.files,
2910
- start: {
2911
- command: "node",
2912
- args: [SUPERVISOR_RUNTIME_FILENAME, SUPERVISOR_CONFIG_FILENAME],
2913
- cwd: options.installDir
2914
- },
2915
- bootstrap: {
2916
- // Preserve the structured bootstrap executable expected by linked consumers,
2917
- // then immediately replace that shell with the clean environment. The
2918
- // constant wrapper treats every following value as an opaque argument.
2919
- command: "sh",
2920
- args: [
2921
- "-c",
2922
- SUPERVISOR_CLEAN_ENVIRONMENT_WRAPPER,
2923
- "neckbeard-bootstrap-environment",
2924
- ...createSupervisorBootstrapEnvironment(options.installDir),
2925
- "sh",
2926
- "-c",
2927
- bootstrapPlan.script
2928
- ],
2929
- cwd: options.installDir,
2930
- timeoutMs: 12e4
2931
- },
2932
- requiredEnvironmentVariables: [
2933
- config.credentialEnv,
2934
- ...config.harness.providerCredentialEnv === void 0 ? [] : [config.harness.providerCredentialEnv]
2935
- ],
2936
- requiredRuntimeModules: [
2937
- {
2938
- specifier: config.harness.moduleSpecifier,
2939
- version: config.harness.expectedVersion
2940
- }
2941
- ]
2942
- };
2943
- }
2944
- async function deployDurableSessionArtifact(sandbox, artifact, options) {
2945
- if (sandbox.provider !== artifact.provider) {
2946
- throw new Error(
2947
- `Supervisor artifact provider ${artifact.provider} cannot be deployed through ${sandbox.provider}.`
2948
- );
2949
- }
2950
- if (artifact.bootstrap.command !== "sh") {
2951
- throw new Error("Supervisor artifact bootstrap command must be sh.");
2952
- }
2953
- const envs = validateDurableSessionDeploymentEnvironment(
2954
- artifact,
2955
- options.envs
2956
- );
2957
- let preparation;
2958
- try {
2959
- preparation = await sandbox.runCommand(
2960
- createInstallPreparationCommand(artifact),
2961
- {
2962
- cwd: "/",
2963
- timeoutMs: SUPERVISOR_INSTALL_PREPARATION_TIMEOUT_MS
2964
- }
2965
- );
2966
- } catch {
2967
- throw new Error("Supervisor install directory preparation failed.");
2968
- }
2969
- if (preparation.exitCode !== 0) {
2970
- throw new Error(
2971
- `Supervisor install directory preparation failed with exit code ${preparation.exitCode}.`
2972
- );
2973
- }
2974
- try {
2975
- await sandbox.makeDir(artifact.config.workspaceDir);
2976
- for (const file of artifact.files)
2977
- await sandbox.writeFile(file.path, file.content);
2978
- } catch {
2979
- throw new Error("Supervisor artifact staging failed.");
2980
- }
2981
- const bootstrapCommand = [
2982
- ...SUPERVISOR_TRUSTED_BOOTSTRAP_ENTRYPOINT,
2983
- ...createSupervisorBootstrapEnvironment(artifact.installDir),
2984
- "/bin/sh",
2985
- ...artifact.bootstrap.args
2986
- ].map(shellQuote).join(" ");
2987
- let bootstrap;
2988
- try {
2989
- bootstrap = await sandbox.runCommand(bootstrapCommand, {
2990
- cwd: artifact.bootstrap.cwd,
2991
- timeoutMs: artifact.bootstrap.timeoutMs
2992
- });
2993
- } catch {
2994
- throw new Error("Supervisor runtime dependency installation failed.");
2995
- }
2996
- if (bootstrap.exitCode !== 0) {
2997
- throw new Error(
2998
- `Supervisor runtime dependency installation failed with exit code ${bootstrap.exitCode}.`
2999
- );
3000
- }
3001
- const structuredCommand = [artifact.start.command, ...artifact.start.args].map(shellQuote).join(" ");
3002
- const command = `exec ${structuredCommand}`;
3003
- let preparedIdentityPersistenceFailed = false;
3004
- const beforeRelease = options.beforeRelease ? async (prepared) => {
3005
- try {
3006
- await options.beforeRelease?.(prepared);
3007
- } catch {
3008
- preparedIdentityPersistenceFailed = true;
3009
- throw new Error("Supervisor prepared identity persistence failed.");
3010
- }
3011
- } : void 0;
3012
- try {
3013
- return await sandbox.startDetachedCommand(command, {
3014
- cwd: artifact.start.cwd,
3015
- envs,
3016
- environmentMode: "supervisor-fd-v1",
3017
- environmentRevision: supervisorEnvironmentRevision(
3018
- envs,
3019
- artifact.config.credentialEnv
3020
- ),
3021
- restartReleasedWhenExited: true,
3022
- launchId: artifact.config.attemptId,
3023
- ...beforeRelease ? { beforeRelease } : {}
3024
- });
3025
- } catch (error) {
3026
- if (isDetachedProcessReleasedGenerationUnavailableError(error)) {
3027
- throw new SupervisorReleasedGenerationUnavailableError();
3028
- }
3029
- if (isDetachedProcessLaunchCancelledError(error)) {
3030
- throw new SupervisorLaunchCancelledError();
3031
- }
3032
- if (preparedIdentityPersistenceFailed) {
3033
- throw new Error("Supervisor prepared identity persistence failed.");
3034
- }
3035
- throw new Error("Supervisor detached launch failed.");
3036
- }
3037
- }
3038
- function validateDurableSessionDeploymentEnvironment(artifact, source) {
3039
- const candidate = /* @__PURE__ */ Object.create(null);
3040
- let entries;
3041
- try {
3042
- entries = Object.entries(source);
3043
- } catch {
3044
- throw new Error("Supervisor launch environment could not be inspected.");
3045
- }
3046
- for (const [key, value] of entries) {
3047
- if (value !== void 0) candidate[key] = value;
3048
- }
3049
- const handoff = serializeSupervisorEnvironmentHandoff(candidate);
3050
- if (!handoff.ok) {
3051
- throw new Error(
3052
- `Supervisor launch environment is invalid (${handoff.reason}).`
3053
- );
3054
- }
3055
- const envs = handoff.environment;
3056
- for (const name of artifact.requiredEnvironmentVariables) {
3057
- if (name === artifact.config.credentialEnv) {
3058
- if (isSupervisorAttemptCredential(envs[name])) continue;
3059
- throw new Error(
3060
- `Supervisor launch requires ${name} as the canonical unpadded base64url encoding of ${SUPERVISOR_CREDENTIAL_BYTE_LENGTH} cryptographically random bytes (${SUPERVISOR_CREDENTIAL_ENCODED_LENGTH} characters).`
3061
- );
3062
- }
3063
- if (!envs[name]?.trim()) {
3064
- throw new Error(`Supervisor launch requires non-empty ${name}.`);
3065
- }
3066
- }
3067
- return envs;
3068
- }
3069
- var createPiSupervisorArtifact = createDurableSessionArtifact;
3070
- var deploySupervisorArtifact = deployDurableSessionArtifact;
3071
-
3072
- // src/supervisor/daytona-target.ts
3073
- var QUICK_COMMAND_TIMEOUT_MS = 3e4;
3074
- async function createDaytonaSupervisorDetachedProcessControl(sandbox, targetOptions) {
3075
- const { homeDir } = await discoverDaytonaSandboxDirectories(sandbox, {
3076
- ...targetOptions.beforeMutation === void 0 ? {} : { beforeIo: targetOptions.beforeMutation },
3077
- failure: (message) => new Error(message)
3078
- });
3079
- return createDaytonaDetachedProcessController(sandbox, {
3080
- homeDir,
3081
- ...targetOptions.beforeMutation === void 0 ? {} : { beforePrepareMutation: targetOptions.beforeMutation },
3082
- ...targetOptions.beforeMutation === void 0 ? {} : { beforeStopOrDisposeMutation: targetOptions.beforeMutation },
3083
- readLegacyLogs: async () => ({ stdout: "", stderr: "" }),
3084
- stopLegacy: async () => {
3085
- throw new Error(
3086
- "Legacy detached handles are not supported by the supervisor-only Daytona target."
3087
- );
3088
- },
3089
- failure: (message) => new Error(message)
3090
- });
3091
- }
3092
- function createDaytonaSupervisorTerminalProcessControl(sandbox, targetOptions) {
3093
- return createDaytonaTerminalDetachedProcessController(sandbox, {
3094
- ...targetOptions.beforeMutation === void 0 ? {} : { beforeStopOrDisposeMutation: targetOptions.beforeMutation },
3095
- readLegacyLogs: async () => ({ stdout: "", stderr: "" }),
3096
- stopLegacy: async () => {
3097
- throw new Error(
3098
- "Legacy detached handles are not supported by the supervisor-only Daytona target."
3099
- );
3100
- },
3101
- failure: (message) => new Error(message)
3102
- });
3103
- }
3104
- async function stopDaytonaSupervisorSession(sandbox, command, targetOptions = {}) {
3105
- const detachedProcesses = createDaytonaSupervisorTerminalProcessControl(
3106
- sandbox,
3107
- targetOptions
3108
- );
3109
- await detachedProcesses.stop(command);
3110
- }
3111
- async function disposeDaytonaSupervisorSessionArtifacts(sandbox, command, targetOptions = {}) {
3112
- const detachedProcesses = createDaytonaSupervisorTerminalProcessControl(
3113
- sandbox,
3114
- targetOptions
3115
- );
3116
- await detachedProcesses.dispose(command);
3117
- }
3118
- async function createDaytonaSupervisorSandboxTarget(sandbox, targetOptions = {}) {
3119
- const detachedProcesses = await createDaytonaSupervisorDetachedProcessControl(
3120
- sandbox,
3121
- targetOptions
3122
- );
3123
- return {
3124
- provider: "daytona",
3125
- async makeDir(path) {
3126
- const result = await makeDaytonaDirectory(sandbox, path, {
3127
- timeoutMs: QUICK_COMMAND_TIMEOUT_MS,
3128
- ...targetOptions.beforeMutation === void 0 ? {} : { beforeIo: targetOptions.beforeMutation }
3129
- });
3130
- if (result.exitCode !== 0) {
3131
- throw new Error(`Failed to create supervisor directory ${path}.`);
3132
- }
3133
- },
3134
- writeFile(path, content) {
3135
- return uploadDaytonaFile(sandbox, path, content, {
3136
- timeoutMs: QUICK_COMMAND_TIMEOUT_MS,
3137
- ...targetOptions.beforeMutation === void 0 ? {} : { beforeIo: targetOptions.beforeMutation }
3138
- });
3139
- },
3140
- async runCommand(command, options) {
3141
- return executeDaytonaCommand(sandbox, command, {
3142
- timeoutMs: options.timeoutMs,
3143
- ...options.cwd === void 0 ? {} : { cwd: options.cwd },
3144
- ...options.envs === void 0 ? {} : { envs: options.envs },
3145
- ...targetOptions.beforeMutation === void 0 ? {} : { beforeIo: targetOptions.beforeMutation }
3146
- });
3147
- },
3148
- startDetachedCommand(command, options) {
3149
- return detachedProcesses.start(command, options);
3150
- }
3151
- };
3152
- }
3153
- export {
3154
- DAYTONA_SUPERVISOR_PROVIDER_VERSION,
3155
- DEFAULT_PI_SDK_MODULE,
3156
- DEFAULT_PI_SDK_VERSION,
3157
- DEFAULT_SUPERVISOR_ATTACHMENT_CONFIG,
3158
- DEFAULT_SUPERVISOR_CREDENTIAL_ENV,
3159
- MIN_SUPERVISOR_CREDENTIAL_LENGTH,
3160
- SUPERVISOR_CONFIG_FILENAME,
3161
- SUPERVISOR_CREDENTIAL_BYTE_LENGTH,
3162
- SUPERVISOR_CREDENTIAL_ENCODED_LENGTH,
3163
- SUPERVISOR_LAUNCH_CANCELLED_CODE,
3164
- SUPERVISOR_PACKAGE_FILENAME,
3165
- SUPERVISOR_PACKAGE_LOCK_FILENAME,
3166
- SUPERVISOR_PROTOCOL_VERSION,
3167
- SUPERVISOR_RECOVERY_STOP_REASON,
3168
- SUPERVISOR_RELEASED_GENERATION_UNAVAILABLE_CODE,
3169
- SUPERVISOR_RUNTIME_FILENAME,
3170
- SUPERVISOR_RUNTIME_VERSION,
3171
- SUPERVISOR_SHRINKWRAP_FILENAME,
3172
- SupervisorLaunchCancelledError,
3173
- SupervisorReleasedGenerationUnavailableError,
3174
- createDaytonaSupervisorSandboxTarget,
3175
- createDurableSessionArtifact,
3176
- createPiSupervisorArtifact,
3177
- createSupervisorEventId,
3178
- deployDurableSessionArtifact,
3179
- deploySupervisorArtifact,
3180
- disposeDaytonaSupervisorSessionArtifacts,
3181
- hasMatchingAttempt,
3182
- parseGatewayToSupervisorFrame,
3183
- parseSupervisorRuntimeConfig,
3184
- serializeSupervisorError,
3185
- stopDaytonaSupervisorSession,
3186
- validateDurableSessionDeploymentEnvironment
3187
- };