agent-neckbeard 1.1.22 → 1.1.23

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.
@@ -2448,7 +2448,7 @@ function isStopConfirmation(output) {
2448
2448
  }
2449
2449
 
2450
2450
  // src/supervisor/runtime-source.generated.ts
2451
- 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: (success) => {\n if (preflightSettled) return;\n preflightSettled = true;\n if (success) {\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';
2451
+ 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';
2452
2452
 
2453
2453
  // src/supervisor/default-pi-package-lock.json
2454
2454
  var default_pi_package_lock_default = {
@@ -2459,52 +2459,17 @@ var default_pi_package_lock_default = {
2459
2459
  "": {
2460
2460
  name: "neckbeard-supervisor-runtime",
2461
2461
  dependencies: {
2462
- "@earendil-works/pi-coding-agent": "0.83.0"
2462
+ "@earendil-works/pi-coding-agent": "1.3.0"
2463
2463
  }
2464
2464
  },
2465
- "node_modules/@earendil-works/pi-coding-agent": {
2466
- version: "0.83.0",
2467
- resolved: "https://registry.npmjs.org/@earendil-works/pi-coding-agent/-/pi-coding-agent-0.83.0.tgz",
2468
- integrity: "sha512-uYhF+FsZxogoSX/AxBcUdiY+ZklubwaXyAoEGA2eQwsHcyEAhUYIKh/WLXe/a8+k8eTCmxb+ZN2Zo9mzQtzbWw==",
2469
- hasShrinkwrap: true,
2465
+ "node_modules/@anthropic-ai/sdk": {
2466
+ version: "0.129.0",
2467
+ resolved: "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.129.0.tgz",
2468
+ integrity: "sha512-MH7LB20kNpGLUpPTe2OG5XvL/KhX8HUO9XyBaFjgFk6TLS4Xjt0VPIuMKywe7POKKPslX+QxSlVok9e+8kG5Nw==",
2470
2469
  license: "MIT",
2471
2470
  dependencies: {
2472
- "@earendil-works/pi-agent-core": "^0.83.0",
2473
- "@earendil-works/pi-ai": "^0.83.0",
2474
- "@earendil-works/pi-tui": "^0.83.0",
2475
- "@silvia-odwyer/photon-node": "0.3.4",
2476
- chalk: "5.6.2",
2477
- "cross-spawn": "7.0.6",
2478
- diff: "8.0.4",
2479
- glob: "13.0.6",
2480
- "highlight.js": "10.7.3",
2481
- "hosted-git-info": "9.0.3",
2482
- ignore: "7.0.5",
2483
- jiti: "2.7.0",
2484
- minimatch: "10.2.5",
2485
- "proper-lockfile": "4.1.2",
2486
- semver: "7.8.0",
2487
- typebox: "1.3.7",
2488
- undici: "8.5.0",
2489
- yaml: "2.9.0"
2490
- },
2491
- bin: {
2492
- pi: "dist/cli.js"
2493
- },
2494
- engines: {
2495
- node: ">=22.19.0"
2496
- },
2497
- optionalDependencies: {
2498
- "@mariozechner/clipboard": "0.3.9"
2499
- }
2500
- },
2501
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@anthropic-ai/sdk": {
2502
- version: "0.91.1",
2503
- resolved: "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.91.1.tgz",
2504
- integrity: "sha512-LAmu761tSN9r66ixvmciswUj/ZC+1Q4iAfpedTfSVLeswRwnY3n2Nb6Tsk+cLPP28aLOPWeMgIuTuCcMC6W/iw==",
2505
- license: "MIT",
2506
- dependencies: {
2507
- "json-schema-to-ts": "^3.1.1"
2471
+ "json-schema-to-ts": "^3.1.1",
2472
+ standardwebhooks: "^1.0.0"
2508
2473
  },
2509
2474
  bin: {
2510
2475
  "anthropic-ai-sdk": "bin/cli"
@@ -2518,106 +2483,41 @@ var default_pi_package_lock_default = {
2518
2483
  }
2519
2484
  }
2520
2485
  },
2521
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-crypto/crc32": {
2522
- version: "5.2.0",
2523
- resolved: "https://registry.npmjs.org/@aws-crypto/crc32/-/crc32-5.2.0.tgz",
2524
- integrity: "sha512-nLbCWqQNgUiwwtFsen1AdzAtvuLRsQS8rYgMuxCrdKf9kOssamGLuPwyTY9wyYblNr9+1XM8v6zoDTPPSIeANg==",
2525
- license: "Apache-2.0",
2526
- dependencies: {
2527
- "@aws-crypto/util": "^5.2.0",
2528
- "@aws-sdk/types": "^3.222.0",
2529
- tslib: "^2.6.2"
2530
- },
2531
- engines: {
2532
- node: ">=16.0.0"
2533
- }
2534
- },
2535
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-crypto/sha256-browser": {
2536
- version: "5.2.0",
2537
- resolved: "https://registry.npmjs.org/@aws-crypto/sha256-browser/-/sha256-browser-5.2.0.tgz",
2538
- integrity: "sha512-AXfN/lGotSQwu6HNcEsIASo7kWXZ5HYWvfOmSNKDsEqC4OashTp8alTmaz+F7TC2L083SFv5RdB+qU3Vs1kZqw==",
2539
- license: "Apache-2.0",
2540
- dependencies: {
2541
- "@aws-crypto/sha256-js": "^5.2.0",
2542
- "@aws-crypto/supports-web-crypto": "^5.2.0",
2543
- "@aws-crypto/util": "^5.2.0",
2544
- "@aws-sdk/types": "^3.222.0",
2545
- "@aws-sdk/util-locate-window": "^3.0.0",
2546
- "@smithy/util-utf8": "^2.0.0",
2547
- tslib: "^2.6.2"
2548
- }
2549
- },
2550
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-crypto/sha256-js": {
2551
- version: "5.2.0",
2552
- resolved: "https://registry.npmjs.org/@aws-crypto/sha256-js/-/sha256-js-5.2.0.tgz",
2553
- integrity: "sha512-FFQQyu7edu4ufvIZ+OadFpHHOt+eSTBaYaki44c+akjg7qZg9oOQeLlk77F6tSYqjDAFClrHJk9tMf0HdVyOvA==",
2554
- license: "Apache-2.0",
2555
- dependencies: {
2556
- "@aws-crypto/util": "^5.2.0",
2557
- "@aws-sdk/types": "^3.222.0",
2558
- tslib: "^2.6.2"
2559
- },
2560
- engines: {
2561
- node: ">=16.0.0"
2562
- }
2563
- },
2564
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-crypto/supports-web-crypto": {
2565
- version: "5.2.0",
2566
- resolved: "https://registry.npmjs.org/@aws-crypto/supports-web-crypto/-/supports-web-crypto-5.2.0.tgz",
2567
- integrity: "sha512-iAvUotm021kM33eCdNfwIN//F77/IADDSs58i+MDaOqFrVjZo9bAal0NK7HurRuWLLpF1iLX7gbWrjHjeo+YFg==",
2568
- license: "Apache-2.0",
2569
- dependencies: {
2570
- tslib: "^2.6.2"
2571
- }
2572
- },
2573
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-crypto/util": {
2574
- version: "5.2.0",
2575
- resolved: "https://registry.npmjs.org/@aws-crypto/util/-/util-5.2.0.tgz",
2576
- integrity: "sha512-4RkU9EsI6ZpBve5fseQlGNUWKMa1RLPQ1dnjnQoe07ldfIzcsGb5hC5W0Dm7u423KWzawlrpbjXBrXCEv9zazQ==",
2577
- license: "Apache-2.0",
2578
- dependencies: {
2579
- "@aws-sdk/types": "^3.222.0",
2580
- "@smithy/util-utf8": "^2.0.0",
2581
- tslib: "^2.6.2"
2582
- }
2583
- },
2584
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/client-bedrock-runtime": {
2585
- version: "3.1048.0",
2586
- resolved: "https://registry.npmjs.org/@aws-sdk/client-bedrock-runtime/-/client-bedrock-runtime-3.1048.0.tgz",
2587
- integrity: "sha512-u+NT61JZEkRFtpL0CAw1N1dwxnaLgwVXQl/zjJxTGgLyS/jTIdg2SdoEoCTHxgDyCnqa1HEi9QOoE9/pYRNpOQ==",
2486
+ "node_modules/@aws-sdk/client-bedrock-runtime": {
2487
+ version: "3.1127.0",
2488
+ resolved: "https://registry.npmjs.org/@aws-sdk/client-bedrock-runtime/-/client-bedrock-runtime-3.1127.0.tgz",
2489
+ integrity: "sha512-IDl/lrPb90aH+pZFHGNDmgH9nAUQj5PlZH1sJ3w7RikctyjHSnY3oNjZhrLoaBoQn/rNK0zsP6OHEqEhj2tdLA==",
2588
2490
  license: "Apache-2.0",
2589
2491
  dependencies: {
2590
- "@aws-crypto/sha256-browser": "5.2.0",
2591
- "@aws-crypto/sha256-js": "5.2.0",
2592
- "@aws-sdk/core": "^3.974.11",
2593
- "@aws-sdk/credential-provider-node": "^3.972.42",
2594
- "@aws-sdk/eventstream-handler-node": "^3.972.16",
2595
- "@aws-sdk/middleware-eventstream": "^3.972.12",
2596
- "@aws-sdk/middleware-websocket": "^3.972.19",
2597
- "@aws-sdk/token-providers": "3.1048.0",
2598
- "@aws-sdk/types": "^3.973.8",
2599
- "@smithy/core": "^3.24.2",
2600
- "@smithy/fetch-http-handler": "^5.4.2",
2601
- "@smithy/node-http-handler": "^4.7.2",
2602
- "@smithy/types": "^4.14.1",
2492
+ "@aws-sdk/core": "^3.977.9",
2493
+ "@aws-sdk/credential-provider-node": "^3.972.82",
2494
+ "@aws-sdk/eventstream-handler-node": "^3.972.34",
2495
+ "@aws-sdk/middleware-eventstream": "^3.972.29",
2496
+ "@aws-sdk/middleware-websocket": "^3.972.52",
2497
+ "@aws-sdk/token-providers": "3.1127.0",
2498
+ "@aws-sdk/types": "^3.974.5",
2499
+ "@smithy/core": "^3.33.3",
2500
+ "@smithy/fetch-http-handler": "^5.7.2",
2501
+ "@smithy/node-http-handler": "^4.11.3",
2502
+ "@smithy/types": "^4.17.2",
2603
2503
  tslib: "^2.6.2"
2604
2504
  },
2605
2505
  engines: {
2606
2506
  node: ">=20.0.0"
2607
2507
  }
2608
2508
  },
2609
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/core": {
2610
- version: "3.974.11",
2611
- resolved: "https://registry.npmjs.org/@aws-sdk/core/-/core-3.974.11.tgz",
2612
- integrity: "sha512-QpnINq5FZH6EOaDEkmHdT7eUunbvD27pDNQypaWjFyYz7Zl1q3UCMQErBZxpmfGfI7MvI2TlK8KTkgNpv8b1ug==",
2509
+ "node_modules/@aws-sdk/core": {
2510
+ version: "3.978.3",
2511
+ resolved: "https://registry.npmjs.org/@aws-sdk/core/-/core-3.978.3.tgz",
2512
+ integrity: "sha512-nslpzUCTI9b2IQMWSd6mSAXldBexPc8rr0d3dXUutXYFLFaTdsHa2GD7sJdsn3PhyjK0O5K8ypd6zi+RXXPVlg==",
2613
2513
  license: "Apache-2.0",
2614
2514
  dependencies: {
2615
- "@aws-sdk/types": "^3.973.8",
2616
- "@aws-sdk/xml-builder": "^3.972.24",
2617
- "@aws/lambda-invoke-store": "^0.2.2",
2618
- "@smithy/core": "^3.24.2",
2619
- "@smithy/signature-v4": "^5.4.2",
2620
- "@smithy/types": "^4.14.1",
2515
+ "@aws-sdk/types": "^3.974.6",
2516
+ "@aws-sdk/xml-builder": "^3.972.41",
2517
+ "@aws/lambda-invoke-store": "^0.3.0",
2518
+ "@smithy/core": "^3.35.2",
2519
+ "@smithy/signature-v4": "^5.7.4",
2520
+ "@smithy/types": "^4.19.0",
2621
2521
  bowser: "^2.11.0",
2622
2522
  tslib: "^2.6.2"
2623
2523
  },
@@ -2625,646 +2525,482 @@ var default_pi_package_lock_default = {
2625
2525
  node: ">=20.0.0"
2626
2526
  }
2627
2527
  },
2628
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/credential-provider-env": {
2629
- version: "3.972.37",
2630
- resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.972.37.tgz",
2631
- integrity: "sha512-/jpPvEh6f7ntmIzf7dNxoNX6Q8vt8UpesCjbW6mFfk4V1NW6bIy9qxcQ6WbA8As5yQhsZOe+xeNd4xHX8kdY2Q==",
2528
+ "node_modules/@aws-sdk/credential-provider-env": {
2529
+ version: "3.972.74",
2530
+ resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.972.74.tgz",
2531
+ integrity: "sha512-rsRJcW2iFUhCgclyD6OSbMEaPl8Eu0qSeRZb2uuCK1ViZ66hl5wOe/p6Vr6MO3b+ydyKgFeqza2p6tZThvILlw==",
2632
2532
  license: "Apache-2.0",
2633
2533
  dependencies: {
2634
- "@aws-sdk/core": "^3.974.11",
2635
- "@aws-sdk/types": "^3.973.8",
2636
- "@smithy/core": "^3.24.2",
2637
- "@smithy/types": "^4.14.1",
2534
+ "@aws-sdk/core": "^3.978.3",
2535
+ "@aws-sdk/types": "^3.974.6",
2536
+ "@smithy/core": "^3.35.2",
2537
+ "@smithy/types": "^4.19.0",
2638
2538
  tslib: "^2.6.2"
2639
2539
  },
2640
2540
  engines: {
2641
2541
  node: ">=20.0.0"
2642
2542
  }
2643
2543
  },
2644
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/credential-provider-http": {
2645
- version: "3.972.39",
2646
- resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.972.39.tgz",
2647
- integrity: "sha512-pIgTpisWyWg7X1bUbzSjuUYosYTD0Ghz2M0hkSTmb3a6i3qV3uU+NYJPI/E2XSC0HcsZh5rsLPzeXrkb2DS0Cg==",
2544
+ "node_modules/@aws-sdk/credential-provider-http": {
2545
+ version: "3.972.76",
2546
+ resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.972.76.tgz",
2547
+ integrity: "sha512-pnKdh0Br7OJPj+7qKjzgTfDTFW0RhEMKXNDR2jv9CAM4oHuG/4z3hRh8KtutLfpmItuRtDbKBmwWkDqHwwAWXw==",
2648
2548
  license: "Apache-2.0",
2649
2549
  dependencies: {
2650
- "@aws-sdk/core": "^3.974.11",
2651
- "@aws-sdk/types": "^3.973.8",
2652
- "@smithy/core": "^3.24.2",
2653
- "@smithy/fetch-http-handler": "^5.4.2",
2654
- "@smithy/node-http-handler": "^4.7.2",
2655
- "@smithy/types": "^4.14.1",
2550
+ "@aws-sdk/core": "^3.978.3",
2551
+ "@aws-sdk/types": "^3.974.6",
2552
+ "@smithy/core": "^3.35.2",
2553
+ "@smithy/fetch-http-handler": "^5.8.0",
2554
+ "@smithy/node-http-handler": "^4.12.1",
2555
+ "@smithy/types": "^4.19.0",
2656
2556
  tslib: "^2.6.2"
2657
2557
  },
2658
2558
  engines: {
2659
2559
  node: ">=20.0.0"
2660
2560
  }
2661
2561
  },
2662
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/credential-provider-ini": {
2663
- version: "3.972.41",
2664
- resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.972.41.tgz",
2665
- integrity: "sha512-u2tyjaxJJzW8UtW4SM1ZcPMDwO6y+kV+llvou+Adts0FAKyzes5jG4izQN+KX3yE8ZROpS5y1LJ//xL2iSf76w==",
2562
+ "node_modules/@aws-sdk/credential-provider-ini": {
2563
+ version: "3.973.19",
2564
+ resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.973.19.tgz",
2565
+ integrity: "sha512-kcjvAxqQEV8yuwkX58RelNn3ne65o7JgRWf3Z/gVvbi7Xuw1qSDLJlatrLD76+40cmRxmNkLxBoyp/vAQChQ5g==",
2666
2566
  license: "Apache-2.0",
2667
2567
  dependencies: {
2668
- "@aws-sdk/core": "^3.974.11",
2669
- "@aws-sdk/credential-provider-env": "^3.972.37",
2670
- "@aws-sdk/credential-provider-http": "^3.972.39",
2671
- "@aws-sdk/credential-provider-login": "^3.972.41",
2672
- "@aws-sdk/credential-provider-process": "^3.972.37",
2673
- "@aws-sdk/credential-provider-sso": "^3.972.41",
2674
- "@aws-sdk/credential-provider-web-identity": "^3.972.41",
2675
- "@aws-sdk/nested-clients": "^3.997.9",
2676
- "@aws-sdk/types": "^3.973.8",
2677
- "@smithy/core": "^3.24.2",
2678
- "@smithy/credential-provider-imds": "^4.3.2",
2679
- "@smithy/types": "^4.14.1",
2568
+ "@aws-sdk/core": "^3.978.3",
2569
+ "@aws-sdk/credential-provider-env": "^3.972.74",
2570
+ "@aws-sdk/credential-provider-http": "^3.972.76",
2571
+ "@aws-sdk/credential-provider-login": "^3.972.81",
2572
+ "@aws-sdk/credential-provider-process": "^3.972.74",
2573
+ "@aws-sdk/credential-provider-sso": "^3.973.18",
2574
+ "@aws-sdk/credential-provider-web-identity": "^3.972.80",
2575
+ "@aws-sdk/nested-clients": "^3.997.48",
2576
+ "@aws-sdk/types": "^3.974.6",
2577
+ "@smithy/core": "^3.35.2",
2578
+ "@smithy/credential-provider-imds": "^4.5.2",
2579
+ "@smithy/types": "^4.19.0",
2680
2580
  tslib: "^2.6.2"
2681
2581
  },
2682
2582
  engines: {
2683
2583
  node: ">=20.0.0"
2684
2584
  }
2685
2585
  },
2686
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/credential-provider-login": {
2687
- version: "3.972.41",
2688
- resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-login/-/credential-provider-login-3.972.41.tgz",
2689
- integrity: "sha512-0LBitxXiAiaE5nlFPfpNIww/8FRY/I7WIndWsc9GmNFOM7cE1wNpVNQEGEk9Outg5l8xl+3vybxFyUy4l9q/LQ==",
2586
+ "node_modules/@aws-sdk/credential-provider-login": {
2587
+ version: "3.972.81",
2588
+ resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-login/-/credential-provider-login-3.972.81.tgz",
2589
+ integrity: "sha512-CeQHSbE2CnVdaHIJ/NayRaCecIER+Pm9faUPkmRATO54rCoMTEPSbVieGHzEwvm1dZM2HIs6qQZCznhayNTWJQ==",
2690
2590
  license: "Apache-2.0",
2691
2591
  dependencies: {
2692
- "@aws-sdk/core": "^3.974.11",
2693
- "@aws-sdk/nested-clients": "^3.997.9",
2694
- "@aws-sdk/types": "^3.973.8",
2695
- "@smithy/core": "^3.24.2",
2696
- "@smithy/types": "^4.14.1",
2592
+ "@aws-sdk/core": "^3.978.3",
2593
+ "@aws-sdk/nested-clients": "^3.997.48",
2594
+ "@aws-sdk/types": "^3.974.6",
2595
+ "@smithy/core": "^3.35.2",
2596
+ "@smithy/types": "^4.19.0",
2697
2597
  tslib: "^2.6.2"
2698
2598
  },
2699
2599
  engines: {
2700
2600
  node: ">=20.0.0"
2701
2601
  }
2702
2602
  },
2703
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/credential-provider-node": {
2704
- version: "3.972.42",
2705
- resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.972.42.tgz",
2706
- integrity: "sha512-D4oon2zbqqsWOJUM99Gm3/ZyJ0IJvTXVN3PyloGb3kQEyI36fjCZheZj422lAgTWWd6TSHgiImLt3RIaLdv3dQ==",
2603
+ "node_modules/@aws-sdk/credential-provider-node": {
2604
+ version: "3.972.86",
2605
+ resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.972.86.tgz",
2606
+ integrity: "sha512-WNttSyr6e8innPtBSty//CdnqJcgZN6eAbtw3v/CR2IObz6MYZEo8eusdtuCHJ2ujwFqC2bSPHVyhXGHx8HruQ==",
2707
2607
  license: "Apache-2.0",
2708
2608
  dependencies: {
2709
- "@aws-sdk/credential-provider-env": "^3.972.37",
2710
- "@aws-sdk/credential-provider-http": "^3.972.39",
2711
- "@aws-sdk/credential-provider-ini": "^3.972.41",
2712
- "@aws-sdk/credential-provider-process": "^3.972.37",
2713
- "@aws-sdk/credential-provider-sso": "^3.972.41",
2714
- "@aws-sdk/credential-provider-web-identity": "^3.972.41",
2715
- "@aws-sdk/types": "^3.973.8",
2716
- "@smithy/core": "^3.24.2",
2717
- "@smithy/credential-provider-imds": "^4.3.2",
2718
- "@smithy/types": "^4.14.1",
2609
+ "@aws-sdk/credential-provider-env": "^3.972.74",
2610
+ "@aws-sdk/credential-provider-http": "^3.972.76",
2611
+ "@aws-sdk/credential-provider-ini": "^3.973.19",
2612
+ "@aws-sdk/credential-provider-process": "^3.972.74",
2613
+ "@aws-sdk/credential-provider-sso": "^3.973.18",
2614
+ "@aws-sdk/credential-provider-web-identity": "^3.972.80",
2615
+ "@aws-sdk/types": "^3.974.6",
2616
+ "@smithy/core": "^3.35.2",
2617
+ "@smithy/credential-provider-imds": "^4.5.2",
2618
+ "@smithy/types": "^4.19.0",
2719
2619
  tslib: "^2.6.2"
2720
2620
  },
2721
2621
  engines: {
2722
2622
  node: ">=20.0.0"
2723
2623
  }
2724
2624
  },
2725
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/credential-provider-process": {
2726
- version: "3.972.37",
2727
- resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.972.37.tgz",
2728
- integrity: "sha512-7nVaHBUaWIddASYfVaA9O4D5ZVjewU3sCol9WqZPGfW0nR+0WqE0xHZnD/U2L33PlOB8KNXGKZ6wOES/QijKzg==",
2625
+ "node_modules/@aws-sdk/credential-provider-process": {
2626
+ version: "3.972.74",
2627
+ resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.972.74.tgz",
2628
+ integrity: "sha512-Yj6kZFJQdbR+PygTkqdVLPHHpdDpOS9GCYVcDCuweCRRig9LF24ELQBMfyUw1vspvrZJUfnOGVyMjhaL094ahw==",
2729
2629
  license: "Apache-2.0",
2730
2630
  dependencies: {
2731
- "@aws-sdk/core": "^3.974.11",
2732
- "@aws-sdk/types": "^3.973.8",
2733
- "@smithy/core": "^3.24.2",
2734
- "@smithy/types": "^4.14.1",
2631
+ "@aws-sdk/core": "^3.978.3",
2632
+ "@aws-sdk/types": "^3.974.6",
2633
+ "@smithy/core": "^3.35.2",
2634
+ "@smithy/types": "^4.19.0",
2735
2635
  tslib: "^2.6.2"
2736
2636
  },
2737
2637
  engines: {
2738
2638
  node: ">=20.0.0"
2739
2639
  }
2740
2640
  },
2741
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/credential-provider-sso": {
2742
- version: "3.972.41",
2743
- resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.972.41.tgz",
2744
- integrity: "sha512-IOWAWEHe5LkjSKkkUUX9ciV6Y1scHTsnfEkdt5yyC4Slrc7AGbkLPrpntjqh18ksJAMOaVhoBsO8p2WyTcY2wQ==",
2641
+ "node_modules/@aws-sdk/credential-provider-sso": {
2642
+ version: "3.973.18",
2643
+ resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.973.18.tgz",
2644
+ integrity: "sha512-FnpPhdY4qUGtX/8X6eKxh+uD+9Y19i9FYibgk4SBe0M935s9vocHkHzaxaMNk+YkHmvzgdu8cHA5SCoeU+kkew==",
2745
2645
  license: "Apache-2.0",
2746
2646
  dependencies: {
2747
- "@aws-sdk/core": "^3.974.11",
2748
- "@aws-sdk/nested-clients": "^3.997.9",
2749
- "@aws-sdk/token-providers": "3.1048.0",
2750
- "@aws-sdk/types": "^3.973.8",
2751
- "@smithy/core": "^3.24.2",
2752
- "@smithy/types": "^4.14.1",
2647
+ "@aws-sdk/core": "^3.978.3",
2648
+ "@aws-sdk/nested-clients": "^3.997.48",
2649
+ "@aws-sdk/token-providers": "3.1150.0",
2650
+ "@aws-sdk/types": "^3.974.6",
2651
+ "@smithy/core": "^3.35.2",
2652
+ "@smithy/types": "^4.19.0",
2753
2653
  tslib: "^2.6.2"
2754
2654
  },
2755
2655
  engines: {
2756
2656
  node: ">=20.0.0"
2757
2657
  }
2758
2658
  },
2759
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/credential-provider-web-identity": {
2760
- version: "3.972.41",
2761
- resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.972.41.tgz",
2762
- integrity: "sha512-mbACk9Yypa8nm4iGZLs0PofOXEcTDOUw6wDnsPXNDNSd2WNXs1tSo+6nc/fh0jLYdfVZThhBL98PHW4aXFsG5A==",
2659
+ "node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers": {
2660
+ version: "3.1150.0",
2661
+ resolved: "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1150.0.tgz",
2662
+ integrity: "sha512-wDU36ofhabZYu+d2KSriyDbwzxNoaOp+4dG0p3qkabk7HeALR5nIWyQbjoyJZLn3iqWkv/xNdyUfbfevDVDzzg==",
2763
2663
  license: "Apache-2.0",
2764
2664
  dependencies: {
2765
- "@aws-sdk/core": "^3.974.11",
2766
- "@aws-sdk/nested-clients": "^3.997.9",
2767
- "@aws-sdk/types": "^3.973.8",
2768
- "@smithy/core": "^3.24.2",
2769
- "@smithy/types": "^4.14.1",
2665
+ "@aws-sdk/core": "^3.978.3",
2666
+ "@aws-sdk/nested-clients": "^3.997.48",
2667
+ "@aws-sdk/types": "^3.974.6",
2668
+ "@smithy/core": "^3.35.2",
2669
+ "@smithy/types": "^4.19.0",
2770
2670
  tslib: "^2.6.2"
2771
2671
  },
2772
2672
  engines: {
2773
2673
  node: ">=20.0.0"
2774
2674
  }
2775
2675
  },
2776
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/eventstream-handler-node": {
2777
- version: "3.972.16",
2778
- resolved: "https://registry.npmjs.org/@aws-sdk/eventstream-handler-node/-/eventstream-handler-node-3.972.16.tgz",
2779
- integrity: "sha512-yedpPgKftqjU5SlPFHfqWpOw6xSCRieWRG1euWOlXn4WJxt2VX92VprCa2PpSOXjVCAeK6dTjW9eJRXVig9yGA==",
2676
+ "node_modules/@aws-sdk/credential-provider-web-identity": {
2677
+ version: "3.972.80",
2678
+ resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.972.80.tgz",
2679
+ integrity: "sha512-TJF25Ndwy2HxcVj6oxMgp8qVlJAawlExHYBXqhuC6Zt2m+A7WpdkjBD6QglNbiArlteYljZHEY3R7KKmno6ISA==",
2780
2680
  license: "Apache-2.0",
2781
2681
  dependencies: {
2782
- "@aws-sdk/types": "^3.973.8",
2783
- "@smithy/core": "^3.24.2",
2784
- "@smithy/types": "^4.14.1",
2682
+ "@aws-sdk/core": "^3.978.3",
2683
+ "@aws-sdk/nested-clients": "^3.997.48",
2684
+ "@aws-sdk/types": "^3.974.6",
2685
+ "@smithy/core": "^3.35.2",
2686
+ "@smithy/types": "^4.19.0",
2785
2687
  tslib: "^2.6.2"
2786
2688
  },
2787
2689
  engines: {
2788
2690
  node: ">=20.0.0"
2789
2691
  }
2790
2692
  },
2791
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/middleware-eventstream": {
2792
- version: "3.972.12",
2793
- resolved: "https://registry.npmjs.org/@aws-sdk/middleware-eventstream/-/middleware-eventstream-3.972.12.tgz",
2794
- integrity: "sha512-tHTHHCHNrq6XklQvlzHBDJG4Iuhh7NVPRdtmvP+nHFA+5sxPlIDzlAHHgfoYHGvT3NXP1yVP/L5c3opUn6T3Qg==",
2693
+ "node_modules/@aws-sdk/eventstream-handler-node": {
2694
+ version: "3.972.36",
2695
+ resolved: "https://registry.npmjs.org/@aws-sdk/eventstream-handler-node/-/eventstream-handler-node-3.972.36.tgz",
2696
+ integrity: "sha512-HFaKXA6ugPVvpR7W/3UT3hylWIPndqGMwduwNVrmGsRT5+OESHN8/ven4eeofraQF5Kxp8A8QgGVrv7iQsTRKQ==",
2795
2697
  license: "Apache-2.0",
2796
2698
  dependencies: {
2797
- "@aws-sdk/types": "^3.973.8",
2798
- "@smithy/core": "^3.24.2",
2799
- "@smithy/types": "^4.14.1",
2699
+ "@aws-sdk/types": "^3.974.6",
2700
+ "@smithy/core": "^3.35.2",
2701
+ "@smithy/types": "^4.19.0",
2800
2702
  tslib: "^2.6.2"
2801
2703
  },
2802
2704
  engines: {
2803
2705
  node: ">=20.0.0"
2804
2706
  }
2805
2707
  },
2806
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/middleware-websocket": {
2807
- version: "3.972.19",
2808
- resolved: "https://registry.npmjs.org/@aws-sdk/middleware-websocket/-/middleware-websocket-3.972.19.tgz",
2809
- integrity: "sha512-mkEhOGYozqKQkbFaVrjwr0faiwwZza1v5/jSY6Tucm3bD+uKTazIUH/4Yo6aMnQD2ua2W9cMP6s8mvwTcjtqHw==",
2708
+ "node_modules/@aws-sdk/middleware-eventstream": {
2709
+ version: "3.972.31",
2710
+ resolved: "https://registry.npmjs.org/@aws-sdk/middleware-eventstream/-/middleware-eventstream-3.972.31.tgz",
2711
+ integrity: "sha512-4yvdTVwPGKCnrwuwlYEmwLqQXKwk0unx3f/FvBi4FA9ruK/WGoPJyqfK7hOYurheIyQL44FR0ovgOHqvkfdpAQ==",
2810
2712
  license: "Apache-2.0",
2811
2713
  dependencies: {
2812
- "@aws-sdk/core": "^3.974.11",
2813
- "@aws-sdk/types": "^3.973.8",
2814
- "@smithy/core": "^3.24.2",
2815
- "@smithy/fetch-http-handler": "^5.4.2",
2816
- "@smithy/signature-v4": "^5.4.2",
2817
- "@smithy/types": "^4.14.1",
2714
+ "@aws-sdk/types": "^3.974.6",
2715
+ "@smithy/core": "^3.35.2",
2716
+ "@smithy/types": "^4.19.0",
2818
2717
  tslib: "^2.6.2"
2819
2718
  },
2820
2719
  engines: {
2821
- node: ">= 14.0.0"
2720
+ node: ">=20.0.0"
2822
2721
  }
2823
2722
  },
2824
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/nested-clients": {
2825
- version: "3.997.9",
2826
- resolved: "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.997.9.tgz",
2827
- integrity: "sha512-jPR3rnmRI4hWYyzfmTGBr7NblMp8QYYeflHXba1H6+7CGrWVqWKQzaXFQ4qbExqPRsXN3T3L3JxFhr6aouXUGQ==",
2723
+ "node_modules/@aws-sdk/middleware-websocket": {
2724
+ version: "3.972.56",
2725
+ resolved: "https://registry.npmjs.org/@aws-sdk/middleware-websocket/-/middleware-websocket-3.972.56.tgz",
2726
+ integrity: "sha512-32d9EnnNM5UMwjVp/qnL0K4XYiZv+YlSbULI3BaoBdJvebAS6cD0bKfPJ7lzovN0qrelvmSh5jo/3tk0KoTuGQ==",
2828
2727
  license: "Apache-2.0",
2829
2728
  dependencies: {
2830
- "@aws-crypto/sha256-browser": "5.2.0",
2831
- "@aws-crypto/sha256-js": "5.2.0",
2832
- "@aws-sdk/core": "^3.974.11",
2833
- "@aws-sdk/signature-v4-multi-region": "^3.996.27",
2834
- "@aws-sdk/types": "^3.973.8",
2835
- "@smithy/core": "^3.24.2",
2836
- "@smithy/fetch-http-handler": "^5.4.2",
2837
- "@smithy/node-http-handler": "^4.7.2",
2838
- "@smithy/types": "^4.14.1",
2729
+ "@aws-sdk/core": "^3.978.3",
2730
+ "@aws-sdk/types": "^3.974.6",
2731
+ "@smithy/core": "^3.35.2",
2732
+ "@smithy/fetch-http-handler": "^5.8.0",
2733
+ "@smithy/signature-v4": "^5.7.4",
2734
+ "@smithy/types": "^4.19.0",
2839
2735
  tslib: "^2.6.2"
2840
2736
  },
2841
2737
  engines: {
2842
- node: ">=20.0.0"
2738
+ node: ">= 14.0.0"
2843
2739
  }
2844
2740
  },
2845
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/signature-v4-multi-region": {
2846
- version: "3.996.27",
2847
- resolved: "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.996.27.tgz",
2848
- integrity: "sha512-0Phbz4t6HI3D3skxvG2uI+VWU034/nSIw1T8d+FPzzQG9EQTrw94o9mOKO2Gv3n3Oc8P7JD7RAUxkoneLWv5Eg==",
2741
+ "node_modules/@aws-sdk/nested-clients": {
2742
+ version: "3.997.48",
2743
+ resolved: "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.997.48.tgz",
2744
+ integrity: "sha512-B01jdXJtAW/XOiUzGdI2mz67WyEHbGEc9X6Euzw3bjLAa+txTqdZDER4X2FsIEcXzV2ABqudVZ5thali8tCCzQ==",
2849
2745
  license: "Apache-2.0",
2850
2746
  dependencies: {
2851
- "@aws-sdk/types": "^3.973.8",
2852
- "@smithy/core": "^3.24.2",
2853
- "@smithy/signature-v4": "^5.4.2",
2854
- "@smithy/types": "^4.14.1",
2747
+ "@aws-sdk/core": "^3.978.3",
2748
+ "@aws-sdk/signature-v4-multi-region": "^3.996.48",
2749
+ "@aws-sdk/types": "^3.974.6",
2750
+ "@smithy/core": "^3.35.2",
2751
+ "@smithy/fetch-http-handler": "^5.8.0",
2752
+ "@smithy/node-http-handler": "^4.12.1",
2753
+ "@smithy/types": "^4.19.0",
2855
2754
  tslib: "^2.6.2"
2856
2755
  },
2857
2756
  engines: {
2858
2757
  node: ">=20.0.0"
2859
2758
  }
2860
2759
  },
2861
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/token-providers": {
2862
- version: "3.1048.0",
2863
- resolved: "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1048.0.tgz",
2864
- integrity: "sha512-k0y/GcuesuSfWyUM0WamrGyeZmltRYaPbHO82UDA6mZ/doB+FOHKutikPAtSXMn/hDz970cF+iRuuiYO9VEbAA==",
2760
+ "node_modules/@aws-sdk/signature-v4-multi-region": {
2761
+ version: "3.996.48",
2762
+ resolved: "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.996.48.tgz",
2763
+ integrity: "sha512-cFDXfEbXaGwbnpvR/DyqfxfjxpjXVRVthQLgkwvcfDS5u3+8G9WSj1X1Ag/pTRg/QOeOno1Tq3ycEdrKsCUcOA==",
2865
2764
  license: "Apache-2.0",
2866
2765
  dependencies: {
2867
- "@aws-sdk/core": "^3.974.11",
2868
- "@aws-sdk/nested-clients": "^3.997.9",
2869
- "@aws-sdk/types": "^3.973.8",
2870
- "@smithy/core": "^3.24.2",
2871
- "@smithy/types": "^4.14.1",
2766
+ "@aws-sdk/types": "^3.974.6",
2767
+ "@smithy/signature-v4": "^5.7.4",
2768
+ "@smithy/types": "^4.19.0",
2872
2769
  tslib: "^2.6.2"
2873
2770
  },
2874
2771
  engines: {
2875
2772
  node: ">=20.0.0"
2876
2773
  }
2877
2774
  },
2878
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/types": {
2879
- version: "3.973.8",
2880
- resolved: "https://registry.npmjs.org/@aws-sdk/types/-/types-3.973.8.tgz",
2881
- integrity: "sha512-gjlAdtHMbtR9X5iIhVUvbVcy55KnznpC6bkDUWW9z915bi0ckdUr5cjf16Kp6xq0bP5HBD2xzgbL9F9Quv5vUw==",
2775
+ "node_modules/@aws-sdk/token-providers": {
2776
+ version: "3.1127.0",
2777
+ resolved: "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1127.0.tgz",
2778
+ integrity: "sha512-Dv2TMWBshJ+tF6ahs2Sy5bh4Iabsd4GAQqVvE9XZmYmnoaVbpS2QKIKE/HRacc7bTtbjEEvP+laGzHvHlf1CiQ==",
2882
2779
  license: "Apache-2.0",
2883
2780
  dependencies: {
2884
- "@smithy/types": "^4.14.1",
2781
+ "@aws-sdk/core": "^3.977.9",
2782
+ "@aws-sdk/nested-clients": "^3.997.44",
2783
+ "@aws-sdk/types": "^3.974.5",
2784
+ "@smithy/core": "^3.33.3",
2785
+ "@smithy/types": "^4.17.2",
2885
2786
  tslib: "^2.6.2"
2886
2787
  },
2887
2788
  engines: {
2888
2789
  node: ">=20.0.0"
2889
2790
  }
2890
2791
  },
2891
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/util-locate-window": {
2892
- version: "3.965.5",
2893
- resolved: "https://registry.npmjs.org/@aws-sdk/util-locate-window/-/util-locate-window-3.965.5.tgz",
2894
- integrity: "sha512-WhlJNNINQB+9qtLtZJcpQdgZw3SCDCpXdUJP7cToGwHbCWCnRckGlc6Bx/OhWwIYFNAn+FIydY8SZ0QmVu3xTQ==",
2792
+ "node_modules/@aws-sdk/types": {
2793
+ version: "3.974.6",
2794
+ resolved: "https://registry.npmjs.org/@aws-sdk/types/-/types-3.974.6.tgz",
2795
+ integrity: "sha512-v/clNZzZnDxGyvpHMOGpJKVXFAExJzUNAAjaWGdcx8QAcXLGwTaOkw33p5SHAi0YAioK32xB3hWwOekRVfmfKg==",
2895
2796
  license: "Apache-2.0",
2896
2797
  dependencies: {
2798
+ "@smithy/types": "^4.19.0",
2897
2799
  tslib: "^2.6.2"
2898
2800
  },
2899
2801
  engines: {
2900
2802
  node: ">=20.0.0"
2901
2803
  }
2902
2804
  },
2903
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/xml-builder": {
2904
- version: "3.972.24",
2905
- resolved: "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.972.24.tgz",
2906
- integrity: "sha512-V8z5YcDPfsvzrBlj0xR1vhRtocblhYbqdreCJB/voGd4Sr5zjNAeWxexbnqVtskTJe0vFb5KMqbSL++ePl+zRw==",
2805
+ "node_modules/@aws-sdk/xml-builder": {
2806
+ version: "3.972.41",
2807
+ resolved: "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.972.41.tgz",
2808
+ integrity: "sha512-ctjVSyCMegrWfXlx6VqzSBFI6UqmQ5ZlnfMhdLIiWmhoH8UAQxSCP5N3OpG7X3k4LnS7ou74C4mt20+bfTW2aQ==",
2907
2809
  license: "Apache-2.0",
2908
2810
  dependencies: {
2909
- "@nodable/entities": "2.1.0",
2910
- "@smithy/types": "^4.14.1",
2911
- "fast-xml-parser": "5.7.3",
2811
+ "@smithy/types": "^4.19.0",
2912
2812
  tslib: "^2.6.2"
2913
2813
  },
2914
2814
  engines: {
2915
2815
  node: ">=20.0.0"
2916
2816
  }
2917
2817
  },
2918
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws/lambda-invoke-store": {
2919
- version: "0.2.4",
2920
- resolved: "https://registry.npmjs.org/@aws/lambda-invoke-store/-/lambda-invoke-store-0.2.4.tgz",
2921
- integrity: "sha512-iY8yvjE0y651BixKNPgmv1WrQc+GZ142sb0z4gYnChDDY2YqI4P/jsSopBWrKfAt7LOJAkOXt7rC/hms+WclQQ==",
2818
+ "node_modules/@aws/lambda-invoke-store": {
2819
+ version: "0.3.0",
2820
+ resolved: "https://registry.npmjs.org/@aws/lambda-invoke-store/-/lambda-invoke-store-0.3.0.tgz",
2821
+ integrity: "sha512-sl4Bm6yiMNYrZKkqqDFWN0UfnWhlS8ivKxrYl+6t0gCLrqr8y3B2IqZZbFRkfaVVp7C/baApyh71P+LeE1A2sQ==",
2922
2822
  license: "Apache-2.0",
2923
2823
  engines: {
2924
2824
  node: ">=18.0.0"
2925
2825
  }
2926
2826
  },
2927
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@babel/runtime": {
2928
- version: "7.29.2",
2929
- resolved: "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.2.tgz",
2930
- integrity: "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g==",
2827
+ "node_modules/@babel/runtime": {
2828
+ version: "7.29.10",
2829
+ resolved: "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.10.tgz",
2830
+ integrity: "sha512-NpugTzbKgGrNe45Ui32cN8vCFFMxVtP/9rtfwv0nP5FRDAjvYBxJcLVpYA9mr1jxP6cnIT7x9LUzuDTbWYYNRA==",
2931
2831
  license: "MIT",
2932
2832
  engines: {
2933
2833
  node: ">=6.9.0"
2934
2834
  }
2935
2835
  },
2936
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@earendil-works/pi-agent-core": {
2937
- version: "0.83.0",
2938
- resolved: "https://registry.npmjs.org/@earendil-works/pi-agent-core/-/pi-agent-core-0.83.0.tgz",
2836
+ "node_modules/@earendil-works/pi-agent-core": {
2837
+ version: "1.3.0",
2838
+ resolved: "https://registry.npmjs.org/@earendil-works/pi-agent-core/-/pi-agent-core-1.3.0.tgz",
2839
+ integrity: "sha512-2jvpxZs47PFD5mSQb/yK0pGHJ5yO7Nu22u9mFjHbSLRgu62vZ9rupimDSIp4arnqOadyv0AWvYHtCSpFoJV7ag==",
2939
2840
  license: "MIT",
2940
2841
  dependencies: {
2941
- "@earendil-works/pi-ai": "^0.83.0",
2942
- diff: "8.0.4",
2943
- ignore: "7.0.5",
2944
- typebox: "1.3.7",
2945
- yaml: "2.9.0"
2842
+ "@earendil-works/pi-ai": "1.3.0",
2843
+ typebox: "1.3.27"
2946
2844
  },
2947
2845
  engines: {
2948
2846
  node: ">=22.19.0"
2949
- },
2950
- integrity: "sha512-RorGp9OH5l3ElpuC5a5ZQ2eWcchZGXflXRzVGkV99y3y6tT+LLNyxoYIdVKvTKWEObwhExeQbTH0fI2tE4iX4g=="
2847
+ }
2951
2848
  },
2952
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@earendil-works/pi-ai": {
2953
- version: "0.83.0",
2954
- resolved: "https://registry.npmjs.org/@earendil-works/pi-ai/-/pi-ai-0.83.0.tgz",
2849
+ "node_modules/@earendil-works/pi-ai": {
2850
+ version: "1.3.0",
2851
+ resolved: "https://registry.npmjs.org/@earendil-works/pi-ai/-/pi-ai-1.3.0.tgz",
2852
+ integrity: "sha512-KaBI8x7q7sPoFUXICNGD9efHzDG+oRNwVvkA9jdIsSQWH1RjFssOlEGsbLtewUPPgCrvmz0l2KTgSLXTyj3acw==",
2955
2853
  license: "MIT",
2956
2854
  dependencies: {
2957
- "@anthropic-ai/sdk": "0.91.1",
2958
- "@aws-sdk/client-bedrock-runtime": "3.1048.0",
2959
- "@google/genai": "1.52.0",
2960
- "@mistralai/mistralai": "2.2.6",
2961
- "@opentelemetry/api": "1.9.0",
2962
- "@smithy/node-http-handler": "4.7.3",
2963
- "http-proxy-agent": "7.0.2",
2964
- "https-proxy-agent": "7.0.6",
2965
- openai: "6.26.0",
2855
+ "@anthropic-ai/sdk": "0.129.0",
2856
+ "@aws-sdk/client-bedrock-runtime": "3.1127.0",
2857
+ "@earendil-works/pi-telemetry": "1.3.0",
2858
+ "@google/genai": "2.21.0",
2859
+ "@smithy/node-http-handler": "4.12.1",
2860
+ "http-proxy-agent": "9.1.0",
2861
+ "https-proxy-agent": "9.1.0",
2862
+ openai: "7.19.0",
2966
2863
  "partial-json": "0.1.7",
2967
- typebox: "1.3.7"
2864
+ typebox: "1.3.27"
2968
2865
  },
2969
2866
  bin: {
2970
2867
  "pi-ai": "dist/cli.js"
2971
2868
  },
2972
2869
  engines: {
2973
2870
  node: ">=22.19.0"
2974
- },
2975
- integrity: "sha512-m3IZD4g3er0V8TC9+Vpgw/sjTKqcJlkcIBy/JvsgRubuuik3tAVzyugUg4rVrShIkkOT69mEd34NEqKUIsl6JQ=="
2871
+ }
2976
2872
  },
2977
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@earendil-works/pi-tui": {
2978
- version: "0.83.0",
2979
- resolved: "https://registry.npmjs.org/@earendil-works/pi-tui/-/pi-tui-0.83.0.tgz",
2873
+ "node_modules/@earendil-works/pi-codemode": {
2874
+ version: "1.3.0",
2875
+ resolved: "https://registry.npmjs.org/@earendil-works/pi-codemode/-/pi-codemode-1.3.0.tgz",
2876
+ integrity: "sha512-2G9tmbsPhgzwfz7cmzJpbLSLqOx3eu22Gbzm+Wc3HqeZMjLQS4F3KfAabozVhv7uEjq3k2O1dZTHmhhWr2xbfQ==",
2980
2877
  license: "MIT",
2981
2878
  dependencies: {
2982
- "get-east-asian-width": "1.6.0",
2983
- marked: "18.0.5"
2879
+ "quickjs-wasi": "3.6.2"
2984
2880
  },
2985
2881
  engines: {
2986
2882
  node: ">=22.19.0"
2987
- },
2988
- integrity: "sha512-IoYrb0rORjELmEpNtoCA/U8je3KopMkRAVJRdSzvXRvgb+Huo1gNh8Q5CSZvNOiYtDxJdj2tYZZHZ4B3+IN3hA=="
2989
- },
2990
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@google/genai": {
2991
- version: "1.52.0",
2992
- resolved: "https://registry.npmjs.org/@google/genai/-/genai-1.52.0.tgz",
2993
- integrity: "sha512-gwSvbpiN/17O9TbsqSsE/OzZcpv5Fo4RQjdngGgogtuB9RsyJ8ZHhX5KjHj1bp5N9snN2eK8LDGXSaWW2hof8Q==",
2994
- hasInstallScript: true,
2995
- license: "Apache-2.0",
2996
- dependencies: {
2997
- "google-auth-library": "^10.3.0",
2998
- "p-retry": "^4.6.2",
2999
- protobufjs: "^7.5.4",
3000
- ws: "^8.18.0"
3001
- },
3002
- engines: {
3003
- node: ">=20.0.0"
3004
- },
3005
- peerDependencies: {
3006
- "@modelcontextprotocol/sdk": "^1.25.2"
3007
- },
3008
- peerDependenciesMeta: {
3009
- "@modelcontextprotocol/sdk": {
3010
- optional: true
3011
- }
3012
2883
  }
3013
2884
  },
3014
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@mariozechner/clipboard": {
3015
- version: "0.3.9",
3016
- resolved: "https://registry.npmjs.org/@mariozechner/clipboard/-/clipboard-0.3.9.tgz",
3017
- integrity: "sha512-ABnA53mdfkGZwOFUdZNv2S0CWGO/EIuPj8Vv9xmBFmSYg/qFc7ihO6q5FcQjvoE67kZpWkEc4AhD6B/os04yuA==",
2885
+ "node_modules/@earendil-works/pi-coding-agent": {
2886
+ version: "1.3.0",
2887
+ resolved: "https://registry.npmjs.org/@earendil-works/pi-coding-agent/-/pi-coding-agent-1.3.0.tgz",
2888
+ integrity: "sha512-V/WoCjA2hQSe3QLWIUB24cTRdtEdeLiIzkDqU5RMXV6VWuD+KGZnzVBMhglwdnQTySkehZsjt8a3g6Jd2g4nnw==",
3018
2889
  license: "MIT",
3019
- optional: true,
3020
- engines: {
3021
- node: ">= 10"
2890
+ dependencies: {
2891
+ "@earendil-works/pi-agent-core": "1.3.0",
2892
+ "@earendil-works/pi-ai": "1.3.0",
2893
+ "@earendil-works/pi-codemode": "1.3.0",
2894
+ "@earendil-works/pi-mcp": "1.3.0",
2895
+ "@earendil-works/pi-tui": "1.3.0",
2896
+ "@silvia-odwyer/photon-node": "0.3.4",
2897
+ "brace-expansion": "5.0.12",
2898
+ chalk: "6.0.0",
2899
+ "cross-spawn": "7.0.6",
2900
+ diff: "8.0.4",
2901
+ "grok-mermaid": "0.2.3",
2902
+ "highlight.js": "10.7.3",
2903
+ "hosted-git-info": "9.0.3",
2904
+ ignore: "7.0.8",
2905
+ jiti: "2.7.0",
2906
+ minimatch: "10.2.6",
2907
+ "proper-lockfile": "4.1.2",
2908
+ "quickjs-wasi": "3.6.2",
2909
+ semver: "7.8.5",
2910
+ typebox: "1.3.27",
2911
+ undici: "8.10.2",
2912
+ yaml: "2.9.0"
2913
+ },
2914
+ bin: {
2915
+ pi: "dist/bundle/cli.js"
3022
2916
  },
3023
- optionalDependencies: {
3024
- "@mariozechner/clipboard-darwin-arm64": "0.3.9",
3025
- "@mariozechner/clipboard-darwin-universal": "0.3.9",
3026
- "@mariozechner/clipboard-darwin-x64": "0.3.9",
3027
- "@mariozechner/clipboard-linux-arm64-gnu": "0.3.9",
3028
- "@mariozechner/clipboard-linux-arm64-musl": "0.3.9",
3029
- "@mariozechner/clipboard-linux-riscv64-gnu": "0.3.9",
3030
- "@mariozechner/clipboard-linux-x64-gnu": "0.3.9",
3031
- "@mariozechner/clipboard-linux-x64-musl": "0.3.9",
3032
- "@mariozechner/clipboard-win32-arm64-msvc": "0.3.9",
3033
- "@mariozechner/clipboard-win32-x64-msvc": "0.3.9"
3034
- }
3035
- },
3036
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@mariozechner/clipboard-darwin-arm64": {
3037
- version: "0.3.9",
3038
- resolved: "https://registry.npmjs.org/@mariozechner/clipboard-darwin-arm64/-/clipboard-darwin-arm64-0.3.9.tgz",
3039
- integrity: "sha512-BfgV7vCEWZwJwZJw03r6bP5+tf0iI/ANuQYCxi9RNn7FrWB3yzGuMKCrNLRl6V761vXRdL8+OqZ0wd4TqlsNOQ==",
3040
- cpu: [
3041
- "arm64"
3042
- ],
3043
- license: "MIT",
3044
- optional: true,
3045
- os: [
3046
- "darwin"
3047
- ],
3048
- engines: {
3049
- node: ">= 10"
3050
- }
3051
- },
3052
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@mariozechner/clipboard-darwin-universal": {
3053
- version: "0.3.9",
3054
- resolved: "https://registry.npmjs.org/@mariozechner/clipboard-darwin-universal/-/clipboard-darwin-universal-0.3.9.tgz",
3055
- integrity: "sha512-BGGR4iA9Z2shAjI65eI5xtyb3LYNlDW9X3gxKxDbqtbnREohsrqznov6zpKoIrsRWpzlYVEdKphS7ksJ0/ndSQ==",
3056
- license: "MIT",
3057
- optional: true,
3058
- os: [
3059
- "darwin"
3060
- ],
3061
- engines: {
3062
- node: ">= 10"
3063
- }
3064
- },
3065
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@mariozechner/clipboard-darwin-x64": {
3066
- version: "0.3.9",
3067
- resolved: "https://registry.npmjs.org/@mariozechner/clipboard-darwin-x64/-/clipboard-darwin-x64-0.3.9.tgz",
3068
- integrity: "sha512-4kURmCbS6nt8uYhtmWpUcJWyPHfmAr5dTpXD1nO3pIfa+TSQ9DbrGOYCKH+aEFW47XhQ4Vp8ZTszie+wfFvDKg==",
3069
- cpu: [
3070
- "x64"
3071
- ],
3072
- license: "MIT",
3073
- optional: true,
3074
- os: [
3075
- "darwin"
3076
- ],
3077
- engines: {
3078
- node: ">= 10"
3079
- }
3080
- },
3081
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@mariozechner/clipboard-linux-arm64-gnu": {
3082
- version: "0.3.9",
3083
- resolved: "https://registry.npmjs.org/@mariozechner/clipboard-linux-arm64-gnu/-/clipboard-linux-arm64-gnu-0.3.9.tgz",
3084
- integrity: "sha512-g59OkUGP2DDfCOIKypHeYgv2M55u/cKvXa5dSxFbEJ34XvIQMdcVmpKCkGUro3ZgefXiGVdwguvTMQGpHWzIXw==",
3085
- cpu: [
3086
- "arm64"
3087
- ],
3088
- license: "MIT",
3089
- optional: true,
3090
- os: [
3091
- "linux"
3092
- ],
3093
- engines: {
3094
- node: ">= 10"
3095
- }
3096
- },
3097
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@mariozechner/clipboard-linux-arm64-musl": {
3098
- version: "0.3.9",
3099
- resolved: "https://registry.npmjs.org/@mariozechner/clipboard-linux-arm64-musl/-/clipboard-linux-arm64-musl-0.3.9.tgz",
3100
- integrity: "sha512-AGuJdgKsmJdm4Pych7kv3sqe591ERRaAHW3xjLooiFzn8J+PxUyof++7YZrB5Y5tpnTO+K18Og3taj2NpluCRQ==",
3101
- cpu: [
3102
- "arm64"
3103
- ],
3104
- license: "MIT",
3105
- optional: true,
3106
- os: [
3107
- "linux"
3108
- ],
3109
- engines: {
3110
- node: ">= 10"
3111
- }
3112
- },
3113
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@mariozechner/clipboard-linux-riscv64-gnu": {
3114
- version: "0.3.9",
3115
- resolved: "https://registry.npmjs.org/@mariozechner/clipboard-linux-riscv64-gnu/-/clipboard-linux-riscv64-gnu-0.3.9.tgz",
3116
- integrity: "sha512-DXBEAiuMpk7dhS1a9NzNxVAFi1vaKoPu7rQNgY8LIDLGrK3lnIp3nT10DUum+PKVJoJppIP+NAA8IZe4DMNDPw==",
3117
- cpu: [
3118
- "riscv64"
3119
- ],
3120
- license: "MIT",
3121
- optional: true,
3122
- os: [
3123
- "linux"
3124
- ],
3125
- engines: {
3126
- node: ">= 10"
3127
- }
3128
- },
3129
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@mariozechner/clipboard-linux-x64-gnu": {
3130
- version: "0.3.9",
3131
- resolved: "https://registry.npmjs.org/@mariozechner/clipboard-linux-x64-gnu/-/clipboard-linux-x64-gnu-0.3.9.tgz",
3132
- integrity: "sha512-WORrMLd6EpElEME7JRKfSaY34nW1P5LbdgK5YNCS1ncG2LqmITsSMEJ8nh2mpvxb3TxqbOOKgY7k9eMJYlW9Mw==",
3133
- cpu: [
3134
- "x64"
3135
- ],
3136
- license: "MIT",
3137
- optional: true,
3138
- os: [
3139
- "linux"
3140
- ],
3141
2917
  engines: {
3142
- node: ">= 10"
2918
+ node: ">=22.19.0"
3143
2919
  }
3144
2920
  },
3145
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@mariozechner/clipboard-linux-x64-musl": {
3146
- version: "0.3.9",
3147
- resolved: "https://registry.npmjs.org/@mariozechner/clipboard-linux-x64-musl/-/clipboard-linux-x64-musl-0.3.9.tgz",
3148
- integrity: "sha512-/DHn+1DrfL6oRaPPWXaOKvonFFrni666fxd+zFqiQEfvBH0tsHVWjq9iqBk0oDp0qaPA72lIMy5BptxISBEhZQ==",
3149
- cpu: [
3150
- "x64"
3151
- ],
2921
+ "node_modules/@earendil-works/pi-mcp": {
2922
+ version: "1.3.0",
2923
+ resolved: "https://registry.npmjs.org/@earendil-works/pi-mcp/-/pi-mcp-1.3.0.tgz",
2924
+ integrity: "sha512-lbktLplmdGamM2t460Q0ziNEfpUEHDTVNf79g/AialJ3XZ+SHgNqa/OJXRR+fU+GV/l+gBhRPcyP8XkQlv8Avw==",
3152
2925
  license: "MIT",
3153
- optional: true,
3154
- os: [
3155
- "linux"
3156
- ],
2926
+ dependencies: {
2927
+ "cross-spawn": "7.0.6"
2928
+ },
3157
2929
  engines: {
3158
- node: ">= 10"
2930
+ node: ">=22.19.0"
3159
2931
  }
3160
2932
  },
3161
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@mariozechner/clipboard-win32-arm64-msvc": {
3162
- version: "0.3.9",
3163
- resolved: "https://registry.npmjs.org/@mariozechner/clipboard-win32-arm64-msvc/-/clipboard-win32-arm64-msvc-0.3.9.tgz",
3164
- integrity: "sha512-O5FHD3ErkMwMhNzAfu3ggy0ug4z7btZuoQgwwxlzPrwV2bxlD6WDpqBY4NCgICAgZdDKdp+loUEKVAVt8aYnhQ==",
3165
- cpu: [
3166
- "arm64"
3167
- ],
2933
+ "node_modules/@earendil-works/pi-telemetry": {
2934
+ version: "1.3.0",
2935
+ resolved: "https://registry.npmjs.org/@earendil-works/pi-telemetry/-/pi-telemetry-1.3.0.tgz",
2936
+ integrity: "sha512-ERGZr+aXjNJzoUbB7ZzHVH3g5otzMHjHLs2Fyizm12By5X+gBEhod9cJXFOk13S7M8a29Am+Mq21zm73mRJFLg==",
3168
2937
  license: "MIT",
3169
- optional: true,
3170
- os: [
3171
- "win32"
3172
- ],
3173
2938
  engines: {
3174
- node: ">= 10"
2939
+ node: ">=22.19.0"
3175
2940
  }
3176
2941
  },
3177
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@mariozechner/clipboard-win32-x64-msvc": {
3178
- version: "0.3.9",
3179
- resolved: "https://registry.npmjs.org/@mariozechner/clipboard-win32-x64-msvc/-/clipboard-win32-x64-msvc-0.3.9.tgz",
3180
- integrity: "sha512-ihQC3EufqEY81vhXBgVBtK4prL+wc62zJsSvxrgz7K1hsdt6OObz6v9p3Rn1OG3GJksTTKMJF0u/guMISHPhSA==",
3181
- cpu: [
3182
- "x64"
3183
- ],
2942
+ "node_modules/@earendil-works/pi-tui": {
2943
+ version: "1.3.0",
2944
+ resolved: "https://registry.npmjs.org/@earendil-works/pi-tui/-/pi-tui-1.3.0.tgz",
2945
+ integrity: "sha512-AlKvEwEWyVtnuw7SVb4N/mUhlfIohyFslUNWarZVdLHHSdt3ca5EhMLwTzblBpDpaofSz+f+tAHie6CfxVrWKA==",
3184
2946
  license: "MIT",
3185
- optional: true,
3186
- os: [
3187
- "win32"
3188
- ],
2947
+ dependencies: {
2948
+ "get-east-asian-width": "1.6.0",
2949
+ marked: "18.0.11"
2950
+ },
3189
2951
  engines: {
3190
- node: ">= 10"
2952
+ node: ">=22.19.0"
3191
2953
  }
3192
2954
  },
3193
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@mistralai/mistralai": {
3194
- version: "2.2.6",
3195
- resolved: "https://registry.npmjs.org/@mistralai/mistralai/-/mistralai-2.2.6.tgz",
3196
- integrity: "sha512-W8pX7zHxjJvMIpw8JMxeJEleapXX0Q9NPszdNzqkM3MIEoIGPObdodujj+WHteXEvGfaP/AMwlNyRfEzSY6dQQ==",
2955
+ "node_modules/@google/genai": {
2956
+ version: "2.21.0",
2957
+ resolved: "https://registry.npmjs.org/@google/genai/-/genai-2.21.0.tgz",
2958
+ integrity: "sha512-+PDtco2/Z0ONdzCGekCoCT+O1VJS9xJQNN4XzQpXG/t3El/SWWMkCWlFRO1KmivOHPa4Q0VjUYu1HBKCZ/v33Q==",
2959
+ hasInstallScript: true,
3197
2960
  license: "Apache-2.0",
3198
2961
  dependencies: {
3199
- "@opentelemetry/semantic-conventions": "^1.40.0",
3200
- ws: "^8.18.0",
3201
- zod: "^3.25.0 || ^4.0.0",
3202
- "zod-to-json-schema": "^3.25.0"
2962
+ "google-auth-library": "^10.3.0",
2963
+ "p-retry": "^4.6.2",
2964
+ protobufjs: "^7.5.4",
2965
+ ws: "^8.18.0"
2966
+ },
2967
+ engines: {
2968
+ node: ">=20.0.0"
3203
2969
  },
3204
2970
  peerDependencies: {
3205
- "@opentelemetry/api": "^1.9.0"
2971
+ "@modelcontextprotocol/sdk": "^1.25.2"
3206
2972
  },
3207
2973
  peerDependenciesMeta: {
3208
- "@opentelemetry/api": {
2974
+ "@modelcontextprotocol/sdk": {
3209
2975
  optional: true
3210
2976
  }
3211
2977
  }
3212
2978
  },
3213
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@nodable/entities": {
3214
- version: "2.1.0",
3215
- resolved: "https://registry.npmjs.org/@nodable/entities/-/entities-2.1.0.tgz",
3216
- integrity: "sha512-nyT7T3nbMyBI/lvr6L5TyWbFJAI9FTgVRakNoBqCD+PmID8DzFrrNdLLtHMwMszOtqZa8PAOV24ZqDnQrhQINA==",
3217
- funding: [
3218
- {
3219
- type: "github",
3220
- url: "https://github.com/sponsors/nodable"
3221
- }
3222
- ],
3223
- license: "MIT"
3224
- },
3225
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@opentelemetry/api": {
3226
- version: "1.9.0",
3227
- resolved: "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.0.tgz",
3228
- integrity: "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==",
3229
- license: "Apache-2.0",
3230
- engines: {
3231
- node: ">=8.0.0"
3232
- }
3233
- },
3234
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@opentelemetry/semantic-conventions": {
3235
- version: "1.41.1",
3236
- resolved: "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.41.1.tgz",
3237
- integrity: "sha512-/UhIkaZgPutTFmQ7RnIJGgDXZmtEJ7Dvi86xNTFWcnRxVRNk/aotsqDJYeEvDP+FSMB2SdW+pQzNMcWP0rwuNA==",
3238
- license: "Apache-2.0",
3239
- engines: {
3240
- node: ">=14"
3241
- }
3242
- },
3243
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@protobufjs/aspromise": {
2979
+ "node_modules/@protobufjs/aspromise": {
3244
2980
  version: "1.1.2",
3245
2981
  resolved: "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz",
3246
2982
  integrity: "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==",
3247
2983
  license: "BSD-3-Clause"
3248
2984
  },
3249
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@protobufjs/base64": {
2985
+ "node_modules/@protobufjs/base64": {
3250
2986
  version: "1.1.2",
3251
2987
  resolved: "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz",
3252
2988
  integrity: "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==",
3253
2989
  license: "BSD-3-Clause"
3254
2990
  },
3255
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@protobufjs/codegen": {
2991
+ "node_modules/@protobufjs/codegen": {
3256
2992
  version: "2.0.5",
3257
2993
  resolved: "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz",
3258
2994
  integrity: "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==",
3259
2995
  license: "BSD-3-Clause"
3260
2996
  },
3261
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@protobufjs/eventemitter": {
2997
+ "node_modules/@protobufjs/eventemitter": {
3262
2998
  version: "1.1.1",
3263
2999
  resolved: "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz",
3264
3000
  integrity: "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==",
3265
3001
  license: "BSD-3-Clause"
3266
3002
  },
3267
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@protobufjs/fetch": {
3003
+ "node_modules/@protobufjs/fetch": {
3268
3004
  version: "1.1.1",
3269
3005
  resolved: "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz",
3270
3006
  integrity: "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==",
@@ -3273,122 +3009,109 @@ var default_pi_package_lock_default = {
3273
3009
  "@protobufjs/aspromise": "^1.1.1"
3274
3010
  }
3275
3011
  },
3276
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@protobufjs/float": {
3012
+ "node_modules/@protobufjs/float": {
3277
3013
  version: "1.0.2",
3278
3014
  resolved: "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz",
3279
3015
  integrity: "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==",
3280
3016
  license: "BSD-3-Clause"
3281
3017
  },
3282
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@protobufjs/path": {
3018
+ "node_modules/@protobufjs/path": {
3283
3019
  version: "1.1.2",
3284
3020
  resolved: "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz",
3285
3021
  integrity: "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==",
3286
3022
  license: "BSD-3-Clause"
3287
3023
  },
3288
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@protobufjs/pool": {
3024
+ "node_modules/@protobufjs/pool": {
3289
3025
  version: "1.1.0",
3290
3026
  resolved: "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz",
3291
3027
  integrity: "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==",
3292
3028
  license: "BSD-3-Clause"
3293
3029
  },
3294
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@protobufjs/utf8": {
3295
- version: "1.1.1",
3296
- resolved: "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.1.tgz",
3297
- integrity: "sha512-oOAWABowe8EAbMyWKM0tYDKi8Yaox52D+HWZhAIJqQXbqe0xI/GV7FhLWqlEKreMkfDjshR5FKgi3mnle0h6Eg==",
3030
+ "node_modules/@protobufjs/utf8": {
3031
+ version: "1.1.2",
3032
+ resolved: "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.2.tgz",
3033
+ integrity: "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==",
3298
3034
  license: "BSD-3-Clause"
3299
3035
  },
3300
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@silvia-odwyer/photon-node": {
3036
+ "node_modules/@silvia-odwyer/photon-node": {
3301
3037
  version: "0.3.4",
3302
3038
  resolved: "https://registry.npmjs.org/@silvia-odwyer/photon-node/-/photon-node-0.3.4.tgz",
3303
3039
  integrity: "sha512-bnly4BKB3KDTFxrUIcgCLbaeVVS8lrAkri1pEzskpmxu9MdfGQTy8b8EgcD83ywD3RPMsIulY8xJH5Awa+t9fA==",
3304
3040
  license: "Apache-2.0"
3305
3041
  },
3306
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@smithy/core": {
3307
- version: "3.24.3",
3308
- resolved: "https://registry.npmjs.org/@smithy/core/-/core-3.24.3.tgz",
3309
- integrity: "sha512-Ep/7tPamGY8mgESE3LyLKtxJyy6U52WWAqr/3wial47Sj4u3PiIF73AOGI27UyLy9duTkhZbgzodOfLV4TduZg==",
3042
+ "node_modules/@smithy/core": {
3043
+ version: "3.36.0",
3044
+ resolved: "https://registry.npmjs.org/@smithy/core/-/core-3.36.0.tgz",
3045
+ integrity: "sha512-3hJiwG1F5t1SoXqp/yOCmYXziyx7ZVqF63S5W6YU201e/qwVaHPex+E/3vvyY9a3ORq/b+BydeNZpP2saQ9X2g==",
3310
3046
  license: "Apache-2.0",
3311
3047
  dependencies: {
3312
- "@aws-crypto/crc32": "5.2.0",
3313
- "@smithy/types": "^4.14.2",
3048
+ "@smithy/types": "^4.19.0",
3314
3049
  tslib: "^2.6.2"
3315
3050
  },
3316
3051
  engines: {
3317
3052
  node: ">=18.0.0"
3318
3053
  }
3319
3054
  },
3320
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@smithy/credential-provider-imds": {
3321
- version: "4.3.3",
3322
- resolved: "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.3.3.tgz",
3323
- integrity: "sha512-I2Bti0DKFo2IJyN28ijCsx51BAumEYR4/1yZ1FXyBygy9MqbnMqCev4JPth/MbpRfBSRAX35hITSnAdJRo1u5w==",
3055
+ "node_modules/@smithy/credential-provider-imds": {
3056
+ version: "4.5.2",
3057
+ resolved: "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.5.2.tgz",
3058
+ integrity: "sha512-A9uSdn72ozbRUSit0eib0TW7nXuNPlaeM0zcGkJ+nE6tFcSDbnmtwoxbTCFBukVQcszDAyvsd7+rTduPTXpygg==",
3324
3059
  license: "Apache-2.0",
3325
3060
  dependencies: {
3326
- "@smithy/core": "^3.24.3",
3327
- "@smithy/types": "^4.14.2",
3061
+ "@smithy/core": "^3.33.2",
3062
+ "@smithy/types": "^4.17.2",
3328
3063
  tslib: "^2.6.2"
3329
3064
  },
3330
3065
  engines: {
3331
3066
  node: ">=18.0.0"
3332
3067
  }
3333
3068
  },
3334
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@smithy/fetch-http-handler": {
3335
- version: "5.4.3",
3336
- resolved: "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.4.3.tgz",
3337
- integrity: "sha512-F+DRf8IJazRJgYog2A/yJK7eYVc0rqTlRzO+5ZxjJd4WkZoKz0IJRncf7G6t1pdVT3kryJcwuTFhN1c5m6N47A==",
3069
+ "node_modules/@smithy/fetch-http-handler": {
3070
+ version: "5.8.0",
3071
+ resolved: "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.8.0.tgz",
3072
+ integrity: "sha512-ycSJu3tFAQ4v04CBB0agqFMVsSQ1iG3yw+SpgxRqKfaURpQD4CZ8Wn0zPMmSnOuTpTh65Vz+EA0rMrw089wvkA==",
3338
3073
  license: "Apache-2.0",
3339
3074
  dependencies: {
3340
- "@smithy/core": "^3.24.3",
3341
- "@smithy/types": "^4.14.2",
3075
+ "@smithy/core": "^3.33.3",
3076
+ "@smithy/types": "^4.18.0",
3342
3077
  tslib: "^2.6.2"
3343
3078
  },
3344
3079
  engines: {
3345
3080
  node: ">=18.0.0"
3346
3081
  }
3347
3082
  },
3348
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@smithy/is-array-buffer": {
3349
- version: "2.2.0",
3350
- resolved: "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-2.2.0.tgz",
3351
- integrity: "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA==",
3352
- license: "Apache-2.0",
3353
- dependencies: {
3354
- tslib: "^2.6.2"
3355
- },
3356
- engines: {
3357
- node: ">=14.0.0"
3358
- }
3359
- },
3360
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@smithy/node-http-handler": {
3361
- version: "4.7.3",
3362
- resolved: "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.7.3.tgz",
3363
- integrity: "sha512-/jPhevcTFPMVl6KNjbaI47iOg1zxC7IsnX4PQDGVZKMFceOXtB8IEYaB7a9VvkP/3oC60WzTeKocvSI7vLT0vA==",
3083
+ "node_modules/@smithy/node-http-handler": {
3084
+ version: "4.12.1",
3085
+ resolved: "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.12.1.tgz",
3086
+ integrity: "sha512-ThMkboGeONWXAelq9FvGsuJC4rOi+qyC4/zhUF58xYpxUg5sQKx2VXZYJmtNjr4dSuBJ1HeJXETQILCz3wOHvw==",
3364
3087
  license: "Apache-2.0",
3365
3088
  dependencies: {
3366
- "@smithy/core": "^3.24.3",
3367
- "@smithy/types": "^4.14.2",
3089
+ "@smithy/core": "^3.33.3",
3090
+ "@smithy/types": "^4.18.0",
3368
3091
  tslib: "^2.6.2"
3369
3092
  },
3370
3093
  engines: {
3371
3094
  node: ">=18.0.0"
3372
3095
  }
3373
3096
  },
3374
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@smithy/signature-v4": {
3375
- version: "5.4.3",
3376
- resolved: "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.4.3.tgz",
3377
- integrity: "sha512-53+75QuPl6DL+ct6vVEB51FDO5oulXr20TPV46VvJZg76lIlXNWfxi8j+G2V/t0I2qxCBOa3vX/8bmjrpFVo9g==",
3097
+ "node_modules/@smithy/signature-v4": {
3098
+ version: "5.7.4",
3099
+ resolved: "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.7.4.tgz",
3100
+ integrity: "sha512-tHy0K0VtqNd5Y7Y41h0a0Lhh0L1GzC08dTWg0F7vRJWFtTENg7IZikf3wQkanYIRdb7ngoIPMTmqgUi401fEeQ==",
3378
3101
  license: "Apache-2.0",
3379
3102
  dependencies: {
3380
- "@smithy/core": "^3.24.3",
3381
- "@smithy/types": "^4.14.2",
3103
+ "@smithy/core": "^3.35.0",
3104
+ "@smithy/types": "^4.19.0",
3382
3105
  tslib: "^2.6.2"
3383
3106
  },
3384
3107
  engines: {
3385
3108
  node: ">=18.0.0"
3386
3109
  }
3387
3110
  },
3388
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@smithy/types": {
3389
- version: "4.14.2",
3390
- resolved: "https://registry.npmjs.org/@smithy/types/-/types-4.14.2.tgz",
3391
- integrity: "sha512-P+otAxbV4CqBybp7EkcJCrig63yE2E7PuNVOmilVMRcx/O+QDzGULTrKsq4DV13gSfak9ObPrWaHl/9bL5YcWw==",
3111
+ "node_modules/@smithy/types": {
3112
+ version: "4.19.0",
3113
+ resolved: "https://registry.npmjs.org/@smithy/types/-/types-4.19.0.tgz",
3114
+ integrity: "sha512-r7jh49VJxGerfAcTQA6gXcKc+98zOp/tqRwzYjgOE+iSQsP6cEU1hq2QzbuipmP68QtYdY9wKEhiCQZIzHgZ4Q==",
3392
3115
  license: "Apache-2.0",
3393
3116
  dependencies: {
3394
3117
  tslib: "^2.6.2"
@@ -3397,51 +3120,37 @@ var default_pi_package_lock_default = {
3397
3120
  node: ">=18.0.0"
3398
3121
  }
3399
3122
  },
3400
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@smithy/util-buffer-from": {
3401
- version: "2.2.0",
3402
- resolved: "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-2.2.0.tgz",
3403
- integrity: "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA==",
3404
- license: "Apache-2.0",
3405
- dependencies: {
3406
- "@smithy/is-array-buffer": "^2.2.0",
3407
- tslib: "^2.6.2"
3408
- },
3409
- engines: {
3410
- node: ">=14.0.0"
3411
- }
3412
- },
3413
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@smithy/util-utf8": {
3414
- version: "2.3.0",
3415
- resolved: "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-2.3.0.tgz",
3416
- integrity: "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A==",
3417
- license: "Apache-2.0",
3418
- dependencies: {
3419
- "@smithy/util-buffer-from": "^2.2.0",
3420
- tslib: "^2.6.2"
3421
- },
3422
- engines: {
3423
- node: ">=14.0.0"
3424
- }
3123
+ "node_modules/@stablelib/base64": {
3124
+ version: "1.0.1",
3125
+ resolved: "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz",
3126
+ integrity: "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==",
3127
+ license: "MIT"
3425
3128
  },
3426
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@types/node": {
3427
- version: "22.19.19",
3428
- resolved: "https://registry.npmjs.org/@types/node/-/node-22.19.19.tgz",
3429
- integrity: "sha512-dyh/xO2Fh5bYrfWaaqGrRQQGkNdmYw6AmaAUvYeUMNTWQtvb796ikLdmTchRmOlOiIJ1TDXfWgVx1QkUlQ6Hew==",
3129
+ "node_modules/@types/node": {
3130
+ version: "26.6.5",
3131
+ resolved: "https://registry.npmjs.org/@types/node/-/node-26.6.5.tgz",
3132
+ integrity: "sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==",
3430
3133
  license: "MIT",
3431
3134
  dependencies: {
3432
- "undici-types": "~6.21.0"
3135
+ "undici-types": "~8.9.0"
3433
3136
  }
3434
3137
  },
3435
- "node_modules/@earendil-works/pi-coding-agent/node_modules/agent-base": {
3436
- version: "7.1.4",
3437
- resolved: "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
3438
- integrity: "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",
3138
+ "node_modules/@types/retry": {
3139
+ version: "0.12.0",
3140
+ resolved: "https://registry.npmjs.org/@types/retry/-/retry-0.12.0.tgz",
3141
+ integrity: "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==",
3142
+ license: "MIT"
3143
+ },
3144
+ "node_modules/agent-base": {
3145
+ version: "9.0.0",
3146
+ resolved: "https://registry.npmjs.org/agent-base/-/agent-base-9.0.0.tgz",
3147
+ integrity: "sha512-TQf59BsZnytt8GdJKLPfUZ54g/iaUL2OWDSFCCvMOhsHduDQxO8xC4PNeyIkVcA5KwL2phPSv0douC0fgWzmnA==",
3439
3148
  license: "MIT",
3440
3149
  engines: {
3441
- node: ">= 14"
3150
+ node: ">= 20"
3442
3151
  }
3443
3152
  },
3444
- "node_modules/@earendil-works/pi-coding-agent/node_modules/balanced-match": {
3153
+ "node_modules/balanced-match": {
3445
3154
  version: "4.0.4",
3446
3155
  resolved: "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",
3447
3156
  integrity: "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",
@@ -3450,7 +3159,7 @@ var default_pi_package_lock_default = {
3450
3159
  node: "18 || 20 || >=22"
3451
3160
  }
3452
3161
  },
3453
- "node_modules/@earendil-works/pi-coding-agent/node_modules/base64-js": {
3162
+ "node_modules/base64-js": {
3454
3163
  version: "1.5.1",
3455
3164
  resolved: "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
3456
3165
  integrity: "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
@@ -3470,7 +3179,7 @@ var default_pi_package_lock_default = {
3470
3179
  ],
3471
3180
  license: "MIT"
3472
3181
  },
3473
- "node_modules/@earendil-works/pi-coding-agent/node_modules/bignumber.js": {
3182
+ "node_modules/bignumber.js": {
3474
3183
  version: "9.3.1",
3475
3184
  resolved: "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.3.1.tgz",
3476
3185
  integrity: "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==",
@@ -3479,43 +3188,43 @@ var default_pi_package_lock_default = {
3479
3188
  node: "*"
3480
3189
  }
3481
3190
  },
3482
- "node_modules/@earendil-works/pi-coding-agent/node_modules/bowser": {
3191
+ "node_modules/bowser": {
3483
3192
  version: "2.14.1",
3484
3193
  resolved: "https://registry.npmjs.org/bowser/-/bowser-2.14.1.tgz",
3485
3194
  integrity: "sha512-tzPjzCxygAKWFOJP011oxFHs57HzIhOEracIgAePE4pqB3LikALKnSzUyU4MGs9/iCEUuHlAJTjTc5M+u7YEGg==",
3486
3195
  license: "MIT"
3487
3196
  },
3488
- "node_modules/@earendil-works/pi-coding-agent/node_modules/brace-expansion": {
3489
- version: "5.0.7",
3490
- resolved: "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.7.tgz",
3491
- integrity: "sha512-7oFy703dxfY3/NLxC1fh2SUCQ0H9rmAY+5EpDVfXjUTTs+HEwR2nYaqLv+GWcTsumwxPfiz6CzCNkwXwBUwqCA==",
3197
+ "node_modules/brace-expansion": {
3198
+ version: "5.0.12",
3199
+ resolved: "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz",
3200
+ integrity: "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==",
3492
3201
  license: "MIT",
3493
3202
  dependencies: {
3494
3203
  "balanced-match": "^4.0.2"
3495
3204
  },
3496
3205
  engines: {
3497
- node: "18 || 20 || >=22"
3206
+ node: "20 || >=22"
3498
3207
  }
3499
3208
  },
3500
- "node_modules/@earendil-works/pi-coding-agent/node_modules/buffer-equal-constant-time": {
3209
+ "node_modules/buffer-equal-constant-time": {
3501
3210
  version: "1.0.1",
3502
3211
  resolved: "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
3503
3212
  integrity: "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",
3504
3213
  license: "BSD-3-Clause"
3505
3214
  },
3506
- "node_modules/@earendil-works/pi-coding-agent/node_modules/chalk": {
3507
- version: "5.6.2",
3508
- resolved: "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz",
3509
- integrity: "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==",
3215
+ "node_modules/chalk": {
3216
+ version: "6.0.0",
3217
+ resolved: "https://registry.npmjs.org/chalk/-/chalk-6.0.0.tgz",
3218
+ integrity: "sha512-2uNTXIuTTxk7ciZgAU1BQcgnchcG0xXnrs6jzkQfj9SsRa9M2s5zE8WT96hS6KmG4MzWHSrvH43DF1m4XRkrFg==",
3510
3219
  license: "MIT",
3511
3220
  engines: {
3512
- node: "^12.17.0 || ^14.13 || >=16.0.0"
3221
+ node: ">=22"
3513
3222
  },
3514
3223
  funding: {
3515
3224
  url: "https://github.com/chalk/chalk"
3516
3225
  }
3517
3226
  },
3518
- "node_modules/@earendil-works/pi-coding-agent/node_modules/cross-spawn": {
3227
+ "node_modules/cross-spawn": {
3519
3228
  version: "7.0.6",
3520
3229
  resolved: "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
3521
3230
  integrity: "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
@@ -3529,7 +3238,7 @@ var default_pi_package_lock_default = {
3529
3238
  node: ">= 8"
3530
3239
  }
3531
3240
  },
3532
- "node_modules/@earendil-works/pi-coding-agent/node_modules/data-uri-to-buffer": {
3241
+ "node_modules/data-uri-to-buffer": {
3533
3242
  version: "4.0.1",
3534
3243
  resolved: "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz",
3535
3244
  integrity: "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==",
@@ -3538,7 +3247,7 @@ var default_pi_package_lock_default = {
3538
3247
  node: ">= 12"
3539
3248
  }
3540
3249
  },
3541
- "node_modules/@earendil-works/pi-coding-agent/node_modules/debug": {
3250
+ "node_modules/debug": {
3542
3251
  version: "4.4.3",
3543
3252
  resolved: "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
3544
3253
  integrity: "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
@@ -3555,7 +3264,7 @@ var default_pi_package_lock_default = {
3555
3264
  }
3556
3265
  }
3557
3266
  },
3558
- "node_modules/@earendil-works/pi-coding-agent/node_modules/diff": {
3267
+ "node_modules/diff": {
3559
3268
  version: "8.0.4",
3560
3269
  resolved: "https://registry.npmjs.org/diff/-/diff-8.0.4.tgz",
3561
3270
  integrity: "sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw==",
@@ -3564,7 +3273,7 @@ var default_pi_package_lock_default = {
3564
3273
  node: ">=0.3.1"
3565
3274
  }
3566
3275
  },
3567
- "node_modules/@earendil-works/pi-coding-agent/node_modules/ecdsa-sig-formatter": {
3276
+ "node_modules/ecdsa-sig-formatter": {
3568
3277
  version: "1.0.11",
3569
3278
  resolved: "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
3570
3279
  integrity: "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",
@@ -3573,50 +3282,19 @@ var default_pi_package_lock_default = {
3573
3282
  "safe-buffer": "^5.0.1"
3574
3283
  }
3575
3284
  },
3576
- "node_modules/@earendil-works/pi-coding-agent/node_modules/extend": {
3285
+ "node_modules/extend": {
3577
3286
  version: "3.0.2",
3578
3287
  resolved: "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",
3579
3288
  integrity: "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",
3580
3289
  license: "MIT"
3581
3290
  },
3582
- "node_modules/@earendil-works/pi-coding-agent/node_modules/fast-xml-builder": {
3583
- version: "1.2.0",
3584
- resolved: "https://registry.npmjs.org/fast-xml-builder/-/fast-xml-builder-1.2.0.tgz",
3585
- integrity: "sha512-00aAWieqff+ZJhsXA4g1g7M8k+7AYoMUUHF+/zFb5U6Uv/P0Vl4QZo84/IcufzYalLuEj9928bXN9PbbFzMF0Q==",
3586
- funding: [
3587
- {
3588
- type: "github",
3589
- url: "https://github.com/sponsors/NaturalIntelligence"
3590
- }
3591
- ],
3592
- license: "MIT",
3593
- dependencies: {
3594
- "path-expression-matcher": "^1.5.0",
3595
- "xml-naming": "^0.1.0"
3596
- }
3597
- },
3598
- "node_modules/@earendil-works/pi-coding-agent/node_modules/fast-xml-parser": {
3599
- version: "5.7.3",
3600
- resolved: "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.7.3.tgz",
3601
- integrity: "sha512-C0AaNuC+mscy6vrAQKAc/rMq+zAPHodfHGZu4sGVehvAQt/JLG1O5zEcYcXSY5zSqr4YVgxsB+pHXTq0i7eDlg==",
3602
- funding: [
3603
- {
3604
- type: "github",
3605
- url: "https://github.com/sponsors/NaturalIntelligence"
3606
- }
3607
- ],
3608
- license: "MIT",
3609
- dependencies: {
3610
- "@nodable/entities": "^2.1.0",
3611
- "fast-xml-builder": "^1.1.7",
3612
- "path-expression-matcher": "^1.5.0",
3613
- strnum: "^2.2.3"
3614
- },
3615
- bin: {
3616
- fxparser: "src/cli/cli.js"
3617
- }
3291
+ "node_modules/fast-sha256": {
3292
+ version: "1.3.0",
3293
+ resolved: "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz",
3294
+ integrity: "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==",
3295
+ license: "Unlicense"
3618
3296
  },
3619
- "node_modules/@earendil-works/pi-coding-agent/node_modules/fetch-blob": {
3297
+ "node_modules/fetch-blob": {
3620
3298
  version: "3.2.0",
3621
3299
  resolved: "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz",
3622
3300
  integrity: "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==",
@@ -3639,7 +3317,7 @@ var default_pi_package_lock_default = {
3639
3317
  node: "^12.20 || >= 14.13"
3640
3318
  }
3641
3319
  },
3642
- "node_modules/@earendil-works/pi-coding-agent/node_modules/formdata-polyfill": {
3320
+ "node_modules/formdata-polyfill": {
3643
3321
  version: "4.0.10",
3644
3322
  resolved: "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz",
3645
3323
  integrity: "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==",
@@ -3651,10 +3329,10 @@ var default_pi_package_lock_default = {
3651
3329
  node: ">=12.20.0"
3652
3330
  }
3653
3331
  },
3654
- "node_modules/@earendil-works/pi-coding-agent/node_modules/gaxios": {
3655
- version: "7.1.4",
3656
- resolved: "https://registry.npmjs.org/gaxios/-/gaxios-7.1.4.tgz",
3657
- integrity: "sha512-bTIgTsM2bWn3XklZISBTQX7ZSddGW+IO3bMdGaemHZ3tbqExMENHLx6kKZ/KlejgrMtj8q7wBItt51yegqalrA==",
3332
+ "node_modules/gaxios": {
3333
+ version: "7.3.1",
3334
+ resolved: "https://registry.npmjs.org/gaxios/-/gaxios-7.3.1.tgz",
3335
+ integrity: "sha512-kB3rzJV7d9juLZh8/56QTXCwQfxyhdOMdyYk1HdQKFtF8TJTDTZQJtixWIwXdE9Jji91mC41DUNpjleo4L4eAQ==",
3658
3336
  license: "Apache-2.0",
3659
3337
  dependencies: {
3660
3338
  extend: "^3.0.2",
@@ -3665,7 +3343,29 @@ var default_pi_package_lock_default = {
3665
3343
  node: ">=18"
3666
3344
  }
3667
3345
  },
3668
- "node_modules/@earendil-works/pi-coding-agent/node_modules/gcp-metadata": {
3346
+ "node_modules/gaxios/node_modules/agent-base": {
3347
+ version: "7.1.4",
3348
+ resolved: "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
3349
+ integrity: "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",
3350
+ license: "MIT",
3351
+ engines: {
3352
+ node: ">= 14"
3353
+ }
3354
+ },
3355
+ "node_modules/gaxios/node_modules/https-proxy-agent": {
3356
+ version: "7.0.6",
3357
+ resolved: "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
3358
+ integrity: "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
3359
+ license: "MIT",
3360
+ dependencies: {
3361
+ "agent-base": "^7.1.2",
3362
+ debug: "4"
3363
+ },
3364
+ engines: {
3365
+ node: ">= 14"
3366
+ }
3367
+ },
3368
+ "node_modules/gcp-metadata": {
3669
3369
  version: "8.1.2",
3670
3370
  resolved: "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-8.1.2.tgz",
3671
3371
  integrity: "sha512-zV/5HKTfCeKWnxG0Dmrw51hEWFGfcF2xiXqcA3+J90WDuP0SvoiSO5ORvcBsifmx/FoIjgQN3oNOGaQ5PhLFkg==",
@@ -3679,7 +3379,7 @@ var default_pi_package_lock_default = {
3679
3379
  node: ">=18"
3680
3380
  }
3681
3381
  },
3682
- "node_modules/@earendil-works/pi-coding-agent/node_modules/get-east-asian-width": {
3382
+ "node_modules/get-east-asian-width": {
3683
3383
  version: "1.6.0",
3684
3384
  resolved: "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.6.0.tgz",
3685
3385
  integrity: "sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA==",
@@ -3691,27 +3391,10 @@ var default_pi_package_lock_default = {
3691
3391
  url: "https://github.com/sponsors/sindresorhus"
3692
3392
  }
3693
3393
  },
3694
- "node_modules/@earendil-works/pi-coding-agent/node_modules/glob": {
3695
- version: "13.0.6",
3696
- resolved: "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz",
3697
- integrity: "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==",
3698
- license: "BlueOak-1.0.0",
3699
- dependencies: {
3700
- minimatch: "^10.2.2",
3701
- minipass: "^7.1.3",
3702
- "path-scurry": "^2.0.2"
3703
- },
3704
- engines: {
3705
- node: "18 || 20 || >=22"
3706
- },
3707
- funding: {
3708
- url: "https://github.com/sponsors/isaacs"
3709
- }
3710
- },
3711
- "node_modules/@earendil-works/pi-coding-agent/node_modules/google-auth-library": {
3712
- version: "10.6.2",
3713
- resolved: "https://registry.npmjs.org/google-auth-library/-/google-auth-library-10.6.2.tgz",
3714
- integrity: "sha512-e27Z6EThmVNNvtYASwQxose/G57rkRuaRbQyxM2bvYLLX/GqWZ5chWq2EBoUchJbCc57eC9ArzO5wMsEmWftCw==",
3394
+ "node_modules/google-auth-library": {
3395
+ version: "10.9.1",
3396
+ resolved: "https://registry.npmjs.org/google-auth-library/-/google-auth-library-10.9.1.tgz",
3397
+ integrity: "sha512-i1ydyHrqcIxXkWh/uBmVkzCvIuq5yiK2ATndIe5XxKholrG/MTYP9xGYka4sQhrbIAgGjL2B6NOE7rFaiF3fXw==",
3715
3398
  license: "Apache-2.0",
3716
3399
  dependencies: {
3717
3400
  "base64-js": "^1.3.0",
@@ -3725,7 +3408,7 @@ var default_pi_package_lock_default = {
3725
3408
  node: ">=18"
3726
3409
  }
3727
3410
  },
3728
- "node_modules/@earendil-works/pi-coding-agent/node_modules/google-logging-utils": {
3411
+ "node_modules/google-logging-utils": {
3729
3412
  version: "1.1.3",
3730
3413
  resolved: "https://registry.npmjs.org/google-logging-utils/-/google-logging-utils-1.1.3.tgz",
3731
3414
  integrity: "sha512-eAmLkjDjAFCVXg7A1unxHsLf961m6y17QFqXqAXGj/gVkKFrEICfStRfwUlGNfeCEjNRa32JEWOUTlYXPyyKvA==",
@@ -3734,13 +3417,22 @@ var default_pi_package_lock_default = {
3734
3417
  node: ">=14"
3735
3418
  }
3736
3419
  },
3737
- "node_modules/@earendil-works/pi-coding-agent/node_modules/graceful-fs": {
3420
+ "node_modules/graceful-fs": {
3738
3421
  version: "4.2.11",
3739
3422
  resolved: "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
3740
3423
  integrity: "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
3741
3424
  license: "ISC"
3742
3425
  },
3743
- "node_modules/@earendil-works/pi-coding-agent/node_modules/highlight.js": {
3426
+ "node_modules/grok-mermaid": {
3427
+ version: "0.2.3",
3428
+ resolved: "https://registry.npmjs.org/grok-mermaid/-/grok-mermaid-0.2.3.tgz",
3429
+ integrity: "sha512-/4KopAbsjvuRP9MdPtlDjOHUmUVEohOX73JNcsWpzAtFxh+bq5+Dhb6gzvRieLDwIPQIR3/vy8V1NNTuz4Zsmg==",
3430
+ license: "Apache-2.0",
3431
+ engines: {
3432
+ node: ">=18"
3433
+ }
3434
+ },
3435
+ "node_modules/highlight.js": {
3744
3436
  version: "10.7.3",
3745
3437
  resolved: "https://registry.npmjs.org/highlight.js/-/highlight.js-10.7.3.tgz",
3746
3438
  integrity: "sha512-tzcUFauisWKNHaRkN4Wjl/ZA07gENAjFl3J/c480dprkGTg5EQstgaNFqBfUqCq54kZRIEcreTsAgF/m2quD7A==",
@@ -3749,7 +3441,7 @@ var default_pi_package_lock_default = {
3749
3441
  node: "*"
3750
3442
  }
3751
3443
  },
3752
- "node_modules/@earendil-works/pi-coding-agent/node_modules/hosted-git-info": {
3444
+ "node_modules/hosted-git-info": {
3753
3445
  version: "9.0.3",
3754
3446
  resolved: "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-9.0.3.tgz",
3755
3447
  integrity: "sha512-Hc+ghLoSt6QaYZUv0WBiIvmMDZuZZ7oaDvdH8MbfOO4lOsxdXLEvuC6ePoGs9H1X9oCLyq6+NVN0MKqD+ydxyg==",
@@ -3761,48 +3453,50 @@ var default_pi_package_lock_default = {
3761
3453
  node: "^20.17.0 || >=22.9.0"
3762
3454
  }
3763
3455
  },
3764
- "node_modules/@earendil-works/pi-coding-agent/node_modules/http-proxy-agent": {
3765
- version: "7.0.2",
3766
- resolved: "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",
3767
- integrity: "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==",
3456
+ "node_modules/http-proxy-agent": {
3457
+ version: "9.1.0",
3458
+ resolved: "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-9.1.0.tgz",
3459
+ integrity: "sha512-2NxoveTT58mjYT4n3RPTEfCZGLMbidoO8XEieXfpSYxu+PQJ1qpx4ypwH6N+uF9twBPIvRRgvkvW5HUTYWENig==",
3768
3460
  license: "MIT",
3769
3461
  dependencies: {
3770
- "agent-base": "^7.1.0",
3771
- debug: "^4.3.4"
3462
+ "agent-base": "9.0.0",
3463
+ debug: "^4.3.4",
3464
+ "proxy-agent-negotiate": "1.1.0"
3772
3465
  },
3773
3466
  engines: {
3774
- node: ">= 14"
3467
+ node: ">= 20"
3775
3468
  }
3776
3469
  },
3777
- "node_modules/@earendil-works/pi-coding-agent/node_modules/https-proxy-agent": {
3778
- version: "7.0.6",
3779
- resolved: "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
3780
- integrity: "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
3470
+ "node_modules/https-proxy-agent": {
3471
+ version: "9.1.0",
3472
+ resolved: "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-9.1.0.tgz",
3473
+ integrity: "sha512-ag87y7cJJ9/3+GxFr8Oy4O5faDsGRGnBGsJj/YjOSsSx/5eadKLYTMPlzuR6obgoCDDm0abAAZitXXQkMOPSpA==",
3781
3474
  license: "MIT",
3782
3475
  dependencies: {
3783
- "agent-base": "^7.1.2",
3784
- debug: "4"
3476
+ "agent-base": "9.0.0",
3477
+ debug: "^4.3.4",
3478
+ "proxy-agent-negotiate": "1.1.0"
3785
3479
  },
3786
3480
  engines: {
3787
- node: ">= 14"
3481
+ node: ">= 20"
3788
3482
  }
3789
3483
  },
3790
- "node_modules/@earendil-works/pi-coding-agent/node_modules/ignore": {
3791
- version: "7.0.5",
3792
- resolved: "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz",
3793
- integrity: "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==",
3484
+ "node_modules/ignore": {
3485
+ version: "7.0.8",
3486
+ resolved: "https://registry.npmjs.org/ignore/-/ignore-7.0.8.tgz",
3487
+ integrity: "sha512-YYNsSlXBjMk92SKnkwvB5LOVSa6OznlFUGcsvrFgNJbJCd0M1XKeFVRc8ZByeCqz32FivYNHJVooLmdqrmvp/Q==",
3794
3488
  license: "MIT",
3795
3489
  engines: {
3796
3490
  node: ">= 4"
3797
3491
  }
3798
3492
  },
3799
- "node_modules/@earendil-works/pi-coding-agent/node_modules/isexe": {
3493
+ "node_modules/isexe": {
3800
3494
  version: "2.0.0",
3801
3495
  resolved: "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
3802
3496
  integrity: "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
3803
3497
  license: "ISC"
3804
3498
  },
3805
- "node_modules/@earendil-works/pi-coding-agent/node_modules/jiti": {
3499
+ "node_modules/jiti": {
3806
3500
  version: "2.7.0",
3807
3501
  resolved: "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz",
3808
3502
  integrity: "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==",
@@ -3811,7 +3505,7 @@ var default_pi_package_lock_default = {
3811
3505
  jiti: "lib/jiti-cli.mjs"
3812
3506
  }
3813
3507
  },
3814
- "node_modules/@earendil-works/pi-coding-agent/node_modules/json-bigint": {
3508
+ "node_modules/json-bigint": {
3815
3509
  version: "1.0.0",
3816
3510
  resolved: "https://registry.npmjs.org/json-bigint/-/json-bigint-1.0.0.tgz",
3817
3511
  integrity: "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==",
@@ -3820,7 +3514,7 @@ var default_pi_package_lock_default = {
3820
3514
  "bignumber.js": "^9.0.0"
3821
3515
  }
3822
3516
  },
3823
- "node_modules/@earendil-works/pi-coding-agent/node_modules/json-schema-to-ts": {
3517
+ "node_modules/json-schema-to-ts": {
3824
3518
  version: "3.1.1",
3825
3519
  resolved: "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz",
3826
3520
  integrity: "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==",
@@ -3833,7 +3527,7 @@ var default_pi_package_lock_default = {
3833
3527
  node: ">=16"
3834
3528
  }
3835
3529
  },
3836
- "node_modules/@earendil-works/pi-coding-agent/node_modules/jwa": {
3530
+ "node_modules/jwa": {
3837
3531
  version: "2.0.1",
3838
3532
  resolved: "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz",
3839
3533
  integrity: "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==",
@@ -3844,7 +3538,7 @@ var default_pi_package_lock_default = {
3844
3538
  "safe-buffer": "^5.0.1"
3845
3539
  }
3846
3540
  },
3847
- "node_modules/@earendil-works/pi-coding-agent/node_modules/jws": {
3541
+ "node_modules/jws": {
3848
3542
  version: "4.0.1",
3849
3543
  resolved: "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz",
3850
3544
  integrity: "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==",
@@ -3854,25 +3548,25 @@ var default_pi_package_lock_default = {
3854
3548
  "safe-buffer": "^5.0.1"
3855
3549
  }
3856
3550
  },
3857
- "node_modules/@earendil-works/pi-coding-agent/node_modules/long": {
3551
+ "node_modules/long": {
3858
3552
  version: "5.3.2",
3859
3553
  resolved: "https://registry.npmjs.org/long/-/long-5.3.2.tgz",
3860
3554
  integrity: "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==",
3861
3555
  license: "Apache-2.0"
3862
3556
  },
3863
- "node_modules/@earendil-works/pi-coding-agent/node_modules/lru-cache": {
3864
- version: "11.4.0",
3865
- resolved: "https://registry.npmjs.org/lru-cache/-/lru-cache-11.4.0.tgz",
3866
- integrity: "sha512-W+R+kFL4HgVxONq2bhXPi3bGpzGe/yEhVOp233qw9wCRtgncJ15P3bC+e4zZMu4Cq7d+WAJjXGW0uUkifhcatA==",
3557
+ "node_modules/lru-cache": {
3558
+ version: "11.5.3",
3559
+ resolved: "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz",
3560
+ integrity: "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==",
3867
3561
  license: "BlueOak-1.0.0",
3868
3562
  engines: {
3869
3563
  node: "20 || >=22"
3870
3564
  }
3871
3565
  },
3872
- "node_modules/@earendil-works/pi-coding-agent/node_modules/marked": {
3873
- version: "18.0.5",
3874
- resolved: "https://registry.npmjs.org/marked/-/marked-18.0.5.tgz",
3875
- integrity: "sha512-S6GcvALHg6K4ohtu4E7x0a1AqhAjp6cV8KhLSyN9qVapnzJkusVBxZRcIU9AeYsbe6P1hKDusSbEOzGyyuce6w==",
3566
+ "node_modules/marked": {
3567
+ version: "18.0.11",
3568
+ resolved: "https://registry.npmjs.org/marked/-/marked-18.0.11.tgz",
3569
+ integrity: "sha512-HnslJfsZkRPBDJRHvVtAaWlZHEpSu7u8LgQuJCELjRKuWR+hpq4A7sLq3p8HaI9ypVoXDXxV34CsQJEe1+J5Aw==",
3876
3570
  license: "MIT",
3877
3571
  bin: {
3878
3572
  marked: "bin/marked.js"
@@ -3881,13 +3575,13 @@ var default_pi_package_lock_default = {
3881
3575
  node: ">= 20"
3882
3576
  }
3883
3577
  },
3884
- "node_modules/@earendil-works/pi-coding-agent/node_modules/minimatch": {
3885
- version: "10.2.5",
3886
- resolved: "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz",
3887
- integrity: "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==",
3578
+ "node_modules/minimatch": {
3579
+ version: "10.2.6",
3580
+ resolved: "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz",
3581
+ integrity: "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==",
3888
3582
  license: "BlueOak-1.0.0",
3889
3583
  dependencies: {
3890
- "brace-expansion": "^5.0.5"
3584
+ "brace-expansion": "^5.0.8"
3891
3585
  },
3892
3586
  engines: {
3893
3587
  node: "18 || 20 || >=22"
@@ -3896,22 +3590,13 @@ var default_pi_package_lock_default = {
3896
3590
  url: "https://github.com/sponsors/isaacs"
3897
3591
  }
3898
3592
  },
3899
- "node_modules/@earendil-works/pi-coding-agent/node_modules/minipass": {
3900
- version: "7.1.3",
3901
- resolved: "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz",
3902
- integrity: "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==",
3903
- license: "BlueOak-1.0.0",
3904
- engines: {
3905
- node: ">=16 || 14 >=14.17"
3906
- }
3907
- },
3908
- "node_modules/@earendil-works/pi-coding-agent/node_modules/ms": {
3593
+ "node_modules/ms": {
3909
3594
  version: "2.1.3",
3910
3595
  resolved: "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
3911
3596
  integrity: "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
3912
3597
  license: "MIT"
3913
3598
  },
3914
- "node_modules/@earendil-works/pi-coding-agent/node_modules/node-domexception": {
3599
+ "node_modules/node-domexception": {
3915
3600
  version: "1.0.0",
3916
3601
  resolved: "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz",
3917
3602
  integrity: "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==",
@@ -3931,7 +3616,7 @@ var default_pi_package_lock_default = {
3931
3616
  node: ">=10.5.0"
3932
3617
  }
3933
3618
  },
3934
- "node_modules/@earendil-works/pi-coding-agent/node_modules/node-fetch": {
3619
+ "node_modules/node-fetch": {
3935
3620
  version: "3.3.2",
3936
3621
  resolved: "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz",
3937
3622
  integrity: "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==",
@@ -3949,19 +3634,35 @@ var default_pi_package_lock_default = {
3949
3634
  url: "https://opencollective.com/node-fetch"
3950
3635
  }
3951
3636
  },
3952
- "node_modules/@earendil-works/pi-coding-agent/node_modules/openai": {
3953
- version: "6.26.0",
3954
- resolved: "https://registry.npmjs.org/openai/-/openai-6.26.0.tgz",
3955
- integrity: "sha512-zd23dbWTjiJ6sSAX6s0HrCZi41JwTA1bQVs0wLQPZ2/5o2gxOJA5wh7yOAUgwYybfhDXyhwlpeQf7Mlgx8EOCA==",
3637
+ "node_modules/openai": {
3638
+ version: "7.19.0",
3639
+ resolved: "https://registry.npmjs.org/openai/-/openai-7.19.0.tgz",
3640
+ integrity: "sha512-MX2s3u2L5racTO0CC/SWpCOasJQBCJrqLKXK+l82cAhdeF8mPMBEe/gxMm0ZFa2xpKpOFLRjxv5afYEZbBXmbQ==",
3956
3641
  license: "Apache-2.0",
3957
- bin: {
3958
- openai: "bin/cli"
3642
+ engines: {
3643
+ node: ">=22.0.0"
3959
3644
  },
3960
3645
  peerDependencies: {
3961
- ws: "^8.18.0",
3646
+ "@aws-sdk/credential-provider-node": ">=3.972.0 <4",
3647
+ "@smithy/hash-node": ">=4.3.0 <5",
3648
+ "@smithy/signature-v4": ">=5.4.0 <6",
3649
+ undici: ">=5 <9",
3650
+ ws: "^8.21.0",
3962
3651
  zod: "^3.25 || ^4.0"
3963
3652
  },
3964
3653
  peerDependenciesMeta: {
3654
+ "@aws-sdk/credential-provider-node": {
3655
+ optional: true
3656
+ },
3657
+ "@smithy/hash-node": {
3658
+ optional: true
3659
+ },
3660
+ "@smithy/signature-v4": {
3661
+ optional: true
3662
+ },
3663
+ undici: {
3664
+ optional: true
3665
+ },
3965
3666
  ws: {
3966
3667
  optional: true
3967
3668
  },
@@ -3970,7 +3671,7 @@ var default_pi_package_lock_default = {
3970
3671
  }
3971
3672
  }
3972
3673
  },
3973
- "node_modules/@earendil-works/pi-coding-agent/node_modules/p-retry": {
3674
+ "node_modules/p-retry": {
3974
3675
  version: "4.6.2",
3975
3676
  resolved: "https://registry.npmjs.org/p-retry/-/p-retry-4.6.2.tgz",
3976
3677
  integrity: "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ==",
@@ -3983,34 +3684,13 @@ var default_pi_package_lock_default = {
3983
3684
  node: ">=8"
3984
3685
  }
3985
3686
  },
3986
- "node_modules/@earendil-works/pi-coding-agent/node_modules/p-retry/node_modules/@types/retry": {
3987
- version: "0.12.0",
3988
- resolved: "https://registry.npmjs.org/@types/retry/-/retry-0.12.0.tgz",
3989
- integrity: "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==",
3990
- license: "MIT"
3991
- },
3992
- "node_modules/@earendil-works/pi-coding-agent/node_modules/partial-json": {
3687
+ "node_modules/partial-json": {
3993
3688
  version: "0.1.7",
3994
3689
  resolved: "https://registry.npmjs.org/partial-json/-/partial-json-0.1.7.tgz",
3995
3690
  integrity: "sha512-Njv/59hHaokb/hRUjce3Hdv12wd60MtM9Z5Olmn+nehe0QDAsRtRbJPvJ0Z91TusF0SuZRIvnM+S4l6EIP8leA==",
3996
3691
  license: "MIT"
3997
3692
  },
3998
- "node_modules/@earendil-works/pi-coding-agent/node_modules/path-expression-matcher": {
3999
- version: "1.5.0",
4000
- resolved: "https://registry.npmjs.org/path-expression-matcher/-/path-expression-matcher-1.5.0.tgz",
4001
- integrity: "sha512-cbrerZV+6rvdQrrD+iGMcZFEiiSrbv9Tfdkvnusy6y0x0GKBXREFg/Y65GhIfm0tnLntThhzCnfKwp1WRjeCyQ==",
4002
- funding: [
4003
- {
4004
- type: "github",
4005
- url: "https://github.com/sponsors/NaturalIntelligence"
4006
- }
4007
- ],
4008
- license: "MIT",
4009
- engines: {
4010
- node: ">=14.0.0"
4011
- }
4012
- },
4013
- "node_modules/@earendil-works/pi-coding-agent/node_modules/path-key": {
3693
+ "node_modules/path-key": {
4014
3694
  version: "3.1.1",
4015
3695
  resolved: "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
4016
3696
  integrity: "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
@@ -4019,23 +3699,7 @@ var default_pi_package_lock_default = {
4019
3699
  node: ">=8"
4020
3700
  }
4021
3701
  },
4022
- "node_modules/@earendil-works/pi-coding-agent/node_modules/path-scurry": {
4023
- version: "2.0.2",
4024
- resolved: "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz",
4025
- integrity: "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==",
4026
- license: "BlueOak-1.0.0",
4027
- dependencies: {
4028
- "lru-cache": "^11.0.0",
4029
- minipass: "^7.1.2"
4030
- },
4031
- engines: {
4032
- node: "18 || 20 || >=22"
4033
- },
4034
- funding: {
4035
- url: "https://github.com/sponsors/isaacs"
4036
- }
4037
- },
4038
- "node_modules/@earendil-works/pi-coding-agent/node_modules/proper-lockfile": {
3702
+ "node_modules/proper-lockfile": {
4039
3703
  version: "4.1.2",
4040
3704
  resolved: "https://registry.npmjs.org/proper-lockfile/-/proper-lockfile-4.1.2.tgz",
4041
3705
  integrity: "sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==",
@@ -4046,7 +3710,7 @@ var default_pi_package_lock_default = {
4046
3710
  "signal-exit": "^3.0.2"
4047
3711
  }
4048
3712
  },
4049
- "node_modules/@earendil-works/pi-coding-agent/node_modules/proper-lockfile/node_modules/retry": {
3713
+ "node_modules/proper-lockfile/node_modules/retry": {
4050
3714
  version: "0.12.0",
4051
3715
  resolved: "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz",
4052
3716
  integrity: "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==",
@@ -4055,10 +3719,10 @@ var default_pi_package_lock_default = {
4055
3719
  node: ">= 4"
4056
3720
  }
4057
3721
  },
4058
- "node_modules/@earendil-works/pi-coding-agent/node_modules/protobufjs": {
4059
- version: "7.6.5",
4060
- resolved: "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.5.tgz",
4061
- integrity: "sha512-/FPD0nUc9jH6rfFjji9IBqOz4pcSE3CsT1m7Ep6Mdb0LxSUMj8hgl6GomOvZzpNpAqqGaXA0P3VSrZLFzIhQrw==",
3722
+ "node_modules/protobufjs": {
3723
+ version: "7.6.6",
3724
+ resolved: "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.6.tgz",
3725
+ integrity: "sha512-dYDWdjSl5RNb7SgPxGQcRU+GtvP7s2fpkrY0r432PcOIaZ0/rBcxEZnQN67iJhFuQiVw754JDoPruPCNdGsbjg==",
4062
3726
  hasInstallScript: true,
4063
3727
  license: "BSD-3-Clause",
4064
3728
  dependencies: {
@@ -4078,7 +3742,30 @@ var default_pi_package_lock_default = {
4078
3742
  node: ">=12.0.0"
4079
3743
  }
4080
3744
  },
4081
- "node_modules/@earendil-works/pi-coding-agent/node_modules/retry": {
3745
+ "node_modules/proxy-agent-negotiate": {
3746
+ version: "1.1.0",
3747
+ resolved: "https://registry.npmjs.org/proxy-agent-negotiate/-/proxy-agent-negotiate-1.1.0.tgz",
3748
+ integrity: "sha512-N8IBcM3UgCVzz2L2Lqv8DVntDnnC8/hiV4nEDUPkqq72TPUgYWjQc+bdZlBPZK9LzPAvOY//gAt0S0DApoOXWQ==",
3749
+ license: "MIT",
3750
+ engines: {
3751
+ node: ">= 20"
3752
+ },
3753
+ peerDependencies: {
3754
+ kerberos: "^2.0.0"
3755
+ },
3756
+ peerDependenciesMeta: {
3757
+ kerberos: {
3758
+ optional: true
3759
+ }
3760
+ }
3761
+ },
3762
+ "node_modules/quickjs-wasi": {
3763
+ version: "3.6.2",
3764
+ resolved: "https://registry.npmjs.org/quickjs-wasi/-/quickjs-wasi-3.6.2.tgz",
3765
+ integrity: "sha512-FCqGtGOrMgzUiIrMNMA2YnsOxCNwo31dzqXvclXUC6xeT35NJLKXQJsvbeCTjvoFAwZgEAPg8U6+KAPDGXn8Mg==",
3766
+ license: "MIT"
3767
+ },
3768
+ "node_modules/retry": {
4082
3769
  version: "0.13.1",
4083
3770
  resolved: "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz",
4084
3771
  integrity: "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==",
@@ -4087,7 +3774,7 @@ var default_pi_package_lock_default = {
4087
3774
  node: ">= 4"
4088
3775
  }
4089
3776
  },
4090
- "node_modules/@earendil-works/pi-coding-agent/node_modules/safe-buffer": {
3777
+ "node_modules/safe-buffer": {
4091
3778
  version: "5.2.1",
4092
3779
  resolved: "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
4093
3780
  integrity: "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
@@ -4107,10 +3794,10 @@ var default_pi_package_lock_default = {
4107
3794
  ],
4108
3795
  license: "MIT"
4109
3796
  },
4110
- "node_modules/@earendil-works/pi-coding-agent/node_modules/semver": {
4111
- version: "7.8.0",
4112
- resolved: "https://registry.npmjs.org/semver/-/semver-7.8.0.tgz",
4113
- integrity: "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==",
3797
+ "node_modules/semver": {
3798
+ version: "7.8.5",
3799
+ resolved: "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
3800
+ integrity: "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
4114
3801
  license: "ISC",
4115
3802
  bin: {
4116
3803
  semver: "bin/semver.js"
@@ -4119,7 +3806,7 @@ var default_pi_package_lock_default = {
4119
3806
  node: ">=10"
4120
3807
  }
4121
3808
  },
4122
- "node_modules/@earendil-works/pi-coding-agent/node_modules/shebang-command": {
3809
+ "node_modules/shebang-command": {
4123
3810
  version: "2.0.0",
4124
3811
  resolved: "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
4125
3812
  integrity: "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
@@ -4131,7 +3818,7 @@ var default_pi_package_lock_default = {
4131
3818
  node: ">=8"
4132
3819
  }
4133
3820
  },
4134
- "node_modules/@earendil-works/pi-coding-agent/node_modules/shebang-regex": {
3821
+ "node_modules/shebang-regex": {
4135
3822
  version: "3.0.0",
4136
3823
  resolved: "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
4137
3824
  integrity: "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
@@ -4140,58 +3827,56 @@ var default_pi_package_lock_default = {
4140
3827
  node: ">=8"
4141
3828
  }
4142
3829
  },
4143
- "node_modules/@earendil-works/pi-coding-agent/node_modules/signal-exit": {
3830
+ "node_modules/signal-exit": {
4144
3831
  version: "3.0.7",
4145
3832
  resolved: "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz",
4146
3833
  integrity: "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==",
4147
3834
  license: "ISC"
4148
3835
  },
4149
- "node_modules/@earendil-works/pi-coding-agent/node_modules/strnum": {
4150
- version: "2.3.0",
4151
- resolved: "https://registry.npmjs.org/strnum/-/strnum-2.3.0.tgz",
4152
- integrity: "sha512-ums3KNd42PGyx5xaoVTO1mjU1bH3NpY4vsrVlnv9PNGqQj8wd7rJ6nEypLrJ7z5vxK5RP0yMLo6J/Gsm62DI5Q==",
4153
- funding: [
4154
- {
4155
- type: "github",
4156
- url: "https://github.com/sponsors/NaturalIntelligence"
4157
- }
4158
- ],
4159
- license: "MIT"
3836
+ "node_modules/standardwebhooks": {
3837
+ version: "1.1.1",
3838
+ resolved: "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.1.1.tgz",
3839
+ integrity: "sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ==",
3840
+ license: "MIT",
3841
+ dependencies: {
3842
+ "@stablelib/base64": "^1.0.0",
3843
+ "fast-sha256": "^1.3.0"
3844
+ }
4160
3845
  },
4161
- "node_modules/@earendil-works/pi-coding-agent/node_modules/ts-algebra": {
3846
+ "node_modules/ts-algebra": {
4162
3847
  version: "2.0.0",
4163
3848
  resolved: "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz",
4164
3849
  integrity: "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==",
4165
3850
  license: "MIT"
4166
3851
  },
4167
- "node_modules/@earendil-works/pi-coding-agent/node_modules/tslib": {
3852
+ "node_modules/tslib": {
4168
3853
  version: "2.8.1",
4169
3854
  resolved: "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
4170
3855
  integrity: "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
4171
3856
  license: "0BSD"
4172
3857
  },
4173
- "node_modules/@earendil-works/pi-coding-agent/node_modules/typebox": {
4174
- version: "1.3.7",
4175
- resolved: "https://registry.npmjs.org/typebox/-/typebox-1.3.7.tgz",
4176
- integrity: "sha512-meKuifc33Pccx0O6PdIzYMq3Og8zvP4TIi/a+Bw3AEMZMxOD0+RHGQvpglEe6Zdy3wZ8nqn/j95h8LUZLk/6Hg==",
3858
+ "node_modules/typebox": {
3859
+ version: "1.3.27",
3860
+ resolved: "https://registry.npmjs.org/typebox/-/typebox-1.3.27.tgz",
3861
+ integrity: "sha512-zu+jc1pcy4UiNThxikUr36f0Rybk9PEeCg/NE6adeWr/SKsdNO4EzZHYRDlv2YCVAfj3Odq3dESSo/jNyoBXzA==",
4177
3862
  license: "MIT"
4178
3863
  },
4179
- "node_modules/@earendil-works/pi-coding-agent/node_modules/undici": {
4180
- version: "8.5.0",
4181
- resolved: "https://registry.npmjs.org/undici/-/undici-8.5.0.tgz",
4182
- integrity: "sha512-xamtWoB1EshgjpmlXd7GGm2VfdDtw1+rD8uhry8pSNW3If6S8E0m2T2+orSKeZXEn/aPJMviCpDBA65WJt8zhg==",
3864
+ "node_modules/undici": {
3865
+ version: "8.10.2",
3866
+ resolved: "https://registry.npmjs.org/undici/-/undici-8.10.2.tgz",
3867
+ integrity: "sha512-/y4/bH9YNU5hi9NIrpOuvGXFcxrj3CMrV+/AYpowAYTpHn8gX/XPFjNy766FPoYY0miQhdW977JFWKGNhBdwyQ==",
4183
3868
  license: "MIT",
4184
3869
  engines: {
4185
3870
  node: ">=22.19.0"
4186
3871
  }
4187
3872
  },
4188
- "node_modules/@earendil-works/pi-coding-agent/node_modules/undici-types": {
4189
- version: "6.21.0",
4190
- resolved: "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
4191
- integrity: "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
3873
+ "node_modules/undici-types": {
3874
+ version: "8.9.0",
3875
+ resolved: "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
3876
+ integrity: "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
4192
3877
  license: "MIT"
4193
3878
  },
4194
- "node_modules/@earendil-works/pi-coding-agent/node_modules/web-streams-polyfill": {
3879
+ "node_modules/web-streams-polyfill": {
4195
3880
  version: "3.3.3",
4196
3881
  resolved: "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz",
4197
3882
  integrity: "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==",
@@ -4200,7 +3885,7 @@ var default_pi_package_lock_default = {
4200
3885
  node: ">= 8"
4201
3886
  }
4202
3887
  },
4203
- "node_modules/@earendil-works/pi-coding-agent/node_modules/which": {
3888
+ "node_modules/which": {
4204
3889
  version: "2.0.2",
4205
3890
  resolved: "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
4206
3891
  integrity: "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
@@ -4215,10 +3900,10 @@ var default_pi_package_lock_default = {
4215
3900
  node: ">= 8"
4216
3901
  }
4217
3902
  },
4218
- "node_modules/@earendil-works/pi-coding-agent/node_modules/ws": {
4219
- version: "8.21.0",
4220
- resolved: "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",
4221
- integrity: "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",
3903
+ "node_modules/ws": {
3904
+ version: "8.22.0",
3905
+ resolved: "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz",
3906
+ integrity: "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==",
4222
3907
  license: "MIT",
4223
3908
  engines: {
4224
3909
  node: ">=10.0.0"
@@ -4236,22 +3921,7 @@ var default_pi_package_lock_default = {
4236
3921
  }
4237
3922
  }
4238
3923
  },
4239
- "node_modules/@earendil-works/pi-coding-agent/node_modules/xml-naming": {
4240
- version: "0.1.0",
4241
- resolved: "https://registry.npmjs.org/xml-naming/-/xml-naming-0.1.0.tgz",
4242
- integrity: "sha512-k8KO9hrMyNk6tUWqUfkTEZbezRRpONVOzUTnc97VnCvyj6Tf9lyUR9EDAIeiVLv56jsMcoXEwjW8Kv5yPY52lw==",
4243
- funding: [
4244
- {
4245
- type: "github",
4246
- url: "https://github.com/sponsors/NaturalIntelligence"
4247
- }
4248
- ],
4249
- license: "MIT",
4250
- engines: {
4251
- node: ">=16.0.0"
4252
- }
4253
- },
4254
- "node_modules/@earendil-works/pi-coding-agent/node_modules/yaml": {
3924
+ "node_modules/yaml": {
4255
3925
  version: "2.9.0",
4256
3926
  resolved: "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz",
4257
3927
  integrity: "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==",
@@ -4265,31 +3935,13 @@ var default_pi_package_lock_default = {
4265
3935
  funding: {
4266
3936
  url: "https://github.com/sponsors/eemeli"
4267
3937
  }
4268
- },
4269
- "node_modules/@earendil-works/pi-coding-agent/node_modules/zod": {
4270
- version: "3.25.76",
4271
- resolved: "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
4272
- integrity: "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
4273
- license: "MIT",
4274
- funding: {
4275
- url: "https://github.com/sponsors/colinhacks"
4276
- }
4277
- },
4278
- "node_modules/@earendil-works/pi-coding-agent/node_modules/zod-to-json-schema": {
4279
- version: "3.25.2",
4280
- resolved: "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz",
4281
- integrity: "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==",
4282
- license: "ISC",
4283
- peerDependencies: {
4284
- zod: "^3.25.28 || ^4"
4285
- }
4286
3938
  }
4287
3939
  }
4288
3940
  };
4289
3941
 
4290
3942
  // src/supervisor/package-lock-policy.mjs
4291
3943
  var DEFAULT_PI_SDK_MODULE = "@earendil-works/pi-coding-agent";
4292
- var DEFAULT_PI_SDK_VERSION = "0.83.0";
3944
+ var DEFAULT_PI_SDK_VERSION = "1.3.0";
4293
3945
  function createSupervisorPackageManifest(moduleSpecifier = DEFAULT_PI_SDK_MODULE, expectedVersion = DEFAULT_PI_SDK_VERSION) {
4294
3946
  return {
4295
3947
  name: "neckbeard-supervisor-runtime",