agent-neckbeard 1.1.21 → 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.
@@ -9,7 +9,7 @@ import {
9
9
  serializeSupervisorEnvironmentHandoff,
10
10
  shellQuote,
11
11
  uploadDaytonaFile
12
- } from "./chunk-FL7Y55YM.js";
12
+ } from "./chunk-6P5I7ZCH.js";
13
13
  import {
14
14
  serializeError
15
15
  } from "./chunk-33IXN6MM.js";
@@ -19,7 +19,7 @@ import { Buffer as Buffer2 } from "buffer";
19
19
  import { createHash as createHash2, createHmac } from "crypto";
20
20
 
21
21
  // src/supervisor/runtime-source.generated.ts
22
- var SUPERVISOR_RUNTIME_SOURCE = '// src/supervisor/runtime-entry.ts\nimport {\n closeSync,\n constants as fsConstants4,\n ftruncateSync,\n fstatSync as fstatSync2,\n readSync as readSync2\n} from "node:fs";\nimport { access, readFile } from "node:fs/promises";\nimport { resolve } from "node:path";\nimport { pathToFileURL } from "node:url";\n\n// src/sandbox-capabilities.ts\nvar SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV = "NECKBEARD_SUPERVISOR_ENVIRONMENT_V1";\nvar SUPERVISOR_ENVIRONMENT_FD_ENV = "NECKBEARD_SUPERVISOR_ENVIRONMENT_FD";\nvar SUPERVISOR_ENVIRONMENT_FD = 3;\nvar SUPERVISOR_ENVIRONMENT_MAX_BYTES = 64 * 1024;\nvar SUPERVISOR_ENVIRONMENT_MAX_ENTRIES = 256;\nvar SUPERVISOR_ENVIRONMENT_MAX_NAME_BYTES = 256;\nvar SUPERVISOR_ENVIRONMENT_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/u;\nfunction supervisorEnvironmentByteLength(value) {\n return new TextEncoder().encode(value).byteLength;\n}\nfunction isRecord(value) {\n if (typeof value !== "object" || value === null) return false;\n try {\n return !Array.isArray(value);\n } catch {\n return false;\n }\n}\nfunction normalizeSupervisorEnvironment(value) {\n if (!isRecord(value)) return { ok: false, reason: "invalid_environment" };\n let entries;\n try {\n entries = Object.entries(value).sort(\n ([left], [right]) => left < right ? -1 : left > right ? 1 : 0\n );\n } catch {\n return { ok: false, reason: "invalid_environment" };\n }\n if (entries.length > SUPERVISOR_ENVIRONMENT_MAX_ENTRIES) {\n return { ok: false, reason: "entry_limit" };\n }\n const environment = /* @__PURE__ */ Object.create(null);\n let environmentBytes = 0;\n let exceedsByteLimit = false;\n for (const [name, item] of entries) {\n if (name.length > SUPERVISOR_ENVIRONMENT_MAX_NAME_BYTES || !SUPERVISOR_ENVIRONMENT_NAME_PATTERN.test(name) || name === SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV || name === SUPERVISOR_ENVIRONMENT_FD_ENV) {\n return { ok: false, reason: "invalid_name" };\n }\n if (typeof item !== "string" || item.includes("\\0")) {\n return { ok: false, reason: "invalid_value" };\n }\n if (!exceedsByteLimit) {\n if (item.length > SUPERVISOR_ENVIRONMENT_MAX_BYTES || environmentBytes + name.length + item.length > SUPERVISOR_ENVIRONMENT_MAX_BYTES) {\n exceedsByteLimit = true;\n } else {\n environmentBytes += name.length + supervisorEnvironmentByteLength(item);\n if (environmentBytes > SUPERVISOR_ENVIRONMENT_MAX_BYTES) {\n exceedsByteLimit = true;\n }\n }\n }\n environment[name] = item;\n }\n if (exceedsByteLimit) return { ok: false, reason: "byte_limit" };\n return {\n ok: true,\n environment,\n environmentKeys: entries.map(([name]) => name)\n };\n}\nfunction deserializeSupervisorEnvironmentHandoff(source) {\n if (typeof source !== "string" || source.length === 0 || source.length > SUPERVISOR_ENVIRONMENT_MAX_BYTES || supervisorEnvironmentByteLength(source) > SUPERVISOR_ENVIRONMENT_MAX_BYTES) {\n return { ok: false, reason: "invalid_payload" };\n }\n let value;\n try {\n value = JSON.parse(source);\n } catch {\n return { ok: false, reason: "invalid_payload" };\n }\n if (!isRecord(value) || value.version !== 1 || !isRecord(value.environment) || Object.keys(value).length !== 2 || !Object.hasOwn(value, "version") || !Object.hasOwn(value, "environment")) {\n return { ok: false, reason: "invalid_payload" };\n }\n const normalized = normalizeSupervisorEnvironment(value.environment);\n return normalized.ok ? { ...normalized, payload: source } : normalized;\n}\n\n// src/supervisor/protocol.ts\nimport { createHash } from "node:crypto";\n\n// src/serialized-error.ts\nfunction isSerializedError(value) {\n if (typeof value !== "object" || value === null || Array.isArray(value)) return false;\n const candidate = value;\n return typeof candidate.message === "string" && (candidate.name === void 0 || typeof candidate.name === "string") && (candidate.stack === void 0 || typeof candidate.stack === "string");\n}\nfunction serializeError(error) {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n ...error.stack === void 0 ? {} : { stack: error.stack }\n };\n }\n return { message: String(error) };\n}\n\n// src/supervisor/runtime-limits.ts\nvar SUPERVISOR_CREDENTIAL_BYTE_LENGTH = 32;\nvar SUPERVISOR_CREDENTIAL_ENCODED_LENGTH = 43;\nfunction isSupervisorAttemptCredential(value) {\n if (typeof value !== "string" || value.length !== SUPERVISOR_CREDENTIAL_ENCODED_LENGTH || !/^[A-Za-z0-9_-]+$/u.test(value)) {\n return false;\n }\n const decoded = Buffer.from(value, "base64url");\n return decoded.byteLength === SUPERVISOR_CREDENTIAL_BYTE_LENGTH && decoded.toString("base64url") === value;\n}\nvar SUPERVISOR_MAX_FRAME_BYTES = 1e6;\nvar SUPERVISOR_MAX_STORE_METADATA_BYTES = 1024 * 1024;\nvar SUPERVISOR_MAX_ACTIVE_TURN_BYTES = 16 * 1024;\nvar SUPERVISOR_MAX_ATTEMPT_POINTER_BYTES = 1024;\nvar SUPERVISOR_MAX_WIRE_ID_BYTES = 512;\nfunction isBoundedUtf8Identifier(value, maxBytes = SUPERVISOR_MAX_WIRE_ID_BYTES) {\n return typeof value === "string" && value.length > 0 && Buffer.byteLength(value, "utf8") <= maxBytes;\n}\nvar SUPERVISOR_MAX_REASON_LENGTH = 2e3;\nvar SUPERVISOR_MAX_ATTACHMENT_ID_LENGTH = SUPERVISOR_MAX_WIRE_ID_BYTES;\nvar SUPERVISOR_MAX_COMMAND_ID_LENGTH = SUPERVISOR_MAX_WIRE_ID_BYTES;\nvar SUPERVISOR_MAX_COMMAND_LEDGER_BYTES = 64 * 1024 * 1024;\nvar SUPERVISOR_COMMAND_LEDGER_RECOVERY_BYTES = 8 * 1024 * 1024;\nvar SUPERVISOR_MAX_COMMAND_LEDGER_RECORDS = 131072;\nvar SUPERVISOR_COMMAND_LEDGER_RECOVERY_RECORDS = 512;\nvar SUPERVISOR_MAX_DISTINCT_COMMANDS = 65536;\nvar SUPERVISOR_MAX_PI_SESSION_HISTORY_BYTES = 64 * 1024 * 1024;\nvar SUPERVISOR_PI_SESSION_HISTORY_TURN_HEADROOM_BYTES = 8 * 1024 * 1024;\nvar SUPERVISOR_PI_SESSION_HISTORY_PROMPT_LIMIT_BYTES = SUPERVISOR_MAX_PI_SESSION_HISTORY_BYTES - SUPERVISOR_PI_SESSION_HISTORY_TURN_HEADROOM_BYTES;\nvar SUPERVISOR_MAX_PENDING_COMMANDS = 256;\nvar SUPERVISOR_MAX_PENDING_COMMAND_BYTES = 8 * 1024 * 1024;\nvar SUPERVISOR_PENDING_COMMAND_SEQUENCE_WINDOW = 256;\n\n// src/supervisor/protocol.ts\nvar SUPERVISOR_PROTOCOL_VERSION = 1;\nvar SUPERVISOR_RUNTIME_VERSION = 2;\nvar DAYTONA_SUPERVISOR_PROVIDER_VERSION = 1;\nvar SUPERVISOR_RECOVERY_STOP_REASON = "supervisor_restarted_during_prompt";\nvar SUPERVISOR_COMMAND_FINGERPRINT_VERSION = 1;\nvar SUPERVISOR_COMMAND_FINGERPRINT_PATTERN = new RegExp(\n `^sha256-v${SUPERVISOR_COMMAND_FINGERPRINT_VERSION}:[a-f0-9]{64}$`,\n "u"\n);\nfunction createSupervisorCommandFingerprint(command) {\n const payload = command.payload.kind === "stop" ? {\n kind: command.payload.kind,\n ...command.payload.reason === void 0 ? {} : { reason: command.payload.reason }\n } : {\n kind: command.payload.kind,\n message: command.payload.message,\n ...!command.payload.attachments?.length ? {} : {\n attachments: command.payload.attachments.map((attachment) => ({\n id: attachment.id,\n path: attachment.path,\n ...attachment.mimeType === void 0 ? {} : { mimeType: attachment.mimeType },\n sha256: attachment.sha256.toLowerCase(),\n sizeBytes: attachment.sizeBytes\n }))\n }\n };\n const canonical = JSON.stringify({\n fingerprintVersion: SUPERVISOR_COMMAND_FINGERPRINT_VERSION,\n protocolVersion: command.protocolVersion,\n sessionId: command.sessionId,\n runId: command.runId,\n attemptId: command.attemptId,\n commandId: command.commandId,\n commandSequence: command.commandSequence,\n payload\n });\n return `sha256-v${SUPERVISOR_COMMAND_FINGERPRINT_VERSION}:${createHash("sha256").update(canonical, "utf8").digest("hex")}`;\n}\nfunction isSupervisorCommandFingerprint(value) {\n return typeof value === "string" && SUPERVISOR_COMMAND_FINGERPRINT_PATTERN.test(value);\n}\nfunction isRecord2(value) {\n return typeof value === "object" && value !== null && !Array.isArray(value);\n}\nfunction isNonEmptyString(value) {\n return typeof value === "string" && value.length > 0;\n}\nfunction isCommandId(value) {\n return isBoundedUtf8Identifier(value, SUPERVISOR_MAX_COMMAND_ID_LENGTH);\n}\nfunction isNonNegativeInteger(value) {\n return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;\n}\nfunction isPositiveInteger(value) {\n return typeof value === "number" && Number.isSafeInteger(value) && value > 0;\n}\nfunction isFiniteNumber(value) {\n return typeof value === "number" && Number.isFinite(value);\n}\nfunction hasOptionalCommandId(value) {\n return value.commandId === void 0 || isCommandId(value.commandId);\n}\nfunction isSupervisorTurnUsage(value) {\n return isRecord2(value) && isNonNegativeInteger(value.inputTokens) && isNonNegativeInteger(value.outputTokens) && isNonNegativeInteger(value.cacheReadTokens) && isNonNegativeInteger(value.cacheWriteTokens) && isNonNegativeInteger(value.totalTokens) && (value.costUsd === void 0 || isFiniteNumber(value.costUsd) && value.costUsd >= 0);\n}\nfunction hasOptionalUsage(value) {\n return value.usage === void 0 || isSupervisorTurnUsage(value.usage);\n}\nfunction isCommandKind(value) {\n return value === "prompt" || value === "steer" || value === "stop";\n}\nfunction isSupervisorReason(value) {\n return typeof value === "string" && value.length <= SUPERVISOR_MAX_REASON_LENGTH;\n}\nfunction sanitizeSupervisorReason(value) {\n if (value.length <= SUPERVISOR_MAX_REASON_LENGTH) return value;\n let end = SUPERVISOR_MAX_REASON_LENGTH;\n const finalCodeUnit = value.charCodeAt(end - 1);\n if (finalCodeUnit >= 55296 && finalCodeUnit <= 56319) end -= 1;\n return value.slice(0, end);\n}\nfunction isSupervisorEvent(value) {\n if (!isRecord2(value) || typeof value.kind !== "string") return false;\n if (value.kind === "supervisor_started") return typeof value.recovered === "boolean";\n if (value.kind === "harness_started") {\n return typeof value.adapter === "string" && (value.pid === void 0 || isPositiveInteger(value.pid));\n }\n if (value.kind === "harness_event") {\n return typeof value.adapter === "string" && Object.hasOwn(value, "payload");\n }\n if (value.kind === "harness_stderr") {\n return typeof value.adapter === "string" && typeof value.data === "string";\n }\n if (value.kind === "harness_exited") {\n return typeof value.adapter === "string" && (value.exitCode === null || isNonNegativeInteger(value.exitCode)) && (value.signal === null || typeof value.signal === "string");\n }\n if (value.kind === "turn_started") {\n return typeof value.adapter === "string" && hasOptionalCommandId(value);\n }\n if (value.kind === "turn_completed") {\n return typeof value.adapter === "string" && hasOptionalCommandId(value) && (value.stopReason === void 0 || isSupervisorReason(value.stopReason)) && hasOptionalUsage(value);\n }\n if (value.kind === "turn_failed") {\n return typeof value.adapter === "string" && hasOptionalCommandId(value) && (value.stopReason === void 0 || isSupervisorReason(value.stopReason)) && isSerializedError(value.error) && hasOptionalUsage(value);\n }\n if (value.kind === "turn_stopped") {\n return typeof value.adapter === "string" && hasOptionalCommandId(value) && (value.reason === void 0 || isSupervisorReason(value.reason)) && hasOptionalUsage(value);\n }\n if (value.kind === "command_received" || value.kind === "command_applied") {\n return isCommandId(value.commandId) && isPositiveInteger(value.commandSequence) && isCommandKind(value.commandKind);\n }\n if (value.kind === "command_failed") {\n return isCommandId(value.commandId) && isPositiveInteger(value.commandSequence) && isCommandKind(value.commandKind) && isSerializedError(value.error);\n }\n if (value.kind === "interrupted" || value.kind === "supervisor_stopping") {\n return isSupervisorReason(value.reason);\n }\n if (value.kind === "protocol_error") return typeof value.message === "string";\n return false;\n}\nfunction hasCurrentProtocolVersion(value) {\n return value.protocolVersion === SUPERVISOR_PROTOCOL_VERSION;\n}\nfunction hasAttemptIdentity(value) {\n return isBoundedUtf8Identifier(value.sessionId) && isBoundedUtf8Identifier(value.runId) && isBoundedUtf8Identifier(value.attemptId);\n}\nfunction parseAttachments(value) {\n if (value === void 0) return void 0;\n if (!Array.isArray(value)) return void 0;\n const attachments = [];\n for (const attachment of value) {\n if (!isRecord2(attachment) || !isBoundedUtf8Identifier(\n attachment.id,\n SUPERVISOR_MAX_ATTACHMENT_ID_LENGTH\n ) || !isNonEmptyString(attachment.url) || !isNonEmptyString(attachment.path) || attachment.mimeType !== void 0 && typeof attachment.mimeType !== "string" || typeof attachment.sha256 !== "string" || !/^[a-fA-F0-9]{64}$/.test(attachment.sha256) || !isNonNegativeInteger(attachment.sizeBytes)) {\n return void 0;\n }\n attachments.push({\n id: attachment.id,\n url: attachment.url,\n path: attachment.path,\n ...attachment.mimeType === void 0 ? {} : { mimeType: attachment.mimeType },\n sha256: attachment.sha256.toLowerCase(),\n sizeBytes: attachment.sizeBytes\n });\n }\n return attachments;\n}\nfunction parseCommandPayload(value) {\n if (!isRecord2(value) || typeof value.kind !== "string") return null;\n if (value.kind === "stop") {\n if (value.reason !== void 0 && !isSupervisorReason(value.reason)) return null;\n return {\n kind: "stop",\n ...value.reason === void 0 ? {} : { reason: value.reason }\n };\n }\n if ((value.kind === "prompt" || value.kind === "steer") && typeof value.message === "string") {\n const attachments = parseAttachments(value.attachments);\n if (value.attachments !== void 0 && attachments === void 0) return null;\n return {\n kind: value.kind,\n message: value.message,\n ...attachments === void 0 ? {} : { attachments }\n };\n }\n return null;\n}\nfunction parseCommandFrame(value) {\n if (!isRecord2(value) || value.type !== "command" || !hasCurrentProtocolVersion(value) || !hasAttemptIdentity(value) || !isCommandId(value.commandId) || !isPositiveInteger(value.commandSequence)) {\n return null;\n }\n const payload = parseCommandPayload(value.payload);\n if (!payload) return null;\n return {\n type: "command",\n protocolVersion: SUPERVISOR_PROTOCOL_VERSION,\n sessionId: value.sessionId,\n runId: value.runId,\n attemptId: value.attemptId,\n commandId: value.commandId,\n commandSequence: value.commandSequence,\n payload\n };\n}\nfunction parseGatewayToSupervisorFrame(value) {\n if (!isRecord2(value) || !hasCurrentProtocolVersion(value) || !hasAttemptIdentity(value)) {\n return null;\n }\n const identity = {\n sessionId: value.sessionId,\n runId: value.runId,\n attemptId: value.attemptId\n };\n if (value.type === "command") return parseCommandFrame(value);\n if (value.type === "event_ack" && isNonNegativeInteger(value.acknowledgedEventSequence)) {\n return {\n type: "event_ack",\n protocolVersion: SUPERVISOR_PROTOCOL_VERSION,\n ...identity,\n acknowledgedEventSequence: value.acknowledgedEventSequence\n };\n }\n if (value.type === "resume_ok" && isNonNegativeInteger(value.acknowledgedEventSequence) && isNonNegativeInteger(value.lastAppliedCommandSequence) && Array.isArray(value.pendingCommands) && value.pendingCommands.length <= SUPERVISOR_MAX_PENDING_COMMANDS) {\n const pendingCommands = value.pendingCommands.map(parseCommandFrame);\n if (pendingCommands.some((command) => command === null)) return null;\n return {\n type: "resume_ok",\n protocolVersion: SUPERVISOR_PROTOCOL_VERSION,\n ...identity,\n acknowledgedEventSequence: value.acknowledgedEventSequence,\n lastAppliedCommandSequence: value.lastAppliedCommandSequence,\n pendingCommands\n };\n }\n if (value.type === "attempt_superseded" && (value.reason === void 0 || isSupervisorReason(value.reason))) {\n return {\n type: "attempt_superseded",\n protocolVersion: SUPERVISOR_PROTOCOL_VERSION,\n ...identity,\n ...value.reason === void 0 ? {} : { reason: value.reason }\n };\n }\n if (value.type === "pong" && typeof value.sentAt === "string") {\n return {\n type: "pong",\n protocolVersion: SUPERVISOR_PROTOCOL_VERSION,\n ...identity,\n sentAt: value.sentAt\n };\n }\n return null;\n}\nfunction hasMatchingAttempt(identity, frame) {\n return identity.sessionId === frame.sessionId && identity.runId === frame.runId && identity.attemptId === frame.attemptId;\n}\nfunction createSupervisorEventId(attemptId, attemptSequence) {\n return `${attemptId}:${attemptSequence}`;\n}\nfunction serializeSupervisorError(error) {\n return serializeError(error);\n}\n\n// src/supervisor/path-policy.ts\nimport { posix } from "node:path";\nfunction containsControlCharacter(value) {\n return /[\\u0000-\\u001f\\u007f]/u.test(value);\n}\nfunction assertCanonicalSandboxPath(name, value) {\n if (!posix.isAbsolute(value) || value === "/" || value.endsWith("/") || value !== posix.normalize(value) || value.includes("\\\\") || containsControlCharacter(value)) {\n throw new Error(\n `${name} must be a canonical absolute non-root POSIX sandbox path.`\n );\n }\n}\nfunction sandboxPathIsEqualToOrBelow(parent, child) {\n const relativePath = posix.relative(parent, child);\n return !posix.isAbsolute(relativePath) && relativePath !== ".." && !relativePath.startsWith("../");\n}\nfunction sandboxPathsOverlap(left, right) {\n return sandboxPathIsEqualToOrBelow(left, right) || sandboxPathIsEqualToOrBelow(right, left);\n}\nfunction assertSafePathSegment(name, value) {\n if (value.length === 0 || value === "." || value === ".." || value.includes("/") || value.includes("\\\\") || containsControlCharacter(value) || Buffer.byteLength(value, "utf8") > 255) {\n throw new Error(\n `${name} must be one safe POSIX path segment of 1 to 255 bytes.`\n );\n }\n}\n\n// src/supervisor/config.ts\nvar PI_THINKING_LEVELS = [\n "off",\n "minimal",\n "low",\n "medium",\n "high",\n "xhigh"\n];\nvar SUPERVISOR_MAX_TIMER_DELAY_MS = 2147483647;\nvar DEFAULT_SUPERVISOR_ATTACHMENT_CONFIG = {\n maxBytesPerAttachment: 100 * 1024 * 1024,\n maxBytesPerCommand: 500 * 1024 * 1024,\n maxFilesPerAttempt: 100,\n maxBytesPerAttempt: 500 * 1024 * 1024,\n downloadTimeoutMs: 12e4\n};\nfunction assertSupervisorHarnessPathOwnership(stateDir, sessionPath, agentDir) {\n const effectiveAgentDir = agentDir ?? `${stateDir}/pi/agent`;\n const reservedStateRoots = [\n `${stateDir}/attempts`,\n `${stateDir}/attempt-data-v${SUPERVISOR_RUNTIME_VERSION}`,\n `${stateDir}/.neckbeard-resource-snapshots`\n ];\n if (reservedStateRoots.some((path) => sandboxPathsOverlap(sessionPath, path))) {\n throw new Error(\n "Supervisor config harness.sessionPath must not overlap supervisor-owned state."\n );\n }\n if (reservedStateRoots.some((path) => sandboxPathsOverlap(effectiveAgentDir, path))) {\n throw new Error(\n "Supervisor config harness.agentDir must not overlap supervisor-owned state."\n );\n }\n if (sandboxPathsOverlap(sessionPath, effectiveAgentDir)) {\n throw new Error(\n "Supervisor config harness.sessionPath and harness.agentDir must not overlap."\n );\n }\n}\nfunction isRecord3(value) {\n return typeof value === "object" && value !== null && !Array.isArray(value);\n}\nfunction isNonEmptyString2(value) {\n return typeof value === "string" && value.length > 0;\n}\nfunction isPositiveInteger2(value) {\n return typeof value === "number" && Number.isSafeInteger(value) && value > 0;\n}\nfunction isTimerDelay(value) {\n return isPositiveInteger2(value) && value <= SUPERVISOR_MAX_TIMER_DELAY_MS;\n}\nfunction isNonNegativeNumber(value) {\n return typeof value === "number" && Number.isFinite(value) && value >= 0;\n}\nfunction parseSupervisorRuntimeConfig(value) {\n if (!isRecord3(value)) throw new Error("Supervisor config must be an object.");\n if (value.protocolVersion !== SUPERVISOR_PROTOCOL_VERSION) {\n throw new Error(\n `Unsupported supervisor protocol version: ${String(value.protocolVersion)}.`\n );\n }\n if (value.runtimeVersion !== SUPERVISOR_RUNTIME_VERSION) {\n throw new Error(\n `Unsupported supervisor runtime version: ${String(value.runtimeVersion)}.`\n );\n }\n if (value.provider !== "daytona") {\n throw new Error(\'Supervisor provider must be "daytona".\');\n }\n if (value.providerVersion !== DAYTONA_SUPERVISOR_PROVIDER_VERSION) {\n throw new Error(\n `Unsupported Daytona supervisor provider version: ${String(value.providerVersion)}.`\n );\n }\n for (const field of [\n "sessionId",\n "runId",\n "attemptId",\n "gatewayUrl",\n "credentialEnv",\n "workspaceDir",\n "stateDurabilityAnchor",\n "stateDir"\n ]) {\n if (!isNonEmptyString2(value[field])) {\n throw new Error(`Supervisor config ${field} must be a non-empty string.`);\n }\n }\n for (const field of ["sessionId", "runId"]) {\n if (!isBoundedUtf8Identifier(value[field])) {\n throw new Error(\n `Supervisor config ${field} must be at most ${SUPERVISOR_MAX_WIRE_ID_BYTES} UTF-8 bytes.`\n );\n }\n }\n assertSafePathSegment(\n "Supervisor config attemptId",\n value.attemptId\n );\n assertCanonicalSandboxPath(\n "Supervisor config workspaceDir",\n value.workspaceDir\n );\n assertCanonicalSandboxPath(\n "Supervisor config stateDurabilityAnchor",\n value.stateDurabilityAnchor\n );\n assertCanonicalSandboxPath(\n "Supervisor config stateDir",\n value.stateDir\n );\n if (!sandboxPathIsEqualToOrBelow(\n value.stateDurabilityAnchor,\n value.stateDir\n )) {\n throw new Error(\n "Supervisor config stateDir must be equal to or below stateDurabilityAnchor."\n );\n }\n if (sandboxPathsOverlap(value.workspaceDir, value.stateDir)) {\n throw new Error(\n "Supervisor config workspaceDir and stateDir must not overlap."\n );\n }\n if (!isTimerDelay(value.heartbeatIntervalMs)) {\n throw new Error(\n `Supervisor config heartbeatIntervalMs must be a positive integer no greater than ${SUPERVISOR_MAX_TIMER_DELAY_MS}.`\n );\n }\n if (!isTimerDelay(value.handshakeTimeoutMs)) {\n throw new Error(\n `Supervisor config handshakeTimeoutMs must be a positive integer no greater than ${SUPERVISOR_MAX_TIMER_DELAY_MS}.`\n );\n }\n if (!isPositiveInteger2(value.maxInFlightEvents)) {\n throw new Error(\n "Supervisor config maxInFlightEvents must be a positive integer."\n );\n }\n if (typeof value.allowInsecureGateway !== "boolean") {\n throw new Error(\n "Supervisor config allowInsecureGateway must be a boolean."\n );\n }\n let gatewayUrl;\n try {\n gatewayUrl = new URL(value.gatewayUrl);\n } catch {\n throw new Error("Supervisor config gatewayUrl must be a valid URL.");\n }\n if (gatewayUrl.protocol !== "wss:" && !(value.allowInsecureGateway && gatewayUrl.protocol === "ws:")) {\n throw new Error("Supervisor config gatewayUrl must use wss://.");\n }\n if (gatewayUrl.username || gatewayUrl.password) {\n throw new Error(\n "Supervisor config gatewayUrl must not contain credentials."\n );\n }\n if (gatewayUrl.search || gatewayUrl.hash) {\n throw new Error(\n "Supervisor config gatewayUrl must not contain a query or fragment."\n );\n }\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(value.credentialEnv)) {\n throw new Error(\n "Supervisor config credentialEnv must be a valid environment variable name."\n );\n }\n const attachments = value.attachments === void 0 ? DEFAULT_SUPERVISOR_ATTACHMENT_CONFIG : value.attachments;\n if (!isRecord3(attachments)) {\n throw new Error("Supervisor config attachments must be an object.");\n }\n if (!isPositiveInteger2(attachments.maxBytesPerAttachment)) {\n throw new Error(\n "Supervisor attachments.maxBytesPerAttachment must be a positive integer."\n );\n }\n if (!isPositiveInteger2(attachments.maxBytesPerCommand)) {\n throw new Error(\n "Supervisor attachments.maxBytesPerCommand must be a positive integer."\n );\n }\n const maxFilesPerAttempt = attachments.maxFilesPerAttempt === void 0 ? DEFAULT_SUPERVISOR_ATTACHMENT_CONFIG.maxFilesPerAttempt : attachments.maxFilesPerAttempt;\n if (!isPositiveInteger2(maxFilesPerAttempt)) {\n throw new Error(\n "Supervisor attachments.maxFilesPerAttempt must be a positive integer."\n );\n }\n const maxBytesPerAttempt = attachments.maxBytesPerAttempt === void 0 ? attachments.maxBytesPerCommand : attachments.maxBytesPerAttempt;\n if (!isPositiveInteger2(maxBytesPerAttempt)) {\n throw new Error(\n "Supervisor attachments.maxBytesPerAttempt must be a positive integer."\n );\n }\n if (!isTimerDelay(attachments.downloadTimeoutMs)) {\n throw new Error(\n `Supervisor attachments.downloadTimeoutMs must be a positive integer no greater than ${SUPERVISOR_MAX_TIMER_DELAY_MS}.`\n );\n }\n if (!isRecord3(value.reconnect)) {\n throw new Error("Supervisor config reconnect must be an object.");\n }\n if (!isTimerDelay(value.reconnect.initialDelayMs)) {\n throw new Error(\n `Supervisor reconnect.initialDelayMs must be a positive integer no greater than ${SUPERVISOR_MAX_TIMER_DELAY_MS}.`\n );\n }\n if (!isTimerDelay(value.reconnect.maximumDelayMs)) {\n throw new Error(\n `Supervisor reconnect.maximumDelayMs must be a positive integer no greater than ${SUPERVISOR_MAX_TIMER_DELAY_MS}.`\n );\n }\n if (value.reconnect.maximumDelayMs < value.reconnect.initialDelayMs) {\n throw new Error(\n "Supervisor reconnect.maximumDelayMs must be >= initialDelayMs."\n );\n }\n if (typeof value.reconnect.multiplier !== "number" || !Number.isFinite(value.reconnect.multiplier) || value.reconnect.multiplier < 1) {\n throw new Error("Supervisor reconnect.multiplier must be at least 1.");\n }\n if (!isNonNegativeNumber(value.reconnect.jitterRatio) || value.reconnect.jitterRatio > 1) {\n throw new Error(\n "Supervisor reconnect.jitterRatio must be between 0 and 1."\n );\n }\n if (value.reconnect.maximumDelayMs * (1 + value.reconnect.jitterRatio) > SUPERVISOR_MAX_TIMER_DELAY_MS) {\n throw new Error(\n `Supervisor reconnect jittered delay must not exceed ${SUPERVISOR_MAX_TIMER_DELAY_MS}.`\n );\n }\n if (!isRecord3(value.harness) || value.harness.adapter !== "pi-sdk") {\n throw new Error(\'Supervisor config harness.adapter must be "pi-sdk".\');\n }\n if (value.harness.adapterVersion !== 1) {\n throw new Error("Supervisor config harness.adapterVersion must be 1.");\n }\n if (!isNonEmptyString2(value.harness.moduleSpecifier)) {\n throw new Error(\n "Supervisor config harness.moduleSpecifier must be a non-empty string."\n );\n }\n if (!isNonEmptyString2(value.harness.expectedVersion)) {\n throw new Error(\n "Supervisor config harness.expectedVersion must be a non-empty string."\n );\n }\n if (!isNonEmptyString2(value.harness.sessionPath)) {\n throw new Error(\n "Supervisor config harness.sessionPath must be a non-empty string."\n );\n }\n assertCanonicalSandboxPath(\n "Supervisor config harness.sessionPath",\n value.harness.sessionPath\n );\n if (value.harness.sessionPath === value.stateDir || !sandboxPathIsEqualToOrBelow(\n value.stateDir,\n value.harness.sessionPath\n )) {\n throw new Error(\n "Supervisor config harness.sessionPath must be strictly below stateDir."\n );\n }\n if (value.harness.agentDir !== void 0 && !isNonEmptyString2(value.harness.agentDir)) {\n throw new Error(\n "Supervisor config harness.agentDir must be a non-empty string when set."\n );\n }\n if (value.harness.agentDir !== void 0) {\n assertCanonicalSandboxPath(\n "Supervisor config harness.agentDir",\n value.harness.agentDir\n );\n if (value.harness.agentDir === value.stateDir || !sandboxPathIsEqualToOrBelow(\n value.stateDir,\n value.harness.agentDir\n )) {\n throw new Error(\n "Supervisor config harness.agentDir must be strictly below stateDir."\n );\n }\n }\n assertSupervisorHarnessPathOwnership(\n value.stateDir,\n value.harness.sessionPath,\n value.harness.agentDir\n );\n if (value.harness.provider !== void 0 && !isNonEmptyString2(value.harness.provider)) {\n throw new Error(\n "Supervisor config harness.provider must be a non-empty string when set."\n );\n }\n if (value.harness.model !== void 0 && !isNonEmptyString2(value.harness.model)) {\n throw new Error(\n "Supervisor config harness.model must be a non-empty string when set."\n );\n }\n if (value.harness.provider === void 0 !== (value.harness.model === void 0)) {\n throw new Error(\n "Supervisor config harness.provider and harness.model must be set together."\n );\n }\n if (value.harness.providerCredentialEnv !== void 0 && (!isNonEmptyString2(value.harness.providerCredentialEnv) || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(value.harness.providerCredentialEnv))) {\n throw new Error(\n "Supervisor config harness.providerCredentialEnv must be a valid environment variable name when set."\n );\n }\n if (value.harness.provider === void 0 !== (value.harness.providerCredentialEnv === void 0)) {\n throw new Error(\n "Supervisor config harness.providerCredentialEnv must be set with provider and model."\n );\n }\n if (value.harness.providerCredentialEnv === value.credentialEnv) {\n throw new Error(\n "Supervisor and provider credentials must use different environment variables."\n );\n }\n if (value.harness.thinking !== void 0 && !PI_THINKING_LEVELS.includes(value.harness.thinking)) {\n throw new Error("Supervisor config harness.thinking is invalid.");\n }\n if (!isTimerDelay(value.harness.stopGraceMs)) {\n throw new Error(\n `Supervisor config harness.stopGraceMs must be a positive integer no greater than ${SUPERVISOR_MAX_TIMER_DELAY_MS}.`\n );\n }\n return {\n ...value,\n attachments: {\n maxBytesPerAttachment: attachments.maxBytesPerAttachment,\n maxBytesPerCommand: attachments.maxBytesPerCommand,\n maxFilesPerAttempt,\n maxBytesPerAttempt,\n downloadTimeoutMs: attachments.downloadTimeoutMs\n }\n };\n}\n\n// src/timeout.ts\nfunction settleOperation(operation, options = {}) {\n const { abort, timeout } = options;\n if (abort?.signal.aborted) throw abort.createError();\n if (!abort && !timeout) {\n try {\n return Promise.resolve(operation());\n } catch (error) {\n return Promise.reject(error);\n }\n }\n return new Promise((resolve2, reject) => {\n let settled = false;\n let timer;\n const cleanup = () => {\n if (timer !== void 0) {\n clearTimeout(timer);\n timer = void 0;\n }\n abort?.signal.removeEventListener("abort", onAbort);\n };\n const settle = (callback) => {\n if (settled) return;\n settled = true;\n cleanup();\n callback();\n };\n const onAbort = () => settle(() => reject(abort.createError()));\n abort?.signal.addEventListener("abort", onAbort, { once: true });\n if (timeout) {\n timer = setTimeout(\n () => settle(() => reject(timeout.createError())),\n timeout.timeoutMs\n );\n }\n let task;\n try {\n task = operation();\n } catch (error) {\n settle(() => reject(error));\n return;\n }\n void Promise.resolve(task).then(\n (value) => settle(() => resolve2(value)),\n (error) => settle(() => reject(error))\n );\n });\n}\nfunction withTimeout(task, timeoutMs, message) {\n return settleOperation(() => task, {\n timeout: {\n timeoutMs,\n createError: () => new Error(message)\n }\n });\n}\n\n// src/supervisor/attachments.ts\nimport { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";\nimport { constants as fsConstants2 } from "node:fs";\nimport { opendir } from "node:fs/promises";\nimport { dirname, join as join2 } from "node:path";\n\n// src/supervisor/durable-fs.ts\nimport { randomUUID } from "node:crypto";\nimport { constants as fsConstants } from "node:fs";\nimport { link, mkdir, open, rename, unlink } from "node:fs/promises";\nimport { isAbsolute, join, relative, sep } from "node:path";\nvar SUPERVISOR_ATTEMPT_POINTER_ROOT = "attempts";\nvar SUPERVISOR_ATTEMPT_DATA_ROOT = `attempt-data-v${SUPERVISOR_RUNTIME_VERSION}`;\nvar SUPERVISOR_ATTEMPT_DIRECTORY_MODE = 448;\nvar SUPERVISOR_ATTEMPT_POINTER_MODE = 384;\nvar DEFAULT_DIRECTORY_DEPENDENCIES = {};\nvar SAFE_DIRECTORY_OPEN_FLAGS = fsConstants.O_RDONLY | fsConstants.O_DIRECTORY | fsConstants.O_NOFOLLOW;\nvar SAFE_LEAF_OPEN_FLAGS = fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK;\nvar BOUNDED_READ_CHUNK_BYTES = 64 * 1024;\nfunction descriptorBoundDirectoryPath(directory) {\n return `/proc/${process.pid}/fd/${directory.handle.fd}`;\n}\nfunction descriptorBoundEntryPath(directory, name) {\n assertSafePathSegment("Descriptor-bound directory entry", name);\n return join(descriptorBoundDirectoryPath(directory), name);\n}\nfunction descriptorBoundFilesystemEntryPath(directory, name) {\n if (!name || name === "." || name === ".." || name.includes("/") || name.includes("\\0")) {\n throw new Error("Descriptor-bound filesystem entry must be one POSIX path segment.");\n }\n return join(descriptorBoundDirectoryPath(directory), name);\n}\nfunction directoryIdentity(stats) {\n return { device: stats.dev, inode: stats.ino };\n}\nfunction matchesDirectoryIdentity(stats, expected) {\n return stats.dev === expected.device && stats.ino === expected.inode;\n}\nasync function openBoundDirectoryHandle(path, displayPath, expectedIdentity) {\n let handle = null;\n try {\n handle = await open(path, SAFE_DIRECTORY_OPEN_FLAGS);\n const stats = await handle.stat({ bigint: true });\n if (!stats.isDirectory() || expectedIdentity !== void 0 && !matchesDirectoryIdentity(stats, expectedIdentity)) {\n throw new Error(`${displayPath} must continue to identify its original directory.`);\n }\n return {\n handle,\n displayPath,\n identity: directoryIdentity(stats)\n };\n } catch (error) {\n await handle?.close().catch(() => void 0);\n const code = error.code;\n if (code === "ELOOP" || code === "ENOTDIR") {\n throw new Error(`${displayPath} must be a directory.`, { cause: error });\n }\n throw error;\n }\n}\nasync function openDescriptorBoundDirectory(path, expectedIdentity) {\n return openBoundDirectoryHandle(path, path, expectedIdentity);\n}\nasync function openDescriptorBoundDirectoryAt(parent, name, expectedIdentity) {\n const displayPath = join(parent.displayPath, name);\n return openBoundDirectoryHandle(\n descriptorBoundEntryPath(parent, name),\n displayPath,\n expectedIdentity\n );\n}\nasync function openDescriptorBoundFilesystemDirectoryAt(parent, name, expectedIdentity) {\n const displayPath = join(parent.displayPath, name);\n return openBoundDirectoryHandle(\n descriptorBoundFilesystemEntryPath(parent, name),\n displayPath,\n expectedIdentity\n );\n}\nfunction relativeDirectorySegments(anchor, path) {\n const relativePath = relative(anchor, path);\n if (isAbsolute(relativePath) || relativePath === ".." || relativePath.startsWith(`..${sep}`)) {\n throw new Error(`${path} must be equal to or below durability anchor ${anchor}.`);\n }\n if (!relativePath) return [];\n const segments = relativePath.split(sep);\n for (const segment of segments) {\n assertSafePathSegment("Durable directory path edge", segment);\n }\n return segments;\n}\nasync function verifyBoundDirectoryEntry(parent, child, name) {\n let current = null;\n try {\n current = await openDescriptorBoundDirectoryAt(parent, name, child.identity);\n } catch (error) {\n throw new Error(`${child.displayPath} must continue to identify its original directory.`, {\n cause: error\n });\n } finally {\n await current?.handle.close().catch(() => void 0);\n }\n}\nasync function syncDescriptorBoundDirectory(directory) {\n try {\n await directory.handle.sync();\n } catch (error) {\n const code = error.code;\n if (code !== "EINVAL" && code !== "ENOTSUP" && code !== "EBADF") throw error;\n }\n}\nasync function ensureDescriptorBoundDirectoryAt(parent, name, mode = SUPERVISOR_ATTEMPT_DIRECTORY_MODE, dependencies = DEFAULT_DIRECTORY_DEPENDENCIES) {\n const path = descriptorBoundEntryPath(parent, name);\n let child;\n try {\n try {\n child = await openDescriptorBoundDirectoryAt(parent, name);\n } catch (error) {\n if (error.code !== "ENOENT") throw error;\n try {\n await mkdir(path, { mode });\n } catch (mkdirError) {\n if (mkdirError.code !== "EEXIST") {\n throw mkdirError;\n }\n }\n child = await openDescriptorBoundDirectoryAt(parent, name);\n }\n await (dependencies.syncDirectory?.(parent) ?? syncDescriptorBoundDirectory(parent));\n const boundChild = child;\n await dependencies.afterDirectoryBound?.(boundChild.displayPath);\n await verifyBoundDirectoryEntry(parent, boundChild, name);\n return boundChild;\n } catch (error) {\n await child?.handle.close().catch(() => void 0);\n throw error;\n }\n}\nasync function bindDescriptorBoundDirectory(anchor, path, expectedIdentity, dependencies = DEFAULT_DIRECTORY_DEPENDENCIES) {\n const segments = relativeDirectorySegments(anchor, path);\n let current = await openDescriptorBoundDirectory(anchor);\n try {\n for (const [index, segment] of segments.entries()) {\n const next = await openDescriptorBoundDirectoryAt(\n current,\n segment,\n index === segments.length - 1 ? expectedIdentity : void 0\n );\n await dependencies.afterDirectoryBound?.(next.displayPath);\n await current.handle.close();\n current = next;\n }\n if (!segments.length && expectedIdentity !== void 0) {\n const stats = await current.handle.stat({ bigint: true });\n if (!matchesDirectoryIdentity(stats, expectedIdentity)) {\n throw new Error(`${path} must continue to identify its original directory.`);\n }\n }\n return current;\n } catch (error) {\n await current.handle.close().catch(() => void 0);\n throw error;\n }\n}\nasync function ensureDescriptorBoundDirectory(anchor, path, mode = SUPERVISOR_ATTEMPT_DIRECTORY_MODE, dependencies = DEFAULT_DIRECTORY_DEPENDENCIES) {\n const segments = relativeDirectorySegments(anchor, path);\n let current = await openDescriptorBoundDirectory(anchor);\n try {\n for (const segment of segments) {\n const next = await ensureDescriptorBoundDirectoryAt(current, segment, mode, dependencies);\n await current.handle.close();\n current = next;\n }\n return current;\n } catch (error) {\n await current.handle.close().catch(() => void 0);\n throw error;\n }\n}\nasync function openRegularFileAt(parent, name, flags, description, mode) {\n return openRegularLeafFile(descriptorBoundEntryPath(parent, name), flags, description, mode);\n}\nasync function openRegularFilesystemEntryAt(parent, name, flags, description, mode) {\n return openRegularLeafFile(\n descriptorBoundFilesystemEntryPath(parent, name),\n flags,\n description,\n mode\n );\n}\nasync function openRegularLeafFile(path, flags, name, mode) {\n const handle = await open(path, flags | SAFE_LEAF_OPEN_FLAGS, mode);\n try {\n const stats = await handle.stat();\n if (!stats.isFile()) throw new Error(`${name} must be a regular file.`);\n return handle;\n } catch (error) {\n await handle.close();\n throw error;\n }\n}\nasync function retainedRegularFileStats(retained, current) {\n return Promise.all([\n retained.stat({ bigint: true }),\n current.stat({ bigint: true })\n ]);\n}\nasync function matchesRetainedRegularFileIdentity(retained, current) {\n const [retainedStats, currentStats] = await retainedRegularFileStats(retained, current);\n return retainedStats.isFile() && currentStats.isFile() && retainedStats.dev === currentStats.dev && retainedStats.ino === currentStats.ino;\n}\nasync function withRevalidatedPrivateRegularFile(retained, openCurrent, operation, options = {}) {\n const { maximumBytes } = options;\n if (maximumBytes !== void 0 && (!Number.isSafeInteger(maximumBytes) || maximumBytes < 0)) {\n throw new Error("Retained private regular file has an invalid size limit.");\n }\n const current = await openCurrent();\n try {\n const [retainedStats, currentStats] = await retainedRegularFileStats(retained, current);\n const expectedUid = typeof process.getuid === "function" ? BigInt(process.getuid()) : null;\n const maximumSize = maximumBytes === void 0 ? null : BigInt(maximumBytes);\n if (!retainedStats.isFile() || !currentStats.isFile() || retainedStats.dev !== currentStats.dev || retainedStats.ino !== currentStats.ino || retainedStats.nlink !== 1n || currentStats.nlink !== 1n || (retainedStats.mode & 0o777n) !== 0o600n || (currentStats.mode & 0o777n) !== 0o600n || maximumSize !== null && (retainedStats.size > maximumSize || currentStats.size > maximumSize) || expectedUid !== null && (retainedStats.uid !== expectedUid || currentStats.uid !== expectedUid)) {\n throw new Error(\n options.failureMessage ?? "Retained private regular file no longer satisfies its descriptor binding."\n );\n }\n return operation();\n } finally {\n await current.close().catch(() => void 0);\n }\n}\nasync function readBoundedRegularTextHandle(handle, maximumBytes, capacityName, options = {}) {\n if (!Number.isSafeInteger(maximumBytes) || maximumBytes < 0) {\n throw new Error(`${capacityName} has an invalid read capacity.`);\n }\n if (options.expectedBytes !== void 0 && (!Number.isSafeInteger(options.expectedBytes) || options.expectedBytes < 0 || options.expectedBytes > maximumBytes)) {\n throw new Error(`${capacityName} has an invalid expected byte length.`);\n }\n const stats = await handle.stat();\n if (!Number.isSafeInteger(stats.size) || stats.size < 0 || stats.size > maximumBytes) {\n throw new Error(`${capacityName} exceeds its bounded on-disk capacity.`);\n }\n const chunks = [];\n let totalBytes = 0;\n const readLimit = options.expectedBytes ?? maximumBytes + 1;\n while (totalBytes < readLimit) {\n const remaining = readLimit - totalBytes;\n const chunk = Buffer.allocUnsafe(Math.min(BOUNDED_READ_CHUNK_BYTES, remaining));\n const { bytesRead } = await handle.read(chunk, 0, chunk.length, totalBytes);\n if (bytesRead === 0) {\n if (options.expectedBytes !== void 0) {\n throw options.prematureEofError?.() ?? new Error(`${capacityName} ended before its expected byte length.`);\n }\n break;\n }\n chunks.push(chunk.subarray(0, bytesRead));\n totalBytes += bytesRead;\n }\n if (totalBytes > maximumBytes) {\n throw new Error(`${capacityName} exceeds its bounded on-disk capacity.`);\n }\n try {\n return new TextDecoder("utf-8", {\n fatal: true,\n ignoreBOM: options.ignoreBOM ?? true\n }).decode(Buffer.concat(chunks, totalBytes));\n } catch (error) {\n if (options.invalidUtf8Error !== void 0) throw options.invalidUtf8Error();\n throw error;\n }\n}\nasync function readBoundedRegularTextFileAt(parent, name, maximumBytes, capacityName) {\n const handle = await openRegularFileAt(parent, name, fsConstants.O_RDONLY, capacityName);\n try {\n return await readBoundedRegularTextHandle(handle, maximumBytes, capacityName);\n } finally {\n await handle.close();\n }\n}\nasync function linkDescriptorBoundEntry(sourceParent, sourceName, destinationParent, destinationName) {\n await link(\n descriptorBoundEntryPath(sourceParent, sourceName),\n descriptorBoundEntryPath(destinationParent, destinationName)\n );\n}\nasync function renameDescriptorBoundEntry(sourceParent, sourceName, destinationParent, destinationName) {\n await rename(\n descriptorBoundEntryPath(sourceParent, sourceName),\n descriptorBoundEntryPath(destinationParent, destinationName)\n );\n}\nasync function unlinkDescriptorBoundEntry(parent, name) {\n await unlink(descriptorBoundEntryPath(parent, name));\n}\nasync function unlinkDescriptorBoundEntryIfPresent(parent, name) {\n try {\n await unlinkDescriptorBoundEntry(parent, name);\n return true;\n } catch (error) {\n if (error.code === "ENOENT") return false;\n throw error;\n }\n}\nfunction supervisorAttemptDataDirectory(config) {\n return join(config.stateDir, SUPERVISOR_ATTEMPT_DATA_ROOT, config.attemptId);\n}\nfunction supervisorAttemptPointer(config) {\n return `${JSON.stringify({\n revision: SUPERVISOR_RUNTIME_VERSION,\n dataDirectory: `${SUPERVISOR_ATTEMPT_DATA_ROOT}/${config.attemptId}`\n })}\n`;\n}\nasync function readAndValidateAttemptPointerAt(pointerParent, name, expected, attemptId) {\n let actual;\n try {\n actual = await readBoundedRegularTextFileAt(\n pointerParent,\n name,\n SUPERVISOR_MAX_ATTEMPT_POINTER_BYTES,\n `Supervisor attempt ${attemptId} storage revision pointer`\n );\n } catch (error) {\n let directory = null;\n try {\n directory = await openDescriptorBoundDirectoryAt(pointerParent, name);\n throw new Error(\n `Supervisor attempt ${attemptId} uses a pre-revision storage layout and cannot be upgraded in place; launch a replacement attempt.`\n );\n } catch (directoryError) {\n if (directoryError instanceof Error && directoryError.message.includes("uses a pre-revision storage layout")) {\n throw directoryError;\n }\n } finally {\n await directory?.handle.close().catch(() => void 0);\n }\n throw error;\n }\n if (actual !== expected) {\n throw new Error(`Supervisor attempt ${attemptId} has an unsupported storage revision pointer.`);\n }\n}\nasync function publishAttemptPointerAt(pointerParent, name, expected, attemptId) {\n const temporaryName = `.${process.pid}.${randomUUID()}.revision.tmp`;\n let temporaryExists = false;\n try {\n const handle = await openRegularFileAt(\n pointerParent,\n temporaryName,\n fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL,\n `Supervisor attempt ${attemptId} temporary storage revision pointer`,\n SUPERVISOR_ATTEMPT_POINTER_MODE\n );\n temporaryExists = true;\n try {\n await handle.writeFile(expected, "utf8");\n await handle.sync();\n } finally {\n await handle.close();\n }\n try {\n await linkDescriptorBoundEntry(pointerParent, temporaryName, pointerParent, name);\n } catch (error) {\n if (error.code !== "EEXIST") throw error;\n }\n await readAndValidateAttemptPointerAt(pointerParent, name, expected, attemptId);\n await syncDescriptorBoundDirectory(pointerParent);\n } finally {\n if (temporaryExists) {\n const removed = await unlinkDescriptorBoundEntryIfPresent(\n pointerParent,\n temporaryName\n );\n if (removed) await syncDescriptorBoundDirectory(pointerParent);\n }\n }\n}\nasync function openSupervisorAttemptStorage(config) {\n const state = await ensureDescriptorBoundDirectory(config.stateDurabilityAnchor, config.stateDir);\n let pointerParent = null;\n let dataParent = null;\n try {\n pointerParent = await ensureDescriptorBoundDirectoryAt(state, SUPERVISOR_ATTEMPT_POINTER_ROOT);\n const expectedPointer = supervisorAttemptPointer(config);\n try {\n await readAndValidateAttemptPointerAt(\n pointerParent,\n config.attemptId,\n expectedPointer,\n config.attemptId\n );\n await syncDescriptorBoundDirectory(pointerParent);\n } catch (error) {\n if (error.code !== "ENOENT") throw error;\n await publishAttemptPointerAt(\n pointerParent,\n config.attemptId,\n expectedPointer,\n config.attemptId\n );\n }\n dataParent = await ensureDescriptorBoundDirectoryAt(state, SUPERVISOR_ATTEMPT_DATA_ROOT);\n return await ensureDescriptorBoundDirectoryAt(dataParent, config.attemptId);\n } finally {\n await dataParent?.handle.close().catch(() => void 0);\n await pointerParent?.handle.close().catch(() => void 0);\n await state.handle.close().catch(() => void 0);\n }\n}\n\n// src/supervisor/attachments.ts\nvar MAX_ATTACHMENTS_PER_COMMAND = 100;\nvar ATTACHMENT_TARGET_SUFFIX_BYTES = 108;\nvar ATTACHMENT_READ_CHUNK_BYTES = 64 * 1024;\nvar ATTACHMENT_BATCH_MARKER_MAX_BYTES = 64 * 1024;\nvar IMMUTABLE_ATTACHMENT_FILENAME_PATTERN = /^[a-f0-9]{64}-[a-f0-9]{64}-[a-f0-9]{16}-.+$/u;\nvar ATTACHMENT_BATCH_MARKER_PATTERN = /^\\.batch-([a-f0-9]{64})\\.(pending|committed)$/u;\nvar DEFAULT_DEPENDENCIES = {\n fetch: globalThis.fetch,\n randomId: randomUUID2\n};\nvar AttachmentMaterializationError = class extends Error {\n name = "AttachmentMaterializationError";\n};\nfunction safeError(attachment, message) {\n const id = typeof attachment.id === "string" ? truncateUtf8(attachment.id, SUPERVISOR_MAX_ATTACHMENT_ID_LENGTH) : "unknown";\n return new AttachmentMaterializationError(`Attachment ${id} ${message}`);\n}\nfunction validateFilename(attachment) {\n try {\n assertSafePathSegment("Attachment path", attachment.path);\n } catch {\n throw safeError(attachment, "path must be a safe single filename.");\n }\n}\nfunction validateSourceUrl(attachment) {\n let url;\n try {\n url = new URL(attachment.url);\n } catch {\n throw safeError(attachment, "download URL is invalid.");\n }\n if (url.protocol !== "https:" || url.username || url.password) {\n throw safeError(attachment, "download URL must use HTTPS without embedded credentials.");\n }\n return url;\n}\nfunction attachmentDirectory(config) {\n return join2(supervisorAttemptDataDirectory(config), "attachments");\n}\nfunction commandDirectoryName(commandId) {\n return createHash2("sha256").update(commandId, "utf8").digest("hex");\n}\nfunction truncateUtf8(value, maximumBytes) {\n let result = "";\n let bytes = 0;\n for (const character of value) {\n const characterBytes = Buffer.byteLength(character, "utf8");\n if (bytes + characterBytes > maximumBytes) break;\n result += character;\n bytes += characterBytes;\n }\n return result;\n}\nfunction immutableAttachmentFilename(commandId, attachment) {\n const commandHash = commandDirectoryName(commandId);\n const nameHash = createHash2("sha256").update(attachment.path, "utf8").digest("hex").slice(0, 16);\n return `${commandHash}-${attachment.sha256.toLowerCase()}-${nameHash}-${truncateUtf8(\n attachment.path,\n ATTACHMENT_TARGET_SUFFIX_BYTES\n )}`;\n}\nfunction throwIfAborted(signal) {\n if (!signal?.aborted) return;\n if (signal.reason instanceof Error) throw signal.reason;\n throw new Error("Attachment materialization was aborted.");\n}\nasync function writeChunk(handle, chunk) {\n let offset = 0;\n while (offset < chunk.byteLength) {\n const { bytesWritten } = await handle.write(chunk, offset, chunk.byteLength - offset, null);\n if (bytesWritten <= 0) throw new Error("Attachment file write made no progress.");\n offset += bytesWritten;\n }\n}\nfunction attachmentBatchMarkerName(commandHash, state) {\n return `.batch-${commandHash}.${state}`;\n}\nfunction isRecord4(value) {\n return typeof value === "object" && value !== null && !Array.isArray(value);\n}\nfunction validatePrivateAttachmentStats(stats, maximumBytes) {\n const expectedUid = typeof process.getuid === "function" ? BigInt(process.getuid()) : null;\n if (!stats.isFile() || stats.nlink !== 1n || (stats.mode & 0o777n) !== 0o600n || stats.size < 0n || stats.size > BigInt(maximumBytes) || expectedUid !== null && stats.uid !== expectedUid) {\n throw new AttachmentMaterializationError(\n "Attempt attachment storage contains an invalid published file."\n );\n }\n return Number(stats.size);\n}\nasync function attachmentDigest(handle, sizeBytes) {\n const hash = createHash2("sha256");\n let offset = 0;\n while (offset < sizeBytes) {\n const chunk = Buffer.allocUnsafe(Math.min(ATTACHMENT_READ_CHUNK_BYTES, sizeBytes - offset));\n const { bytesRead } = await handle.read(chunk, 0, chunk.byteLength, offset);\n if (bytesRead <= 0) {\n throw new AttachmentMaterializationError(\n "Attempt attachment storage contains a truncated published file."\n );\n }\n hash.update(chunk.subarray(0, bytesRead));\n offset += bytesRead;\n }\n return hash.digest("hex");\n}\nvar SupervisorAttachmentMaterializer = class {\n constructor(config, dependencies = {}) {\n this.config = config;\n this.directory = attachmentDirectory(config);\n this.dependencies = { ...DEFAULT_DEPENDENCIES, ...dependencies };\n this.maxFilesPerAttempt = config.attachments.maxFilesPerAttempt ?? DEFAULT_SUPERVISOR_ATTACHMENT_CONFIG.maxFilesPerAttempt;\n this.maxBytesPerAttempt = config.attachments.maxBytesPerAttempt ?? config.attachments.maxBytesPerCommand;\n }\n config;\n directory;\n dependencies;\n maxFilesPerAttempt;\n maxBytesPerAttempt;\n attachmentDirectoryPromise = null;\n activeMaterializations = /* @__PURE__ */ new Set();\n materializationTail = Promise.resolve();\n closed = false;\n closePromise = null;\n materialize(commandId, attachments, signal) {\n if (this.closed) {\n return Promise.reject(new Error("Supervisor attachment materializer is closed."));\n }\n const materializing = this.materializationTail.then(\n () => this.materializeBound(commandId, attachments, signal)\n );\n this.materializationTail = materializing.then(\n () => void 0,\n () => void 0\n );\n this.activeMaterializations.add(materializing);\n void materializing.then(\n () => this.activeMaterializations.delete(materializing),\n () => this.activeMaterializations.delete(materializing)\n );\n return materializing;\n }\n async close() {\n if (this.closePromise !== null) return this.closePromise;\n this.closed = true;\n const closing = (async () => {\n await Promise.allSettled([...this.activeMaterializations]);\n const directoryPromise = this.attachmentDirectoryPromise;\n this.attachmentDirectoryPromise = null;\n const directory = await directoryPromise?.catch(() => null);\n await directory?.handle.close();\n })();\n this.closePromise = closing;\n return closing;\n }\n async materializeBound(commandId, attachments, signal) {\n throwIfAborted(signal);\n if (!attachments?.length) return void 0;\n if (attachments.length > MAX_ATTACHMENTS_PER_COMMAND) {\n throw new AttachmentMaterializationError(\n `A command may contain at most ${MAX_ATTACHMENTS_PER_COMMAND} attachments.`\n );\n }\n let declaredTotal = 0;\n const ids = /* @__PURE__ */ new Set();\n const paths = /* @__PURE__ */ new Set();\n const sources = /* @__PURE__ */ new Map();\n for (const attachment of attachments) {\n validateFilename(attachment);\n if (!/^[a-fA-F0-9]{64}$/.test(attachment.sha256)) {\n throw safeError(attachment, "SHA-256 must contain exactly 64 hexadecimal characters.");\n }\n if (!Number.isSafeInteger(attachment.sizeBytes) || attachment.sizeBytes < 0) {\n throw safeError(attachment, "sizeBytes must be a nonnegative safe integer.");\n }\n if (attachment.sizeBytes > this.config.attachments.maxBytesPerAttachment) {\n throw safeError(attachment, "exceeds the per-attachment byte limit.");\n }\n declaredTotal += attachment.sizeBytes;\n if (!Number.isSafeInteger(declaredTotal) || declaredTotal > this.config.attachments.maxBytesPerCommand) {\n throw new AttachmentMaterializationError(\n "Command attachments exceed the aggregate byte limit."\n );\n }\n if (ids.has(attachment.id)) throw safeError(attachment, "ID is duplicated.");\n if (paths.has(attachment.path)) throw safeError(attachment, "path is duplicated.");\n ids.add(attachment.id);\n paths.add(attachment.path);\n sources.set(attachment, validateSourceUrl(attachment));\n }\n const attachmentDirectory2 = await this.getAttachmentDirectory();\n throwIfAborted(signal);\n const usage = await this.recoverAttachmentUsage(attachmentDirectory2);\n const targetNames = /* @__PURE__ */ new Map();\n const requestedTargets = /* @__PURE__ */ new Set();\n let reservedFiles = 0;\n let reservedBytes = 0;\n for (const attachment of attachments) {\n const targetName = immutableAttachmentFilename(commandId, attachment);\n if (requestedTargets.has(targetName)) {\n throw safeError(attachment, "resolves to a duplicate immutable target.");\n }\n requestedTargets.add(targetName);\n targetNames.set(attachment, targetName);\n const existing = usage.files.get(targetName);\n if (existing) {\n if (existing.sizeBytes !== attachment.sizeBytes) {\n throw safeError(attachment, "does not match its existing immutable target.");\n }\n } else {\n reservedFiles += 1;\n reservedBytes += attachment.sizeBytes;\n }\n }\n if (usage.files.size + reservedFiles > this.maxFilesPerAttempt) {\n throw new AttachmentMaterializationError(\n "Attempt attachments exceed the persistent file limit."\n );\n }\n const reservedTotalBytes = usage.bytes + reservedBytes;\n if (!Number.isSafeInteger(reservedBytes) || !Number.isSafeInteger(reservedTotalBytes) || reservedTotalBytes > this.maxBytesPerAttempt) {\n throw new AttachmentMaterializationError(\n "Attempt attachments exceed the persistent byte limit."\n );\n }\n const rollbackTargets = attachments.map((attachment) => targetNames.get(attachment)).filter(\n (targetName) => targetName !== void 0 && !usage.files.has(targetName)\n );\n const batchMarkerName = rollbackTargets.length === 0 ? null : await this.beginAttachmentBatch(\n attachmentDirectory2,\n commandDirectoryName(commandId),\n rollbackTargets\n );\n const materialized = [];\n try {\n for (const attachment of attachments) {\n throwIfAborted(signal);\n const source = sources.get(attachment);\n const targetName = targetNames.get(attachment);\n if (!source || !targetName) {\n throw safeError(attachment, "validated materialization metadata was lost.");\n }\n let path;\n if (usage.files.has(targetName)) {\n path = await this.reuseExisting(\n attachmentDirectory2,\n targetName,\n attachment\n );\n } else {\n const downloaded = await this.download(\n attachmentDirectory2,\n targetName,\n attachment,\n source,\n signal\n );\n path = downloaded.path;\n }\n materialized.push({\n id: attachment.id,\n path,\n ...attachment.mimeType === void 0 ? {} : { mimeType: attachment.mimeType }\n });\n }\n if (batchMarkerName !== null) {\n await this.commitAttachmentBatch(attachmentDirectory2, batchMarkerName);\n }\n return materialized;\n } catch (error) {\n try {\n await this.rollbackBatch(\n attachmentDirectory2,\n rollbackTargets,\n batchMarkerName\n );\n } catch {\n throw new AttachmentMaterializationError(\n "Attachment batch rollback could not be durably completed."\n );\n }\n throw error;\n }\n }\n /**\n * The published files are the durable quota ledger. A restarted supervisor\n * reconstructs exact usage through its retained directory descriptor and\n * removes only crash-left temporary names from the reserved namespace.\n */\n async recoverAttachmentUsage(attachmentDirectory2) {\n await this.removeCrashLeftPartials(attachmentDirectory2);\n await this.recoverAttachmentBatches(attachmentDirectory2);\n const publishedNames = [];\n let unexpectedEntry = false;\n let tooManyFiles = false;\n let removedPartial = false;\n const scanner = await opendir(descriptorBoundDirectoryPath(attachmentDirectory2));\n try {\n while (true) {\n const entry = await scanner.read();\n if (entry === null) break;\n if (entry.name.startsWith(".") && entry.name.endsWith(".partial")) {\n const removed = await unlinkDescriptorBoundEntryIfPresent(\n attachmentDirectory2,\n entry.name\n );\n removedPartial ||= removed;\n continue;\n }\n if (!IMMUTABLE_ATTACHMENT_FILENAME_PATTERN.test(entry.name)) {\n unexpectedEntry = true;\n continue;\n }\n if (publishedNames.length >= this.maxFilesPerAttempt) {\n tooManyFiles = true;\n continue;\n }\n publishedNames.push(entry.name);\n }\n } finally {\n await scanner.close().catch((error) => {\n if (error.code !== "ERR_DIR_CLOSED") throw error;\n });\n if (removedPartial) await syncDescriptorBoundDirectory(attachmentDirectory2);\n }\n if (unexpectedEntry) {\n throw new AttachmentMaterializationError(\n "Attempt attachment storage contains an unexpected entry."\n );\n }\n if (tooManyFiles) {\n throw new AttachmentMaterializationError(\n "Attempt attachment storage exceeds its persistent budget."\n );\n }\n const files = /* @__PURE__ */ new Map();\n let bytes = 0;\n for (const name of publishedNames) {\n const handle = await openRegularFilesystemEntryAt(\n attachmentDirectory2,\n name,\n fsConstants2.O_RDONLY,\n "Supervisor persisted attachment"\n );\n try {\n const sizeBytes = validatePrivateAttachmentStats(\n await handle.stat({ bigint: true }),\n this.config.attachments.maxBytesPerAttachment\n );\n files.set(name, { sizeBytes });\n bytes += sizeBytes;\n if (!Number.isSafeInteger(bytes) || bytes > this.maxBytesPerAttempt) {\n throw new AttachmentMaterializationError(\n "Attempt attachment storage exceeds its persistent budget."\n );\n }\n } finally {\n await handle.close().catch(() => void 0);\n }\n }\n return { files, bytes };\n }\n async removeCrashLeftPartials(attachmentDirectory2) {\n let removed = false;\n const scanner = await opendir(descriptorBoundDirectoryPath(attachmentDirectory2));\n try {\n while (true) {\n const entry = await scanner.read();\n if (entry === null) break;\n if (!entry.name.startsWith(".") || !entry.name.endsWith(".partial")) continue;\n const didRemove = await unlinkDescriptorBoundEntryIfPresent(\n attachmentDirectory2,\n entry.name\n );\n removed ||= didRemove;\n }\n } finally {\n await scanner.close().catch((error) => {\n if (error.code !== "ERR_DIR_CLOSED") throw error;\n });\n }\n if (removed) await syncDescriptorBoundDirectory(attachmentDirectory2);\n }\n async readAttachmentBatchMarker(attachmentDirectory2, markerName, expectedCommandHash) {\n const handle = await openRegularFilesystemEntryAt(\n attachmentDirectory2,\n markerName,\n fsConstants2.O_RDONLY,\n "Supervisor attachment batch marker"\n );\n try {\n const stats = await handle.stat({ bigint: true });\n const expectedUid = typeof process.getuid === "function" ? BigInt(process.getuid()) : null;\n if (!stats.isFile() || stats.nlink !== 1n || (stats.mode & 0o777n) !== 0o600n || stats.size <= 0n || stats.size > BigInt(ATTACHMENT_BATCH_MARKER_MAX_BYTES) || expectedUid !== null && stats.uid !== expectedUid) {\n throw new AttachmentMaterializationError(\n "Attempt attachment storage contains an invalid batch marker."\n );\n }\n const size = Number(stats.size);\n const text = await readBoundedRegularTextHandle(\n handle,\n ATTACHMENT_BATCH_MARKER_MAX_BYTES,\n "Supervisor attachment batch marker",\n {\n expectedBytes: size,\n ignoreBOM: false,\n prematureEofError: () => new AttachmentMaterializationError(\n "Attempt attachment storage contains a truncated batch marker."\n ),\n invalidUtf8Error: () => new AttachmentMaterializationError(\n "Attempt attachment storage contains an invalid batch marker."\n )\n }\n );\n let value;\n try {\n value = JSON.parse(text);\n } catch {\n throw new AttachmentMaterializationError(\n "Attempt attachment storage contains an invalid batch marker."\n );\n }\n if (!isRecord4(value) || value.version !== 1 || value.commandHash !== expectedCommandHash || !Array.isArray(value.targets) || value.targets.length === 0 || value.targets.length > MAX_ATTACHMENTS_PER_COMMAND || Object.keys(value).length !== 3) {\n throw new AttachmentMaterializationError(\n "Attempt attachment storage contains an invalid batch marker."\n );\n }\n const targets = /* @__PURE__ */ new Set();\n for (const target of value.targets) {\n if (typeof target !== "string" || !IMMUTABLE_ATTACHMENT_FILENAME_PATTERN.test(target) || !target.startsWith(`${expectedCommandHash}-`) || targets.has(target)) {\n throw new AttachmentMaterializationError(\n "Attempt attachment storage contains an invalid batch marker."\n );\n }\n targets.add(target);\n }\n return {\n version: 1,\n commandHash: expectedCommandHash,\n targets: [...targets]\n };\n } finally {\n await handle.close().catch(() => void 0);\n }\n }\n async recoverAttachmentBatches(attachmentDirectory2) {\n const markers = /* @__PURE__ */ new Map();\n const scanner = await opendir(descriptorBoundDirectoryPath(attachmentDirectory2));\n try {\n while (true) {\n const entry = await scanner.read();\n if (entry === null) break;\n const match = ATTACHMENT_BATCH_MARKER_PATTERN.exec(entry.name);\n if (!match) continue;\n const commandHash = match[1];\n const state = match[2];\n const existing = markers.get(commandHash) ?? {};\n existing[state] = entry.name;\n markers.set(commandHash, existing);\n }\n } finally {\n await scanner.close().catch((error) => {\n if (error.code !== "ERR_DIR_CLOSED") throw error;\n });\n }\n for (const [commandHash, markerNames] of markers) {\n if (markerNames.pending && markerNames.committed) {\n throw new AttachmentMaterializationError(\n "Attempt attachment storage contains conflicting batch markers."\n );\n }\n const markerName = markerNames.pending ?? markerNames.committed;\n if (!markerName) continue;\n const marker = await this.readAttachmentBatchMarker(\n attachmentDirectory2,\n markerName,\n commandHash\n );\n let changed = false;\n if (markerNames.pending) {\n for (const targetName of marker.targets) {\n const removed = await unlinkDescriptorBoundEntryIfPresent(\n attachmentDirectory2,\n targetName\n );\n changed ||= removed;\n }\n if (changed) await syncDescriptorBoundDirectory(attachmentDirectory2);\n }\n await unlinkDescriptorBoundEntry(attachmentDirectory2, markerName);\n await syncDescriptorBoundDirectory(attachmentDirectory2);\n }\n }\n async beginAttachmentBatch(attachmentDirectory2, commandHash, targets) {\n const markerName = attachmentBatchMarkerName(commandHash, "pending");\n const marker = { version: 1, commandHash, targets };\n const encoded = Buffer.from(`${JSON.stringify(marker)}\n`, "utf8");\n if (encoded.byteLength > ATTACHMENT_BATCH_MARKER_MAX_BYTES) {\n throw new AttachmentMaterializationError(\n "Attachment batch marker exceeds its bounded capacity."\n );\n }\n const temporaryName = `.batch-${commandHash}-${randomUUID2()}.partial`;\n let handle = null;\n let temporaryExists = false;\n let markerPublished = false;\n try {\n handle = await openRegularFileAt(\n attachmentDirectory2,\n temporaryName,\n fsConstants2.O_WRONLY | fsConstants2.O_CREAT | fsConstants2.O_EXCL,\n "Supervisor attachment batch marker temporary file",\n 384\n );\n temporaryExists = true;\n await writeChunk(handle, encoded);\n await handle.chmod(384);\n await handle.sync();\n await linkDescriptorBoundEntry(\n attachmentDirectory2,\n temporaryName,\n attachmentDirectory2,\n markerName\n );\n markerPublished = true;\n await unlinkDescriptorBoundEntry(attachmentDirectory2, temporaryName);\n temporaryExists = false;\n await syncDescriptorBoundDirectory(attachmentDirectory2);\n return markerName;\n } catch (error) {\n if (markerPublished) {\n await unlinkDescriptorBoundEntry(attachmentDirectory2, markerName).catch(() => void 0);\n }\n if (temporaryExists) {\n await unlinkDescriptorBoundEntry(attachmentDirectory2, temporaryName).catch(() => void 0);\n }\n if (markerPublished || temporaryExists) {\n await syncDescriptorBoundDirectory(attachmentDirectory2).catch(() => void 0);\n }\n throw error;\n } finally {\n await handle?.close().catch(() => void 0);\n }\n }\n async commitAttachmentBatch(attachmentDirectory2, pendingMarkerName) {\n const committedMarkerName = pendingMarkerName.replace(/\\.pending$/u, ".committed");\n await renameDescriptorBoundEntry(\n attachmentDirectory2,\n pendingMarkerName,\n attachmentDirectory2,\n committedMarkerName\n );\n await syncDescriptorBoundDirectory(attachmentDirectory2);\n await unlinkDescriptorBoundEntry(attachmentDirectory2, committedMarkerName).then(\n async () => syncDescriptorBoundDirectory(attachmentDirectory2),\n () => void 0\n );\n }\n async reuseExisting(attachmentDirectory2, targetName, attachment) {\n let handle = null;\n try {\n handle = await openRegularFileAt(\n attachmentDirectory2,\n targetName,\n fsConstants2.O_RDONLY,\n "Supervisor existing attachment"\n );\n const before = await handle.stat({ bigint: true });\n const sizeBytes = validatePrivateAttachmentStats(\n before,\n this.config.attachments.maxBytesPerAttachment\n );\n if (sizeBytes !== attachment.sizeBytes) {\n throw safeError(attachment, "does not match its existing immutable target.");\n }\n const digest = await attachmentDigest(handle, sizeBytes);\n const after = await handle.stat({ bigint: true });\n validatePrivateAttachmentStats(after, this.config.attachments.maxBytesPerAttachment);\n if (before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || digest !== attachment.sha256.toLowerCase()) {\n throw safeError(attachment, "does not match its existing immutable target.");\n }\n return await this.canonicalAttachmentPath(attachmentDirectory2, targetName, handle);\n } catch (error) {\n if (error instanceof AttachmentMaterializationError) throw error;\n throw safeError(attachment, "existing immutable target failed validation.");\n } finally {\n await handle?.close().catch(() => void 0);\n }\n }\n async canonicalAttachmentPath(attachmentDirectory2, targetName, handle) {\n const stablePath = join2(attachmentDirectory2.displayPath, targetName);\n await this.dependencies.beforeAttachmentPathPublished?.(stablePath);\n const canonicalDirectory = await bindDescriptorBoundDirectory(\n this.config.stateDurabilityAnchor,\n attachmentDirectory2.displayPath,\n attachmentDirectory2.identity\n );\n let path;\n try {\n await this.dependencies.afterCanonicalAttachmentDirectoryBound?.(\n canonicalDirectory.displayPath\n );\n path = await withRevalidatedPrivateRegularFile(\n handle,\n () => openRegularFileAt(\n canonicalDirectory,\n targetName,\n fsConstants2.O_RDONLY,\n "Supervisor attachment canonical file"\n ),\n () => stablePath,\n {\n maximumBytes: this.config.attachments.maxBytesPerAttachment,\n failureMessage: "Supervisor attachment canonical path no longer identifies the materialized file."\n }\n );\n } finally {\n await canonicalDirectory.handle.close().catch(() => void 0);\n }\n const finalCanonicalDirectory = await bindDescriptorBoundDirectory(\n this.config.stateDurabilityAnchor,\n attachmentDirectory2.displayPath,\n attachmentDirectory2.identity\n );\n try {\n await withRevalidatedPrivateRegularFile(\n handle,\n () => openRegularFileAt(\n finalCanonicalDirectory,\n targetName,\n fsConstants2.O_RDONLY,\n "Supervisor attachment final canonical file"\n ),\n () => void 0,\n {\n maximumBytes: this.config.attachments.maxBytesPerAttachment,\n failureMessage: "Supervisor attachment canonical path no longer identifies the materialized file."\n }\n );\n } finally {\n await finalCanonicalDirectory.handle.close().catch(() => void 0);\n }\n return path;\n }\n async rollbackBatch(attachmentDirectory2, targetNames, pendingMarkerName) {\n let removed = false;\n let failure;\n for (const targetName of [...targetNames].reverse()) {\n try {\n const didRemove = await unlinkDescriptorBoundEntryIfPresent(\n attachmentDirectory2,\n targetName\n );\n removed ||= didRemove;\n } catch (error) {\n failure ??= error;\n }\n }\n if (removed) {\n try {\n await syncDescriptorBoundDirectory(attachmentDirectory2);\n } catch (error) {\n failure ??= error;\n }\n }\n if (failure !== void 0) throw failure;\n if (pendingMarkerName !== null) {\n const committedMarkerName = pendingMarkerName.replace(/\\.pending$/u, ".committed");\n for (const markerName of [pendingMarkerName, committedMarkerName]) {\n try {\n const didRemove = await unlinkDescriptorBoundEntryIfPresent(\n attachmentDirectory2,\n markerName\n );\n if (didRemove) await syncDescriptorBoundDirectory(attachmentDirectory2);\n } catch (error) {\n failure ??= error;\n }\n }\n }\n if (failure !== void 0) throw failure;\n }\n getAttachmentDirectory() {\n if (this.attachmentDirectoryPromise !== null) {\n return this.attachmentDirectoryPromise;\n }\n const opening = this.openAttachmentDirectory();\n this.attachmentDirectoryPromise = opening;\n void opening.catch(() => {\n if (this.attachmentDirectoryPromise === opening) {\n this.attachmentDirectoryPromise = null;\n }\n });\n return opening;\n }\n async openAttachmentDirectory() {\n const attemptDirectory = await openSupervisorAttemptStorage(this.config);\n let attachmentDirectory2 = null;\n let retained = false;\n try {\n if (dirname(this.directory) !== attemptDirectory.displayPath) {\n throw new Error("Supervisor attachment storage resolved to an unexpected directory.");\n }\n attachmentDirectory2 = await ensureDescriptorBoundDirectoryAt(attemptDirectory, "attachments");\n await attachmentDirectory2.handle.chmod(448);\n await this.dependencies.afterAttachmentDirectoryBound?.(attachmentDirectory2.displayPath);\n retained = true;\n return attachmentDirectory2;\n } finally {\n if (!retained) await attachmentDirectory2?.handle.close().catch(() => void 0);\n await attemptDirectory.handle.close().catch(() => void 0);\n }\n }\n async download(attachmentDirectory2, targetName, attachment, source, externalSignal) {\n const temporaryName = `.${this.dependencies.randomId()}.partial`;\n const abortController = new AbortController();\n const abortFromExternalSignal = () => abortController.abort(externalSignal?.reason);\n if (externalSignal?.aborted) abortFromExternalSignal();\n else\n externalSignal?.addEventListener("abort", abortFromExternalSignal, {\n once: true\n });\n const timeout = setTimeout(\n () => abortController.abort(new Error("Attachment download timed out.")),\n this.config.attachments.downloadTimeoutMs\n );\n let handle = null;\n let temporaryExists = false;\n let targetPublished = false;\n let published = false;\n try {\n throwIfAborted(abortController.signal);\n handle = await openRegularFileAt(\n attachmentDirectory2,\n temporaryName,\n fsConstants2.O_WRONLY | fsConstants2.O_CREAT | fsConstants2.O_EXCL,\n "Supervisor attachment temporary file",\n 384\n );\n temporaryExists = true;\n let response;\n try {\n response = await this.dependencies.fetch(source, {\n redirect: "error",\n signal: abortController.signal\n });\n } catch {\n throw safeError(attachment, "download failed.");\n }\n if (!response.ok) {\n throw safeError(attachment, `download returned HTTP ${response.status}.`);\n }\n if (!response.body && attachment.sizeBytes !== 0) {\n throw safeError(attachment, "download returned an empty body.");\n }\n const hash = createHash2("sha256");\n let receivedBytes = 0;\n if (response.body) {\n const reader = response.body.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n throwIfAborted(abortController.signal);\n receivedBytes += value.byteLength;\n if (receivedBytes > attachment.sizeBytes) {\n throw safeError(attachment, "download exceeded its declared size.");\n }\n hash.update(value);\n await writeChunk(handle, value);\n }\n } finally {\n reader.releaseLock();\n }\n }\n if (receivedBytes !== attachment.sizeBytes) {\n throw safeError(\n attachment,\n `download size did not match the declared ${attachment.sizeBytes} bytes.`\n );\n }\n if (hash.digest("hex") !== attachment.sha256.toLowerCase()) {\n throw safeError(attachment, "download did not match its declared SHA-256.");\n }\n await handle.chmod(384);\n await handle.sync();\n throwIfAborted(abortController.signal);\n await linkDescriptorBoundEntry(\n attachmentDirectory2,\n temporaryName,\n attachmentDirectory2,\n targetName\n );\n targetPublished = true;\n await unlinkDescriptorBoundEntry(attachmentDirectory2, temporaryName);\n temporaryExists = false;\n await syncDescriptorBoundDirectory(attachmentDirectory2);\n const path = await this.canonicalAttachmentPath(\n attachmentDirectory2,\n targetName,\n handle\n );\n published = true;\n return { path, targetName };\n } catch (error) {\n abortController.abort();\n if (error instanceof AttachmentMaterializationError) throw error;\n throw safeError(attachment, "could not be materialized.");\n } finally {\n clearTimeout(timeout);\n externalSignal?.removeEventListener("abort", abortFromExternalSignal);\n await handle?.close().catch(() => void 0);\n let removed = false;\n let cleanupFailure;\n if (!published) {\n if (targetPublished) {\n removed = await unlinkDescriptorBoundEntryIfPresent(\n attachmentDirectory2,\n targetName\n ).catch((error) => {\n cleanupFailure ??= error;\n return false;\n });\n }\n if (temporaryExists) {\n const removedTemporary = await unlinkDescriptorBoundEntryIfPresent(\n attachmentDirectory2,\n temporaryName\n ).catch((error) => {\n cleanupFailure ??= error;\n return false;\n });\n removed ||= removedTemporary;\n }\n if (removed) {\n await syncDescriptorBoundDirectory(attachmentDirectory2).catch((error) => {\n cleanupFailure ??= error;\n });\n }\n if (cleanupFailure !== void 0) {\n throw new AttachmentMaterializationError(\n "Attachment cleanup could not be durably completed."\n );\n }\n }\n }\n }\n};\n\n// src/supervisor/execution-gate.ts\nvar SupervisorExecutionClosedError = class extends Error {\n constructor(kind, reason, options = {}) {\n super(`Supervisor execution is closed: ${reason}`, options);\n this.kind = kind;\n this.reason = reason;\n }\n kind;\n reason;\n name = "SupervisorExecutionClosedError";\n};\nvar SupervisorExecutionGate = class {\n controller = new AbortController();\n closureValue = null;\n get signal() {\n return this.controller.signal;\n }\n get closure() {\n return this.closureValue;\n }\n get isClosed() {\n return this.closureValue !== null;\n }\n close(kind, reason, cause) {\n if (this.closureValue) return false;\n const error = new SupervisorExecutionClosedError(kind, reason, { cause });\n this.closureValue = { kind, reason, error };\n this.controller.abort(error);\n return true;\n }\n throwIfClosed() {\n if (this.closureValue) throw this.closureValue.error;\n }\n};\n\n// src/sensitive-value-redactor.ts\nvar DEFAULT_MINIMUM_CAPTURE_LENGTH = 8;\nvar DEFAULT_CREDENTIAL_ENV_NAME_PATTERN = /(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)/iu;\nfunction defaultEnvironmentValueIsSensitive(name, value) {\n return value.length >= DEFAULT_MINIMUM_CAPTURE_LENGTH && DEFAULT_CREDENTIAL_ENV_NAME_PATTERN.test(name);\n}\nvar SensitiveValueRedactor = class {\n secrets = /* @__PURE__ */ new Set();\n minimumCaptureLength;\n environment;\n isEnvironmentValueSensitive;\n constructor(values = [], options = {}) {\n this.minimumCaptureLength = options.minimumCaptureLength ?? DEFAULT_MINIMUM_CAPTURE_LENGTH;\n const environment = options.environment;\n this.environment = typeof environment === "function" ? environment : () => environment ?? process.env;\n this.isEnvironmentValueSensitive = options.isEnvironmentValueSensitive ?? defaultEnvironmentValueIsSensitive;\n this.captureAll(values);\n }\n capture(value) {\n if (value) this.secrets.add(value);\n }\n captureAll(values) {\n for (const value of values) {\n if (value.length >= this.minimumCaptureLength) this.capture(value);\n }\n }\n redact(value) {\n const environmentSecrets = Object.entries(this.environment()).filter(\n (entry) => Boolean(entry[1]) && this.isEnvironmentValueSensitive(entry[0], entry[1])\n ).map(([, secret]) => secret);\n const orderedSecrets = [.../* @__PURE__ */ new Set([...this.secrets, ...environmentSecrets])].sort(\n (left, right) => {\n const lengthDifference = right.length - left.length;\n if (lengthDifference !== 0) return lengthDifference;\n return left < right ? -1 : left > right ? 1 : 0;\n }\n );\n let redacted = value;\n for (const secret of orderedSecrets) {\n redacted = redacted.split(secret).join("[REDACTED]");\n }\n return redacted;\n }\n serialize(error) {\n const serialized = serializeError(error);\n return {\n ...serialized.name === void 0 ? {} : { name: this.redact(serialized.name) },\n message: this.redact(serialized.message),\n ...serialized.stack === void 0 ? {} : { stack: this.redact(serialized.stack) }\n };\n }\n};\n\n// src/supervisor/runtime-support.ts\nfunction isRecord5(value) {\n return typeof value === "object" && value !== null && !Array.isArray(value);\n}\nfunction errorFromUnknown(error) {\n return error instanceof Error ? error : new Error(String(error));\n}\n\n// src/supervisor/gateway-transport.ts\nvar WEBSOCKET_OPEN = 1;\nvar MAX_WEBSOCKET_BUFFERED_BYTES = 1024 * 1024;\nvar MAX_OUTBOUND_BATCH_BYTES = 1024 * 1024;\nvar MAX_OUTBOUND_IN_FLIGHT_BYTES = 8 * 1024 * 1024;\nvar SUPERVISOR_MAX_PENDING_INBOUND_FRAMES = SUPERVISOR_MAX_PENDING_COMMANDS * 2 + 4;\nvar SUPERVISOR_MAX_PENDING_INBOUND_BYTES = SUPERVISOR_MAX_PENDING_COMMAND_BYTES + SUPERVISOR_MAX_FRAME_BYTES * 2;\nvar DEFAULT_GATEWAY_TRANSPORT_DEPENDENCIES = {\n createWebSocket(url) {\n const WebSocketConstructor = globalThis.WebSocket;\n if (!WebSocketConstructor) {\n throw new Error("The supervisor runtime requires a Node.js version with global WebSocket.");\n }\n return new WebSocketConstructor(url);\n },\n random: Math.random,\n now: Date.now\n};\nvar SupervisorInboundFrameTooLargeError = class extends Error {\n name = "SupervisorInboundFrameTooLargeError";\n};\nfunction decodeGatewayMessage(data) {\n let text;\n let byteLength;\n if (typeof data === "string") {\n byteLength = Buffer.byteLength(data, "utf8");\n if (byteLength >= SUPERVISOR_MAX_FRAME_BYTES) {\n throw new SupervisorInboundFrameTooLargeError(\n `Gateway frame exceeds the ${SUPERVISOR_MAX_FRAME_BYTES}-byte limit.`\n );\n }\n text = data;\n } else if (data instanceof ArrayBuffer) {\n byteLength = data.byteLength;\n if (byteLength >= SUPERVISOR_MAX_FRAME_BYTES) {\n throw new SupervisorInboundFrameTooLargeError(\n `Gateway frame exceeds the ${SUPERVISOR_MAX_FRAME_BYTES}-byte limit.`\n );\n }\n try {\n text = new TextDecoder("utf-8", { fatal: true }).decode(data);\n } catch {\n return {\n decoded: { ok: false, error: "Gateway sent invalid UTF-8." },\n byteLength\n };\n }\n } else if (ArrayBuffer.isView(data)) {\n const view = data;\n byteLength = view.byteLength;\n if (byteLength >= SUPERVISOR_MAX_FRAME_BYTES) {\n throw new SupervisorInboundFrameTooLargeError(\n `Gateway frame exceeds the ${SUPERVISOR_MAX_FRAME_BYTES}-byte limit.`\n );\n }\n try {\n text = new TextDecoder("utf-8", { fatal: true }).decode(\n new Uint8Array(view.buffer, view.byteOffset, view.byteLength)\n );\n } catch {\n return {\n decoded: { ok: false, error: "Gateway sent invalid UTF-8." },\n byteLength\n };\n }\n } else {\n return {\n decoded: { ok: false, error: "Gateway sent a non-text frame." },\n byteLength: 0\n };\n }\n let raw;\n try {\n raw = JSON.parse(text);\n } catch {\n return {\n decoded: { ok: false, error: "Gateway sent malformed JSON." },\n byteLength\n };\n }\n const frame = parseGatewayToSupervisorFrame(raw);\n return {\n decoded: frame ? { ok: true, frame } : { ok: false, error: "Gateway sent an invalid frame." },\n byteLength\n };\n}\nvar SupervisorGatewayTransport = class {\n constructor(config, store, harness, commands, executionGate, redactor, callbacks, dependencies = DEFAULT_GATEWAY_TRANSPORT_DEPENDENCIES) {\n this.config = config;\n this.store = store;\n this.harness = harness;\n this.commands = commands;\n this.executionGate = executionGate;\n this.redactor = redactor;\n this.callbacks = callbacks;\n this.dependencies = dependencies;\n }\n config;\n store;\n harness;\n commands;\n executionGate;\n redactor;\n callbacks;\n dependencies;\n connection = null;\n nextConnectionGeneration = 1;\n reconnectAttempt = 0;\n reconnectTimer = null;\n stopping = false;\n // Old socket generations can retain their queued closures while a durable\n // handler is blocked. Account across the transport lifetime so reconnects\n // cannot each allocate another full generation-local inbound window.\n pendingInboundFrames = 0;\n pendingInboundBytes = 0;\n start() {\n this.connect();\n }\n beginShutdown() {\n this.stopping = true;\n if (this.reconnectTimer) clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n this.clearConnectionTimers(this.connection);\n }\n finishShutdown(options) {\n const connection = this.connection;\n if (!options.fatal) this.flushOutbox(connection);\n if (this.isActiveConnection(connection)) {\n connection.socket.close(\n 1e3,\n options.superseded ? "attempt superseded" : "supervisor stopped"\n );\n this.connection = null;\n }\n }\n failActiveConnection() {\n const connection = this.connection;\n this.clearConnectionTimers(connection);\n if (!this.isActiveConnection(connection)) return;\n connection.failed = true;\n connection.socket.close(1011, "durable supervisor failure");\n }\n flushOutbox(connection = this.connection) {\n if (!this.isActiveConnection(connection) || connection.failed || !connection.resumed || connection.socket.readyState !== WEBSOCKET_OPEN || connection.socket.bufferedAmount > MAX_WEBSOCKET_BUFFERED_BYTES) {\n return;\n }\n const acknowledged = this.store.lastAcknowledgedEventSequence;\n const inFlight = Math.max(0, connection.transmittedEventSequence - acknowledged);\n const allowance = Math.max(0, this.config.maxInFlightEvents - inFlight);\n if (!allowance) return;\n let inFlightBytes = 0;\n for (const frame of this.store.listEventsAfter(acknowledged, inFlight)) {\n inFlightBytes += Buffer.byteLength(JSON.stringify(frame), "utf8");\n }\n if (inFlightBytes >= MAX_OUTBOUND_IN_FLIGHT_BYTES) return;\n let batchBytes = 0;\n const events = this.store.listEventsAfter(connection.transmittedEventSequence, allowance);\n for (const event of events) {\n if (!this.isActiveConnection(connection) || connection.failed || connection.socket.readyState !== WEBSOCKET_OPEN || connection.socket.bufferedAmount > MAX_WEBSOCKET_BUFFERED_BYTES) {\n break;\n }\n const serialized = JSON.stringify(event);\n const frameBytes = Buffer.byteLength(serialized, "utf8");\n if (frameBytes >= SUPERVISOR_MAX_FRAME_BYTES) {\n this.callbacks.failRuntime(\n new Error(\n `Durable event ${event.eventId} exceeds the supervisor WebSocket frame limit.`\n )\n );\n break;\n }\n if (batchBytes > 0 && batchBytes + frameBytes > MAX_OUTBOUND_BATCH_BYTES) break;\n if (inFlightBytes > 0 && inFlightBytes + frameBytes > MAX_OUTBOUND_IN_FLIGHT_BYTES) break;\n try {\n connection.socket.send(serialized);\n } catch {\n connection.socket.close(1011, "event send failed");\n break;\n }\n connection.transmittedEventSequence = event.attemptSequence;\n batchBytes += frameBytes;\n inFlightBytes += frameBytes;\n if (batchBytes >= MAX_OUTBOUND_BATCH_BYTES || inFlightBytes >= MAX_OUTBOUND_IN_FLIGHT_BYTES || connection.socket.bufferedAmount > MAX_WEBSOCKET_BUFFERED_BYTES) {\n break;\n }\n }\n }\n connect() {\n if (this.stopping || this.executionGate.isClosed) return;\n const socket = this.dependencies.createWebSocket(this.config.gatewayUrl);\n socket.binaryType = "arraybuffer";\n if (this.stopping || this.executionGate.isClosed) {\n socket.close(1e3, "supervisor stopped");\n return;\n }\n const connection = {\n generation: this.nextConnectionGeneration,\n socket,\n resumed: false,\n failed: false,\n transmittedEventSequence: 0,\n lastGatewayActivityAt: this.dependencies.now(),\n pendingInboundFrames: 0,\n pendingInboundBytes: 0,\n inboundTail: Promise.resolve(),\n handshakeTimer: null,\n heartbeatTimer: null\n };\n this.nextConnectionGeneration += 1;\n this.connection = connection;\n socket.addEventListener("open", () => {\n if (!this.isActiveConnection(connection) || this.stopping) return;\n const credential = this.callbacks.getCredential();\n if (!credential) {\n void this.callbacks.emitEvent({\n kind: "protocol_error",\n message: `Missing required credential environment variable ${this.config.credentialEnv}.`\n }).then(\n () => connection.socket.close(1008, "missing credential"),\n () => connection.socket.close(1008, "missing credential")\n );\n return;\n }\n const resume = {\n type: "resume",\n protocolVersion: SUPERVISOR_PROTOCOL_VERSION,\n runtimeVersion: SUPERVISOR_RUNTIME_VERSION,\n provider: "daytona",\n providerVersion: DAYTONA_SUPERVISOR_PROVIDER_VERSION,\n sessionId: this.config.sessionId,\n runId: this.config.runId,\n attemptId: this.config.attemptId,\n credential,\n lastAcknowledgedEventSequence: this.store.lastAcknowledgedEventSequence,\n lastAppliedCommandSequence: this.store.lastAppliedCommandSequence\n };\n try {\n connection.socket.send(JSON.stringify(resume));\n } catch {\n connection.failed = true;\n connection.socket.close(1011, "resume send failed");\n return;\n }\n connection.handshakeTimer = setTimeout(\n () => connection.socket.close(4e3, "resume handshake timeout"),\n this.config.handshakeTimeoutMs\n );\n });\n socket.addEventListener("message", (message) => {\n if (!this.isActiveConnection(connection) || this.stopping || connection.failed) {\n return;\n }\n connection.lastGatewayActivityAt = this.dependencies.now();\n let envelope;\n try {\n envelope = decodeGatewayMessage(message.data);\n } catch (error) {\n if (error instanceof SupervisorInboundFrameTooLargeError) {\n if (this.isActiveConnection(connection)) {\n connection.failed = true;\n connection.socket.close(1009, "gateway frame too large");\n }\n return;\n }\n throw error;\n }\n const { decoded, byteLength } = envelope;\n if (decoded.ok && decoded.frame.type === "attempt_superseded" && hasMatchingAttempt(this.config, decoded.frame)) {\n this.callbacks.acceptSupersession(decoded.frame.reason ?? "attempt_superseded");\n return;\n }\n if (connection.pendingInboundFrames + 1 > SUPERVISOR_MAX_PENDING_INBOUND_FRAMES || connection.pendingInboundBytes + byteLength > SUPERVISOR_MAX_PENDING_INBOUND_BYTES || this.pendingInboundFrames + 1 > SUPERVISOR_MAX_PENDING_INBOUND_FRAMES || this.pendingInboundBytes + byteLength > SUPERVISOR_MAX_PENDING_INBOUND_BYTES) {\n connection.failed = true;\n connection.socket.close(1013, "gateway inbound backpressure");\n return;\n }\n connection.pendingInboundFrames += 1;\n connection.pendingInboundBytes += byteLength;\n this.pendingInboundFrames += 1;\n this.pendingInboundBytes += byteLength;\n const handling = connection.inboundTail.then(() => this.handleGatewayMessage(connection, decoded)).then(() => void 0).catch((error) => {\n connection.failed = true;\n this.handleFrameFailure(connection, errorFromUnknown(error));\n }).finally(() => {\n connection.pendingInboundFrames -= 1;\n connection.pendingInboundBytes -= byteLength;\n this.pendingInboundFrames -= 1;\n this.pendingInboundBytes -= byteLength;\n });\n connection.inboundTail = handling;\n });\n socket.addEventListener("error", () => {\n if (this.isActiveConnection(connection)) {\n connection.socket.close(1011, "transport error");\n }\n });\n socket.addEventListener("close", () => {\n if (!this.isActiveConnection(connection)) return;\n this.clearConnectionTimers(connection);\n this.connection = null;\n this.scheduleReconnect();\n });\n }\n async handleGatewayMessage(connection, decoded) {\n if (!this.isActiveConnection(connection) || this.stopping || connection.failed) return;\n if (!decoded.ok) {\n await this.callbacks.emitEvent({ kind: "protocol_error", message: decoded.error });\n return;\n }\n const frame = decoded.frame;\n if (!hasMatchingAttempt(this.config, frame)) {\n connection.failed = true;\n connection.socket.close(1008, "attempt fence mismatch");\n return;\n }\n await this.handleGatewayFrame(connection, frame);\n }\n async handleGatewayFrame(connection, frame) {\n if (frame.type === "resume_ok") {\n if (connection.resumed) {\n this.rejectGatewayCursor(connection);\n return;\n }\n if (frame.acknowledgedEventSequence > this.store.lastEventSequence || frame.acknowledgedEventSequence < this.store.lastAcknowledgedEventSequence) {\n this.rejectGatewayCursor(connection);\n return;\n }\n const pendingCommands = [...frame.pendingCommands].sort(\n (left, right) => left.commandSequence - right.commandSequence\n );\n const resumeBatchToken = await this.commands.prepareResumeBatch(\n pendingCommands,\n frame.lastAppliedCommandSequence\n );\n let committed = false;\n try {\n if (!this.isActiveConnection(connection) || this.executionGate.isClosed) return;\n await this.store.acknowledgeEvents(frame.acknowledgedEventSequence);\n if (!this.isActiveConnection(connection) || this.executionGate.isClosed) return;\n await this.store.advanceCommandCursor(frame.lastAppliedCommandSequence);\n if (!this.isActiveConnection(connection) || this.executionGate.isClosed) return;\n committed = await this.commands.commitResumeBatch(\n resumeBatchToken,\n () => this.isActiveConnection(connection) && !this.executionGate.isClosed\n );\n } finally {\n if (!committed) await this.commands.abortResumeBatch(resumeBatchToken);\n }\n if (!committed || !this.isActiveConnection(connection) || this.executionGate.isClosed) {\n return;\n }\n if (connection.handshakeTimer) clearTimeout(connection.handshakeTimer);\n connection.handshakeTimer = null;\n connection.resumed = true;\n connection.transmittedEventSequence = frame.acknowledgedEventSequence;\n this.reconnectAttempt = 0;\n this.startHeartbeat(connection);\n this.flushOutbox(connection);\n return;\n }\n if (frame.type === "event_ack") {\n if (!connection.resumed || frame.acknowledgedEventSequence > connection.transmittedEventSequence) {\n this.rejectGatewayCursor(connection);\n return;\n }\n await this.store.acknowledgeEvents(frame.acknowledgedEventSequence);\n if (this.isActiveConnection(connection)) this.flushOutbox(connection);\n return;\n }\n if (frame.type === "command") {\n if (!connection.resumed) {\n await this.callbacks.emitEvent({\n kind: "protocol_error",\n message: "Gateway delivered a command before resume_ok."\n });\n return;\n }\n await this.commands.enqueue(frame);\n return;\n }\n if (frame.type === "attempt_superseded") {\n this.callbacks.acceptSupersession(frame.reason ?? "attempt_superseded");\n }\n }\n handleFrameFailure(connection, error) {\n if (!this.isActiveConnection(connection)) return;\n if (this.executionGate.isClosed) {\n connection.socket.close(1008, "supervisor execution closed");\n return;\n }\n void this.callbacks.emitEvent({\n kind: "protocol_error",\n message: this.redactor.redact(\n `Failed to process gateway frame: ${serializeSupervisorError(error).message}`\n )\n }).then(\n () => connection.socket.close(1011, "frame processing failed"),\n () => connection.socket.close(1011, "frame processing failed")\n );\n }\n rejectGatewayCursor(connection) {\n connection.failed = true;\n if (this.isActiveConnection(connection)) {\n connection.socket.close(1008, "invalid event cursor");\n }\n }\n startHeartbeat(connection) {\n if (connection.heartbeatTimer) clearInterval(connection.heartbeatTimer);\n this.sendHeartbeat(connection);\n connection.heartbeatTimer = setInterval(() => {\n if (!this.isActiveConnection(connection)) return;\n if (this.dependencies.now() - connection.lastGatewayActivityAt > this.config.heartbeatIntervalMs * 3) {\n connection.socket.close(4001, "gateway heartbeat stale");\n return;\n }\n this.sendHeartbeat(connection);\n this.flushOutbox(connection);\n }, this.config.heartbeatIntervalMs);\n }\n sendHeartbeat(connection) {\n if (!this.isActiveConnection(connection) || connection.failed || !connection.resumed || connection.socket.readyState !== WEBSOCKET_OPEN || connection.socket.bufferedAmount > MAX_WEBSOCKET_BUFFERED_BYTES) {\n return;\n }\n const heartbeat = {\n type: "heartbeat",\n protocolVersion: SUPERVISOR_PROTOCOL_VERSION,\n runtimeVersion: SUPERVISOR_RUNTIME_VERSION,\n sessionId: this.config.sessionId,\n runId: this.config.runId,\n attemptId: this.config.attemptId,\n sentAt: (/* @__PURE__ */ new Date()).toISOString(),\n harnessState: this.harness.state,\n outboxDepth: this.store.outboxDepth,\n lastAcknowledgedEventSequence: this.store.lastAcknowledgedEventSequence,\n lastAppliedCommandSequence: this.store.lastAppliedCommandSequence\n };\n try {\n connection.socket.send(JSON.stringify(heartbeat));\n } catch {\n connection.socket.close(1011, "heartbeat send failed");\n }\n }\n clearConnectionTimers(connection) {\n if (!connection) return;\n if (connection.handshakeTimer) clearTimeout(connection.handshakeTimer);\n if (connection.heartbeatTimer) clearInterval(connection.heartbeatTimer);\n connection.handshakeTimer = null;\n connection.heartbeatTimer = null;\n }\n isActiveConnection(connection) {\n return connection !== null && this.connection === connection && this.connection.generation === connection.generation;\n }\n scheduleReconnect() {\n if (this.stopping || this.executionGate.isClosed || this.reconnectTimer) return;\n const exponential = this.config.reconnect.initialDelayMs * this.config.reconnect.multiplier ** this.reconnectAttempt;\n const capped = Math.min(exponential, this.config.reconnect.maximumDelayMs);\n const jitter = capped * this.config.reconnect.jitterRatio;\n const delayMs = Math.max(\n 0,\n Math.round(capped - jitter + this.dependencies.random() * jitter * 2)\n );\n this.reconnectAttempt += 1;\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = null;\n try {\n this.connect();\n } catch (error) {\n if (this.stopping || this.executionGate.isClosed) return;\n this.callbacks.failTransport(errorFromUnknown(error));\n }\n }, delayMs);\n }\n};\n\n// src/supervisor/pi-sdk-harness.ts\nimport {\n constants as constants2,\n fstatSync,\n readSync,\n writeSync\n} from "node:fs";\nimport {\n lstat,\n mkdir as mkdir3,\n realpath as realpath2\n} from "node:fs/promises";\nimport { basename, dirname as dirname3, join as join4 } from "node:path";\nimport { types as nodeUtilTypes } from "node:util";\n\n// src/supervisor/pi-resource-snapshot-manager.ts\nimport { randomUUID as randomUUID3 } from "node:crypto";\nimport { constants } from "node:fs";\nimport {\n mkdir as mkdir2,\n opendir as opendir2,\n realpath,\n rm\n} from "node:fs/promises";\nimport { dirname as dirname2, join as join3 } from "node:path";\nvar DEFAULT_PI_RESOURCE_SNAPSHOT_LIMITS = {\n maximumFileBytes: 16 * 1024 * 1024,\n maximumTreeBytes: 64 * 1024 * 1024,\n maximumFiles: 4096,\n maximumDirectories: 1024,\n maximumDepth: 32,\n maximumRetainedGenerations: 8\n};\nvar DEFAULT_RESOURCE_SNAPSHOT_DEPENDENCIES = {};\nvar PI_RESOURCE_SNAPSHOT_ROOT = ".neckbeard-resource-snapshots";\nfunction resolvePiResourceSnapshotLimits(overrides) {\n const limits = { ...DEFAULT_PI_RESOURCE_SNAPSHOT_LIMITS, ...overrides };\n for (const [name, value] of Object.entries(limits)) {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw new Error(\n `Pi resource snapshot ${name} must be a positive integer.`\n );\n }\n }\n return limits;\n}\nfunction capturePiResourceSnapshotIdentity(stats) {\n return {\n device: stats.dev,\n inode: stats.ino,\n mode: stats.mode,\n uid: stats.uid,\n gid: stats.gid,\n linkCount: stats.nlink,\n size: stats.size,\n modifiedAt: stats.mtimeNs,\n changedAt: stats.ctimeNs\n };\n}\nfunction matchesPiResourceSnapshotIdentity(stats, identity) {\n return stats.dev === identity.device && stats.ino === identity.inode && stats.mode === identity.mode && stats.uid === identity.uid && stats.gid === identity.gid && stats.nlink === identity.linkCount && stats.size === identity.size && stats.mtimeNs === identity.modifiedAt && stats.ctimeNs === identity.changedAt;\n}\nasync function openPiResourceDirectory(parent, name, displayPath, expectedIdentity) {\n try {\n const directory = await openDescriptorBoundFilesystemDirectoryAt(\n { handle: parent, displayPath: dirname2(displayPath) },\n name,\n expectedIdentity\n );\n return directory.handle;\n } catch (error) {\n if (error.message.startsWith("Pi agent resource ")) throw error;\n throw new Error(\n `Pi agent resource ${displayPath} must be a real directory.`,\n {\n cause: error\n }\n );\n }\n}\nasync function assertPiResourceDirectoryEntryUnchanged(parent, name, expected, displayPath) {\n let current = null;\n try {\n const expectedStats = await expected.stat({ bigint: true });\n current = await openPiResourceDirectory(parent, name, displayPath, {\n device: expectedStats.dev,\n inode: expectedStats.ino\n });\n } catch (error) {\n throw new Error(\n `Pi resource snapshot directory ${displayPath} changed while it was being created.`,\n { cause: error }\n );\n } finally {\n await current?.close();\n }\n}\nasync function assertPiResourceFileEntryUnchanged(parent, name, expected, displayPath) {\n let current = null;\n try {\n current = await openRegularFilesystemEntryAt(\n { handle: parent },\n name,\n constants.O_RDONLY,\n `Pi resource snapshot file ${displayPath}`\n );\n if (!await matchesRetainedRegularFileIdentity(expected, current)) {\n throw new Error("file identity changed");\n }\n } catch (error) {\n throw new Error(\n `Pi resource snapshot file ${displayPath} changed while it was being created.`,\n { cause: error }\n );\n } finally {\n await current?.close();\n }\n}\nasync function assertPiResourceSnapshotNamespace(directory, manifest, displayPath) {\n try {\n const before = await directory.stat({ bigint: true });\n if (!before.isDirectory() || !matchesPiResourceSnapshotIdentity(before, manifest.identity)) {\n throw new Error("directory identity changed");\n }\n const seen = /* @__PURE__ */ new Set();\n const entries = await opendir2(descriptorBoundDirectoryPath({ handle: directory }));\n for await (const entry of entries) {\n const expected = manifest.entries.get(entry.name);\n if (expected === void 0 || seen.has(entry.name)) {\n throw new Error("directory contains an unvalidated entry");\n }\n seen.add(entry.name);\n const entryPath = join3(displayPath, entry.name);\n if (expected.kind === "directory") {\n const child = await openPiResourceDirectory(\n directory,\n entry.name,\n entryPath\n );\n try {\n await assertPiResourceSnapshotNamespace(\n child,\n expected.manifest,\n entryPath\n );\n } finally {\n await child.close();\n }\n } else {\n const child = await openRegularFilesystemEntryAt(\n { handle: directory },\n entry.name,\n constants.O_RDONLY,\n `Pi resource snapshot file ${entryPath}`\n );\n try {\n const stats = await child.stat({ bigint: true });\n if (!stats.isFile() || !matchesPiResourceSnapshotIdentity(stats, expected.identity)) {\n throw new Error("file identity changed");\n }\n } finally {\n await child.close();\n }\n }\n }\n if (seen.size !== manifest.entries.size) {\n throw new Error("directory is missing a validated entry");\n }\n const after = await directory.stat({ bigint: true });\n if (!after.isDirectory() || !matchesPiResourceSnapshotIdentity(after, manifest.identity)) {\n throw new Error("directory changed during validation");\n }\n } catch (error) {\n if (error instanceof Error && error.message.startsWith("Pi resource snapshot directory ") && error.message.endsWith(" changed while it was being created.")) {\n throw error;\n }\n throw new Error(\n `Pi resource snapshot directory ${displayPath} changed while it was being created.`,\n { cause: error }\n );\n }\n}\nasync function copyPiResourceDirectory(source, sourcePath, destination, destinationPath, dependencies, budget, depth) {\n if (depth >= budget.limits.maximumDepth) {\n throw new Error(\n `Pi agent resource directory ${sourcePath} exceeds the ${budget.limits.maximumDepth}-directory depth limit.`\n );\n }\n const sourceBefore = await source.stat({ bigint: true });\n const destinationEntries = /* @__PURE__ */ new Map();\n const entries = await opendir2(descriptorBoundDirectoryPath({ handle: source }));\n for await (const entry of entries) {\n const sourceEntryPath = join3(sourcePath, entry.name);\n const destinationEntryPath = join3(destinationPath, entry.name);\n if (entry.isSymbolicLink()) {\n throw new Error(\n `Pi agent resource ${sourceEntryPath} must not be a symbolic link.`\n );\n }\n if (entry.isDirectory()) {\n budget.directories += 1;\n if (budget.directories > budget.limits.maximumDirectories) {\n throw new Error(\n `Pi agent resource tree exceeds the ${budget.limits.maximumDirectories}-directory limit.`\n );\n }\n const child = await openPiResourceDirectory(\n source,\n entry.name,\n sourceEntryPath\n );\n let destinationChild = null;\n try {\n await dependencies.afterSourceDirectoryOpened?.(sourceEntryPath);\n await mkdir2(descriptorBoundFilesystemEntryPath({ handle: destination }, entry.name), {\n mode: 448\n });\n destinationChild = await openPiResourceDirectory(\n destination,\n entry.name,\n destinationEntryPath\n );\n await dependencies.afterDestinationDirectoryOpened?.(\n sourceEntryPath,\n destinationEntryPath\n );\n const childEntries = await copyPiResourceDirectory(\n child,\n sourceEntryPath,\n destinationChild,\n destinationEntryPath,\n dependencies,\n budget,\n depth + 1\n );\n await destinationChild.chmod(320);\n await assertPiResourceDirectoryEntryUnchanged(\n destination,\n entry.name,\n destinationChild,\n destinationEntryPath\n );\n destinationEntries.set(entry.name, {\n kind: "directory",\n manifest: {\n identity: capturePiResourceSnapshotIdentity(\n await destinationChild.stat({ bigint: true })\n ),\n entries: childEntries\n }\n });\n } finally {\n await destinationChild?.close();\n await child.close();\n }\n continue;\n }\n if (!entry.isFile()) {\n throw new Error(\n `Pi agent resource ${sourceEntryPath} must be a regular file or directory.`\n );\n }\n budget.files += 1;\n if (budget.files > budget.limits.maximumFiles) {\n throw new Error(\n `Pi agent resource tree exceeds the ${budget.limits.maximumFiles}-file limit.`\n );\n }\n const input = await openRegularFilesystemEntryAt(\n { handle: source },\n entry.name,\n constants.O_RDONLY,\n `Pi agent resource ${sourceEntryPath}`\n );\n try {\n const inputBefore = await input.stat({ bigint: true });\n if (inputBefore.size > BigInt(budget.limits.maximumFileBytes)) {\n throw new Error(\n `Pi agent resource ${sourceEntryPath} exceeds the ${budget.limits.maximumFileBytes}-byte per-file limit.`\n );\n }\n const declaredSizeBytes = Number(inputBefore.size);\n if (budget.bytes + declaredSizeBytes > budget.limits.maximumTreeBytes) {\n throw new Error(\n `Pi agent resource tree exceeds the ${budget.limits.maximumTreeBytes}-byte limit.`\n );\n }\n budget.bytes += declaredSizeBytes;\n await dependencies.afterSourceFileStat?.(\n sourceEntryPath,\n declaredSizeBytes\n );\n const output = await openRegularFilesystemEntryAt(\n { handle: destination },\n entry.name,\n constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY,\n `Pi resource snapshot file ${destinationEntryPath}`,\n 384\n );\n try {\n let position = 0;\n const buffer = Buffer.allocUnsafe(64 * 1024);\n while (position <= declaredSizeBytes) {\n const remaining = declaredSizeBytes + 1 - position;\n const { bytesRead } = await input.read(\n buffer,\n 0,\n Math.min(buffer.length, remaining),\n null\n );\n if (bytesRead === 0) break;\n if (position + bytesRead > declaredSizeBytes) {\n throw new Error(\n `Pi agent resource ${sourceEntryPath} changed while it was being snapshotted.`\n );\n }\n let written = 0;\n while (written < bytesRead) {\n const result = await output.write(\n buffer,\n written,\n bytesRead - written,\n position\n );\n if (result.bytesWritten <= 0) {\n throw new Error(\n `Pi agent resource ${sourceEntryPath} could not be copied.`\n );\n }\n written += result.bytesWritten;\n position += result.bytesWritten;\n }\n }\n if (position !== declaredSizeBytes) {\n throw new Error(\n `Pi agent resource ${sourceEntryPath} changed while it was being snapshotted.`\n );\n }\n await output.sync();\n const snapshotMode = (inputBefore.mode & 0o111n) === 0n ? 256 : 320;\n await output.chmod(snapshotMode);\n await assertPiResourceFileEntryUnchanged(\n destination,\n entry.name,\n output,\n destinationEntryPath\n );\n const inputAfter = await input.stat({ bigint: true });\n if (inputBefore.dev !== inputAfter.dev || inputBefore.ino !== inputAfter.ino || inputBefore.size !== inputAfter.size || inputBefore.mtimeNs !== inputAfter.mtimeNs || inputBefore.ctimeNs !== inputAfter.ctimeNs) {\n throw new Error(\n `Pi agent resource ${sourceEntryPath} changed while it was being snapshotted.`\n );\n }\n destinationEntries.set(entry.name, {\n kind: "file",\n identity: capturePiResourceSnapshotIdentity(\n await output.stat({ bigint: true })\n )\n });\n } finally {\n await output.close();\n }\n } finally {\n await input.close();\n }\n }\n const sourceAfter = await source.stat({ bigint: true });\n if (sourceBefore.dev !== sourceAfter.dev || sourceBefore.ino !== sourceAfter.ino || sourceBefore.mtimeNs !== sourceAfter.mtimeNs || sourceBefore.ctimeNs !== sourceAfter.ctimeNs) {\n throw new Error(\n `Pi agent resource directory ${sourcePath} changed while it was being snapshotted.`\n );\n }\n return destinationEntries;\n}\nasync function bindAgentResourceRoot(agentDir, expectedIdentity) {\n let root;\n try {\n root = await openDescriptorBoundDirectory(\n agentDir,\n expectedIdentity === void 0 ? void 0 : {\n device: expectedIdentity.device,\n inode: expectedIdentity.inode\n }\n );\n } catch (error) {\n if (expectedIdentity !== void 0 && error instanceof Error && error.message === `${agentDir} must continue to identify its original directory.`) {\n throw new Error(\n `Pi agent resource root ${agentDir} must continue to identify its original directory.`,\n { cause: error }\n );\n }\n throw new Error(\n `Pi agent resource root ${agentDir} must be a real directory.`,\n {\n cause: error\n }\n );\n }\n let identity;\n let retainRootHandle = false;\n try {\n const physicalPath = await realpath(descriptorBoundDirectoryPath(root));\n identity = {\n physicalPath,\n device: root.identity.device,\n inode: root.identity.inode,\n handle: root.handle,\n authHandle: null\n };\n if (expectedIdentity !== void 0 && physicalPath !== expectedIdentity.physicalPath) {\n throw new Error(\n `Pi agent resource root ${agentDir} must continue to identify its original directory.`\n );\n }\n if (expectedIdentity === void 0) retainRootHandle = true;\n return expectedIdentity ?? identity;\n } finally {\n if (!retainRootHandle) {\n await root.handle.close();\n }\n }\n}\nasync function adoptAgentResourceRoot(agentDir, directory) {\n try {\n const stats = await directory.handle.stat({ bigint: true });\n const expectedUid = typeof process.getuid === "function" ? BigInt(process.getuid()) : null;\n if (!stats.isDirectory() || expectedUid !== null && BigInt(stats.uid) !== expectedUid) {\n throw new Error(\n `Pi agent resource root ${agentDir} must be a process-owned real directory.`\n );\n }\n await directory.handle.chmod(448);\n await directory.handle.sync();\n const privateStats = await directory.handle.stat({ bigint: true });\n if (!privateStats.isDirectory() || (privateStats.mode & 0o777n) !== 0o700n || privateStats.dev !== stats.dev || privateStats.ino !== stats.ino || expectedUid !== null && privateStats.uid !== expectedUid) {\n throw new Error(\n `Pi agent resource root ${agentDir} must remain a process-owned private writable directory.`\n );\n }\n return {\n physicalPath: await realpath(descriptorBoundDirectoryPath(directory)),\n device: stats.dev,\n inode: stats.ino,\n handle: directory.handle,\n authHandle: null\n };\n } catch (error) {\n await directory.handle.close().catch(() => void 0);\n throw error;\n }\n}\nasync function openPiResourceSnapshotRoot(stateDurabilityAnchor, stateDir, attemptId, dependencies) {\n const parentPath = join3(stateDir, PI_RESOURCE_SNAPSHOT_ROOT);\n let parentDirectory;\n try {\n parentDirectory = await ensureDescriptorBoundDirectory(\n stateDurabilityAnchor,\n parentPath,\n 448\n );\n } catch (error) {\n throw new Error(\n `Pi resource snapshot parent ${parentPath} must be a real directory.`,\n { cause: error }\n );\n }\n const parentHandle = parentDirectory.handle;\n const path = descriptorBoundEntryPath(parentDirectory, attemptId);\n let handle = null;\n try {\n await dependencies.afterSnapshotParentBound?.(parentPath);\n const parentStats = await parentHandle.stat();\n if (!parentStats.isDirectory()) {\n throw new Error(\n `Pi resource snapshot parent ${parentPath} must be a real directory.`\n );\n }\n await parentHandle.chmod(448);\n const staleDirectory = await openDescriptorBoundDirectoryAt(\n parentDirectory,\n attemptId\n ).catch((error) => {\n if (error.code === "ENOENT") return null;\n throw error;\n });\n if (staleDirectory !== null) {\n try {\n await makePiResourceSnapshotRemovable(staleDirectory.handle);\n } finally {\n await staleDirectory.handle.close();\n }\n await rm(path, { recursive: true, force: true });\n }\n await mkdir2(path, { mode: 448 });\n handle = (await openDescriptorBoundDirectoryAt(parentDirectory, attemptId)).handle;\n await handle.chmod(448);\n return { entryName: attemptId, handle, parentHandle };\n } catch (error) {\n await handle?.close().catch(() => void 0);\n await parentHandle.close();\n throw error;\n }\n}\nasync function preparePiRuntimeAuth(agentRoot, dependencies, maximumBytes) {\n const displayPath = join3(agentRoot.physicalPath, "auth.json");\n let sourceHandle = null;\n let retained = false;\n try {\n let created = false;\n try {\n sourceHandle = await openRegularFileAt(\n { handle: agentRoot.handle },\n "auth.json",\n constants.O_RDWR | constants.O_CREAT | constants.O_EXCL,\n "Pi auth path",\n 384\n );\n created = true;\n } catch (error) {\n if (error.code !== "EEXIST") {\n throw new Error(\n `Pi auth path ${displayPath} must be a process-owned single-link regular file.`,\n { cause: error }\n );\n }\n try {\n sourceHandle = await openRegularFileAt(\n { handle: agentRoot.handle },\n "auth.json",\n constants.O_RDWR,\n "Pi auth path"\n );\n } catch (openError) {\n throw new Error(\n `Pi auth path ${displayPath} must be a process-owned single-link regular file.`,\n { cause: openError }\n );\n }\n }\n const before = await sourceHandle.stat({ bigint: true });\n const expectedUid = typeof process.getuid === "function" ? BigInt(process.getuid()) : null;\n if (!before.isFile() || before.nlink !== 1n || before.size > BigInt(maximumBytes) || expectedUid !== null && before.uid !== expectedUid) {\n throw new Error(\n `Pi auth path ${displayPath} must be a process-owned single-link regular file within the configured size limit.`\n );\n }\n if (created) await sourceHandle.writeFile("{}\\n", "utf8");\n await sourceHandle.chmod(384);\n await sourceHandle.sync();\n await agentRoot.handle.sync();\n await dependencies.afterAuthSourceOpened?.(displayPath);\n try {\n await withRevalidatedPrivateRegularFile(\n sourceHandle,\n () => openRegularFileAt(\n { handle: agentRoot.handle },\n "auth.json",\n constants.O_RDONLY,\n "Pi auth path"\n ),\n () => void 0,\n { maximumBytes, failureMessage: "auth file identity changed" }\n );\n } catch (error) {\n throw new Error(\n `Pi auth path ${displayPath} changed while its descriptor binding was created.`,\n { cause: error }\n );\n }\n agentRoot.authHandle = sourceHandle;\n sourceHandle = null;\n retained = true;\n } finally {\n if (!retained) {\n await sourceHandle?.close().catch(() => void 0);\n }\n }\n}\nasync function assertPiRuntimeAuthReady(agentRoot, maximumBytes) {\n const retained = agentRoot.authHandle;\n if (retained === null) {\n throw new Error("Pi runtime auth has not been prepared.");\n }\n try {\n await withRevalidatedPrivateRegularFile(\n retained,\n () => openRegularFileAt(\n { handle: agentRoot.handle },\n "auth.json",\n constants.O_RDONLY,\n "Pi auth path"\n ),\n () => void 0,\n { maximumBytes, failureMessage: "auth file identity changed" }\n );\n } catch (error) {\n throw new Error(\n `Pi auth path ${join3(agentRoot.physicalPath, "auth.json")} changed before SDK use.`,\n { cause: error }\n );\n }\n}\nasync function createPiResourceSnapshot(agentDir, rootIdentity, snapshotRoot, dependencies, limits) {\n const source = await bindAgentResourceRoot(agentDir, rootIdentity);\n const generation = randomUUID3();\n const snapshotPath = descriptorBoundEntryPath({ handle: snapshotRoot.handle }, generation);\n let snapshotHandle = null;\n await snapshotRoot.handle.chmod(448);\n try {\n await mkdir2(snapshotPath, { mode: 448 });\n snapshotHandle = await openPiResourceDirectory(\n snapshotRoot.handle,\n generation,\n snapshotPath\n );\n const entries = await copyPiResourceDirectory(\n source.handle,\n agentDir,\n snapshotHandle,\n snapshotPath,\n dependencies,\n { limits, files: 0, directories: 1, bytes: 0 },\n 0\n );\n await snapshotHandle.chmod(320);\n const manifest = {\n identity: capturePiResourceSnapshotIdentity(\n await snapshotHandle.stat({ bigint: true })\n ),\n entries\n };\n await assertPiResourceDirectoryEntryUnchanged(\n snapshotRoot.handle,\n generation,\n snapshotHandle,\n snapshotPath\n );\n await assertPiResourceSnapshotNamespace(\n snapshotHandle,\n manifest,\n snapshotPath\n );\n await assertPiResourceDirectoryEntryUnchanged(\n snapshotRoot.handle,\n generation,\n snapshotHandle,\n snapshotPath\n );\n await snapshotRoot.handle.chmod(320);\n return { entryName: generation, handle: snapshotHandle, manifest };\n } catch (error) {\n if (snapshotHandle !== null) {\n await makePiResourceSnapshotRemovable(snapshotHandle).catch(\n () => void 0\n );\n await snapshotHandle.close().catch(() => void 0);\n }\n await rm(snapshotPath, { recursive: true, force: true }).catch(\n () => void 0\n );\n await snapshotRoot.handle.chmod(320).catch(() => void 0);\n throw error;\n }\n}\nasync function makePiResourceSnapshotRemovable(handle) {\n const entries = await opendir2(descriptorBoundDirectoryPath({ handle }));\n for await (const entry of entries) {\n if (!entry.isDirectory() || entry.isSymbolicLink()) continue;\n const child = await openPiResourceDirectory(\n handle,\n entry.name,\n descriptorBoundFilesystemEntryPath({ handle }, entry.name)\n );\n try {\n await makePiResourceSnapshotRemovable(child);\n await child.chmod(448);\n } finally {\n await child.close();\n }\n }\n await handle.chmod(448);\n}\nasync function removePiResourceSnapshot(snapshotRoot, snapshot) {\n await snapshotRoot.handle.chmod(448);\n let failure;\n await makePiResourceSnapshotRemovable(snapshot.handle).catch(\n (error) => {\n failure ??= error;\n }\n );\n await snapshot.handle.close().catch((error) => {\n failure ??= error;\n });\n await rm(descriptorBoundEntryPath({ handle: snapshotRoot.handle }, snapshot.entryName), {\n recursive: true,\n force: true\n }).catch((error) => {\n failure ??= error;\n });\n await snapshotRoot.handle.chmod(320).catch((error) => {\n failure ??= error;\n });\n if (failure !== void 0) throw failure;\n}\nvar piResourceReloadTail = Promise.resolve();\nasync function withContainedPiResourceHome(agentDir, rootIdentity, snapshotRoot, retainedSnapshots, dependencies, limits, lifecycle, operation, preparedSnapshot) {\n const run = async () => {\n if (lifecycle.closed) {\n throw new Error("Pi resource snapshot manager is closed.");\n }\n let snapshot = preparedSnapshot;\n let createdSnapshot = false;\n if (snapshot === void 0) {\n if (retainedSnapshots.length >= limits.maximumRetainedGenerations) {\n throw new Error(\n `Pi resource reload exceeds the ${limits.maximumRetainedGenerations}-generation retention limit.`\n );\n }\n snapshot = await createPiResourceSnapshot(\n agentDir,\n rootIdentity,\n snapshotRoot,\n dependencies,\n limits\n );\n createdSnapshot = true;\n }\n const previousHome = process.env.HOME;\n const snapshotPath = descriptorBoundDirectoryPath({ handle: snapshot.handle });\n try {\n await dependencies.beforeSnapshotUse?.(snapshotPath);\n await assertPiResourceSnapshotNamespace(\n snapshot.handle,\n snapshot.manifest,\n snapshotPath\n );\n if (lifecycle.closed) {\n throw new Error("Pi resource snapshot manager is closed.");\n }\n process.env.HOME = snapshotPath;\n const result2 = await operation(snapshotPath);\n if (createdSnapshot) retainedSnapshots.push(snapshot);\n return result2;\n } catch (error) {\n if (createdSnapshot) {\n await removePiResourceSnapshot(snapshotRoot, snapshot).catch(\n () => void 0\n );\n }\n throw error;\n } finally {\n if (previousHome === void 0) delete process.env.HOME;\n else process.env.HOME = previousHome;\n }\n };\n const result = piResourceReloadTail.then(run, run);\n piResourceReloadTail = result.then(\n () => void 0,\n () => void 0\n );\n return result;\n}\nvar PI_RESOURCE_LOADER_METHODS = [\n "getExtensions",\n "getSkills",\n "getPrompts",\n "getThemes",\n "getAgentsFiles",\n "getSystemPrompt",\n "getSystemPromptSource",\n "getAppendSystemPrompt",\n "getAppendSystemPromptSources",\n "extendResources"\n];\nfunction containPiResourceLoader(createResourceLoader, agentDir, rootIdentity, snapshotRoot, retainedSnapshots, dependencies, limits, initialSnapshot, lifecycle) {\n let current = null;\n let preparedSnapshot = initialSnapshot;\n const wrapper = {\n reload: (...args) => {\n if (lifecycle.closed) {\n return Promise.reject(\n new Error("Pi resource snapshot manager is closed.")\n );\n }\n const snapshot = preparedSnapshot;\n preparedSnapshot = void 0;\n const reloading = withContainedPiResourceHome(\n agentDir,\n rootIdentity,\n snapshotRoot,\n retainedSnapshots,\n dependencies,\n limits,\n lifecycle,\n async (snapshotPath) => {\n const candidate = createResourceLoader(snapshotPath);\n await candidate.reload(...args);\n current = candidate;\n },\n snapshot\n );\n lifecycle.tail = Promise.allSettled([lifecycle.tail, reloading]).then(\n () => void 0\n );\n return reloading;\n }\n };\n for (const method of PI_RESOURCE_LOADER_METHODS) {\n wrapper[method] = (...args) => {\n if (current === null) {\n throw new Error(\n "Pi resource loader has not completed its initial reload."\n );\n }\n const candidate = current;\n const implementation = candidate[method];\n if (typeof implementation !== "function") {\n throw new Error(`Pi resource loader does not expose ${method}().`);\n }\n return Reflect.apply(implementation, current, args);\n };\n }\n return wrapper;\n}\nvar PiResourceSnapshotManager = class {\n constructor(options, dependencies = DEFAULT_RESOURCE_SNAPSHOT_DEPENDENCIES) {\n this.dependencies = dependencies;\n this.agentDir = options.agentDir;\n this.authPath = join3(options.agentDir, "auth.json");\n this.stateDir = options.stateDir;\n this.stateDurabilityAnchor = options.stateDurabilityAnchor;\n this.attemptId = options.attemptId;\n this.limits = resolvePiResourceSnapshotLimits(dependencies.limits);\n }\n dependencies;\n agentDir;\n authPath;\n stateDir;\n stateDurabilityAnchor;\n attemptId;\n limits;\n rootIdentity = null;\n snapshotRoot = null;\n retainedSnapshots = [];\n preparedSnapshot = null;\n loaderCreated = false;\n reloadLifecycle = {\n closed: false,\n tail: Promise.resolve()\n };\n closePromise = null;\n get runtimeAgentDir() {\n const snapshot = this.retainedSnapshots[0];\n if (snapshot === void 0) {\n throw new Error("Pi resource snapshot manager has not been prepared.");\n }\n return descriptorBoundDirectoryPath({ handle: snapshot.handle });\n }\n get runtimeAuthPath() {\n const identity = this.rootIdentity;\n if (identity?.authHandle === null || identity === null) {\n throw new Error("Pi resource snapshot manager has not been prepared.");\n }\n return descriptorBoundEntryPath({ handle: identity.handle }, "auth.json");\n }\n async validateRuntimeAuth() {\n const identity = this.rootIdentity;\n if (identity === null) {\n throw new Error("Pi resource snapshot manager has not been prepared.");\n }\n await assertPiRuntimeAuthReady(identity, this.limits.maximumFileBytes);\n }\n async prepare() {\n if (this.reloadLifecycle.closed || this.rootIdentity !== null || this.snapshotRoot !== null || this.preparedSnapshot !== null) {\n throw new Error("Pi resource snapshot manager is already prepared.");\n }\n const snapshotParent = join3(this.stateDir, PI_RESOURCE_SNAPSHOT_ROOT);\n if (sandboxPathsOverlap(this.agentDir, snapshotParent)) {\n throw new Error(\n "Pi agent resource directory must not overlap its snapshot directory."\n );\n }\n const agentDirectory = await ensureDescriptorBoundDirectory(\n this.stateDurabilityAnchor,\n this.agentDir\n );\n let rootIdentity;\n try {\n await this.dependencies.afterAgentRootBound?.(this.agentDir);\n rootIdentity = await adoptAgentResourceRoot(\n this.agentDir,\n agentDirectory\n );\n } catch (error) {\n await agentDirectory.handle.close().catch(() => void 0);\n throw error;\n }\n this.rootIdentity = rootIdentity;\n const snapshotRoot = await openPiResourceSnapshotRoot(\n this.stateDurabilityAnchor,\n this.stateDir,\n this.attemptId,\n this.dependencies\n );\n this.snapshotRoot = snapshotRoot;\n await preparePiRuntimeAuth(\n rootIdentity,\n this.dependencies,\n this.limits.maximumFileBytes\n );\n const initialSnapshot = await createPiResourceSnapshot(\n this.agentDir,\n rootIdentity,\n snapshotRoot,\n this.dependencies,\n this.limits\n );\n this.retainedSnapshots.push(initialSnapshot);\n this.preparedSnapshot = initialSnapshot;\n }\n createResourceLoader(createResourceLoader) {\n if (this.loaderCreated) {\n throw new Error("Pi resource loader has already been created.");\n }\n const rootIdentity = this.rootIdentity;\n const snapshotRoot = this.snapshotRoot;\n const initialSnapshot = this.preparedSnapshot;\n if (rootIdentity === null || snapshotRoot === null || initialSnapshot === null) {\n throw new Error("Pi resource snapshot manager has not been prepared.");\n }\n this.loaderCreated = true;\n this.preparedSnapshot = null;\n return containPiResourceLoader(\n createResourceLoader,\n this.agentDir,\n rootIdentity,\n snapshotRoot,\n this.retainedSnapshots,\n this.dependencies,\n this.limits,\n initialSnapshot,\n this.reloadLifecycle\n );\n }\n async close() {\n if (this.closePromise !== null) return this.closePromise;\n this.reloadLifecycle.closed = true;\n const closing = this.closePreparedState();\n this.closePromise = closing;\n return closing;\n }\n async closePreparedState() {\n await this.reloadLifecycle.tail;\n const identity = this.rootIdentity;\n this.rootIdentity = null;\n const snapshotRoot = this.snapshotRoot;\n this.snapshotRoot = null;\n this.preparedSnapshot = null;\n const snapshots = this.retainedSnapshots.splice(0);\n let failure;\n for (const snapshot of snapshots) {\n try {\n await snapshot.handle.close();\n } catch (error) {\n failure ??= error;\n await snapshot.handle.close().catch(() => void 0);\n }\n }\n if (snapshotRoot !== null) {\n await makePiResourceSnapshotRemovable(snapshotRoot.handle).catch(\n (error) => {\n failure ??= error;\n }\n );\n await snapshotRoot.handle.close().catch((error) => {\n failure ??= error;\n });\n await rm(\n descriptorBoundEntryPath(\n { handle: snapshotRoot.parentHandle },\n snapshotRoot.entryName\n ),\n { recursive: true, force: true }\n ).catch((error) => {\n failure ??= error;\n });\n await snapshotRoot.parentHandle.close().catch((error) => {\n failure ??= error;\n });\n }\n if (identity?.authHandle !== null && identity !== null) {\n await identity.authHandle.sync().catch((error) => {\n failure ??= error;\n });\n await identity.authHandle.close().catch((error) => {\n failure ??= error;\n });\n identity.authHandle = null;\n await identity.handle.sync().catch((error) => {\n failure ??= error;\n });\n }\n await identity?.handle.close().catch((error) => {\n failure ??= error;\n });\n if (failure !== void 0) throw failure;\n }\n};\n\n// src/supervisor/pi-sdk-harness.ts\nvar MAX_PERSISTED_PI_EVENT_PAYLOAD_BYTES = 512 * 1024;\nvar MAX_TRUNCATED_PI_EVENT_PAYLOAD_BYTES = 32 * 1024;\nvar MAX_PI_EVENT_METADATA_STRING_LENGTH = 256;\nvar MAX_PI_EVENT_LIFECYCLE_STRING_LENGTH = 8 * 1024;\nvar MAX_PI_EVENT_LIFECYCLE_MESSAGE_SCAN = 4 * 1024;\nvar MAX_PI_EVENT_TRAVERSAL_DEPTH = 64;\nvar MAX_PI_EVENT_TRAVERSAL_NODES = MAX_PERSISTED_PI_EVENT_PAYLOAD_BYTES;\nvar MAX_PENDING_HARNESS_EVENTS = 256;\nvar MAX_PENDING_HARNESS_EVENT_BYTES = 8 * 1024 * 1024;\nvar PI_EVENT_SCALAR_METADATA_KEYS = [\n "type",\n "id",\n "eventId",\n "messageId",\n "toolCallId",\n "toolName",\n "role",\n "stopReason",\n "provider",\n "model",\n "timestamp",\n "contentIndex",\n "isError"\n];\nvar PI_EVENT_NESTED_METADATA_KEYS = [\n "assistantMessageEvent",\n "message",\n "usage",\n "result"\n];\nvar PI_EVENT_ARRAY_METADATA_KEYS = [\n "messages",\n "toolResults",\n "content"\n];\nvar SESSION_FILE_CREATE_FLAGS = constants2.O_RDWR | constants2.O_CREAT;\nvar PI_SESSION_FORMAT_VERSION = 3;\nvar MAX_PI_SESSION_HEADER_BYTES = 64 * 1024;\nfunction piSessionHistoryLimitError(limitBytes, context) {\n return new Error(\n `Pi session history ${context} the ${limitBytes}-byte per-attempt limit; start a replacement attempt.`\n );\n}\nfunction assertPiSessionHistorySize(stats, limitBytes, comparison, context) {\n const limit = BigInt(limitBytes);\n const exceeded = comparison === "at_or_above" ? stats.size >= limit : stats.size > limit;\n if (exceeded) throw piSessionHistoryLimitError(limitBytes, context);\n}\nfunction assertPiSessionHistoryReadyForSdkOpen(handle, displayPath) {\n const stats = fstatSync(handle.fd, { bigint: true });\n assertPiSessionHistorySize(\n stats,\n SUPERVISOR_MAX_PI_SESSION_HISTORY_BYTES,\n "above",\n "exceeds"\n );\n if (stats.size === 0n) return;\n const scanBytes = Math.min(\n Number(stats.size),\n MAX_PI_SESSION_HEADER_BYTES + 1\n );\n const buffer = Buffer.allocUnsafe(scanBytes);\n let offset = 0;\n while (offset < scanBytes) {\n const bytesRead = readSync(\n handle.fd,\n buffer,\n offset,\n scanBytes - offset,\n offset\n );\n if (bytesRead === 0) {\n throw new Error(\n `Pi session path ${displayPath} changed while its header was validated.`\n );\n }\n offset += bytesRead;\n }\n const newline = buffer.indexOf(10, 0);\n const headerBytes = newline === -1 ? offset : newline;\n if (headerBytes > MAX_PI_SESSION_HEADER_BYTES || newline === -1 && stats.size > BigInt(MAX_PI_SESSION_HEADER_BYTES)) {\n throw new Error(\n `Pi session path ${displayPath} has an oversized session header.`\n );\n }\n let source;\n try {\n source = new TextDecoder("utf-8", { fatal: true }).decode(\n buffer.subarray(0, headerBytes)\n );\n } catch (error) {\n throw new Error(\n `Pi session path ${displayPath} has an invalid session header.`,\n { cause: error }\n );\n }\n if (source.endsWith("\\r")) source = source.slice(0, -1);\n let header;\n try {\n header = JSON.parse(source);\n } catch (error) {\n throw new Error(\n `Pi session path ${displayPath} has an invalid session header.`,\n { cause: error }\n );\n }\n if (!isRecord5(header) || header.type !== "session" || header.version !== PI_SESSION_FORMAT_VERSION) {\n throw new Error(\n `Pi session path ${displayPath} must use current Pi session format version ${PI_SESSION_FORMAT_VERSION}; start a replacement attempt for legacy history.`\n );\n }\n}\nasync function openPiSessionFile(directory, name, displayPath, flags, mode) {\n try {\n return await openRegularFileAt(\n directory,\n name,\n flags,\n `Pi session path ${displayPath}`,\n mode\n );\n } catch (error) {\n if (error.code === "ELOOP") {\n throw new Error(\n `Pi session path ${displayPath} must not be a symbolic link.`,\n { cause: error }\n );\n }\n throw error;\n }\n}\nasync function preparePiSessionFile(directory, name, displayPath) {\n const handle = await openPiSessionFile(\n directory,\n name,\n displayPath,\n SESSION_FILE_CREATE_FLAGS,\n 384\n );\n try {\n const before = await handle.stat({ bigint: true });\n const expectedUid = typeof process.getuid === "function" ? BigInt(process.getuid()) : null;\n if (!before.isFile() || before.nlink !== 1n || expectedUid !== null && before.uid !== expectedUid) {\n throw new Error(\n `Pi session path ${displayPath} must be a process-owned single-link regular file.`\n );\n }\n assertPiSessionHistorySize(\n before,\n SUPERVISOR_MAX_PI_SESSION_HISTORY_BYTES,\n "above",\n "exceeds"\n );\n await handle.chmod(384);\n const after = await handle.stat({ bigint: true });\n if (!after.isFile() || after.dev !== before.dev || after.ino !== before.ino || after.nlink !== 1n || expectedUid !== null && after.uid !== expectedUid) {\n throw new Error(\n `Pi session path ${displayPath} must remain a process-owned single-link regular file.`\n );\n }\n assertPiSessionHistorySize(\n after,\n SUPERVISOR_MAX_PI_SESSION_HISTORY_BYTES,\n "above",\n "exceeds"\n );\n await handle.sync();\n await syncDescriptorBoundDirectory(directory);\n return handle;\n } catch (error) {\n await handle.close();\n throw error;\n }\n}\nasync function withPiSessionFileReady(directory, name, handle, displayPath, operation) {\n return withRevalidatedPrivateRegularFile(\n handle,\n () => openPiSessionFile(\n directory,\n name,\n displayPath,\n constants2.O_RDONLY\n ),\n // The helper keeps the matching path descriptor open and invokes this\n // synchronous SDK open without yielding after its final identity checks.\n operation,\n {\n maximumBytes: SUPERVISOR_MAX_PI_SESSION_HISTORY_BYTES,\n failureMessage: `Pi session path ${displayPath} must remain the process-owned single-link private regular file bound at startup.`\n }\n );\n}\nasync function assertWorkspaceIsolated(workspaceDir, stateDir) {\n const workspaceStats = await lstat(workspaceDir);\n if (workspaceStats.isSymbolicLink() || !workspaceStats.isDirectory()) {\n throw new Error(\n `Pi workspace path ${workspaceDir} must be a real directory.`\n );\n }\n const [physicalWorkspace, physicalState] = await Promise.all([\n realpath2(workspaceDir),\n realpath2(stateDir)\n ]);\n if (sandboxPathsOverlap(physicalWorkspace, physicalState)) {\n throw new Error(\n "Pi workspace and supervisor state directories must not physically overlap."\n );\n }\n}\nfunction hasCallableProperty(value, property) {\n if ((typeof value !== "object" || value === null || Array.isArray(value)) && typeof value !== "function") {\n return false;\n }\n return typeof value[property] === "function";\n}\nfunction attachFilesToMessage(input) {\n if (!input.attachments?.length) return input.message;\n const files = input.attachments.map((attachment) => `- ${attachment.path}`).join("\\n");\n return `${input.message}\n\nFiles available in the sandbox:\n${files}`;\n}\nfunction isCoalescedPiEvent(value) {\n if (typeof value !== "object" || value === null || nodeUtilTypes.isProxy(value)) {\n return false;\n }\n const event = value;\n if (readPiLifecycleProperty(event, "type") !== "message_update") return false;\n const assistantEvent = readPiLifecycleProperty(\n event,\n "assistantMessageEvent"\n );\n if (!isRecord5(assistantEvent) || nodeUtilTypes.isProxy(assistantEvent)) {\n return false;\n }\n const assistantEventType = readPiLifecycleProperty(assistantEvent, "type");\n return typeof assistantEventType === "string" && assistantEventType.endsWith("_delta");\n}\nfunction assertPiSdkModule(value) {\n if (!isRecord5(value) || !hasCallableProperty(value.ModelRuntime, "create") || !hasCallableProperty(value.SessionManager, "open") || !hasCallableProperty(value.SettingsManager, "inMemory") || typeof value.DefaultResourceLoader !== "function" || typeof value.createAgentSession !== "function") {\n throw new Error(\n "The configured Pi SDK module does not expose the required session API."\n );\n }\n}\nfunction assertPiSdkSession(value) {\n if (!isRecord5(value) || typeof value.sessionId !== "string" || typeof value.prompt !== "function" || typeof value.steer !== "function" || typeof value.abort !== "function" || typeof value.dispose !== "function" || typeof value.subscribe !== "function") {\n throw new Error("Pi createAgentSession returned an invalid session.");\n }\n}\nfunction assertPiSdkSessionManager(value) {\n const flushed = isRecord5(value) ? Object.getOwnPropertyDescriptor(value, "flushed") : void 0;\n if (!isRecord5(value) || flushed?.value !== true || typeof value._persist !== "function" || typeof value.getSessionFile !== "function") {\n throw new Error(\n "The configured Pi SDK SessionManager does not expose the pinned persistent-session API."\n );\n }\n}\nfunction boundedMetadataString(value) {\n if (value.length <= MAX_PI_EVENT_METADATA_STRING_LENGTH) return value;\n return `${value.slice(0, MAX_PI_EVENT_METADATA_STRING_LENGTH - 3)}...`;\n}\nfunction copyPiEventScalarMetadata(source, target) {\n if (nodeUtilTypes.isProxy(source)) return;\n for (const key of PI_EVENT_SCALAR_METADATA_KEYS) {\n const item = source[key];\n if (typeof item === "string") {\n target[key] = boundedMetadataString(item);\n } else if (item === null || typeof item === "boolean" || typeof item === "number" && Number.isFinite(item)) {\n target[key] = item;\n }\n }\n}\nfunction summarizePiEventMetadata(value) {\n if (!isRecord5(value) || nodeUtilTypes.isProxy(value)) return {};\n const summary = /* @__PURE__ */ Object.create(null);\n copyPiEventScalarMetadata(value, summary);\n for (const key of PI_EVENT_NESTED_METADATA_KEYS) {\n const item = value[key];\n if (!isRecord5(item) || nodeUtilTypes.isProxy(item)) continue;\n const nested = /* @__PURE__ */ Object.create(null);\n copyPiEventScalarMetadata(item, nested);\n if (Object.keys(nested).length > 0) summary[key] = nested;\n }\n for (const key of PI_EVENT_ARRAY_METADATA_KEYS) {\n const item = value[key];\n if (Array.isArray(item) && !nodeUtilTypes.isProxy(item)) {\n summary[`${key}Count`] = item.length;\n }\n }\n return summary;\n}\nfunction truncatedPiEvent(event, reason, redactor, originalPayloadBytes) {\n let metadata;\n try {\n metadata = redactJsonStrings(\n summarizePiEventMetadata(event),\n redactor\n );\n } catch {\n metadata = {};\n }\n const truncation = {\n truncated: true,\n reason,\n maxPayloadBytes: MAX_PERSISTED_PI_EVENT_PAYLOAD_BYTES,\n ...originalPayloadBytes === void 0 ? {} : { originalPayloadBytes }\n };\n const candidate = {\n ...metadata,\n neckbeardTruncation: truncation\n };\n if (Buffer.byteLength(JSON.stringify(candidate), "utf8") <= MAX_TRUNCATED_PI_EVENT_PAYLOAD_BYTES) {\n return candidate;\n }\n return {\n ...typeof metadata.type === "string" ? { type: metadata.type } : {},\n neckbeardTruncation: truncation\n };\n}\nfunction redactJsonStrings(value, redactor) {\n if (typeof value === "string") return redactor.redact(value);\n if (typeof value === "object" && value !== null && nodeUtilTypes.isProxy(value)) {\n return void 0;\n }\n if (Array.isArray(value))\n return value.map((item) => redactJsonStrings(item, redactor));\n if (!isRecord5(value)) return value;\n const redacted = /* @__PURE__ */ Object.create(null);\n for (const [key, item] of Object.entries(value)) {\n redacted[redactor.redact(key)] = redactJsonStrings(item, redactor);\n }\n return redacted;\n}\nvar PiEventTraversalLimitError = class extends Error {\n};\nvar PiEventSerializationError = class extends Error {\n};\nfunction consumePiEventTraversalNode(writer) {\n writer.visitedNodes += 1;\n if (writer.visitedNodes > MAX_PI_EVENT_TRAVERSAL_NODES) {\n throw new PiEventTraversalLimitError();\n }\n}\nfunction appendPiEventJson(writer, chunk) {\n const remainingBytes = MAX_PERSISTED_PI_EVENT_PAYLOAD_BYTES - writer.sizeBytes;\n if (chunk.length > remainingBytes) throw new PiEventTraversalLimitError();\n const chunkBytes = Buffer.byteLength(chunk, "utf8");\n if (chunkBytes > remainingBytes) throw new PiEventTraversalLimitError();\n writer.chunks.push(chunk);\n writer.sizeBytes += chunkBytes;\n}\nfunction appendRedactedPiEventString(writer, value) {\n const remainingBytes = MAX_PERSISTED_PI_EVENT_PAYLOAD_BYTES - writer.sizeBytes;\n if (value.length + 2 > remainingBytes)\n throw new PiEventTraversalLimitError();\n const redacted = writer.redactor.redact(value);\n if (redacted.length + 2 > remainingBytes)\n throw new PiEventTraversalLimitError();\n appendPiEventJson(writer, JSON.stringify(redacted));\n}\nfunction readPiEventProperty(value, key) {\n try {\n return Reflect.get(value, key);\n } catch {\n throw new PiEventSerializationError();\n }\n}\nfunction writePiEventJsonValue(writer, value, key, depth, applyToJson = true) {\n consumePiEventTraversalNode(writer);\n if (value === null) {\n appendPiEventJson(writer, "null");\n return true;\n }\n if (typeof value === "string") {\n appendRedactedPiEventString(writer, value);\n return true;\n }\n if (typeof value === "boolean") {\n appendPiEventJson(writer, value ? "true" : "false");\n return true;\n }\n if (typeof value === "number") {\n appendPiEventJson(writer, Number.isFinite(value) ? JSON.stringify(value) : "null");\n return true;\n }\n if (value === void 0 || typeof value === "function" || typeof value === "symbol") {\n return false;\n }\n if (typeof value === "bigint") {\n const boxed = Object(value);\n const toJSON = readPiEventProperty(boxed, "toJSON");\n if (typeof toJSON !== "function") throw new PiEventSerializationError();\n let normalized;\n try {\n normalized = Reflect.apply(toJSON, value, [key]);\n } catch {\n throw new PiEventSerializationError();\n }\n return writePiEventJsonValue(writer, normalized, key, depth, false);\n }\n if (typeof value !== "object") throw new PiEventSerializationError();\n if (depth > MAX_PI_EVENT_TRAVERSAL_DEPTH)\n throw new PiEventTraversalLimitError();\n if (nodeUtilTypes.isProxy(value)) throw new PiEventSerializationError();\n if (applyToJson) {\n const toJSON = readPiEventProperty(value, "toJSON");\n if (typeof toJSON === "function") {\n let normalized;\n try {\n normalized = Reflect.apply(toJSON, value, [key]);\n } catch {\n throw new PiEventSerializationError();\n }\n return writePiEventJsonValue(writer, normalized, key, depth, false);\n }\n }\n if (nodeUtilTypes.isNumberObject(value)) {\n return writePiEventJsonValue(writer, Number(value), key, depth, false);\n }\n if (nodeUtilTypes.isStringObject(value)) {\n return writePiEventJsonValue(writer, String(value), key, depth, false);\n }\n if (nodeUtilTypes.isBooleanObject(value)) {\n return writePiEventJsonValue(writer, Boolean(value.valueOf()), key, depth, false);\n }\n if (nodeUtilTypes.isBigIntObject(value)) {\n throw new PiEventSerializationError();\n }\n if (writer.activeObjects.has(value)) throw new PiEventSerializationError();\n writer.activeObjects.add(value);\n try {\n if (Array.isArray(value)) {\n appendPiEventJson(writer, "[");\n for (let index = 0; index < value.length; index += 1) {\n consumePiEventTraversalNode(writer);\n if (index > 0) appendPiEventJson(writer, ",");\n const item = readPiEventProperty(value, String(index));\n if (!writePiEventJsonValue(writer, item, String(index), depth + 1)) {\n appendPiEventJson(writer, "null");\n }\n }\n appendPiEventJson(writer, "]");\n return true;\n }\n appendPiEventJson(writer, "{");\n let wroteProperty = false;\n try {\n for (const property in value) {\n consumePiEventTraversalNode(writer);\n if (!Object.hasOwn(value, property)) continue;\n const item = readPiEventProperty(value, property);\n const checkpointChunks = writer.chunks.length;\n const checkpointBytes = writer.sizeBytes;\n if (wroteProperty) appendPiEventJson(writer, ",");\n appendRedactedPiEventString(writer, property);\n appendPiEventJson(writer, ":");\n if (writePiEventJsonValue(writer, item, property, depth + 1)) {\n wroteProperty = true;\n } else {\n writer.chunks.length = checkpointChunks;\n writer.sizeBytes = checkpointBytes;\n }\n }\n } catch (error) {\n if (error instanceof PiEventTraversalLimitError || error instanceof PiEventSerializationError) {\n throw error;\n }\n throw new PiEventSerializationError();\n }\n appendPiEventJson(writer, "}");\n return true;\n } finally {\n writer.activeObjects.delete(value);\n }\n}\nfunction serializeBoundedPiEvent(event, redactor) {\n const writer = {\n chunks: [],\n activeObjects: /* @__PURE__ */ new WeakSet(),\n redactor,\n sizeBytes: 0,\n visitedNodes: 0\n };\n if (!writePiEventJsonValue(writer, event, "", 0)) {\n throw new PiEventSerializationError();\n }\n return writer.chunks.join("");\n}\nfunction jsonSafePiEvent(event, redactor) {\n try {\n return JSON.parse(serializeBoundedPiEvent(event, redactor));\n } catch (error) {\n if (error instanceof PiEventTraversalLimitError) {\n return truncatedPiEvent(event, "payload_exceeded_limit", redactor);\n }\n return truncatedPiEvent(event, "payload_not_json_serializable", redactor);\n }\n}\nfunction finiteNonnegative(value) {\n return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;\n}\nfunction nonnegativeInteger(value) {\n return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0;\n}\nfunction usageFromAssistantMessage(message) {\n if (!message || !isRecord5(message.usage)) return void 0;\n const usage = message.usage;\n const inputTokens = nonnegativeInteger(usage.input);\n const outputTokens = nonnegativeInteger(usage.output);\n const cacheReadTokens = nonnegativeInteger(usage.cacheRead);\n const cacheWriteTokens = nonnegativeInteger(usage.cacheWrite);\n const reportedTotal = nonnegativeInteger(usage.totalTokens);\n const calculatedTotal = inputTokens + outputTokens + cacheReadTokens + cacheWriteTokens;\n const totalTokens = reportedTotal || (Number.isSafeInteger(calculatedTotal) ? calculatedTotal : Number.MAX_SAFE_INTEGER);\n const totalCost = isRecord5(usage.cost) ? finiteNonnegative(usage.cost.total) : 0;\n return {\n inputTokens,\n outputTokens,\n cacheReadTokens,\n cacheWriteTokens,\n totalTokens,\n ...totalCost === 0 ? {} : { costUsd: totalCost }\n };\n}\nfunction lastAssistantMessage(messages) {\n if (!Array.isArray(messages) || nodeUtilTypes.isProxy(messages)) return null;\n const minimumIndex = Math.max(\n 0,\n messages.length - MAX_PI_EVENT_LIFECYCLE_MESSAGE_SCAN\n );\n for (let index = messages.length - 1; index >= minimumIndex; index -= 1) {\n const message = boundedAssistantMessage(\n readPiLifecycleProperty(messages, String(index))\n );\n if (message?.role === "assistant") return message;\n }\n return null;\n}\nfunction boundedLifecycleString(value) {\n return value.length <= MAX_PI_EVENT_LIFECYCLE_STRING_LENGTH ? value : `${value.slice(0, MAX_PI_EVENT_LIFECYCLE_STRING_LENGTH - 3)}...`;\n}\nfunction readPiLifecycleProperty(value, property) {\n try {\n let current = value;\n for (let depth = 0; current !== null && depth < 4; depth += 1) {\n if (nodeUtilTypes.isProxy(current)) return void 0;\n const descriptor = Object.getOwnPropertyDescriptor(current, property);\n if (descriptor) {\n return "value" in descriptor ? descriptor.value : void 0;\n }\n current = Object.getPrototypeOf(current);\n }\n return void 0;\n } catch {\n return void 0;\n }\n}\nfunction boundedAssistantMessage(value) {\n if (!isRecord5(value) || nodeUtilTypes.isProxy(value)) return null;\n const bounded = /* @__PURE__ */ Object.create(null);\n for (const property of ["role", "stopReason", "errorMessage"]) {\n const item = readPiLifecycleProperty(value, property);\n if (typeof item === "string") bounded[property] = boundedLifecycleString(item);\n }\n const usage = readPiLifecycleProperty(value, "usage");\n if (isRecord5(usage) && !nodeUtilTypes.isProxy(usage)) {\n const boundedUsage = /* @__PURE__ */ Object.create(null);\n for (const property of [\n "input",\n "output",\n "cacheRead",\n "cacheWrite",\n "totalTokens"\n ]) {\n const item = readPiLifecycleProperty(usage, property);\n if (typeof item === "number" && Number.isFinite(item)) {\n boundedUsage[property] = item;\n }\n }\n const cost = readPiLifecycleProperty(usage, "cost");\n if (isRecord5(cost) && !nodeUtilTypes.isProxy(cost)) {\n const total = readPiLifecycleProperty(cost, "total");\n if (typeof total === "number" && Number.isFinite(total)) {\n boundedUsage.cost = { total };\n }\n }\n bounded.usage = boundedUsage;\n }\n return bounded;\n}\nfunction boundedLifecycleFailure(value) {\n let isError = false;\n try {\n isError = value instanceof Error;\n } catch {\n return new Error("Pi turn failed.");\n }\n if (isError && typeof value === "object" && value !== null) {\n const record = value;\n const message = readPiLifecycleProperty(record, "message");\n const name = readPiLifecycleProperty(record, "name");\n const stack = readPiLifecycleProperty(record, "stack");\n const bounded = new Error(\n typeof message === "string" ? boundedLifecycleString(message) : "Pi turn failed."\n );\n if (typeof name === "string") {\n bounded.name = boundedLifecycleString(name);\n }\n if (typeof stack === "string") {\n bounded.stack = boundedLifecycleString(stack);\n }\n return bounded;\n }\n if (typeof value === "string") return boundedLifecycleString(value);\n return new Error("Pi turn failed.");\n}\nvar PiSdkHarnessAdapter = class {\n constructor(config, executionGate = new SupervisorExecutionGate(), redactor = new SensitiveValueRedactor(), dependencies = {}) {\n this.config = config;\n this.executionGate = executionGate;\n this.redactor = redactor;\n this.dependencies = dependencies;\n assertSupervisorHarnessPathOwnership(\n config.stateDir,\n config.harness.sessionPath,\n config.harness.agentDir\n );\n this.resourceSnapshotManager = new PiResourceSnapshotManager(\n {\n agentDir: config.harness.agentDir ?? join4(config.stateDir, "pi/agent"),\n stateDir: config.stateDir,\n stateDurabilityAnchor: config.stateDurabilityAnchor,\n attemptId: config.attemptId\n },\n dependencies\n );\n }\n config;\n executionGate;\n redactor;\n dependencies;\n name = "pi-sdk";\n state = "idle";\n listeners = /* @__PURE__ */ new Set();\n session = null;\n unsubscribe = null;\n startPromise = null;\n stopPromise = null;\n activeTurn = null;\n eventQueue = [];\n eventQueueBytes = 0;\n eventPump = null;\n eventFailure = null;\n commandApplied = /* @__PURE__ */ new Set();\n commandAppliedWaiters = /* @__PURE__ */ new Map();\n resourceSnapshotManager;\n sessionDirectory = null;\n sessionFile = null;\n sessionHistoryFailure = null;\n subscribe(listener) {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n async start() {\n this.executionGate.throwIfClosed();\n if (this.state === "running") return;\n if (this.startPromise) return this.startPromise;\n if (this.state !== "idle") {\n throw new Error(`Pi cannot start while harness state is ${this.state}.`);\n }\n const starting = this.startSession();\n this.startPromise = starting;\n try {\n await starting;\n } finally {\n if (this.startPromise === starting) this.startPromise = null;\n }\n }\n async prompt(input) {\n this.executionGate.throwIfClosed();\n await this.start();\n this.executionGate.throwIfClosed();\n const session = this.session;\n if (!session) throw new Error("Pi SDK session is unavailable.");\n if (this.activeTurn || session.isStreaming) {\n throw new Error(\n "Pi already has an active turn; use a steer command instead."\n );\n }\n await this.assertSessionHistoryPromptCapacity();\n this.executionGate.throwIfClosed();\n const turn = {\n commandId: input.commandId,\n run: null,\n terminalTask: null,\n terminalClaim: null,\n terminalFinalized: false,\n started: false,\n latestAssistantMessage: null\n };\n this.activeTurn = turn;\n let preflightSettled = false;\n let preflightAccepted = false;\n let resolvePreflight;\n let rejectPreflight;\n const preflight = new Promise((resolveAccepted, rejectAccepted) => {\n resolvePreflight = resolveAccepted;\n rejectPreflight = rejectAccepted;\n });\n let run;\n try {\n this.assertSessionHistoryPromptCapacitySync();\n this.executionGate.throwIfClosed();\n run = session.prompt(attachFilesToMessage(input), {\n preflightResult: (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';
22
+ var SUPERVISOR_RUNTIME_SOURCE = '// src/supervisor/runtime-entry.ts\nimport {\n closeSync,\n constants as fsConstants4,\n ftruncateSync,\n fstatSync as fstatSync2,\n readSync as readSync2\n} from "node:fs";\nimport { access, readFile } from "node:fs/promises";\nimport { resolve } from "node:path";\nimport { pathToFileURL } from "node:url";\n\n// src/sandbox-capabilities.ts\nvar SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV = "NECKBEARD_SUPERVISOR_ENVIRONMENT_V1";\nvar SUPERVISOR_ENVIRONMENT_FD_ENV = "NECKBEARD_SUPERVISOR_ENVIRONMENT_FD";\nvar SUPERVISOR_ENVIRONMENT_FD = 3;\nvar SUPERVISOR_ENVIRONMENT_MAX_BYTES = 64 * 1024;\nvar SUPERVISOR_ENVIRONMENT_MAX_ENTRIES = 256;\nvar SUPERVISOR_ENVIRONMENT_MAX_NAME_BYTES = 256;\nvar SUPERVISOR_ENVIRONMENT_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/u;\nfunction supervisorEnvironmentByteLength(value) {\n return new TextEncoder().encode(value).byteLength;\n}\nfunction isRecord(value) {\n if (typeof value !== "object" || value === null) return false;\n try {\n return !Array.isArray(value);\n } catch {\n return false;\n }\n}\nfunction normalizeSupervisorEnvironment(value) {\n if (!isRecord(value)) return { ok: false, reason: "invalid_environment" };\n let entries;\n try {\n entries = Object.entries(value).sort(\n ([left], [right]) => left < right ? -1 : left > right ? 1 : 0\n );\n } catch {\n return { ok: false, reason: "invalid_environment" };\n }\n if (entries.length > SUPERVISOR_ENVIRONMENT_MAX_ENTRIES) {\n return { ok: false, reason: "entry_limit" };\n }\n const environment = /* @__PURE__ */ Object.create(null);\n let environmentBytes = 0;\n let exceedsByteLimit = false;\n for (const [name, item] of entries) {\n if (name.length > SUPERVISOR_ENVIRONMENT_MAX_NAME_BYTES || !SUPERVISOR_ENVIRONMENT_NAME_PATTERN.test(name) || name === SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV || name === SUPERVISOR_ENVIRONMENT_FD_ENV) {\n return { ok: false, reason: "invalid_name" };\n }\n if (typeof item !== "string" || item.includes("\\0")) {\n return { ok: false, reason: "invalid_value" };\n }\n if (!exceedsByteLimit) {\n if (item.length > SUPERVISOR_ENVIRONMENT_MAX_BYTES || environmentBytes + name.length + item.length > SUPERVISOR_ENVIRONMENT_MAX_BYTES) {\n exceedsByteLimit = true;\n } else {\n environmentBytes += name.length + supervisorEnvironmentByteLength(item);\n if (environmentBytes > SUPERVISOR_ENVIRONMENT_MAX_BYTES) {\n exceedsByteLimit = true;\n }\n }\n }\n environment[name] = item;\n }\n if (exceedsByteLimit) return { ok: false, reason: "byte_limit" };\n return {\n ok: true,\n environment,\n environmentKeys: entries.map(([name]) => name)\n };\n}\nfunction deserializeSupervisorEnvironmentHandoff(source) {\n if (typeof source !== "string" || source.length === 0 || source.length > SUPERVISOR_ENVIRONMENT_MAX_BYTES || supervisorEnvironmentByteLength(source) > SUPERVISOR_ENVIRONMENT_MAX_BYTES) {\n return { ok: false, reason: "invalid_payload" };\n }\n let value;\n try {\n value = JSON.parse(source);\n } catch {\n return { ok: false, reason: "invalid_payload" };\n }\n if (!isRecord(value) || value.version !== 1 || !isRecord(value.environment) || Object.keys(value).length !== 2 || !Object.hasOwn(value, "version") || !Object.hasOwn(value, "environment")) {\n return { ok: false, reason: "invalid_payload" };\n }\n const normalized = normalizeSupervisorEnvironment(value.environment);\n return normalized.ok ? { ...normalized, payload: source } : normalized;\n}\n\n// src/supervisor/protocol.ts\nimport { createHash } from "node:crypto";\n\n// src/serialized-error.ts\nfunction isSerializedError(value) {\n if (typeof value !== "object" || value === null || Array.isArray(value)) return false;\n const candidate = value;\n return typeof candidate.message === "string" && (candidate.name === void 0 || typeof candidate.name === "string") && (candidate.stack === void 0 || typeof candidate.stack === "string");\n}\nfunction serializeError(error) {\n if (error instanceof Error) {\n return {\n name: error.name,\n message: error.message,\n ...error.stack === void 0 ? {} : { stack: error.stack }\n };\n }\n return { message: String(error) };\n}\n\n// src/supervisor/runtime-limits.ts\nvar SUPERVISOR_CREDENTIAL_BYTE_LENGTH = 32;\nvar SUPERVISOR_CREDENTIAL_ENCODED_LENGTH = 43;\nfunction isSupervisorAttemptCredential(value) {\n if (typeof value !== "string" || value.length !== SUPERVISOR_CREDENTIAL_ENCODED_LENGTH || !/^[A-Za-z0-9_-]+$/u.test(value)) {\n return false;\n }\n const decoded = Buffer.from(value, "base64url");\n return decoded.byteLength === SUPERVISOR_CREDENTIAL_BYTE_LENGTH && decoded.toString("base64url") === value;\n}\nvar SUPERVISOR_MAX_FRAME_BYTES = 1e6;\nvar SUPERVISOR_MAX_STORE_METADATA_BYTES = 1024 * 1024;\nvar SUPERVISOR_MAX_ACTIVE_TURN_BYTES = 16 * 1024;\nvar SUPERVISOR_MAX_ATTEMPT_POINTER_BYTES = 1024;\nvar SUPERVISOR_MAX_WIRE_ID_BYTES = 512;\nfunction isBoundedUtf8Identifier(value, maxBytes = SUPERVISOR_MAX_WIRE_ID_BYTES) {\n return typeof value === "string" && value.length > 0 && Buffer.byteLength(value, "utf8") <= maxBytes;\n}\nvar SUPERVISOR_MAX_REASON_LENGTH = 2e3;\nvar SUPERVISOR_MAX_ATTACHMENT_ID_LENGTH = SUPERVISOR_MAX_WIRE_ID_BYTES;\nvar SUPERVISOR_MAX_COMMAND_ID_LENGTH = SUPERVISOR_MAX_WIRE_ID_BYTES;\nvar SUPERVISOR_MAX_COMMAND_LEDGER_BYTES = 64 * 1024 * 1024;\nvar SUPERVISOR_COMMAND_LEDGER_RECOVERY_BYTES = 8 * 1024 * 1024;\nvar SUPERVISOR_MAX_COMMAND_LEDGER_RECORDS = 131072;\nvar SUPERVISOR_COMMAND_LEDGER_RECOVERY_RECORDS = 512;\nvar SUPERVISOR_MAX_DISTINCT_COMMANDS = 65536;\nvar SUPERVISOR_MAX_PI_SESSION_HISTORY_BYTES = 64 * 1024 * 1024;\nvar SUPERVISOR_PI_SESSION_HISTORY_TURN_HEADROOM_BYTES = 8 * 1024 * 1024;\nvar SUPERVISOR_PI_SESSION_HISTORY_PROMPT_LIMIT_BYTES = SUPERVISOR_MAX_PI_SESSION_HISTORY_BYTES - SUPERVISOR_PI_SESSION_HISTORY_TURN_HEADROOM_BYTES;\nvar SUPERVISOR_MAX_PENDING_COMMANDS = 256;\nvar SUPERVISOR_MAX_PENDING_COMMAND_BYTES = 8 * 1024 * 1024;\nvar SUPERVISOR_PENDING_COMMAND_SEQUENCE_WINDOW = 256;\n\n// src/supervisor/protocol.ts\nvar SUPERVISOR_PROTOCOL_VERSION = 1;\nvar SUPERVISOR_RUNTIME_VERSION = 2;\nvar DAYTONA_SUPERVISOR_PROVIDER_VERSION = 1;\nvar SUPERVISOR_RECOVERY_STOP_REASON = "supervisor_restarted_during_prompt";\nvar SUPERVISOR_COMMAND_FINGERPRINT_VERSION = 1;\nvar SUPERVISOR_COMMAND_FINGERPRINT_PATTERN = new RegExp(\n `^sha256-v${SUPERVISOR_COMMAND_FINGERPRINT_VERSION}:[a-f0-9]{64}$`,\n "u"\n);\nfunction createSupervisorCommandFingerprint(command) {\n const payload = command.payload.kind === "stop" ? {\n kind: command.payload.kind,\n ...command.payload.reason === void 0 ? {} : { reason: command.payload.reason }\n } : {\n kind: command.payload.kind,\n message: command.payload.message,\n ...!command.payload.attachments?.length ? {} : {\n attachments: command.payload.attachments.map((attachment) => ({\n id: attachment.id,\n path: attachment.path,\n ...attachment.mimeType === void 0 ? {} : { mimeType: attachment.mimeType },\n sha256: attachment.sha256.toLowerCase(),\n sizeBytes: attachment.sizeBytes\n }))\n }\n };\n const canonical = JSON.stringify({\n fingerprintVersion: SUPERVISOR_COMMAND_FINGERPRINT_VERSION,\n protocolVersion: command.protocolVersion,\n sessionId: command.sessionId,\n runId: command.runId,\n attemptId: command.attemptId,\n commandId: command.commandId,\n commandSequence: command.commandSequence,\n payload\n });\n return `sha256-v${SUPERVISOR_COMMAND_FINGERPRINT_VERSION}:${createHash("sha256").update(canonical, "utf8").digest("hex")}`;\n}\nfunction isSupervisorCommandFingerprint(value) {\n return typeof value === "string" && SUPERVISOR_COMMAND_FINGERPRINT_PATTERN.test(value);\n}\nfunction isRecord2(value) {\n return typeof value === "object" && value !== null && !Array.isArray(value);\n}\nfunction isNonEmptyString(value) {\n return typeof value === "string" && value.length > 0;\n}\nfunction isCommandId(value) {\n return isBoundedUtf8Identifier(value, SUPERVISOR_MAX_COMMAND_ID_LENGTH);\n}\nfunction isNonNegativeInteger(value) {\n return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;\n}\nfunction isPositiveInteger(value) {\n return typeof value === "number" && Number.isSafeInteger(value) && value > 0;\n}\nfunction isFiniteNumber(value) {\n return typeof value === "number" && Number.isFinite(value);\n}\nfunction hasOptionalCommandId(value) {\n return value.commandId === void 0 || isCommandId(value.commandId);\n}\nfunction isSupervisorTurnUsage(value) {\n return isRecord2(value) && isNonNegativeInteger(value.inputTokens) && isNonNegativeInteger(value.outputTokens) && isNonNegativeInteger(value.cacheReadTokens) && isNonNegativeInteger(value.cacheWriteTokens) && isNonNegativeInteger(value.totalTokens) && (value.costUsd === void 0 || isFiniteNumber(value.costUsd) && value.costUsd >= 0);\n}\nfunction hasOptionalUsage(value) {\n return value.usage === void 0 || isSupervisorTurnUsage(value.usage);\n}\nfunction isCommandKind(value) {\n return value === "prompt" || value === "steer" || value === "stop";\n}\nfunction isSupervisorReason(value) {\n return typeof value === "string" && value.length <= SUPERVISOR_MAX_REASON_LENGTH;\n}\nfunction sanitizeSupervisorReason(value) {\n if (value.length <= SUPERVISOR_MAX_REASON_LENGTH) return value;\n let end = SUPERVISOR_MAX_REASON_LENGTH;\n const finalCodeUnit = value.charCodeAt(end - 1);\n if (finalCodeUnit >= 55296 && finalCodeUnit <= 56319) end -= 1;\n return value.slice(0, end);\n}\nfunction isSupervisorEvent(value) {\n if (!isRecord2(value) || typeof value.kind !== "string") return false;\n if (value.kind === "supervisor_started") return typeof value.recovered === "boolean";\n if (value.kind === "harness_started") {\n return typeof value.adapter === "string" && (value.pid === void 0 || isPositiveInteger(value.pid));\n }\n if (value.kind === "harness_event") {\n return typeof value.adapter === "string" && Object.hasOwn(value, "payload");\n }\n if (value.kind === "harness_stderr") {\n return typeof value.adapter === "string" && typeof value.data === "string";\n }\n if (value.kind === "harness_exited") {\n return typeof value.adapter === "string" && (value.exitCode === null || isNonNegativeInteger(value.exitCode)) && (value.signal === null || typeof value.signal === "string");\n }\n if (value.kind === "turn_started") {\n return typeof value.adapter === "string" && hasOptionalCommandId(value);\n }\n if (value.kind === "turn_completed") {\n return typeof value.adapter === "string" && hasOptionalCommandId(value) && (value.stopReason === void 0 || isSupervisorReason(value.stopReason)) && hasOptionalUsage(value);\n }\n if (value.kind === "turn_failed") {\n return typeof value.adapter === "string" && hasOptionalCommandId(value) && (value.stopReason === void 0 || isSupervisorReason(value.stopReason)) && isSerializedError(value.error) && hasOptionalUsage(value);\n }\n if (value.kind === "turn_stopped") {\n return typeof value.adapter === "string" && hasOptionalCommandId(value) && (value.reason === void 0 || isSupervisorReason(value.reason)) && hasOptionalUsage(value);\n }\n if (value.kind === "command_received" || value.kind === "command_applied") {\n return isCommandId(value.commandId) && isPositiveInteger(value.commandSequence) && isCommandKind(value.commandKind);\n }\n if (value.kind === "command_failed") {\n return isCommandId(value.commandId) && isPositiveInteger(value.commandSequence) && isCommandKind(value.commandKind) && isSerializedError(value.error);\n }\n if (value.kind === "interrupted" || value.kind === "supervisor_stopping") {\n return isSupervisorReason(value.reason);\n }\n if (value.kind === "protocol_error") return typeof value.message === "string";\n return false;\n}\nfunction hasCurrentProtocolVersion(value) {\n return value.protocolVersion === SUPERVISOR_PROTOCOL_VERSION;\n}\nfunction hasAttemptIdentity(value) {\n return isBoundedUtf8Identifier(value.sessionId) && isBoundedUtf8Identifier(value.runId) && isBoundedUtf8Identifier(value.attemptId);\n}\nfunction parseAttachments(value) {\n if (value === void 0) return void 0;\n if (!Array.isArray(value)) return void 0;\n const attachments = [];\n for (const attachment of value) {\n if (!isRecord2(attachment) || !isBoundedUtf8Identifier(\n attachment.id,\n SUPERVISOR_MAX_ATTACHMENT_ID_LENGTH\n ) || !isNonEmptyString(attachment.url) || !isNonEmptyString(attachment.path) || attachment.mimeType !== void 0 && typeof attachment.mimeType !== "string" || typeof attachment.sha256 !== "string" || !/^[a-fA-F0-9]{64}$/.test(attachment.sha256) || !isNonNegativeInteger(attachment.sizeBytes)) {\n return void 0;\n }\n attachments.push({\n id: attachment.id,\n url: attachment.url,\n path: attachment.path,\n ...attachment.mimeType === void 0 ? {} : { mimeType: attachment.mimeType },\n sha256: attachment.sha256.toLowerCase(),\n sizeBytes: attachment.sizeBytes\n });\n }\n return attachments;\n}\nfunction parseCommandPayload(value) {\n if (!isRecord2(value) || typeof value.kind !== "string") return null;\n if (value.kind === "stop") {\n if (value.reason !== void 0 && !isSupervisorReason(value.reason)) return null;\n return {\n kind: "stop",\n ...value.reason === void 0 ? {} : { reason: value.reason }\n };\n }\n if ((value.kind === "prompt" || value.kind === "steer") && typeof value.message === "string") {\n const attachments = parseAttachments(value.attachments);\n if (value.attachments !== void 0 && attachments === void 0) return null;\n return {\n kind: value.kind,\n message: value.message,\n ...attachments === void 0 ? {} : { attachments }\n };\n }\n return null;\n}\nfunction parseCommandFrame(value) {\n if (!isRecord2(value) || value.type !== "command" || !hasCurrentProtocolVersion(value) || !hasAttemptIdentity(value) || !isCommandId(value.commandId) || !isPositiveInteger(value.commandSequence)) {\n return null;\n }\n const payload = parseCommandPayload(value.payload);\n if (!payload) return null;\n return {\n type: "command",\n protocolVersion: SUPERVISOR_PROTOCOL_VERSION,\n sessionId: value.sessionId,\n runId: value.runId,\n attemptId: value.attemptId,\n commandId: value.commandId,\n commandSequence: value.commandSequence,\n payload\n };\n}\nfunction parseGatewayToSupervisorFrame(value) {\n if (!isRecord2(value) || !hasCurrentProtocolVersion(value) || !hasAttemptIdentity(value)) {\n return null;\n }\n const identity = {\n sessionId: value.sessionId,\n runId: value.runId,\n attemptId: value.attemptId\n };\n if (value.type === "command") return parseCommandFrame(value);\n if (value.type === "event_ack" && isNonNegativeInteger(value.acknowledgedEventSequence)) {\n return {\n type: "event_ack",\n protocolVersion: SUPERVISOR_PROTOCOL_VERSION,\n ...identity,\n acknowledgedEventSequence: value.acknowledgedEventSequence\n };\n }\n if (value.type === "resume_ok" && isNonNegativeInteger(value.acknowledgedEventSequence) && isNonNegativeInteger(value.lastAppliedCommandSequence) && Array.isArray(value.pendingCommands) && value.pendingCommands.length <= SUPERVISOR_MAX_PENDING_COMMANDS) {\n const pendingCommands = value.pendingCommands.map(parseCommandFrame);\n if (pendingCommands.some((command) => command === null)) return null;\n return {\n type: "resume_ok",\n protocolVersion: SUPERVISOR_PROTOCOL_VERSION,\n ...identity,\n acknowledgedEventSequence: value.acknowledgedEventSequence,\n lastAppliedCommandSequence: value.lastAppliedCommandSequence,\n pendingCommands\n };\n }\n if (value.type === "attempt_superseded" && (value.reason === void 0 || isSupervisorReason(value.reason))) {\n return {\n type: "attempt_superseded",\n protocolVersion: SUPERVISOR_PROTOCOL_VERSION,\n ...identity,\n ...value.reason === void 0 ? {} : { reason: value.reason }\n };\n }\n if (value.type === "pong" && typeof value.sentAt === "string") {\n return {\n type: "pong",\n protocolVersion: SUPERVISOR_PROTOCOL_VERSION,\n ...identity,\n sentAt: value.sentAt\n };\n }\n return null;\n}\nfunction hasMatchingAttempt(identity, frame) {\n return identity.sessionId === frame.sessionId && identity.runId === frame.runId && identity.attemptId === frame.attemptId;\n}\nfunction createSupervisorEventId(attemptId, attemptSequence) {\n return `${attemptId}:${attemptSequence}`;\n}\nfunction serializeSupervisorError(error) {\n return serializeError(error);\n}\n\n// src/supervisor/path-policy.ts\nimport { posix } from "node:path";\nfunction containsControlCharacter(value) {\n return /[\\u0000-\\u001f\\u007f]/u.test(value);\n}\nfunction assertCanonicalSandboxPath(name, value) {\n if (!posix.isAbsolute(value) || value === "/" || value.endsWith("/") || value !== posix.normalize(value) || value.includes("\\\\") || containsControlCharacter(value)) {\n throw new Error(\n `${name} must be a canonical absolute non-root POSIX sandbox path.`\n );\n }\n}\nfunction sandboxPathIsEqualToOrBelow(parent, child) {\n const relativePath = posix.relative(parent, child);\n return !posix.isAbsolute(relativePath) && relativePath !== ".." && !relativePath.startsWith("../");\n}\nfunction sandboxPathsOverlap(left, right) {\n return sandboxPathIsEqualToOrBelow(left, right) || sandboxPathIsEqualToOrBelow(right, left);\n}\nfunction assertSafePathSegment(name, value) {\n if (value.length === 0 || value === "." || value === ".." || value.includes("/") || value.includes("\\\\") || containsControlCharacter(value) || Buffer.byteLength(value, "utf8") > 255) {\n throw new Error(\n `${name} must be one safe POSIX path segment of 1 to 255 bytes.`\n );\n }\n}\n\n// src/supervisor/config.ts\nvar PI_THINKING_LEVELS = [\n "off",\n "minimal",\n "low",\n "medium",\n "high",\n "xhigh"\n];\nvar SUPERVISOR_MAX_TIMER_DELAY_MS = 2147483647;\nvar DEFAULT_SUPERVISOR_ATTACHMENT_CONFIG = {\n maxBytesPerAttachment: 100 * 1024 * 1024,\n maxBytesPerCommand: 500 * 1024 * 1024,\n maxFilesPerAttempt: 100,\n maxBytesPerAttempt: 500 * 1024 * 1024,\n downloadTimeoutMs: 12e4\n};\nfunction assertSupervisorHarnessPathOwnership(stateDir, sessionPath, agentDir) {\n const effectiveAgentDir = agentDir ?? `${stateDir}/pi/agent`;\n const reservedStateRoots = [\n `${stateDir}/attempts`,\n `${stateDir}/attempt-data-v${SUPERVISOR_RUNTIME_VERSION}`,\n `${stateDir}/.neckbeard-resource-snapshots`\n ];\n if (reservedStateRoots.some((path) => sandboxPathsOverlap(sessionPath, path))) {\n throw new Error(\n "Supervisor config harness.sessionPath must not overlap supervisor-owned state."\n );\n }\n if (reservedStateRoots.some((path) => sandboxPathsOverlap(effectiveAgentDir, path))) {\n throw new Error(\n "Supervisor config harness.agentDir must not overlap supervisor-owned state."\n );\n }\n if (sandboxPathsOverlap(sessionPath, effectiveAgentDir)) {\n throw new Error(\n "Supervisor config harness.sessionPath and harness.agentDir must not overlap."\n );\n }\n}\nfunction isRecord3(value) {\n return typeof value === "object" && value !== null && !Array.isArray(value);\n}\nfunction isNonEmptyString2(value) {\n return typeof value === "string" && value.length > 0;\n}\nfunction isPositiveInteger2(value) {\n return typeof value === "number" && Number.isSafeInteger(value) && value > 0;\n}\nfunction isTimerDelay(value) {\n return isPositiveInteger2(value) && value <= SUPERVISOR_MAX_TIMER_DELAY_MS;\n}\nfunction isNonNegativeNumber(value) {\n return typeof value === "number" && Number.isFinite(value) && value >= 0;\n}\nfunction parseSupervisorRuntimeConfig(value) {\n if (!isRecord3(value)) throw new Error("Supervisor config must be an object.");\n if (value.protocolVersion !== SUPERVISOR_PROTOCOL_VERSION) {\n throw new Error(\n `Unsupported supervisor protocol version: ${String(value.protocolVersion)}.`\n );\n }\n if (value.runtimeVersion !== SUPERVISOR_RUNTIME_VERSION) {\n throw new Error(\n `Unsupported supervisor runtime version: ${String(value.runtimeVersion)}.`\n );\n }\n if (value.provider !== "daytona") {\n throw new Error(\'Supervisor provider must be "daytona".\');\n }\n if (value.providerVersion !== DAYTONA_SUPERVISOR_PROVIDER_VERSION) {\n throw new Error(\n `Unsupported Daytona supervisor provider version: ${String(value.providerVersion)}.`\n );\n }\n for (const field of [\n "sessionId",\n "runId",\n "attemptId",\n "gatewayUrl",\n "credentialEnv",\n "workspaceDir",\n "stateDurabilityAnchor",\n "stateDir"\n ]) {\n if (!isNonEmptyString2(value[field])) {\n throw new Error(`Supervisor config ${field} must be a non-empty string.`);\n }\n }\n for (const field of ["sessionId", "runId"]) {\n if (!isBoundedUtf8Identifier(value[field])) {\n throw new Error(\n `Supervisor config ${field} must be at most ${SUPERVISOR_MAX_WIRE_ID_BYTES} UTF-8 bytes.`\n );\n }\n }\n assertSafePathSegment(\n "Supervisor config attemptId",\n value.attemptId\n );\n assertCanonicalSandboxPath(\n "Supervisor config workspaceDir",\n value.workspaceDir\n );\n assertCanonicalSandboxPath(\n "Supervisor config stateDurabilityAnchor",\n value.stateDurabilityAnchor\n );\n assertCanonicalSandboxPath(\n "Supervisor config stateDir",\n value.stateDir\n );\n if (!sandboxPathIsEqualToOrBelow(\n value.stateDurabilityAnchor,\n value.stateDir\n )) {\n throw new Error(\n "Supervisor config stateDir must be equal to or below stateDurabilityAnchor."\n );\n }\n if (sandboxPathsOverlap(value.workspaceDir, value.stateDir)) {\n throw new Error(\n "Supervisor config workspaceDir and stateDir must not overlap."\n );\n }\n if (!isTimerDelay(value.heartbeatIntervalMs)) {\n throw new Error(\n `Supervisor config heartbeatIntervalMs must be a positive integer no greater than ${SUPERVISOR_MAX_TIMER_DELAY_MS}.`\n );\n }\n if (!isTimerDelay(value.handshakeTimeoutMs)) {\n throw new Error(\n `Supervisor config handshakeTimeoutMs must be a positive integer no greater than ${SUPERVISOR_MAX_TIMER_DELAY_MS}.`\n );\n }\n if (!isPositiveInteger2(value.maxInFlightEvents)) {\n throw new Error(\n "Supervisor config maxInFlightEvents must be a positive integer."\n );\n }\n if (typeof value.allowInsecureGateway !== "boolean") {\n throw new Error(\n "Supervisor config allowInsecureGateway must be a boolean."\n );\n }\n let gatewayUrl;\n try {\n gatewayUrl = new URL(value.gatewayUrl);\n } catch {\n throw new Error("Supervisor config gatewayUrl must be a valid URL.");\n }\n if (gatewayUrl.protocol !== "wss:" && !(value.allowInsecureGateway && gatewayUrl.protocol === "ws:")) {\n throw new Error("Supervisor config gatewayUrl must use wss://.");\n }\n if (gatewayUrl.username || gatewayUrl.password) {\n throw new Error(\n "Supervisor config gatewayUrl must not contain credentials."\n );\n }\n if (gatewayUrl.search || gatewayUrl.hash) {\n throw new Error(\n "Supervisor config gatewayUrl must not contain a query or fragment."\n );\n }\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(value.credentialEnv)) {\n throw new Error(\n "Supervisor config credentialEnv must be a valid environment variable name."\n );\n }\n const attachments = value.attachments === void 0 ? DEFAULT_SUPERVISOR_ATTACHMENT_CONFIG : value.attachments;\n if (!isRecord3(attachments)) {\n throw new Error("Supervisor config attachments must be an object.");\n }\n if (!isPositiveInteger2(attachments.maxBytesPerAttachment)) {\n throw new Error(\n "Supervisor attachments.maxBytesPerAttachment must be a positive integer."\n );\n }\n if (!isPositiveInteger2(attachments.maxBytesPerCommand)) {\n throw new Error(\n "Supervisor attachments.maxBytesPerCommand must be a positive integer."\n );\n }\n const maxFilesPerAttempt = attachments.maxFilesPerAttempt === void 0 ? DEFAULT_SUPERVISOR_ATTACHMENT_CONFIG.maxFilesPerAttempt : attachments.maxFilesPerAttempt;\n if (!isPositiveInteger2(maxFilesPerAttempt)) {\n throw new Error(\n "Supervisor attachments.maxFilesPerAttempt must be a positive integer."\n );\n }\n const maxBytesPerAttempt = attachments.maxBytesPerAttempt === void 0 ? attachments.maxBytesPerCommand : attachments.maxBytesPerAttempt;\n if (!isPositiveInteger2(maxBytesPerAttempt)) {\n throw new Error(\n "Supervisor attachments.maxBytesPerAttempt must be a positive integer."\n );\n }\n if (!isTimerDelay(attachments.downloadTimeoutMs)) {\n throw new Error(\n `Supervisor attachments.downloadTimeoutMs must be a positive integer no greater than ${SUPERVISOR_MAX_TIMER_DELAY_MS}.`\n );\n }\n if (!isRecord3(value.reconnect)) {\n throw new Error("Supervisor config reconnect must be an object.");\n }\n if (!isTimerDelay(value.reconnect.initialDelayMs)) {\n throw new Error(\n `Supervisor reconnect.initialDelayMs must be a positive integer no greater than ${SUPERVISOR_MAX_TIMER_DELAY_MS}.`\n );\n }\n if (!isTimerDelay(value.reconnect.maximumDelayMs)) {\n throw new Error(\n `Supervisor reconnect.maximumDelayMs must be a positive integer no greater than ${SUPERVISOR_MAX_TIMER_DELAY_MS}.`\n );\n }\n if (value.reconnect.maximumDelayMs < value.reconnect.initialDelayMs) {\n throw new Error(\n "Supervisor reconnect.maximumDelayMs must be >= initialDelayMs."\n );\n }\n if (typeof value.reconnect.multiplier !== "number" || !Number.isFinite(value.reconnect.multiplier) || value.reconnect.multiplier < 1) {\n throw new Error("Supervisor reconnect.multiplier must be at least 1.");\n }\n if (!isNonNegativeNumber(value.reconnect.jitterRatio) || value.reconnect.jitterRatio > 1) {\n throw new Error(\n "Supervisor reconnect.jitterRatio must be between 0 and 1."\n );\n }\n if (value.reconnect.maximumDelayMs * (1 + value.reconnect.jitterRatio) > SUPERVISOR_MAX_TIMER_DELAY_MS) {\n throw new Error(\n `Supervisor reconnect jittered delay must not exceed ${SUPERVISOR_MAX_TIMER_DELAY_MS}.`\n );\n }\n if (!isRecord3(value.harness) || value.harness.adapter !== "pi-sdk") {\n throw new Error(\'Supervisor config harness.adapter must be "pi-sdk".\');\n }\n if (value.harness.adapterVersion !== 1) {\n throw new Error("Supervisor config harness.adapterVersion must be 1.");\n }\n if (!isNonEmptyString2(value.harness.moduleSpecifier)) {\n throw new Error(\n "Supervisor config harness.moduleSpecifier must be a non-empty string."\n );\n }\n if (!isNonEmptyString2(value.harness.expectedVersion)) {\n throw new Error(\n "Supervisor config harness.expectedVersion must be a non-empty string."\n );\n }\n if (!isNonEmptyString2(value.harness.sessionPath)) {\n throw new Error(\n "Supervisor config harness.sessionPath must be a non-empty string."\n );\n }\n assertCanonicalSandboxPath(\n "Supervisor config harness.sessionPath",\n value.harness.sessionPath\n );\n if (value.harness.sessionPath === value.stateDir || !sandboxPathIsEqualToOrBelow(\n value.stateDir,\n value.harness.sessionPath\n )) {\n throw new Error(\n "Supervisor config harness.sessionPath must be strictly below stateDir."\n );\n }\n if (value.harness.agentDir !== void 0 && !isNonEmptyString2(value.harness.agentDir)) {\n throw new Error(\n "Supervisor config harness.agentDir must be a non-empty string when set."\n );\n }\n if (value.harness.agentDir !== void 0) {\n assertCanonicalSandboxPath(\n "Supervisor config harness.agentDir",\n value.harness.agentDir\n );\n if (value.harness.agentDir === value.stateDir || !sandboxPathIsEqualToOrBelow(\n value.stateDir,\n value.harness.agentDir\n )) {\n throw new Error(\n "Supervisor config harness.agentDir must be strictly below stateDir."\n );\n }\n }\n assertSupervisorHarnessPathOwnership(\n value.stateDir,\n value.harness.sessionPath,\n value.harness.agentDir\n );\n if (value.harness.provider !== void 0 && !isNonEmptyString2(value.harness.provider)) {\n throw new Error(\n "Supervisor config harness.provider must be a non-empty string when set."\n );\n }\n if (value.harness.model !== void 0 && !isNonEmptyString2(value.harness.model)) {\n throw new Error(\n "Supervisor config harness.model must be a non-empty string when set."\n );\n }\n if (value.harness.provider === void 0 !== (value.harness.model === void 0)) {\n throw new Error(\n "Supervisor config harness.provider and harness.model must be set together."\n );\n }\n if (value.harness.providerCredentialEnv !== void 0 && (!isNonEmptyString2(value.harness.providerCredentialEnv) || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(value.harness.providerCredentialEnv))) {\n throw new Error(\n "Supervisor config harness.providerCredentialEnv must be a valid environment variable name when set."\n );\n }\n if (value.harness.provider === void 0 !== (value.harness.providerCredentialEnv === void 0)) {\n throw new Error(\n "Supervisor config harness.providerCredentialEnv must be set with provider and model."\n );\n }\n if (value.harness.providerCredentialEnv === value.credentialEnv) {\n throw new Error(\n "Supervisor and provider credentials must use different environment variables."\n );\n }\n if (value.harness.thinking !== void 0 && !PI_THINKING_LEVELS.includes(value.harness.thinking)) {\n throw new Error("Supervisor config harness.thinking is invalid.");\n }\n if (!isTimerDelay(value.harness.stopGraceMs)) {\n throw new Error(\n `Supervisor config harness.stopGraceMs must be a positive integer no greater than ${SUPERVISOR_MAX_TIMER_DELAY_MS}.`\n );\n }\n return {\n ...value,\n attachments: {\n maxBytesPerAttachment: attachments.maxBytesPerAttachment,\n maxBytesPerCommand: attachments.maxBytesPerCommand,\n maxFilesPerAttempt,\n maxBytesPerAttempt,\n downloadTimeoutMs: attachments.downloadTimeoutMs\n }\n };\n}\n\n// src/timeout.ts\nfunction settleOperation(operation, options = {}) {\n const { abort, timeout } = options;\n if (abort?.signal.aborted) throw abort.createError();\n if (!abort && !timeout) {\n try {\n return Promise.resolve(operation());\n } catch (error) {\n return Promise.reject(error);\n }\n }\n return new Promise((resolve2, reject) => {\n let settled = false;\n let timer;\n const cleanup = () => {\n if (timer !== void 0) {\n clearTimeout(timer);\n timer = void 0;\n }\n abort?.signal.removeEventListener("abort", onAbort);\n };\n const settle = (callback) => {\n if (settled) return;\n settled = true;\n cleanup();\n callback();\n };\n const onAbort = () => settle(() => reject(abort.createError()));\n abort?.signal.addEventListener("abort", onAbort, { once: true });\n if (timeout) {\n timer = setTimeout(\n () => settle(() => reject(timeout.createError())),\n timeout.timeoutMs\n );\n }\n let task;\n try {\n task = operation();\n } catch (error) {\n settle(() => reject(error));\n return;\n }\n void Promise.resolve(task).then(\n (value) => settle(() => resolve2(value)),\n (error) => settle(() => reject(error))\n );\n });\n}\nfunction withTimeout(task, timeoutMs, message) {\n return settleOperation(() => task, {\n timeout: {\n timeoutMs,\n createError: () => new Error(message)\n }\n });\n}\n\n// src/supervisor/attachments.ts\nimport { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";\nimport { constants as fsConstants2 } from "node:fs";\nimport { opendir } from "node:fs/promises";\nimport { dirname, join as join2 } from "node:path";\n\n// src/supervisor/durable-fs.ts\nimport { randomUUID } from "node:crypto";\nimport { constants as fsConstants } from "node:fs";\nimport { link, mkdir, open, rename, unlink } from "node:fs/promises";\nimport { isAbsolute, join, relative, sep } from "node:path";\nvar SUPERVISOR_ATTEMPT_POINTER_ROOT = "attempts";\nvar SUPERVISOR_ATTEMPT_DATA_ROOT = `attempt-data-v${SUPERVISOR_RUNTIME_VERSION}`;\nvar SUPERVISOR_ATTEMPT_DIRECTORY_MODE = 448;\nvar SUPERVISOR_ATTEMPT_POINTER_MODE = 384;\nvar DEFAULT_DIRECTORY_DEPENDENCIES = {};\nvar SAFE_DIRECTORY_OPEN_FLAGS = fsConstants.O_RDONLY | fsConstants.O_DIRECTORY | fsConstants.O_NOFOLLOW;\nvar SAFE_LEAF_OPEN_FLAGS = fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK;\nvar BOUNDED_READ_CHUNK_BYTES = 64 * 1024;\nfunction descriptorBoundDirectoryPath(directory) {\n return `/proc/${process.pid}/fd/${directory.handle.fd}`;\n}\nfunction descriptorBoundEntryPath(directory, name) {\n assertSafePathSegment("Descriptor-bound directory entry", name);\n return join(descriptorBoundDirectoryPath(directory), name);\n}\nfunction descriptorBoundFilesystemEntryPath(directory, name) {\n if (!name || name === "." || name === ".." || name.includes("/") || name.includes("\\0")) {\n throw new Error("Descriptor-bound filesystem entry must be one POSIX path segment.");\n }\n return join(descriptorBoundDirectoryPath(directory), name);\n}\nfunction directoryIdentity(stats) {\n return { device: stats.dev, inode: stats.ino };\n}\nfunction matchesDirectoryIdentity(stats, expected) {\n return stats.dev === expected.device && stats.ino === expected.inode;\n}\nasync function openBoundDirectoryHandle(path, displayPath, expectedIdentity) {\n let handle = null;\n try {\n handle = await open(path, SAFE_DIRECTORY_OPEN_FLAGS);\n const stats = await handle.stat({ bigint: true });\n if (!stats.isDirectory() || expectedIdentity !== void 0 && !matchesDirectoryIdentity(stats, expectedIdentity)) {\n throw new Error(`${displayPath} must continue to identify its original directory.`);\n }\n return {\n handle,\n displayPath,\n identity: directoryIdentity(stats)\n };\n } catch (error) {\n await handle?.close().catch(() => void 0);\n const code = error.code;\n if (code === "ELOOP" || code === "ENOTDIR") {\n throw new Error(`${displayPath} must be a directory.`, { cause: error });\n }\n throw error;\n }\n}\nasync function openDescriptorBoundDirectory(path, expectedIdentity) {\n return openBoundDirectoryHandle(path, path, expectedIdentity);\n}\nasync function openDescriptorBoundDirectoryAt(parent, name, expectedIdentity) {\n const displayPath = join(parent.displayPath, name);\n return openBoundDirectoryHandle(\n descriptorBoundEntryPath(parent, name),\n displayPath,\n expectedIdentity\n );\n}\nasync function openDescriptorBoundFilesystemDirectoryAt(parent, name, expectedIdentity) {\n const displayPath = join(parent.displayPath, name);\n return openBoundDirectoryHandle(\n descriptorBoundFilesystemEntryPath(parent, name),\n displayPath,\n expectedIdentity\n );\n}\nfunction relativeDirectorySegments(anchor, path) {\n const relativePath = relative(anchor, path);\n if (isAbsolute(relativePath) || relativePath === ".." || relativePath.startsWith(`..${sep}`)) {\n throw new Error(`${path} must be equal to or below durability anchor ${anchor}.`);\n }\n if (!relativePath) return [];\n const segments = relativePath.split(sep);\n for (const segment of segments) {\n assertSafePathSegment("Durable directory path edge", segment);\n }\n return segments;\n}\nasync function verifyBoundDirectoryEntry(parent, child, name) {\n let current = null;\n try {\n current = await openDescriptorBoundDirectoryAt(parent, name, child.identity);\n } catch (error) {\n throw new Error(`${child.displayPath} must continue to identify its original directory.`, {\n cause: error\n });\n } finally {\n await current?.handle.close().catch(() => void 0);\n }\n}\nasync function syncDescriptorBoundDirectory(directory) {\n try {\n await directory.handle.sync();\n } catch (error) {\n const code = error.code;\n if (code !== "EINVAL" && code !== "ENOTSUP" && code !== "EBADF") throw error;\n }\n}\nasync function ensureDescriptorBoundDirectoryAt(parent, name, mode = SUPERVISOR_ATTEMPT_DIRECTORY_MODE, dependencies = DEFAULT_DIRECTORY_DEPENDENCIES) {\n const path = descriptorBoundEntryPath(parent, name);\n let child;\n try {\n try {\n child = await openDescriptorBoundDirectoryAt(parent, name);\n } catch (error) {\n if (error.code !== "ENOENT") throw error;\n try {\n await mkdir(path, { mode });\n } catch (mkdirError) {\n if (mkdirError.code !== "EEXIST") {\n throw mkdirError;\n }\n }\n child = await openDescriptorBoundDirectoryAt(parent, name);\n }\n await (dependencies.syncDirectory?.(parent) ?? syncDescriptorBoundDirectory(parent));\n const boundChild = child;\n await dependencies.afterDirectoryBound?.(boundChild.displayPath);\n await verifyBoundDirectoryEntry(parent, boundChild, name);\n return boundChild;\n } catch (error) {\n await child?.handle.close().catch(() => void 0);\n throw error;\n }\n}\nasync function bindDescriptorBoundDirectory(anchor, path, expectedIdentity, dependencies = DEFAULT_DIRECTORY_DEPENDENCIES) {\n const segments = relativeDirectorySegments(anchor, path);\n let current = await openDescriptorBoundDirectory(anchor);\n try {\n for (const [index, segment] of segments.entries()) {\n const next = await openDescriptorBoundDirectoryAt(\n current,\n segment,\n index === segments.length - 1 ? expectedIdentity : void 0\n );\n await dependencies.afterDirectoryBound?.(next.displayPath);\n await current.handle.close();\n current = next;\n }\n if (!segments.length && expectedIdentity !== void 0) {\n const stats = await current.handle.stat({ bigint: true });\n if (!matchesDirectoryIdentity(stats, expectedIdentity)) {\n throw new Error(`${path} must continue to identify its original directory.`);\n }\n }\n return current;\n } catch (error) {\n await current.handle.close().catch(() => void 0);\n throw error;\n }\n}\nasync function ensureDescriptorBoundDirectory(anchor, path, mode = SUPERVISOR_ATTEMPT_DIRECTORY_MODE, dependencies = DEFAULT_DIRECTORY_DEPENDENCIES) {\n const segments = relativeDirectorySegments(anchor, path);\n let current = await openDescriptorBoundDirectory(anchor);\n try {\n for (const segment of segments) {\n const next = await ensureDescriptorBoundDirectoryAt(current, segment, mode, dependencies);\n await current.handle.close();\n current = next;\n }\n return current;\n } catch (error) {\n await current.handle.close().catch(() => void 0);\n throw error;\n }\n}\nasync function openRegularFileAt(parent, name, flags, description, mode) {\n return openRegularLeafFile(descriptorBoundEntryPath(parent, name), flags, description, mode);\n}\nasync function openRegularFilesystemEntryAt(parent, name, flags, description, mode) {\n return openRegularLeafFile(\n descriptorBoundFilesystemEntryPath(parent, name),\n flags,\n description,\n mode\n );\n}\nasync function openRegularLeafFile(path, flags, name, mode) {\n const handle = await open(path, flags | SAFE_LEAF_OPEN_FLAGS, mode);\n try {\n const stats = await handle.stat();\n if (!stats.isFile()) throw new Error(`${name} must be a regular file.`);\n return handle;\n } catch (error) {\n await handle.close();\n throw error;\n }\n}\nasync function retainedRegularFileStats(retained, current) {\n return Promise.all([\n retained.stat({ bigint: true }),\n current.stat({ bigint: true })\n ]);\n}\nasync function matchesRetainedRegularFileIdentity(retained, current) {\n const [retainedStats, currentStats] = await retainedRegularFileStats(retained, current);\n return retainedStats.isFile() && currentStats.isFile() && retainedStats.dev === currentStats.dev && retainedStats.ino === currentStats.ino;\n}\nasync function withRevalidatedPrivateRegularFile(retained, openCurrent, operation, options = {}) {\n const { maximumBytes } = options;\n if (maximumBytes !== void 0 && (!Number.isSafeInteger(maximumBytes) || maximumBytes < 0)) {\n throw new Error("Retained private regular file has an invalid size limit.");\n }\n const current = await openCurrent();\n try {\n const [retainedStats, currentStats] = await retainedRegularFileStats(retained, current);\n const expectedUid = typeof process.getuid === "function" ? BigInt(process.getuid()) : null;\n const maximumSize = maximumBytes === void 0 ? null : BigInt(maximumBytes);\n if (!retainedStats.isFile() || !currentStats.isFile() || retainedStats.dev !== currentStats.dev || retainedStats.ino !== currentStats.ino || retainedStats.nlink !== 1n || currentStats.nlink !== 1n || (retainedStats.mode & 0o777n) !== 0o600n || (currentStats.mode & 0o777n) !== 0o600n || maximumSize !== null && (retainedStats.size > maximumSize || currentStats.size > maximumSize) || expectedUid !== null && (retainedStats.uid !== expectedUid || currentStats.uid !== expectedUid)) {\n throw new Error(\n options.failureMessage ?? "Retained private regular file no longer satisfies its descriptor binding."\n );\n }\n return operation();\n } finally {\n await current.close().catch(() => void 0);\n }\n}\nasync function readBoundedRegularTextHandle(handle, maximumBytes, capacityName, options = {}) {\n if (!Number.isSafeInteger(maximumBytes) || maximumBytes < 0) {\n throw new Error(`${capacityName} has an invalid read capacity.`);\n }\n if (options.expectedBytes !== void 0 && (!Number.isSafeInteger(options.expectedBytes) || options.expectedBytes < 0 || options.expectedBytes > maximumBytes)) {\n throw new Error(`${capacityName} has an invalid expected byte length.`);\n }\n const stats = await handle.stat();\n if (!Number.isSafeInteger(stats.size) || stats.size < 0 || stats.size > maximumBytes) {\n throw new Error(`${capacityName} exceeds its bounded on-disk capacity.`);\n }\n const chunks = [];\n let totalBytes = 0;\n const readLimit = options.expectedBytes ?? maximumBytes + 1;\n while (totalBytes < readLimit) {\n const remaining = readLimit - totalBytes;\n const chunk = Buffer.allocUnsafe(Math.min(BOUNDED_READ_CHUNK_BYTES, remaining));\n const { bytesRead } = await handle.read(chunk, 0, chunk.length, totalBytes);\n if (bytesRead === 0) {\n if (options.expectedBytes !== void 0) {\n throw options.prematureEofError?.() ?? new Error(`${capacityName} ended before its expected byte length.`);\n }\n break;\n }\n chunks.push(chunk.subarray(0, bytesRead));\n totalBytes += bytesRead;\n }\n if (totalBytes > maximumBytes) {\n throw new Error(`${capacityName} exceeds its bounded on-disk capacity.`);\n }\n try {\n return new TextDecoder("utf-8", {\n fatal: true,\n ignoreBOM: options.ignoreBOM ?? true\n }).decode(Buffer.concat(chunks, totalBytes));\n } catch (error) {\n if (options.invalidUtf8Error !== void 0) throw options.invalidUtf8Error();\n throw error;\n }\n}\nasync function readBoundedRegularTextFileAt(parent, name, maximumBytes, capacityName) {\n const handle = await openRegularFileAt(parent, name, fsConstants.O_RDONLY, capacityName);\n try {\n return await readBoundedRegularTextHandle(handle, maximumBytes, capacityName);\n } finally {\n await handle.close();\n }\n}\nasync function linkDescriptorBoundEntry(sourceParent, sourceName, destinationParent, destinationName) {\n await link(\n descriptorBoundEntryPath(sourceParent, sourceName),\n descriptorBoundEntryPath(destinationParent, destinationName)\n );\n}\nasync function renameDescriptorBoundEntry(sourceParent, sourceName, destinationParent, destinationName) {\n await rename(\n descriptorBoundEntryPath(sourceParent, sourceName),\n descriptorBoundEntryPath(destinationParent, destinationName)\n );\n}\nasync function unlinkDescriptorBoundEntry(parent, name) {\n await unlink(descriptorBoundEntryPath(parent, name));\n}\nasync function unlinkDescriptorBoundEntryIfPresent(parent, name) {\n try {\n await unlinkDescriptorBoundEntry(parent, name);\n return true;\n } catch (error) {\n if (error.code === "ENOENT") return false;\n throw error;\n }\n}\nfunction supervisorAttemptDataDirectory(config) {\n return join(config.stateDir, SUPERVISOR_ATTEMPT_DATA_ROOT, config.attemptId);\n}\nfunction supervisorAttemptPointer(config) {\n return `${JSON.stringify({\n revision: SUPERVISOR_RUNTIME_VERSION,\n dataDirectory: `${SUPERVISOR_ATTEMPT_DATA_ROOT}/${config.attemptId}`\n })}\n`;\n}\nasync function readAndValidateAttemptPointerAt(pointerParent, name, expected, attemptId) {\n let actual;\n try {\n actual = await readBoundedRegularTextFileAt(\n pointerParent,\n name,\n SUPERVISOR_MAX_ATTEMPT_POINTER_BYTES,\n `Supervisor attempt ${attemptId} storage revision pointer`\n );\n } catch (error) {\n let directory = null;\n try {\n directory = await openDescriptorBoundDirectoryAt(pointerParent, name);\n throw new Error(\n `Supervisor attempt ${attemptId} uses a pre-revision storage layout and cannot be upgraded in place; launch a replacement attempt.`\n );\n } catch (directoryError) {\n if (directoryError instanceof Error && directoryError.message.includes("uses a pre-revision storage layout")) {\n throw directoryError;\n }\n } finally {\n await directory?.handle.close().catch(() => void 0);\n }\n throw error;\n }\n if (actual !== expected) {\n throw new Error(`Supervisor attempt ${attemptId} has an unsupported storage revision pointer.`);\n }\n}\nasync function publishAttemptPointerAt(pointerParent, name, expected, attemptId) {\n const temporaryName = `.${process.pid}.${randomUUID()}.revision.tmp`;\n let temporaryExists = false;\n try {\n const handle = await openRegularFileAt(\n pointerParent,\n temporaryName,\n fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL,\n `Supervisor attempt ${attemptId} temporary storage revision pointer`,\n SUPERVISOR_ATTEMPT_POINTER_MODE\n );\n temporaryExists = true;\n try {\n await handle.writeFile(expected, "utf8");\n await handle.sync();\n } finally {\n await handle.close();\n }\n try {\n await linkDescriptorBoundEntry(pointerParent, temporaryName, pointerParent, name);\n } catch (error) {\n if (error.code !== "EEXIST") throw error;\n }\n await readAndValidateAttemptPointerAt(pointerParent, name, expected, attemptId);\n await syncDescriptorBoundDirectory(pointerParent);\n } finally {\n if (temporaryExists) {\n const removed = await unlinkDescriptorBoundEntryIfPresent(\n pointerParent,\n temporaryName\n );\n if (removed) await syncDescriptorBoundDirectory(pointerParent);\n }\n }\n}\nasync function openSupervisorAttemptStorage(config) {\n const state = await ensureDescriptorBoundDirectory(config.stateDurabilityAnchor, config.stateDir);\n let pointerParent = null;\n let dataParent = null;\n try {\n pointerParent = await ensureDescriptorBoundDirectoryAt(state, SUPERVISOR_ATTEMPT_POINTER_ROOT);\n const expectedPointer = supervisorAttemptPointer(config);\n try {\n await readAndValidateAttemptPointerAt(\n pointerParent,\n config.attemptId,\n expectedPointer,\n config.attemptId\n );\n await syncDescriptorBoundDirectory(pointerParent);\n } catch (error) {\n if (error.code !== "ENOENT") throw error;\n await publishAttemptPointerAt(\n pointerParent,\n config.attemptId,\n expectedPointer,\n config.attemptId\n );\n }\n dataParent = await ensureDescriptorBoundDirectoryAt(state, SUPERVISOR_ATTEMPT_DATA_ROOT);\n return await ensureDescriptorBoundDirectoryAt(dataParent, config.attemptId);\n } finally {\n await dataParent?.handle.close().catch(() => void 0);\n await pointerParent?.handle.close().catch(() => void 0);\n await state.handle.close().catch(() => void 0);\n }\n}\n\n// src/supervisor/attachments.ts\nvar MAX_ATTACHMENTS_PER_COMMAND = 100;\nvar ATTACHMENT_TARGET_SUFFIX_BYTES = 108;\nvar ATTACHMENT_READ_CHUNK_BYTES = 64 * 1024;\nvar ATTACHMENT_BATCH_MARKER_MAX_BYTES = 64 * 1024;\nvar IMMUTABLE_ATTACHMENT_FILENAME_PATTERN = /^[a-f0-9]{64}-[a-f0-9]{64}-[a-f0-9]{16}-.+$/u;\nvar ATTACHMENT_BATCH_MARKER_PATTERN = /^\\.batch-([a-f0-9]{64})\\.(pending|committed)$/u;\nvar DEFAULT_DEPENDENCIES = {\n fetch: globalThis.fetch,\n randomId: randomUUID2\n};\nvar AttachmentMaterializationError = class extends Error {\n name = "AttachmentMaterializationError";\n};\nfunction safeError(attachment, message) {\n const id = typeof attachment.id === "string" ? truncateUtf8(attachment.id, SUPERVISOR_MAX_ATTACHMENT_ID_LENGTH) : "unknown";\n return new AttachmentMaterializationError(`Attachment ${id} ${message}`);\n}\nfunction validateFilename(attachment) {\n try {\n assertSafePathSegment("Attachment path", attachment.path);\n } catch {\n throw safeError(attachment, "path must be a safe single filename.");\n }\n}\nfunction validateSourceUrl(attachment) {\n let url;\n try {\n url = new URL(attachment.url);\n } catch {\n throw safeError(attachment, "download URL is invalid.");\n }\n if (url.protocol !== "https:" || url.username || url.password) {\n throw safeError(attachment, "download URL must use HTTPS without embedded credentials.");\n }\n return url;\n}\nfunction attachmentDirectory(config) {\n return join2(supervisorAttemptDataDirectory(config), "attachments");\n}\nfunction commandDirectoryName(commandId) {\n return createHash2("sha256").update(commandId, "utf8").digest("hex");\n}\nfunction truncateUtf8(value, maximumBytes) {\n let result = "";\n let bytes = 0;\n for (const character of value) {\n const characterBytes = Buffer.byteLength(character, "utf8");\n if (bytes + characterBytes > maximumBytes) break;\n result += character;\n bytes += characterBytes;\n }\n return result;\n}\nfunction immutableAttachmentFilename(commandId, attachment) {\n const commandHash = commandDirectoryName(commandId);\n const nameHash = createHash2("sha256").update(attachment.path, "utf8").digest("hex").slice(0, 16);\n return `${commandHash}-${attachment.sha256.toLowerCase()}-${nameHash}-${truncateUtf8(\n attachment.path,\n ATTACHMENT_TARGET_SUFFIX_BYTES\n )}`;\n}\nfunction throwIfAborted(signal) {\n if (!signal?.aborted) return;\n if (signal.reason instanceof Error) throw signal.reason;\n throw new Error("Attachment materialization was aborted.");\n}\nasync function writeChunk(handle, chunk) {\n let offset = 0;\n while (offset < chunk.byteLength) {\n const { bytesWritten } = await handle.write(chunk, offset, chunk.byteLength - offset, null);\n if (bytesWritten <= 0) throw new Error("Attachment file write made no progress.");\n offset += bytesWritten;\n }\n}\nfunction attachmentBatchMarkerName(commandHash, state) {\n return `.batch-${commandHash}.${state}`;\n}\nfunction isRecord4(value) {\n return typeof value === "object" && value !== null && !Array.isArray(value);\n}\nfunction validatePrivateAttachmentStats(stats, maximumBytes) {\n const expectedUid = typeof process.getuid === "function" ? BigInt(process.getuid()) : null;\n if (!stats.isFile() || stats.nlink !== 1n || (stats.mode & 0o777n) !== 0o600n || stats.size < 0n || stats.size > BigInt(maximumBytes) || expectedUid !== null && stats.uid !== expectedUid) {\n throw new AttachmentMaterializationError(\n "Attempt attachment storage contains an invalid published file."\n );\n }\n return Number(stats.size);\n}\nasync function attachmentDigest(handle, sizeBytes) {\n const hash = createHash2("sha256");\n let offset = 0;\n while (offset < sizeBytes) {\n const chunk = Buffer.allocUnsafe(Math.min(ATTACHMENT_READ_CHUNK_BYTES, sizeBytes - offset));\n const { bytesRead } = await handle.read(chunk, 0, chunk.byteLength, offset);\n if (bytesRead <= 0) {\n throw new AttachmentMaterializationError(\n "Attempt attachment storage contains a truncated published file."\n );\n }\n hash.update(chunk.subarray(0, bytesRead));\n offset += bytesRead;\n }\n return hash.digest("hex");\n}\nvar SupervisorAttachmentMaterializer = class {\n constructor(config, dependencies = {}) {\n this.config = config;\n this.directory = attachmentDirectory(config);\n this.dependencies = { ...DEFAULT_DEPENDENCIES, ...dependencies };\n this.maxFilesPerAttempt = config.attachments.maxFilesPerAttempt ?? DEFAULT_SUPERVISOR_ATTACHMENT_CONFIG.maxFilesPerAttempt;\n this.maxBytesPerAttempt = config.attachments.maxBytesPerAttempt ?? config.attachments.maxBytesPerCommand;\n }\n config;\n directory;\n dependencies;\n maxFilesPerAttempt;\n maxBytesPerAttempt;\n attachmentDirectoryPromise = null;\n activeMaterializations = /* @__PURE__ */ new Set();\n materializationTail = Promise.resolve();\n closed = false;\n closePromise = null;\n materialize(commandId, attachments, signal) {\n if (this.closed) {\n return Promise.reject(new Error("Supervisor attachment materializer is closed."));\n }\n const materializing = this.materializationTail.then(\n () => this.materializeBound(commandId, attachments, signal)\n );\n this.materializationTail = materializing.then(\n () => void 0,\n () => void 0\n );\n this.activeMaterializations.add(materializing);\n void materializing.then(\n () => this.activeMaterializations.delete(materializing),\n () => this.activeMaterializations.delete(materializing)\n );\n return materializing;\n }\n async close() {\n if (this.closePromise !== null) return this.closePromise;\n this.closed = true;\n const closing = (async () => {\n await Promise.allSettled([...this.activeMaterializations]);\n const directoryPromise = this.attachmentDirectoryPromise;\n this.attachmentDirectoryPromise = null;\n const directory = await directoryPromise?.catch(() => null);\n await directory?.handle.close();\n })();\n this.closePromise = closing;\n return closing;\n }\n async materializeBound(commandId, attachments, signal) {\n throwIfAborted(signal);\n if (!attachments?.length) return void 0;\n if (attachments.length > MAX_ATTACHMENTS_PER_COMMAND) {\n throw new AttachmentMaterializationError(\n `A command may contain at most ${MAX_ATTACHMENTS_PER_COMMAND} attachments.`\n );\n }\n let declaredTotal = 0;\n const ids = /* @__PURE__ */ new Set();\n const paths = /* @__PURE__ */ new Set();\n const sources = /* @__PURE__ */ new Map();\n for (const attachment of attachments) {\n validateFilename(attachment);\n if (!/^[a-fA-F0-9]{64}$/.test(attachment.sha256)) {\n throw safeError(attachment, "SHA-256 must contain exactly 64 hexadecimal characters.");\n }\n if (!Number.isSafeInteger(attachment.sizeBytes) || attachment.sizeBytes < 0) {\n throw safeError(attachment, "sizeBytes must be a nonnegative safe integer.");\n }\n if (attachment.sizeBytes > this.config.attachments.maxBytesPerAttachment) {\n throw safeError(attachment, "exceeds the per-attachment byte limit.");\n }\n declaredTotal += attachment.sizeBytes;\n if (!Number.isSafeInteger(declaredTotal) || declaredTotal > this.config.attachments.maxBytesPerCommand) {\n throw new AttachmentMaterializationError(\n "Command attachments exceed the aggregate byte limit."\n );\n }\n if (ids.has(attachment.id)) throw safeError(attachment, "ID is duplicated.");\n if (paths.has(attachment.path)) throw safeError(attachment, "path is duplicated.");\n ids.add(attachment.id);\n paths.add(attachment.path);\n sources.set(attachment, validateSourceUrl(attachment));\n }\n const attachmentDirectory2 = await this.getAttachmentDirectory();\n throwIfAborted(signal);\n const usage = await this.recoverAttachmentUsage(attachmentDirectory2);\n const targetNames = /* @__PURE__ */ new Map();\n const requestedTargets = /* @__PURE__ */ new Set();\n let reservedFiles = 0;\n let reservedBytes = 0;\n for (const attachment of attachments) {\n const targetName = immutableAttachmentFilename(commandId, attachment);\n if (requestedTargets.has(targetName)) {\n throw safeError(attachment, "resolves to a duplicate immutable target.");\n }\n requestedTargets.add(targetName);\n targetNames.set(attachment, targetName);\n const existing = usage.files.get(targetName);\n if (existing) {\n if (existing.sizeBytes !== attachment.sizeBytes) {\n throw safeError(attachment, "does not match its existing immutable target.");\n }\n } else {\n reservedFiles += 1;\n reservedBytes += attachment.sizeBytes;\n }\n }\n if (usage.files.size + reservedFiles > this.maxFilesPerAttempt) {\n throw new AttachmentMaterializationError(\n "Attempt attachments exceed the persistent file limit."\n );\n }\n const reservedTotalBytes = usage.bytes + reservedBytes;\n if (!Number.isSafeInteger(reservedBytes) || !Number.isSafeInteger(reservedTotalBytes) || reservedTotalBytes > this.maxBytesPerAttempt) {\n throw new AttachmentMaterializationError(\n "Attempt attachments exceed the persistent byte limit."\n );\n }\n const rollbackTargets = attachments.map((attachment) => targetNames.get(attachment)).filter(\n (targetName) => targetName !== void 0 && !usage.files.has(targetName)\n );\n const batchMarkerName = rollbackTargets.length === 0 ? null : await this.beginAttachmentBatch(\n attachmentDirectory2,\n commandDirectoryName(commandId),\n rollbackTargets\n );\n const materialized = [];\n try {\n for (const attachment of attachments) {\n throwIfAborted(signal);\n const source = sources.get(attachment);\n const targetName = targetNames.get(attachment);\n if (!source || !targetName) {\n throw safeError(attachment, "validated materialization metadata was lost.");\n }\n let path;\n if (usage.files.has(targetName)) {\n path = await this.reuseExisting(\n attachmentDirectory2,\n targetName,\n attachment\n );\n } else {\n const downloaded = await this.download(\n attachmentDirectory2,\n targetName,\n attachment,\n source,\n signal\n );\n path = downloaded.path;\n }\n materialized.push({\n id: attachment.id,\n path,\n ...attachment.mimeType === void 0 ? {} : { mimeType: attachment.mimeType }\n });\n }\n if (batchMarkerName !== null) {\n await this.commitAttachmentBatch(attachmentDirectory2, batchMarkerName);\n }\n return materialized;\n } catch (error) {\n try {\n await this.rollbackBatch(\n attachmentDirectory2,\n rollbackTargets,\n batchMarkerName\n );\n } catch {\n throw new AttachmentMaterializationError(\n "Attachment batch rollback could not be durably completed."\n );\n }\n throw error;\n }\n }\n /**\n * The published files are the durable quota ledger. A restarted supervisor\n * reconstructs exact usage through its retained directory descriptor and\n * removes only crash-left temporary names from the reserved namespace.\n */\n async recoverAttachmentUsage(attachmentDirectory2) {\n await this.removeCrashLeftPartials(attachmentDirectory2);\n await this.recoverAttachmentBatches(attachmentDirectory2);\n const publishedNames = [];\n let unexpectedEntry = false;\n let tooManyFiles = false;\n let removedPartial = false;\n const scanner = await opendir(descriptorBoundDirectoryPath(attachmentDirectory2));\n try {\n while (true) {\n const entry = await scanner.read();\n if (entry === null) break;\n if (entry.name.startsWith(".") && entry.name.endsWith(".partial")) {\n const removed = await unlinkDescriptorBoundEntryIfPresent(\n attachmentDirectory2,\n entry.name\n );\n removedPartial ||= removed;\n continue;\n }\n if (!IMMUTABLE_ATTACHMENT_FILENAME_PATTERN.test(entry.name)) {\n unexpectedEntry = true;\n continue;\n }\n if (publishedNames.length >= this.maxFilesPerAttempt) {\n tooManyFiles = true;\n continue;\n }\n publishedNames.push(entry.name);\n }\n } finally {\n await scanner.close().catch((error) => {\n if (error.code !== "ERR_DIR_CLOSED") throw error;\n });\n if (removedPartial) await syncDescriptorBoundDirectory(attachmentDirectory2);\n }\n if (unexpectedEntry) {\n throw new AttachmentMaterializationError(\n "Attempt attachment storage contains an unexpected entry."\n );\n }\n if (tooManyFiles) {\n throw new AttachmentMaterializationError(\n "Attempt attachment storage exceeds its persistent budget."\n );\n }\n const files = /* @__PURE__ */ new Map();\n let bytes = 0;\n for (const name of publishedNames) {\n const handle = await openRegularFilesystemEntryAt(\n attachmentDirectory2,\n name,\n fsConstants2.O_RDONLY,\n "Supervisor persisted attachment"\n );\n try {\n const sizeBytes = validatePrivateAttachmentStats(\n await handle.stat({ bigint: true }),\n this.config.attachments.maxBytesPerAttachment\n );\n files.set(name, { sizeBytes });\n bytes += sizeBytes;\n if (!Number.isSafeInteger(bytes) || bytes > this.maxBytesPerAttempt) {\n throw new AttachmentMaterializationError(\n "Attempt attachment storage exceeds its persistent budget."\n );\n }\n } finally {\n await handle.close().catch(() => void 0);\n }\n }\n return { files, bytes };\n }\n async removeCrashLeftPartials(attachmentDirectory2) {\n let removed = false;\n const scanner = await opendir(descriptorBoundDirectoryPath(attachmentDirectory2));\n try {\n while (true) {\n const entry = await scanner.read();\n if (entry === null) break;\n if (!entry.name.startsWith(".") || !entry.name.endsWith(".partial")) continue;\n const didRemove = await unlinkDescriptorBoundEntryIfPresent(\n attachmentDirectory2,\n entry.name\n );\n removed ||= didRemove;\n }\n } finally {\n await scanner.close().catch((error) => {\n if (error.code !== "ERR_DIR_CLOSED") throw error;\n });\n }\n if (removed) await syncDescriptorBoundDirectory(attachmentDirectory2);\n }\n async readAttachmentBatchMarker(attachmentDirectory2, markerName, expectedCommandHash) {\n const handle = await openRegularFilesystemEntryAt(\n attachmentDirectory2,\n markerName,\n fsConstants2.O_RDONLY,\n "Supervisor attachment batch marker"\n );\n try {\n const stats = await handle.stat({ bigint: true });\n const expectedUid = typeof process.getuid === "function" ? BigInt(process.getuid()) : null;\n if (!stats.isFile() || stats.nlink !== 1n || (stats.mode & 0o777n) !== 0o600n || stats.size <= 0n || stats.size > BigInt(ATTACHMENT_BATCH_MARKER_MAX_BYTES) || expectedUid !== null && stats.uid !== expectedUid) {\n throw new AttachmentMaterializationError(\n "Attempt attachment storage contains an invalid batch marker."\n );\n }\n const size = Number(stats.size);\n const text = await readBoundedRegularTextHandle(\n handle,\n ATTACHMENT_BATCH_MARKER_MAX_BYTES,\n "Supervisor attachment batch marker",\n {\n expectedBytes: size,\n ignoreBOM: false,\n prematureEofError: () => new AttachmentMaterializationError(\n "Attempt attachment storage contains a truncated batch marker."\n ),\n invalidUtf8Error: () => new AttachmentMaterializationError(\n "Attempt attachment storage contains an invalid batch marker."\n )\n }\n );\n let value;\n try {\n value = JSON.parse(text);\n } catch {\n throw new AttachmentMaterializationError(\n "Attempt attachment storage contains an invalid batch marker."\n );\n }\n if (!isRecord4(value) || value.version !== 1 || value.commandHash !== expectedCommandHash || !Array.isArray(value.targets) || value.targets.length === 0 || value.targets.length > MAX_ATTACHMENTS_PER_COMMAND || Object.keys(value).length !== 3) {\n throw new AttachmentMaterializationError(\n "Attempt attachment storage contains an invalid batch marker."\n );\n }\n const targets = /* @__PURE__ */ new Set();\n for (const target of value.targets) {\n if (typeof target !== "string" || !IMMUTABLE_ATTACHMENT_FILENAME_PATTERN.test(target) || !target.startsWith(`${expectedCommandHash}-`) || targets.has(target)) {\n throw new AttachmentMaterializationError(\n "Attempt attachment storage contains an invalid batch marker."\n );\n }\n targets.add(target);\n }\n return {\n version: 1,\n commandHash: expectedCommandHash,\n targets: [...targets]\n };\n } finally {\n await handle.close().catch(() => void 0);\n }\n }\n async recoverAttachmentBatches(attachmentDirectory2) {\n const markers = /* @__PURE__ */ new Map();\n const scanner = await opendir(descriptorBoundDirectoryPath(attachmentDirectory2));\n try {\n while (true) {\n const entry = await scanner.read();\n if (entry === null) break;\n const match = ATTACHMENT_BATCH_MARKER_PATTERN.exec(entry.name);\n if (!match) continue;\n const commandHash = match[1];\n const state = match[2];\n const existing = markers.get(commandHash) ?? {};\n existing[state] = entry.name;\n markers.set(commandHash, existing);\n }\n } finally {\n await scanner.close().catch((error) => {\n if (error.code !== "ERR_DIR_CLOSED") throw error;\n });\n }\n for (const [commandHash, markerNames] of markers) {\n if (markerNames.pending && markerNames.committed) {\n throw new AttachmentMaterializationError(\n "Attempt attachment storage contains conflicting batch markers."\n );\n }\n const markerName = markerNames.pending ?? markerNames.committed;\n if (!markerName) continue;\n const marker = await this.readAttachmentBatchMarker(\n attachmentDirectory2,\n markerName,\n commandHash\n );\n let changed = false;\n if (markerNames.pending) {\n for (const targetName of marker.targets) {\n const removed = await unlinkDescriptorBoundEntryIfPresent(\n attachmentDirectory2,\n targetName\n );\n changed ||= removed;\n }\n if (changed) await syncDescriptorBoundDirectory(attachmentDirectory2);\n }\n await unlinkDescriptorBoundEntry(attachmentDirectory2, markerName);\n await syncDescriptorBoundDirectory(attachmentDirectory2);\n }\n }\n async beginAttachmentBatch(attachmentDirectory2, commandHash, targets) {\n const markerName = attachmentBatchMarkerName(commandHash, "pending");\n const marker = { version: 1, commandHash, targets };\n const encoded = Buffer.from(`${JSON.stringify(marker)}\n`, "utf8");\n if (encoded.byteLength > ATTACHMENT_BATCH_MARKER_MAX_BYTES) {\n throw new AttachmentMaterializationError(\n "Attachment batch marker exceeds its bounded capacity."\n );\n }\n const temporaryName = `.batch-${commandHash}-${randomUUID2()}.partial`;\n let handle = null;\n let temporaryExists = false;\n let markerPublished = false;\n try {\n handle = await openRegularFileAt(\n attachmentDirectory2,\n temporaryName,\n fsConstants2.O_WRONLY | fsConstants2.O_CREAT | fsConstants2.O_EXCL,\n "Supervisor attachment batch marker temporary file",\n 384\n );\n temporaryExists = true;\n await writeChunk(handle, encoded);\n await handle.chmod(384);\n await handle.sync();\n await linkDescriptorBoundEntry(\n attachmentDirectory2,\n temporaryName,\n attachmentDirectory2,\n markerName\n );\n markerPublished = true;\n await unlinkDescriptorBoundEntry(attachmentDirectory2, temporaryName);\n temporaryExists = false;\n await syncDescriptorBoundDirectory(attachmentDirectory2);\n return markerName;\n } catch (error) {\n if (markerPublished) {\n await unlinkDescriptorBoundEntry(attachmentDirectory2, markerName).catch(() => void 0);\n }\n if (temporaryExists) {\n await unlinkDescriptorBoundEntry(attachmentDirectory2, temporaryName).catch(() => void 0);\n }\n if (markerPublished || temporaryExists) {\n await syncDescriptorBoundDirectory(attachmentDirectory2).catch(() => void 0);\n }\n throw error;\n } finally {\n await handle?.close().catch(() => void 0);\n }\n }\n async commitAttachmentBatch(attachmentDirectory2, pendingMarkerName) {\n const committedMarkerName = pendingMarkerName.replace(/\\.pending$/u, ".committed");\n await renameDescriptorBoundEntry(\n attachmentDirectory2,\n pendingMarkerName,\n attachmentDirectory2,\n committedMarkerName\n );\n await syncDescriptorBoundDirectory(attachmentDirectory2);\n await unlinkDescriptorBoundEntry(attachmentDirectory2, committedMarkerName).then(\n async () => syncDescriptorBoundDirectory(attachmentDirectory2),\n () => void 0\n );\n }\n async reuseExisting(attachmentDirectory2, targetName, attachment) {\n let handle = null;\n try {\n handle = await openRegularFileAt(\n attachmentDirectory2,\n targetName,\n fsConstants2.O_RDONLY,\n "Supervisor existing attachment"\n );\n const before = await handle.stat({ bigint: true });\n const sizeBytes = validatePrivateAttachmentStats(\n before,\n this.config.attachments.maxBytesPerAttachment\n );\n if (sizeBytes !== attachment.sizeBytes) {\n throw safeError(attachment, "does not match its existing immutable target.");\n }\n const digest = await attachmentDigest(handle, sizeBytes);\n const after = await handle.stat({ bigint: true });\n validatePrivateAttachmentStats(after, this.config.attachments.maxBytesPerAttachment);\n if (before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || digest !== attachment.sha256.toLowerCase()) {\n throw safeError(attachment, "does not match its existing immutable target.");\n }\n return await this.canonicalAttachmentPath(attachmentDirectory2, targetName, handle);\n } catch (error) {\n if (error instanceof AttachmentMaterializationError) throw error;\n throw safeError(attachment, "existing immutable target failed validation.");\n } finally {\n await handle?.close().catch(() => void 0);\n }\n }\n async canonicalAttachmentPath(attachmentDirectory2, targetName, handle) {\n const stablePath = join2(attachmentDirectory2.displayPath, targetName);\n await this.dependencies.beforeAttachmentPathPublished?.(stablePath);\n const canonicalDirectory = await bindDescriptorBoundDirectory(\n this.config.stateDurabilityAnchor,\n attachmentDirectory2.displayPath,\n attachmentDirectory2.identity\n );\n let path;\n try {\n await this.dependencies.afterCanonicalAttachmentDirectoryBound?.(\n canonicalDirectory.displayPath\n );\n path = await withRevalidatedPrivateRegularFile(\n handle,\n () => openRegularFileAt(\n canonicalDirectory,\n targetName,\n fsConstants2.O_RDONLY,\n "Supervisor attachment canonical file"\n ),\n () => stablePath,\n {\n maximumBytes: this.config.attachments.maxBytesPerAttachment,\n failureMessage: "Supervisor attachment canonical path no longer identifies the materialized file."\n }\n );\n } finally {\n await canonicalDirectory.handle.close().catch(() => void 0);\n }\n const finalCanonicalDirectory = await bindDescriptorBoundDirectory(\n this.config.stateDurabilityAnchor,\n attachmentDirectory2.displayPath,\n attachmentDirectory2.identity\n );\n try {\n await withRevalidatedPrivateRegularFile(\n handle,\n () => openRegularFileAt(\n finalCanonicalDirectory,\n targetName,\n fsConstants2.O_RDONLY,\n "Supervisor attachment final canonical file"\n ),\n () => void 0,\n {\n maximumBytes: this.config.attachments.maxBytesPerAttachment,\n failureMessage: "Supervisor attachment canonical path no longer identifies the materialized file."\n }\n );\n } finally {\n await finalCanonicalDirectory.handle.close().catch(() => void 0);\n }\n return path;\n }\n async rollbackBatch(attachmentDirectory2, targetNames, pendingMarkerName) {\n let removed = false;\n let failure;\n for (const targetName of [...targetNames].reverse()) {\n try {\n const didRemove = await unlinkDescriptorBoundEntryIfPresent(\n attachmentDirectory2,\n targetName\n );\n removed ||= didRemove;\n } catch (error) {\n failure ??= error;\n }\n }\n if (removed) {\n try {\n await syncDescriptorBoundDirectory(attachmentDirectory2);\n } catch (error) {\n failure ??= error;\n }\n }\n if (failure !== void 0) throw failure;\n if (pendingMarkerName !== null) {\n const committedMarkerName = pendingMarkerName.replace(/\\.pending$/u, ".committed");\n for (const markerName of [pendingMarkerName, committedMarkerName]) {\n try {\n const didRemove = await unlinkDescriptorBoundEntryIfPresent(\n attachmentDirectory2,\n markerName\n );\n if (didRemove) await syncDescriptorBoundDirectory(attachmentDirectory2);\n } catch (error) {\n failure ??= error;\n }\n }\n }\n if (failure !== void 0) throw failure;\n }\n getAttachmentDirectory() {\n if (this.attachmentDirectoryPromise !== null) {\n return this.attachmentDirectoryPromise;\n }\n const opening = this.openAttachmentDirectory();\n this.attachmentDirectoryPromise = opening;\n void opening.catch(() => {\n if (this.attachmentDirectoryPromise === opening) {\n this.attachmentDirectoryPromise = null;\n }\n });\n return opening;\n }\n async openAttachmentDirectory() {\n const attemptDirectory = await openSupervisorAttemptStorage(this.config);\n let attachmentDirectory2 = null;\n let retained = false;\n try {\n if (dirname(this.directory) !== attemptDirectory.displayPath) {\n throw new Error("Supervisor attachment storage resolved to an unexpected directory.");\n }\n attachmentDirectory2 = await ensureDescriptorBoundDirectoryAt(attemptDirectory, "attachments");\n await attachmentDirectory2.handle.chmod(448);\n await this.dependencies.afterAttachmentDirectoryBound?.(attachmentDirectory2.displayPath);\n retained = true;\n return attachmentDirectory2;\n } finally {\n if (!retained) await attachmentDirectory2?.handle.close().catch(() => void 0);\n await attemptDirectory.handle.close().catch(() => void 0);\n }\n }\n async download(attachmentDirectory2, targetName, attachment, source, externalSignal) {\n const temporaryName = `.${this.dependencies.randomId()}.partial`;\n const abortController = new AbortController();\n const abortFromExternalSignal = () => abortController.abort(externalSignal?.reason);\n if (externalSignal?.aborted) abortFromExternalSignal();\n else\n externalSignal?.addEventListener("abort", abortFromExternalSignal, {\n once: true\n });\n const timeout = setTimeout(\n () => abortController.abort(new Error("Attachment download timed out.")),\n this.config.attachments.downloadTimeoutMs\n );\n let handle = null;\n let temporaryExists = false;\n let targetPublished = false;\n let published = false;\n try {\n throwIfAborted(abortController.signal);\n handle = await openRegularFileAt(\n attachmentDirectory2,\n temporaryName,\n fsConstants2.O_WRONLY | fsConstants2.O_CREAT | fsConstants2.O_EXCL,\n "Supervisor attachment temporary file",\n 384\n );\n temporaryExists = true;\n let response;\n try {\n response = await this.dependencies.fetch(source, {\n redirect: "error",\n signal: abortController.signal\n });\n } catch {\n throw safeError(attachment, "download failed.");\n }\n if (!response.ok) {\n throw safeError(attachment, `download returned HTTP ${response.status}.`);\n }\n if (!response.body && attachment.sizeBytes !== 0) {\n throw safeError(attachment, "download returned an empty body.");\n }\n const hash = createHash2("sha256");\n let receivedBytes = 0;\n if (response.body) {\n const reader = response.body.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n throwIfAborted(abortController.signal);\n receivedBytes += value.byteLength;\n if (receivedBytes > attachment.sizeBytes) {\n throw safeError(attachment, "download exceeded its declared size.");\n }\n hash.update(value);\n await writeChunk(handle, value);\n }\n } finally {\n reader.releaseLock();\n }\n }\n if (receivedBytes !== attachment.sizeBytes) {\n throw safeError(\n attachment,\n `download size did not match the declared ${attachment.sizeBytes} bytes.`\n );\n }\n if (hash.digest("hex") !== attachment.sha256.toLowerCase()) {\n throw safeError(attachment, "download did not match its declared SHA-256.");\n }\n await handle.chmod(384);\n await handle.sync();\n throwIfAborted(abortController.signal);\n await linkDescriptorBoundEntry(\n attachmentDirectory2,\n temporaryName,\n attachmentDirectory2,\n targetName\n );\n targetPublished = true;\n await unlinkDescriptorBoundEntry(attachmentDirectory2, temporaryName);\n temporaryExists = false;\n await syncDescriptorBoundDirectory(attachmentDirectory2);\n const path = await this.canonicalAttachmentPath(\n attachmentDirectory2,\n targetName,\n handle\n );\n published = true;\n return { path, targetName };\n } catch (error) {\n abortController.abort();\n if (error instanceof AttachmentMaterializationError) throw error;\n throw safeError(attachment, "could not be materialized.");\n } finally {\n clearTimeout(timeout);\n externalSignal?.removeEventListener("abort", abortFromExternalSignal);\n await handle?.close().catch(() => void 0);\n let removed = false;\n let cleanupFailure;\n if (!published) {\n if (targetPublished) {\n removed = await unlinkDescriptorBoundEntryIfPresent(\n attachmentDirectory2,\n targetName\n ).catch((error) => {\n cleanupFailure ??= error;\n return false;\n });\n }\n if (temporaryExists) {\n const removedTemporary = await unlinkDescriptorBoundEntryIfPresent(\n attachmentDirectory2,\n temporaryName\n ).catch((error) => {\n cleanupFailure ??= error;\n return false;\n });\n removed ||= removedTemporary;\n }\n if (removed) {\n await syncDescriptorBoundDirectory(attachmentDirectory2).catch((error) => {\n cleanupFailure ??= error;\n });\n }\n if (cleanupFailure !== void 0) {\n throw new AttachmentMaterializationError(\n "Attachment cleanup could not be durably completed."\n );\n }\n }\n }\n }\n};\n\n// src/supervisor/execution-gate.ts\nvar SupervisorExecutionClosedError = class extends Error {\n constructor(kind, reason, options = {}) {\n super(`Supervisor execution is closed: ${reason}`, options);\n this.kind = kind;\n this.reason = reason;\n }\n kind;\n reason;\n name = "SupervisorExecutionClosedError";\n};\nvar SupervisorExecutionGate = class {\n controller = new AbortController();\n closureValue = null;\n get signal() {\n return this.controller.signal;\n }\n get closure() {\n return this.closureValue;\n }\n get isClosed() {\n return this.closureValue !== null;\n }\n close(kind, reason, cause) {\n if (this.closureValue) return false;\n const error = new SupervisorExecutionClosedError(kind, reason, { cause });\n this.closureValue = { kind, reason, error };\n this.controller.abort(error);\n return true;\n }\n throwIfClosed() {\n if (this.closureValue) throw this.closureValue.error;\n }\n};\n\n// src/sensitive-value-redactor.ts\nvar DEFAULT_MINIMUM_CAPTURE_LENGTH = 8;\nvar DEFAULT_CREDENTIAL_ENV_NAME_PATTERN = /(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)/iu;\nfunction defaultEnvironmentValueIsSensitive(name, value) {\n return value.length >= DEFAULT_MINIMUM_CAPTURE_LENGTH && DEFAULT_CREDENTIAL_ENV_NAME_PATTERN.test(name);\n}\nvar SensitiveValueRedactor = class {\n secrets = /* @__PURE__ */ new Set();\n minimumCaptureLength;\n environment;\n isEnvironmentValueSensitive;\n constructor(values = [], options = {}) {\n this.minimumCaptureLength = options.minimumCaptureLength ?? DEFAULT_MINIMUM_CAPTURE_LENGTH;\n const environment = options.environment;\n this.environment = typeof environment === "function" ? environment : () => environment ?? process.env;\n this.isEnvironmentValueSensitive = options.isEnvironmentValueSensitive ?? defaultEnvironmentValueIsSensitive;\n this.captureAll(values);\n }\n capture(value) {\n if (value) this.secrets.add(value);\n }\n captureAll(values) {\n for (const value of values) {\n if (value.length >= this.minimumCaptureLength) this.capture(value);\n }\n }\n redact(value) {\n const environmentSecrets = Object.entries(this.environment()).filter(\n (entry) => Boolean(entry[1]) && this.isEnvironmentValueSensitive(entry[0], entry[1])\n ).map(([, secret]) => secret);\n const orderedSecrets = [.../* @__PURE__ */ new Set([...this.secrets, ...environmentSecrets])].sort(\n (left, right) => {\n const lengthDifference = right.length - left.length;\n if (lengthDifference !== 0) return lengthDifference;\n return left < right ? -1 : left > right ? 1 : 0;\n }\n );\n let redacted = value;\n for (const secret of orderedSecrets) {\n redacted = redacted.split(secret).join("[REDACTED]");\n }\n return redacted;\n }\n serialize(error) {\n const serialized = serializeError(error);\n return {\n ...serialized.name === void 0 ? {} : { name: this.redact(serialized.name) },\n message: this.redact(serialized.message),\n ...serialized.stack === void 0 ? {} : { stack: this.redact(serialized.stack) }\n };\n }\n};\n\n// src/supervisor/runtime-support.ts\nfunction isRecord5(value) {\n return typeof value === "object" && value !== null && !Array.isArray(value);\n}\nfunction errorFromUnknown(error) {\n return error instanceof Error ? error : new Error(String(error));\n}\n\n// src/supervisor/gateway-transport.ts\nvar WEBSOCKET_OPEN = 1;\nvar MAX_WEBSOCKET_BUFFERED_BYTES = 1024 * 1024;\nvar MAX_OUTBOUND_BATCH_BYTES = 1024 * 1024;\nvar MAX_OUTBOUND_IN_FLIGHT_BYTES = 8 * 1024 * 1024;\nvar SUPERVISOR_MAX_PENDING_INBOUND_FRAMES = SUPERVISOR_MAX_PENDING_COMMANDS * 2 + 4;\nvar SUPERVISOR_MAX_PENDING_INBOUND_BYTES = SUPERVISOR_MAX_PENDING_COMMAND_BYTES + SUPERVISOR_MAX_FRAME_BYTES * 2;\nvar DEFAULT_GATEWAY_TRANSPORT_DEPENDENCIES = {\n createWebSocket(url) {\n const WebSocketConstructor = globalThis.WebSocket;\n if (!WebSocketConstructor) {\n throw new Error("The supervisor runtime requires a Node.js version with global WebSocket.");\n }\n return new WebSocketConstructor(url);\n },\n random: Math.random,\n now: Date.now\n};\nvar SupervisorInboundFrameTooLargeError = class extends Error {\n name = "SupervisorInboundFrameTooLargeError";\n};\nfunction decodeGatewayMessage(data) {\n let text;\n let byteLength;\n if (typeof data === "string") {\n byteLength = Buffer.byteLength(data, "utf8");\n if (byteLength >= SUPERVISOR_MAX_FRAME_BYTES) {\n throw new SupervisorInboundFrameTooLargeError(\n `Gateway frame exceeds the ${SUPERVISOR_MAX_FRAME_BYTES}-byte limit.`\n );\n }\n text = data;\n } else if (data instanceof ArrayBuffer) {\n byteLength = data.byteLength;\n if (byteLength >= SUPERVISOR_MAX_FRAME_BYTES) {\n throw new SupervisorInboundFrameTooLargeError(\n `Gateway frame exceeds the ${SUPERVISOR_MAX_FRAME_BYTES}-byte limit.`\n );\n }\n try {\n text = new TextDecoder("utf-8", { fatal: true }).decode(data);\n } catch {\n return {\n decoded: { ok: false, error: "Gateway sent invalid UTF-8." },\n byteLength\n };\n }\n } else if (ArrayBuffer.isView(data)) {\n const view = data;\n byteLength = view.byteLength;\n if (byteLength >= SUPERVISOR_MAX_FRAME_BYTES) {\n throw new SupervisorInboundFrameTooLargeError(\n `Gateway frame exceeds the ${SUPERVISOR_MAX_FRAME_BYTES}-byte limit.`\n );\n }\n try {\n text = new TextDecoder("utf-8", { fatal: true }).decode(\n new Uint8Array(view.buffer, view.byteOffset, view.byteLength)\n );\n } catch {\n return {\n decoded: { ok: false, error: "Gateway sent invalid UTF-8." },\n byteLength\n };\n }\n } else {\n return {\n decoded: { ok: false, error: "Gateway sent a non-text frame." },\n byteLength: 0\n };\n }\n let raw;\n try {\n raw = JSON.parse(text);\n } catch {\n return {\n decoded: { ok: false, error: "Gateway sent malformed JSON." },\n byteLength\n };\n }\n const frame = parseGatewayToSupervisorFrame(raw);\n return {\n decoded: frame ? { ok: true, frame } : { ok: false, error: "Gateway sent an invalid frame." },\n byteLength\n };\n}\nvar SupervisorGatewayTransport = class {\n constructor(config, store, harness, commands, executionGate, redactor, callbacks, dependencies = DEFAULT_GATEWAY_TRANSPORT_DEPENDENCIES) {\n this.config = config;\n this.store = store;\n this.harness = harness;\n this.commands = commands;\n this.executionGate = executionGate;\n this.redactor = redactor;\n this.callbacks = callbacks;\n this.dependencies = dependencies;\n }\n config;\n store;\n harness;\n commands;\n executionGate;\n redactor;\n callbacks;\n dependencies;\n connection = null;\n nextConnectionGeneration = 1;\n reconnectAttempt = 0;\n reconnectTimer = null;\n stopping = false;\n // Old socket generations can retain their queued closures while a durable\n // handler is blocked. Account across the transport lifetime so reconnects\n // cannot each allocate another full generation-local inbound window.\n pendingInboundFrames = 0;\n pendingInboundBytes = 0;\n start() {\n this.connect();\n }\n beginShutdown() {\n this.stopping = true;\n if (this.reconnectTimer) clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n this.clearConnectionTimers(this.connection);\n }\n finishShutdown(options) {\n const connection = this.connection;\n if (!options.fatal) this.flushOutbox(connection);\n if (this.isActiveConnection(connection)) {\n connection.socket.close(\n 1e3,\n options.superseded ? "attempt superseded" : "supervisor stopped"\n );\n this.connection = null;\n }\n }\n failActiveConnection() {\n const connection = this.connection;\n this.clearConnectionTimers(connection);\n if (!this.isActiveConnection(connection)) return;\n connection.failed = true;\n connection.socket.close(1011, "durable supervisor failure");\n }\n flushOutbox(connection = this.connection) {\n if (!this.isActiveConnection(connection) || connection.failed || !connection.resumed || connection.socket.readyState !== WEBSOCKET_OPEN || connection.socket.bufferedAmount > MAX_WEBSOCKET_BUFFERED_BYTES) {\n return;\n }\n const acknowledged = this.store.lastAcknowledgedEventSequence;\n const inFlight = Math.max(0, connection.transmittedEventSequence - acknowledged);\n const allowance = Math.max(0, this.config.maxInFlightEvents - inFlight);\n if (!allowance) return;\n let inFlightBytes = 0;\n for (const frame of this.store.listEventsAfter(acknowledged, inFlight)) {\n inFlightBytes += Buffer.byteLength(JSON.stringify(frame), "utf8");\n }\n if (inFlightBytes >= MAX_OUTBOUND_IN_FLIGHT_BYTES) return;\n let batchBytes = 0;\n const events = this.store.listEventsAfter(connection.transmittedEventSequence, allowance);\n for (const event of events) {\n if (!this.isActiveConnection(connection) || connection.failed || connection.socket.readyState !== WEBSOCKET_OPEN || connection.socket.bufferedAmount > MAX_WEBSOCKET_BUFFERED_BYTES) {\n break;\n }\n const serialized = JSON.stringify(event);\n const frameBytes = Buffer.byteLength(serialized, "utf8");\n if (frameBytes >= SUPERVISOR_MAX_FRAME_BYTES) {\n this.callbacks.failRuntime(\n new Error(\n `Durable event ${event.eventId} exceeds the supervisor WebSocket frame limit.`\n )\n );\n break;\n }\n if (batchBytes > 0 && batchBytes + frameBytes > MAX_OUTBOUND_BATCH_BYTES) break;\n if (inFlightBytes > 0 && inFlightBytes + frameBytes > MAX_OUTBOUND_IN_FLIGHT_BYTES) break;\n try {\n connection.socket.send(serialized);\n } catch {\n connection.socket.close(1011, "event send failed");\n break;\n }\n connection.transmittedEventSequence = event.attemptSequence;\n batchBytes += frameBytes;\n inFlightBytes += frameBytes;\n if (batchBytes >= MAX_OUTBOUND_BATCH_BYTES || inFlightBytes >= MAX_OUTBOUND_IN_FLIGHT_BYTES || connection.socket.bufferedAmount > MAX_WEBSOCKET_BUFFERED_BYTES) {\n break;\n }\n }\n }\n connect() {\n if (this.stopping || this.executionGate.isClosed) return;\n const socket = this.dependencies.createWebSocket(this.config.gatewayUrl);\n socket.binaryType = "arraybuffer";\n if (this.stopping || this.executionGate.isClosed) {\n socket.close(1e3, "supervisor stopped");\n return;\n }\n const connection = {\n generation: this.nextConnectionGeneration,\n socket,\n resumed: false,\n failed: false,\n transmittedEventSequence: 0,\n lastGatewayActivityAt: this.dependencies.now(),\n pendingInboundFrames: 0,\n pendingInboundBytes: 0,\n inboundTail: Promise.resolve(),\n handshakeTimer: null,\n heartbeatTimer: null\n };\n this.nextConnectionGeneration += 1;\n this.connection = connection;\n socket.addEventListener("open", () => {\n if (!this.isActiveConnection(connection) || this.stopping) return;\n const credential = this.callbacks.getCredential();\n if (!credential) {\n void this.callbacks.emitEvent({\n kind: "protocol_error",\n message: `Missing required credential environment variable ${this.config.credentialEnv}.`\n }).then(\n () => connection.socket.close(1008, "missing credential"),\n () => connection.socket.close(1008, "missing credential")\n );\n return;\n }\n const resume = {\n type: "resume",\n protocolVersion: SUPERVISOR_PROTOCOL_VERSION,\n runtimeVersion: SUPERVISOR_RUNTIME_VERSION,\n provider: "daytona",\n providerVersion: DAYTONA_SUPERVISOR_PROVIDER_VERSION,\n sessionId: this.config.sessionId,\n runId: this.config.runId,\n attemptId: this.config.attemptId,\n credential,\n lastAcknowledgedEventSequence: this.store.lastAcknowledgedEventSequence,\n lastAppliedCommandSequence: this.store.lastAppliedCommandSequence\n };\n try {\n connection.socket.send(JSON.stringify(resume));\n } catch {\n connection.failed = true;\n connection.socket.close(1011, "resume send failed");\n return;\n }\n connection.handshakeTimer = setTimeout(\n () => connection.socket.close(4e3, "resume handshake timeout"),\n this.config.handshakeTimeoutMs\n );\n });\n socket.addEventListener("message", (message) => {\n if (!this.isActiveConnection(connection) || this.stopping || connection.failed) {\n return;\n }\n connection.lastGatewayActivityAt = this.dependencies.now();\n let envelope;\n try {\n envelope = decodeGatewayMessage(message.data);\n } catch (error) {\n if (error instanceof SupervisorInboundFrameTooLargeError) {\n if (this.isActiveConnection(connection)) {\n connection.failed = true;\n connection.socket.close(1009, "gateway frame too large");\n }\n return;\n }\n throw error;\n }\n const { decoded, byteLength } = envelope;\n if (decoded.ok && decoded.frame.type === "attempt_superseded" && hasMatchingAttempt(this.config, decoded.frame)) {\n this.callbacks.acceptSupersession(decoded.frame.reason ?? "attempt_superseded");\n return;\n }\n if (connection.pendingInboundFrames + 1 > SUPERVISOR_MAX_PENDING_INBOUND_FRAMES || connection.pendingInboundBytes + byteLength > SUPERVISOR_MAX_PENDING_INBOUND_BYTES || this.pendingInboundFrames + 1 > SUPERVISOR_MAX_PENDING_INBOUND_FRAMES || this.pendingInboundBytes + byteLength > SUPERVISOR_MAX_PENDING_INBOUND_BYTES) {\n connection.failed = true;\n connection.socket.close(1013, "gateway inbound backpressure");\n return;\n }\n connection.pendingInboundFrames += 1;\n connection.pendingInboundBytes += byteLength;\n this.pendingInboundFrames += 1;\n this.pendingInboundBytes += byteLength;\n const handling = connection.inboundTail.then(() => this.handleGatewayMessage(connection, decoded)).then(() => void 0).catch((error) => {\n connection.failed = true;\n this.handleFrameFailure(connection, errorFromUnknown(error));\n }).finally(() => {\n connection.pendingInboundFrames -= 1;\n connection.pendingInboundBytes -= byteLength;\n this.pendingInboundFrames -= 1;\n this.pendingInboundBytes -= byteLength;\n });\n connection.inboundTail = handling;\n });\n socket.addEventListener("error", () => {\n if (this.isActiveConnection(connection)) {\n connection.socket.close(1011, "transport error");\n }\n });\n socket.addEventListener("close", () => {\n if (!this.isActiveConnection(connection)) return;\n this.clearConnectionTimers(connection);\n this.connection = null;\n this.scheduleReconnect();\n });\n }\n async handleGatewayMessage(connection, decoded) {\n if (!this.isActiveConnection(connection) || this.stopping || connection.failed) return;\n if (!decoded.ok) {\n await this.callbacks.emitEvent({ kind: "protocol_error", message: decoded.error });\n return;\n }\n const frame = decoded.frame;\n if (!hasMatchingAttempt(this.config, frame)) {\n connection.failed = true;\n connection.socket.close(1008, "attempt fence mismatch");\n return;\n }\n await this.handleGatewayFrame(connection, frame);\n }\n async handleGatewayFrame(connection, frame) {\n if (frame.type === "resume_ok") {\n if (connection.resumed) {\n this.rejectGatewayCursor(connection);\n return;\n }\n if (frame.acknowledgedEventSequence > this.store.lastEventSequence || frame.acknowledgedEventSequence < this.store.lastAcknowledgedEventSequence) {\n this.rejectGatewayCursor(connection);\n return;\n }\n const pendingCommands = [...frame.pendingCommands].sort(\n (left, right) => left.commandSequence - right.commandSequence\n );\n const resumeBatchToken = await this.commands.prepareResumeBatch(\n pendingCommands,\n frame.lastAppliedCommandSequence\n );\n let committed = false;\n try {\n if (!this.isActiveConnection(connection) || this.executionGate.isClosed) return;\n await this.store.acknowledgeEvents(frame.acknowledgedEventSequence);\n if (!this.isActiveConnection(connection) || this.executionGate.isClosed) return;\n await this.store.advanceCommandCursor(frame.lastAppliedCommandSequence);\n if (!this.isActiveConnection(connection) || this.executionGate.isClosed) return;\n committed = await this.commands.commitResumeBatch(\n resumeBatchToken,\n () => this.isActiveConnection(connection) && !this.executionGate.isClosed\n );\n } finally {\n if (!committed) await this.commands.abortResumeBatch(resumeBatchToken);\n }\n if (!committed || !this.isActiveConnection(connection) || this.executionGate.isClosed) {\n return;\n }\n if (connection.handshakeTimer) clearTimeout(connection.handshakeTimer);\n connection.handshakeTimer = null;\n connection.resumed = true;\n connection.transmittedEventSequence = frame.acknowledgedEventSequence;\n this.reconnectAttempt = 0;\n this.startHeartbeat(connection);\n this.flushOutbox(connection);\n return;\n }\n if (frame.type === "event_ack") {\n if (!connection.resumed || frame.acknowledgedEventSequence > connection.transmittedEventSequence) {\n this.rejectGatewayCursor(connection);\n return;\n }\n await this.store.acknowledgeEvents(frame.acknowledgedEventSequence);\n if (this.isActiveConnection(connection)) this.flushOutbox(connection);\n return;\n }\n if (frame.type === "command") {\n if (!connection.resumed) {\n await this.callbacks.emitEvent({\n kind: "protocol_error",\n message: "Gateway delivered a command before resume_ok."\n });\n return;\n }\n await this.commands.enqueue(frame);\n return;\n }\n if (frame.type === "attempt_superseded") {\n this.callbacks.acceptSupersession(frame.reason ?? "attempt_superseded");\n }\n }\n handleFrameFailure(connection, error) {\n if (!this.isActiveConnection(connection)) return;\n if (this.executionGate.isClosed) {\n connection.socket.close(1008, "supervisor execution closed");\n return;\n }\n void this.callbacks.emitEvent({\n kind: "protocol_error",\n message: this.redactor.redact(\n `Failed to process gateway frame: ${serializeSupervisorError(error).message}`\n )\n }).then(\n () => connection.socket.close(1011, "frame processing failed"),\n () => connection.socket.close(1011, "frame processing failed")\n );\n }\n rejectGatewayCursor(connection) {\n connection.failed = true;\n if (this.isActiveConnection(connection)) {\n connection.socket.close(1008, "invalid event cursor");\n }\n }\n startHeartbeat(connection) {\n if (connection.heartbeatTimer) clearInterval(connection.heartbeatTimer);\n this.sendHeartbeat(connection);\n connection.heartbeatTimer = setInterval(() => {\n if (!this.isActiveConnection(connection)) return;\n if (this.dependencies.now() - connection.lastGatewayActivityAt > this.config.heartbeatIntervalMs * 3) {\n connection.socket.close(4001, "gateway heartbeat stale");\n return;\n }\n this.sendHeartbeat(connection);\n this.flushOutbox(connection);\n }, this.config.heartbeatIntervalMs);\n }\n sendHeartbeat(connection) {\n if (!this.isActiveConnection(connection) || connection.failed || !connection.resumed || connection.socket.readyState !== WEBSOCKET_OPEN || connection.socket.bufferedAmount > MAX_WEBSOCKET_BUFFERED_BYTES) {\n return;\n }\n const heartbeat = {\n type: "heartbeat",\n protocolVersion: SUPERVISOR_PROTOCOL_VERSION,\n runtimeVersion: SUPERVISOR_RUNTIME_VERSION,\n sessionId: this.config.sessionId,\n runId: this.config.runId,\n attemptId: this.config.attemptId,\n sentAt: (/* @__PURE__ */ new Date()).toISOString(),\n harnessState: this.harness.state,\n outboxDepth: this.store.outboxDepth,\n lastAcknowledgedEventSequence: this.store.lastAcknowledgedEventSequence,\n lastAppliedCommandSequence: this.store.lastAppliedCommandSequence\n };\n try {\n connection.socket.send(JSON.stringify(heartbeat));\n } catch {\n connection.socket.close(1011, "heartbeat send failed");\n }\n }\n clearConnectionTimers(connection) {\n if (!connection) return;\n if (connection.handshakeTimer) clearTimeout(connection.handshakeTimer);\n if (connection.heartbeatTimer) clearInterval(connection.heartbeatTimer);\n connection.handshakeTimer = null;\n connection.heartbeatTimer = null;\n }\n isActiveConnection(connection) {\n return connection !== null && this.connection === connection && this.connection.generation === connection.generation;\n }\n scheduleReconnect() {\n if (this.stopping || this.executionGate.isClosed || this.reconnectTimer) return;\n const exponential = this.config.reconnect.initialDelayMs * this.config.reconnect.multiplier ** this.reconnectAttempt;\n const capped = Math.min(exponential, this.config.reconnect.maximumDelayMs);\n const jitter = capped * this.config.reconnect.jitterRatio;\n const delayMs = Math.max(\n 0,\n Math.round(capped - jitter + this.dependencies.random() * jitter * 2)\n );\n this.reconnectAttempt += 1;\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = null;\n try {\n this.connect();\n } catch (error) {\n if (this.stopping || this.executionGate.isClosed) return;\n this.callbacks.failTransport(errorFromUnknown(error));\n }\n }, delayMs);\n }\n};\n\n// src/supervisor/pi-sdk-harness.ts\nimport {\n constants as constants2,\n fstatSync,\n readSync,\n writeSync\n} from "node:fs";\nimport {\n lstat,\n mkdir as mkdir3,\n realpath as realpath2\n} from "node:fs/promises";\nimport { basename, dirname as dirname3, join as join4 } from "node:path";\nimport { types as nodeUtilTypes } from "node:util";\n\n// src/supervisor/pi-resource-snapshot-manager.ts\nimport { randomUUID as randomUUID3 } from "node:crypto";\nimport { constants } from "node:fs";\nimport {\n mkdir as mkdir2,\n opendir as opendir2,\n realpath,\n rm\n} from "node:fs/promises";\nimport { dirname as dirname2, join as join3 } from "node:path";\nvar DEFAULT_PI_RESOURCE_SNAPSHOT_LIMITS = {\n maximumFileBytes: 16 * 1024 * 1024,\n maximumTreeBytes: 64 * 1024 * 1024,\n maximumFiles: 4096,\n maximumDirectories: 1024,\n maximumDepth: 32,\n maximumRetainedGenerations: 8\n};\nvar DEFAULT_RESOURCE_SNAPSHOT_DEPENDENCIES = {};\nvar PI_RESOURCE_SNAPSHOT_ROOT = ".neckbeard-resource-snapshots";\nfunction resolvePiResourceSnapshotLimits(overrides) {\n const limits = { ...DEFAULT_PI_RESOURCE_SNAPSHOT_LIMITS, ...overrides };\n for (const [name, value] of Object.entries(limits)) {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw new Error(\n `Pi resource snapshot ${name} must be a positive integer.`\n );\n }\n }\n return limits;\n}\nfunction capturePiResourceSnapshotIdentity(stats) {\n return {\n device: stats.dev,\n inode: stats.ino,\n mode: stats.mode,\n uid: stats.uid,\n gid: stats.gid,\n linkCount: stats.nlink,\n size: stats.size,\n modifiedAt: stats.mtimeNs,\n changedAt: stats.ctimeNs\n };\n}\nfunction matchesPiResourceSnapshotIdentity(stats, identity) {\n return stats.dev === identity.device && stats.ino === identity.inode && stats.mode === identity.mode && stats.uid === identity.uid && stats.gid === identity.gid && stats.nlink === identity.linkCount && stats.size === identity.size && stats.mtimeNs === identity.modifiedAt && stats.ctimeNs === identity.changedAt;\n}\nasync function openPiResourceDirectory(parent, name, displayPath, expectedIdentity) {\n try {\n const directory = await openDescriptorBoundFilesystemDirectoryAt(\n { handle: parent, displayPath: dirname2(displayPath) },\n name,\n expectedIdentity\n );\n return directory.handle;\n } catch (error) {\n if (error.message.startsWith("Pi agent resource ")) throw error;\n throw new Error(\n `Pi agent resource ${displayPath} must be a real directory.`,\n {\n cause: error\n }\n );\n }\n}\nasync function assertPiResourceDirectoryEntryUnchanged(parent, name, expected, displayPath) {\n let current = null;\n try {\n const expectedStats = await expected.stat({ bigint: true });\n current = await openPiResourceDirectory(parent, name, displayPath, {\n device: expectedStats.dev,\n inode: expectedStats.ino\n });\n } catch (error) {\n throw new Error(\n `Pi resource snapshot directory ${displayPath} changed while it was being created.`,\n { cause: error }\n );\n } finally {\n await current?.close();\n }\n}\nasync function assertPiResourceFileEntryUnchanged(parent, name, expected, displayPath) {\n let current = null;\n try {\n current = await openRegularFilesystemEntryAt(\n { handle: parent },\n name,\n constants.O_RDONLY,\n `Pi resource snapshot file ${displayPath}`\n );\n if (!await matchesRetainedRegularFileIdentity(expected, current)) {\n throw new Error("file identity changed");\n }\n } catch (error) {\n throw new Error(\n `Pi resource snapshot file ${displayPath} changed while it was being created.`,\n { cause: error }\n );\n } finally {\n await current?.close();\n }\n}\nasync function assertPiResourceSnapshotNamespace(directory, manifest, displayPath) {\n try {\n const before = await directory.stat({ bigint: true });\n if (!before.isDirectory() || !matchesPiResourceSnapshotIdentity(before, manifest.identity)) {\n throw new Error("directory identity changed");\n }\n const seen = /* @__PURE__ */ new Set();\n const entries = await opendir2(descriptorBoundDirectoryPath({ handle: directory }));\n for await (const entry of entries) {\n const expected = manifest.entries.get(entry.name);\n if (expected === void 0 || seen.has(entry.name)) {\n throw new Error("directory contains an unvalidated entry");\n }\n seen.add(entry.name);\n const entryPath = join3(displayPath, entry.name);\n if (expected.kind === "directory") {\n const child = await openPiResourceDirectory(\n directory,\n entry.name,\n entryPath\n );\n try {\n await assertPiResourceSnapshotNamespace(\n child,\n expected.manifest,\n entryPath\n );\n } finally {\n await child.close();\n }\n } else {\n const child = await openRegularFilesystemEntryAt(\n { handle: directory },\n entry.name,\n constants.O_RDONLY,\n `Pi resource snapshot file ${entryPath}`\n );\n try {\n const stats = await child.stat({ bigint: true });\n if (!stats.isFile() || !matchesPiResourceSnapshotIdentity(stats, expected.identity)) {\n throw new Error("file identity changed");\n }\n } finally {\n await child.close();\n }\n }\n }\n if (seen.size !== manifest.entries.size) {\n throw new Error("directory is missing a validated entry");\n }\n const after = await directory.stat({ bigint: true });\n if (!after.isDirectory() || !matchesPiResourceSnapshotIdentity(after, manifest.identity)) {\n throw new Error("directory changed during validation");\n }\n } catch (error) {\n if (error instanceof Error && error.message.startsWith("Pi resource snapshot directory ") && error.message.endsWith(" changed while it was being created.")) {\n throw error;\n }\n throw new Error(\n `Pi resource snapshot directory ${displayPath} changed while it was being created.`,\n { cause: error }\n );\n }\n}\nasync function copyPiResourceDirectory(source, sourcePath, destination, destinationPath, dependencies, budget, depth) {\n if (depth >= budget.limits.maximumDepth) {\n throw new Error(\n `Pi agent resource directory ${sourcePath} exceeds the ${budget.limits.maximumDepth}-directory depth limit.`\n );\n }\n const sourceBefore = await source.stat({ bigint: true });\n const destinationEntries = /* @__PURE__ */ new Map();\n const entries = await opendir2(descriptorBoundDirectoryPath({ handle: source }));\n for await (const entry of entries) {\n const sourceEntryPath = join3(sourcePath, entry.name);\n const destinationEntryPath = join3(destinationPath, entry.name);\n if (entry.isSymbolicLink()) {\n throw new Error(\n `Pi agent resource ${sourceEntryPath} must not be a symbolic link.`\n );\n }\n if (entry.isDirectory()) {\n budget.directories += 1;\n if (budget.directories > budget.limits.maximumDirectories) {\n throw new Error(\n `Pi agent resource tree exceeds the ${budget.limits.maximumDirectories}-directory limit.`\n );\n }\n const child = await openPiResourceDirectory(\n source,\n entry.name,\n sourceEntryPath\n );\n let destinationChild = null;\n try {\n await dependencies.afterSourceDirectoryOpened?.(sourceEntryPath);\n await mkdir2(descriptorBoundFilesystemEntryPath({ handle: destination }, entry.name), {\n mode: 448\n });\n destinationChild = await openPiResourceDirectory(\n destination,\n entry.name,\n destinationEntryPath\n );\n await dependencies.afterDestinationDirectoryOpened?.(\n sourceEntryPath,\n destinationEntryPath\n );\n const childEntries = await copyPiResourceDirectory(\n child,\n sourceEntryPath,\n destinationChild,\n destinationEntryPath,\n dependencies,\n budget,\n depth + 1\n );\n await destinationChild.chmod(320);\n await assertPiResourceDirectoryEntryUnchanged(\n destination,\n entry.name,\n destinationChild,\n destinationEntryPath\n );\n destinationEntries.set(entry.name, {\n kind: "directory",\n manifest: {\n identity: capturePiResourceSnapshotIdentity(\n await destinationChild.stat({ bigint: true })\n ),\n entries: childEntries\n }\n });\n } finally {\n await destinationChild?.close();\n await child.close();\n }\n continue;\n }\n if (!entry.isFile()) {\n throw new Error(\n `Pi agent resource ${sourceEntryPath} must be a regular file or directory.`\n );\n }\n budget.files += 1;\n if (budget.files > budget.limits.maximumFiles) {\n throw new Error(\n `Pi agent resource tree exceeds the ${budget.limits.maximumFiles}-file limit.`\n );\n }\n const input = await openRegularFilesystemEntryAt(\n { handle: source },\n entry.name,\n constants.O_RDONLY,\n `Pi agent resource ${sourceEntryPath}`\n );\n try {\n const inputBefore = await input.stat({ bigint: true });\n if (inputBefore.size > BigInt(budget.limits.maximumFileBytes)) {\n throw new Error(\n `Pi agent resource ${sourceEntryPath} exceeds the ${budget.limits.maximumFileBytes}-byte per-file limit.`\n );\n }\n const declaredSizeBytes = Number(inputBefore.size);\n if (budget.bytes + declaredSizeBytes > budget.limits.maximumTreeBytes) {\n throw new Error(\n `Pi agent resource tree exceeds the ${budget.limits.maximumTreeBytes}-byte limit.`\n );\n }\n budget.bytes += declaredSizeBytes;\n await dependencies.afterSourceFileStat?.(\n sourceEntryPath,\n declaredSizeBytes\n );\n const output = await openRegularFilesystemEntryAt(\n { handle: destination },\n entry.name,\n constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY,\n `Pi resource snapshot file ${destinationEntryPath}`,\n 384\n );\n try {\n let position = 0;\n const buffer = Buffer.allocUnsafe(64 * 1024);\n while (position <= declaredSizeBytes) {\n const remaining = declaredSizeBytes + 1 - position;\n const { bytesRead } = await input.read(\n buffer,\n 0,\n Math.min(buffer.length, remaining),\n null\n );\n if (bytesRead === 0) break;\n if (position + bytesRead > declaredSizeBytes) {\n throw new Error(\n `Pi agent resource ${sourceEntryPath} changed while it was being snapshotted.`\n );\n }\n let written = 0;\n while (written < bytesRead) {\n const result = await output.write(\n buffer,\n written,\n bytesRead - written,\n position\n );\n if (result.bytesWritten <= 0) {\n throw new Error(\n `Pi agent resource ${sourceEntryPath} could not be copied.`\n );\n }\n written += result.bytesWritten;\n position += result.bytesWritten;\n }\n }\n if (position !== declaredSizeBytes) {\n throw new Error(\n `Pi agent resource ${sourceEntryPath} changed while it was being snapshotted.`\n );\n }\n await output.sync();\n const snapshotMode = (inputBefore.mode & 0o111n) === 0n ? 256 : 320;\n await output.chmod(snapshotMode);\n await assertPiResourceFileEntryUnchanged(\n destination,\n entry.name,\n output,\n destinationEntryPath\n );\n const inputAfter = await input.stat({ bigint: true });\n if (inputBefore.dev !== inputAfter.dev || inputBefore.ino !== inputAfter.ino || inputBefore.size !== inputAfter.size || inputBefore.mtimeNs !== inputAfter.mtimeNs || inputBefore.ctimeNs !== inputAfter.ctimeNs) {\n throw new Error(\n `Pi agent resource ${sourceEntryPath} changed while it was being snapshotted.`\n );\n }\n destinationEntries.set(entry.name, {\n kind: "file",\n identity: capturePiResourceSnapshotIdentity(\n await output.stat({ bigint: true })\n )\n });\n } finally {\n await output.close();\n }\n } finally {\n await input.close();\n }\n }\n const sourceAfter = await source.stat({ bigint: true });\n if (sourceBefore.dev !== sourceAfter.dev || sourceBefore.ino !== sourceAfter.ino || sourceBefore.mtimeNs !== sourceAfter.mtimeNs || sourceBefore.ctimeNs !== sourceAfter.ctimeNs) {\n throw new Error(\n `Pi agent resource directory ${sourcePath} changed while it was being snapshotted.`\n );\n }\n return destinationEntries;\n}\nasync function bindAgentResourceRoot(agentDir, expectedIdentity) {\n let root;\n try {\n root = await openDescriptorBoundDirectory(\n agentDir,\n expectedIdentity === void 0 ? void 0 : {\n device: expectedIdentity.device,\n inode: expectedIdentity.inode\n }\n );\n } catch (error) {\n if (expectedIdentity !== void 0 && error instanceof Error && error.message === `${agentDir} must continue to identify its original directory.`) {\n throw new Error(\n `Pi agent resource root ${agentDir} must continue to identify its original directory.`,\n { cause: error }\n );\n }\n throw new Error(\n `Pi agent resource root ${agentDir} must be a real directory.`,\n {\n cause: error\n }\n );\n }\n let identity;\n let retainRootHandle = false;\n try {\n const physicalPath = await realpath(descriptorBoundDirectoryPath(root));\n identity = {\n physicalPath,\n device: root.identity.device,\n inode: root.identity.inode,\n handle: root.handle,\n authHandle: null\n };\n if (expectedIdentity !== void 0 && physicalPath !== expectedIdentity.physicalPath) {\n throw new Error(\n `Pi agent resource root ${agentDir} must continue to identify its original directory.`\n );\n }\n if (expectedIdentity === void 0) retainRootHandle = true;\n return expectedIdentity ?? identity;\n } finally {\n if (!retainRootHandle) {\n await root.handle.close();\n }\n }\n}\nasync function adoptAgentResourceRoot(agentDir, directory) {\n try {\n const stats = await directory.handle.stat({ bigint: true });\n const expectedUid = typeof process.getuid === "function" ? BigInt(process.getuid()) : null;\n if (!stats.isDirectory() || expectedUid !== null && BigInt(stats.uid) !== expectedUid) {\n throw new Error(\n `Pi agent resource root ${agentDir} must be a process-owned real directory.`\n );\n }\n await directory.handle.chmod(448);\n await directory.handle.sync();\n const privateStats = await directory.handle.stat({ bigint: true });\n if (!privateStats.isDirectory() || (privateStats.mode & 0o777n) !== 0o700n || privateStats.dev !== stats.dev || privateStats.ino !== stats.ino || expectedUid !== null && privateStats.uid !== expectedUid) {\n throw new Error(\n `Pi agent resource root ${agentDir} must remain a process-owned private writable directory.`\n );\n }\n return {\n physicalPath: await realpath(descriptorBoundDirectoryPath(directory)),\n device: stats.dev,\n inode: stats.ino,\n handle: directory.handle,\n authHandle: null\n };\n } catch (error) {\n await directory.handle.close().catch(() => void 0);\n throw error;\n }\n}\nasync function openPiResourceSnapshotRoot(stateDurabilityAnchor, stateDir, attemptId, dependencies) {\n const parentPath = join3(stateDir, PI_RESOURCE_SNAPSHOT_ROOT);\n let parentDirectory;\n try {\n parentDirectory = await ensureDescriptorBoundDirectory(\n stateDurabilityAnchor,\n parentPath,\n 448\n );\n } catch (error) {\n throw new Error(\n `Pi resource snapshot parent ${parentPath} must be a real directory.`,\n { cause: error }\n );\n }\n const parentHandle = parentDirectory.handle;\n const path = descriptorBoundEntryPath(parentDirectory, attemptId);\n let handle = null;\n try {\n await dependencies.afterSnapshotParentBound?.(parentPath);\n const parentStats = await parentHandle.stat();\n if (!parentStats.isDirectory()) {\n throw new Error(\n `Pi resource snapshot parent ${parentPath} must be a real directory.`\n );\n }\n await parentHandle.chmod(448);\n const staleDirectory = await openDescriptorBoundDirectoryAt(\n parentDirectory,\n attemptId\n ).catch((error) => {\n if (error.code === "ENOENT") return null;\n throw error;\n });\n if (staleDirectory !== null) {\n try {\n await makePiResourceSnapshotRemovable(staleDirectory.handle);\n } finally {\n await staleDirectory.handle.close();\n }\n await rm(path, { recursive: true, force: true });\n }\n await mkdir2(path, { mode: 448 });\n handle = (await openDescriptorBoundDirectoryAt(parentDirectory, attemptId)).handle;\n await handle.chmod(448);\n return { entryName: attemptId, handle, parentHandle };\n } catch (error) {\n await handle?.close().catch(() => void 0);\n await parentHandle.close();\n throw error;\n }\n}\nasync function preparePiRuntimeAuth(agentRoot, dependencies, maximumBytes) {\n const displayPath = join3(agentRoot.physicalPath, "auth.json");\n let sourceHandle = null;\n let retained = false;\n try {\n let created = false;\n try {\n sourceHandle = await openRegularFileAt(\n { handle: agentRoot.handle },\n "auth.json",\n constants.O_RDWR | constants.O_CREAT | constants.O_EXCL,\n "Pi auth path",\n 384\n );\n created = true;\n } catch (error) {\n if (error.code !== "EEXIST") {\n throw new Error(\n `Pi auth path ${displayPath} must be a process-owned single-link regular file.`,\n { cause: error }\n );\n }\n try {\n sourceHandle = await openRegularFileAt(\n { handle: agentRoot.handle },\n "auth.json",\n constants.O_RDWR,\n "Pi auth path"\n );\n } catch (openError) {\n throw new Error(\n `Pi auth path ${displayPath} must be a process-owned single-link regular file.`,\n { cause: openError }\n );\n }\n }\n const before = await sourceHandle.stat({ bigint: true });\n const expectedUid = typeof process.getuid === "function" ? BigInt(process.getuid()) : null;\n if (!before.isFile() || before.nlink !== 1n || before.size > BigInt(maximumBytes) || expectedUid !== null && before.uid !== expectedUid) {\n throw new Error(\n `Pi auth path ${displayPath} must be a process-owned single-link regular file within the configured size limit.`\n );\n }\n if (created) await sourceHandle.writeFile("{}\\n", "utf8");\n await sourceHandle.chmod(384);\n await sourceHandle.sync();\n await agentRoot.handle.sync();\n await dependencies.afterAuthSourceOpened?.(displayPath);\n try {\n await withRevalidatedPrivateRegularFile(\n sourceHandle,\n () => openRegularFileAt(\n { handle: agentRoot.handle },\n "auth.json",\n constants.O_RDONLY,\n "Pi auth path"\n ),\n () => void 0,\n { maximumBytes, failureMessage: "auth file identity changed" }\n );\n } catch (error) {\n throw new Error(\n `Pi auth path ${displayPath} changed while its descriptor binding was created.`,\n { cause: error }\n );\n }\n agentRoot.authHandle = sourceHandle;\n sourceHandle = null;\n retained = true;\n } finally {\n if (!retained) {\n await sourceHandle?.close().catch(() => void 0);\n }\n }\n}\nasync function assertPiRuntimeAuthReady(agentRoot, maximumBytes) {\n const retained = agentRoot.authHandle;\n if (retained === null) {\n throw new Error("Pi runtime auth has not been prepared.");\n }\n try {\n await withRevalidatedPrivateRegularFile(\n retained,\n () => openRegularFileAt(\n { handle: agentRoot.handle },\n "auth.json",\n constants.O_RDONLY,\n "Pi auth path"\n ),\n () => void 0,\n { maximumBytes, failureMessage: "auth file identity changed" }\n );\n } catch (error) {\n throw new Error(\n `Pi auth path ${join3(agentRoot.physicalPath, "auth.json")} changed before SDK use.`,\n { cause: error }\n );\n }\n}\nasync function createPiResourceSnapshot(agentDir, rootIdentity, snapshotRoot, dependencies, limits) {\n const source = await bindAgentResourceRoot(agentDir, rootIdentity);\n const generation = randomUUID3();\n const snapshotPath = descriptorBoundEntryPath({ handle: snapshotRoot.handle }, generation);\n let snapshotHandle = null;\n await snapshotRoot.handle.chmod(448);\n try {\n await mkdir2(snapshotPath, { mode: 448 });\n snapshotHandle = await openPiResourceDirectory(\n snapshotRoot.handle,\n generation,\n snapshotPath\n );\n const entries = await copyPiResourceDirectory(\n source.handle,\n agentDir,\n snapshotHandle,\n snapshotPath,\n dependencies,\n { limits, files: 0, directories: 1, bytes: 0 },\n 0\n );\n await snapshotHandle.chmod(320);\n const manifest = {\n identity: capturePiResourceSnapshotIdentity(\n await snapshotHandle.stat({ bigint: true })\n ),\n entries\n };\n await assertPiResourceDirectoryEntryUnchanged(\n snapshotRoot.handle,\n generation,\n snapshotHandle,\n snapshotPath\n );\n await assertPiResourceSnapshotNamespace(\n snapshotHandle,\n manifest,\n snapshotPath\n );\n await assertPiResourceDirectoryEntryUnchanged(\n snapshotRoot.handle,\n generation,\n snapshotHandle,\n snapshotPath\n );\n await snapshotRoot.handle.chmod(320);\n return { entryName: generation, handle: snapshotHandle, manifest };\n } catch (error) {\n if (snapshotHandle !== null) {\n await makePiResourceSnapshotRemovable(snapshotHandle).catch(\n () => void 0\n );\n await snapshotHandle.close().catch(() => void 0);\n }\n await rm(snapshotPath, { recursive: true, force: true }).catch(\n () => void 0\n );\n await snapshotRoot.handle.chmod(320).catch(() => void 0);\n throw error;\n }\n}\nasync function makePiResourceSnapshotRemovable(handle) {\n const entries = await opendir2(descriptorBoundDirectoryPath({ handle }));\n for await (const entry of entries) {\n if (!entry.isDirectory() || entry.isSymbolicLink()) continue;\n const child = await openPiResourceDirectory(\n handle,\n entry.name,\n descriptorBoundFilesystemEntryPath({ handle }, entry.name)\n );\n try {\n await makePiResourceSnapshotRemovable(child);\n await child.chmod(448);\n } finally {\n await child.close();\n }\n }\n await handle.chmod(448);\n}\nasync function removePiResourceSnapshot(snapshotRoot, snapshot) {\n await snapshotRoot.handle.chmod(448);\n let failure;\n await makePiResourceSnapshotRemovable(snapshot.handle).catch(\n (error) => {\n failure ??= error;\n }\n );\n await snapshot.handle.close().catch((error) => {\n failure ??= error;\n });\n await rm(descriptorBoundEntryPath({ handle: snapshotRoot.handle }, snapshot.entryName), {\n recursive: true,\n force: true\n }).catch((error) => {\n failure ??= error;\n });\n await snapshotRoot.handle.chmod(320).catch((error) => {\n failure ??= error;\n });\n if (failure !== void 0) throw failure;\n}\nvar piResourceReloadTail = Promise.resolve();\nasync function withContainedPiResourceHome(agentDir, rootIdentity, snapshotRoot, retainedSnapshots, dependencies, limits, lifecycle, operation, preparedSnapshot) {\n const run = async () => {\n if (lifecycle.closed) {\n throw new Error("Pi resource snapshot manager is closed.");\n }\n let snapshot = preparedSnapshot;\n let createdSnapshot = false;\n if (snapshot === void 0) {\n if (retainedSnapshots.length >= limits.maximumRetainedGenerations) {\n throw new Error(\n `Pi resource reload exceeds the ${limits.maximumRetainedGenerations}-generation retention limit.`\n );\n }\n snapshot = await createPiResourceSnapshot(\n agentDir,\n rootIdentity,\n snapshotRoot,\n dependencies,\n limits\n );\n createdSnapshot = true;\n }\n const previousHome = process.env.HOME;\n const snapshotPath = descriptorBoundDirectoryPath({ handle: snapshot.handle });\n try {\n await dependencies.beforeSnapshotUse?.(snapshotPath);\n await assertPiResourceSnapshotNamespace(\n snapshot.handle,\n snapshot.manifest,\n snapshotPath\n );\n if (lifecycle.closed) {\n throw new Error("Pi resource snapshot manager is closed.");\n }\n process.env.HOME = snapshotPath;\n const result2 = await operation(snapshotPath);\n if (createdSnapshot) retainedSnapshots.push(snapshot);\n return result2;\n } catch (error) {\n if (createdSnapshot) {\n await removePiResourceSnapshot(snapshotRoot, snapshot).catch(\n () => void 0\n );\n }\n throw error;\n } finally {\n if (previousHome === void 0) delete process.env.HOME;\n else process.env.HOME = previousHome;\n }\n };\n const result = piResourceReloadTail.then(run, run);\n piResourceReloadTail = result.then(\n () => void 0,\n () => void 0\n );\n return result;\n}\nvar PI_RESOURCE_LOADER_METHODS = [\n "getExtensions",\n "getSkills",\n "getPrompts",\n "getThemes",\n "getAgentsFiles",\n "getSystemPrompt",\n "getSystemPromptSource",\n "getAppendSystemPrompt",\n "getAppendSystemPromptSources",\n "extendResources"\n];\nfunction containPiResourceLoader(createResourceLoader, agentDir, rootIdentity, snapshotRoot, retainedSnapshots, dependencies, limits, initialSnapshot, lifecycle) {\n let current = null;\n let preparedSnapshot = initialSnapshot;\n const wrapper = {\n reload: (...args) => {\n if (lifecycle.closed) {\n return Promise.reject(\n new Error("Pi resource snapshot manager is closed.")\n );\n }\n const snapshot = preparedSnapshot;\n preparedSnapshot = void 0;\n const reloading = withContainedPiResourceHome(\n agentDir,\n rootIdentity,\n snapshotRoot,\n retainedSnapshots,\n dependencies,\n limits,\n lifecycle,\n async (snapshotPath) => {\n const candidate = createResourceLoader(snapshotPath);\n await candidate.reload(...args);\n current = candidate;\n },\n snapshot\n );\n lifecycle.tail = Promise.allSettled([lifecycle.tail, reloading]).then(\n () => void 0\n );\n return reloading;\n }\n };\n for (const method of PI_RESOURCE_LOADER_METHODS) {\n wrapper[method] = (...args) => {\n if (current === null) {\n throw new Error(\n "Pi resource loader has not completed its initial reload."\n );\n }\n const candidate = current;\n const implementation = candidate[method];\n if (typeof implementation !== "function") {\n throw new Error(`Pi resource loader does not expose ${method}().`);\n }\n return Reflect.apply(implementation, current, args);\n };\n }\n return wrapper;\n}\nvar PiResourceSnapshotManager = class {\n constructor(options, dependencies = DEFAULT_RESOURCE_SNAPSHOT_DEPENDENCIES) {\n this.dependencies = dependencies;\n this.agentDir = options.agentDir;\n this.authPath = join3(options.agentDir, "auth.json");\n this.stateDir = options.stateDir;\n this.stateDurabilityAnchor = options.stateDurabilityAnchor;\n this.attemptId = options.attemptId;\n this.limits = resolvePiResourceSnapshotLimits(dependencies.limits);\n }\n dependencies;\n agentDir;\n authPath;\n stateDir;\n stateDurabilityAnchor;\n attemptId;\n limits;\n rootIdentity = null;\n snapshotRoot = null;\n retainedSnapshots = [];\n preparedSnapshot = null;\n loaderCreated = false;\n reloadLifecycle = {\n closed: false,\n tail: Promise.resolve()\n };\n closePromise = null;\n get runtimeAgentDir() {\n const snapshot = this.retainedSnapshots[0];\n if (snapshot === void 0) {\n throw new Error("Pi resource snapshot manager has not been prepared.");\n }\n return descriptorBoundDirectoryPath({ handle: snapshot.handle });\n }\n get runtimeAuthPath() {\n const identity = this.rootIdentity;\n if (identity?.authHandle === null || identity === null) {\n throw new Error("Pi resource snapshot manager has not been prepared.");\n }\n return descriptorBoundEntryPath({ handle: identity.handle }, "auth.json");\n }\n async validateRuntimeAuth() {\n const identity = this.rootIdentity;\n if (identity === null) {\n throw new Error("Pi resource snapshot manager has not been prepared.");\n }\n await assertPiRuntimeAuthReady(identity, this.limits.maximumFileBytes);\n }\n async prepare() {\n if (this.reloadLifecycle.closed || this.rootIdentity !== null || this.snapshotRoot !== null || this.preparedSnapshot !== null) {\n throw new Error("Pi resource snapshot manager is already prepared.");\n }\n const snapshotParent = join3(this.stateDir, PI_RESOURCE_SNAPSHOT_ROOT);\n if (sandboxPathsOverlap(this.agentDir, snapshotParent)) {\n throw new Error(\n "Pi agent resource directory must not overlap its snapshot directory."\n );\n }\n const agentDirectory = await ensureDescriptorBoundDirectory(\n this.stateDurabilityAnchor,\n this.agentDir\n );\n let rootIdentity;\n try {\n await this.dependencies.afterAgentRootBound?.(this.agentDir);\n rootIdentity = await adoptAgentResourceRoot(\n this.agentDir,\n agentDirectory\n );\n } catch (error) {\n await agentDirectory.handle.close().catch(() => void 0);\n throw error;\n }\n this.rootIdentity = rootIdentity;\n const snapshotRoot = await openPiResourceSnapshotRoot(\n this.stateDurabilityAnchor,\n this.stateDir,\n this.attemptId,\n this.dependencies\n );\n this.snapshotRoot = snapshotRoot;\n await preparePiRuntimeAuth(\n rootIdentity,\n this.dependencies,\n this.limits.maximumFileBytes\n );\n const initialSnapshot = await createPiResourceSnapshot(\n this.agentDir,\n rootIdentity,\n snapshotRoot,\n this.dependencies,\n this.limits\n );\n this.retainedSnapshots.push(initialSnapshot);\n this.preparedSnapshot = initialSnapshot;\n }\n createResourceLoader(createResourceLoader) {\n if (this.loaderCreated) {\n throw new Error("Pi resource loader has already been created.");\n }\n const rootIdentity = this.rootIdentity;\n const snapshotRoot = this.snapshotRoot;\n const initialSnapshot = this.preparedSnapshot;\n if (rootIdentity === null || snapshotRoot === null || initialSnapshot === null) {\n throw new Error("Pi resource snapshot manager has not been prepared.");\n }\n this.loaderCreated = true;\n this.preparedSnapshot = null;\n return containPiResourceLoader(\n createResourceLoader,\n this.agentDir,\n rootIdentity,\n snapshotRoot,\n this.retainedSnapshots,\n this.dependencies,\n this.limits,\n initialSnapshot,\n this.reloadLifecycle\n );\n }\n async close() {\n if (this.closePromise !== null) return this.closePromise;\n this.reloadLifecycle.closed = true;\n const closing = this.closePreparedState();\n this.closePromise = closing;\n return closing;\n }\n async closePreparedState() {\n await this.reloadLifecycle.tail;\n const identity = this.rootIdentity;\n this.rootIdentity = null;\n const snapshotRoot = this.snapshotRoot;\n this.snapshotRoot = null;\n this.preparedSnapshot = null;\n const snapshots = this.retainedSnapshots.splice(0);\n let failure;\n for (const snapshot of snapshots) {\n try {\n await snapshot.handle.close();\n } catch (error) {\n failure ??= error;\n await snapshot.handle.close().catch(() => void 0);\n }\n }\n if (snapshotRoot !== null) {\n await makePiResourceSnapshotRemovable(snapshotRoot.handle).catch(\n (error) => {\n failure ??= error;\n }\n );\n await snapshotRoot.handle.close().catch((error) => {\n failure ??= error;\n });\n await rm(\n descriptorBoundEntryPath(\n { handle: snapshotRoot.parentHandle },\n snapshotRoot.entryName\n ),\n { recursive: true, force: true }\n ).catch((error) => {\n failure ??= error;\n });\n await snapshotRoot.parentHandle.close().catch((error) => {\n failure ??= error;\n });\n }\n if (identity?.authHandle !== null && identity !== null) {\n await identity.authHandle.sync().catch((error) => {\n failure ??= error;\n });\n await identity.authHandle.close().catch((error) => {\n failure ??= error;\n });\n identity.authHandle = null;\n await identity.handle.sync().catch((error) => {\n failure ??= error;\n });\n }\n await identity?.handle.close().catch((error) => {\n failure ??= error;\n });\n if (failure !== void 0) throw failure;\n }\n};\n\n// src/supervisor/pi-sdk-harness.ts\nvar MAX_PERSISTED_PI_EVENT_PAYLOAD_BYTES = 512 * 1024;\nvar MAX_TRUNCATED_PI_EVENT_PAYLOAD_BYTES = 32 * 1024;\nvar MAX_PI_EVENT_METADATA_STRING_LENGTH = 256;\nvar MAX_PI_EVENT_LIFECYCLE_STRING_LENGTH = 8 * 1024;\nvar MAX_PI_EVENT_LIFECYCLE_MESSAGE_SCAN = 4 * 1024;\nvar MAX_PI_EVENT_TRAVERSAL_DEPTH = 64;\nvar MAX_PI_EVENT_TRAVERSAL_NODES = MAX_PERSISTED_PI_EVENT_PAYLOAD_BYTES;\nvar MAX_PENDING_HARNESS_EVENTS = 256;\nvar MAX_PENDING_HARNESS_EVENT_BYTES = 8 * 1024 * 1024;\nvar PI_EVENT_SCALAR_METADATA_KEYS = [\n "type",\n "id",\n "eventId",\n "messageId",\n "toolCallId",\n "toolName",\n "role",\n "stopReason",\n "provider",\n "model",\n "timestamp",\n "contentIndex",\n "isError"\n];\nvar PI_EVENT_NESTED_METADATA_KEYS = [\n "assistantMessageEvent",\n "message",\n "usage",\n "result"\n];\nvar PI_EVENT_ARRAY_METADATA_KEYS = [\n "messages",\n "toolResults",\n "content"\n];\nvar SESSION_FILE_CREATE_FLAGS = constants2.O_RDWR | constants2.O_CREAT;\nvar PI_SESSION_FORMAT_VERSION = 3;\nvar MAX_PI_SESSION_HEADER_BYTES = 64 * 1024;\nfunction piSessionHistoryLimitError(limitBytes, context) {\n return new Error(\n `Pi session history ${context} the ${limitBytes}-byte per-attempt limit; start a replacement attempt.`\n );\n}\nfunction assertPiSessionHistorySize(stats, limitBytes, comparison, context) {\n const limit = BigInt(limitBytes);\n const exceeded = comparison === "at_or_above" ? stats.size >= limit : stats.size > limit;\n if (exceeded) throw piSessionHistoryLimitError(limitBytes, context);\n}\nfunction assertPiSessionHistoryReadyForSdkOpen(handle, displayPath) {\n const stats = fstatSync(handle.fd, { bigint: true });\n assertPiSessionHistorySize(\n stats,\n SUPERVISOR_MAX_PI_SESSION_HISTORY_BYTES,\n "above",\n "exceeds"\n );\n if (stats.size === 0n) return;\n const scanBytes = Math.min(\n Number(stats.size),\n MAX_PI_SESSION_HEADER_BYTES + 1\n );\n const buffer = Buffer.allocUnsafe(scanBytes);\n let offset = 0;\n while (offset < scanBytes) {\n const bytesRead = readSync(\n handle.fd,\n buffer,\n offset,\n scanBytes - offset,\n offset\n );\n if (bytesRead === 0) {\n throw new Error(\n `Pi session path ${displayPath} changed while its header was validated.`\n );\n }\n offset += bytesRead;\n }\n const newline = buffer.indexOf(10, 0);\n const headerBytes = newline === -1 ? offset : newline;\n if (headerBytes > MAX_PI_SESSION_HEADER_BYTES || newline === -1 && stats.size > BigInt(MAX_PI_SESSION_HEADER_BYTES)) {\n throw new Error(\n `Pi session path ${displayPath} has an oversized session header.`\n );\n }\n let source;\n try {\n source = new TextDecoder("utf-8", { fatal: true }).decode(\n buffer.subarray(0, headerBytes)\n );\n } catch (error) {\n throw new Error(\n `Pi session path ${displayPath} has an invalid session header.`,\n { cause: error }\n );\n }\n if (source.endsWith("\\r")) source = source.slice(0, -1);\n let header;\n try {\n header = JSON.parse(source);\n } catch (error) {\n throw new Error(\n `Pi session path ${displayPath} has an invalid session header.`,\n { cause: error }\n );\n }\n if (!isRecord5(header) || header.type !== "session" || header.version !== PI_SESSION_FORMAT_VERSION) {\n throw new Error(\n `Pi session path ${displayPath} must use current Pi session format version ${PI_SESSION_FORMAT_VERSION}; start a replacement attempt for legacy history.`\n );\n }\n}\nasync function openPiSessionFile(directory, name, displayPath, flags, mode) {\n try {\n return await openRegularFileAt(\n directory,\n name,\n flags,\n `Pi session path ${displayPath}`,\n mode\n );\n } catch (error) {\n if (error.code === "ELOOP") {\n throw new Error(\n `Pi session path ${displayPath} must not be a symbolic link.`,\n { cause: error }\n );\n }\n throw error;\n }\n}\nasync function preparePiSessionFile(directory, name, displayPath) {\n const handle = await openPiSessionFile(\n directory,\n name,\n displayPath,\n SESSION_FILE_CREATE_FLAGS,\n 384\n );\n try {\n const before = await handle.stat({ bigint: true });\n const expectedUid = typeof process.getuid === "function" ? BigInt(process.getuid()) : null;\n if (!before.isFile() || before.nlink !== 1n || expectedUid !== null && before.uid !== expectedUid) {\n throw new Error(\n `Pi session path ${displayPath} must be a process-owned single-link regular file.`\n );\n }\n assertPiSessionHistorySize(\n before,\n SUPERVISOR_MAX_PI_SESSION_HISTORY_BYTES,\n "above",\n "exceeds"\n );\n await handle.chmod(384);\n const after = await handle.stat({ bigint: true });\n if (!after.isFile() || after.dev !== before.dev || after.ino !== before.ino || after.nlink !== 1n || expectedUid !== null && after.uid !== expectedUid) {\n throw new Error(\n `Pi session path ${displayPath} must remain a process-owned single-link regular file.`\n );\n }\n assertPiSessionHistorySize(\n after,\n SUPERVISOR_MAX_PI_SESSION_HISTORY_BYTES,\n "above",\n "exceeds"\n );\n await handle.sync();\n await syncDescriptorBoundDirectory(directory);\n return handle;\n } catch (error) {\n await handle.close();\n throw error;\n }\n}\nasync function withPiSessionFileReady(directory, name, handle, displayPath, operation) {\n return withRevalidatedPrivateRegularFile(\n handle,\n () => openPiSessionFile(\n directory,\n name,\n displayPath,\n constants2.O_RDONLY\n ),\n // The helper keeps the matching path descriptor open and invokes this\n // synchronous SDK open without yielding after its final identity checks.\n operation,\n {\n maximumBytes: SUPERVISOR_MAX_PI_SESSION_HISTORY_BYTES,\n failureMessage: `Pi session path ${displayPath} must remain the process-owned single-link private regular file bound at startup.`\n }\n );\n}\nasync function assertWorkspaceIsolated(workspaceDir, stateDir) {\n const workspaceStats = await lstat(workspaceDir);\n if (workspaceStats.isSymbolicLink() || !workspaceStats.isDirectory()) {\n throw new Error(\n `Pi workspace path ${workspaceDir} must be a real directory.`\n );\n }\n const [physicalWorkspace, physicalState] = await Promise.all([\n realpath2(workspaceDir),\n realpath2(stateDir)\n ]);\n if (sandboxPathsOverlap(physicalWorkspace, physicalState)) {\n throw new Error(\n "Pi workspace and supervisor state directories must not physically overlap."\n );\n }\n}\nfunction hasCallableProperty(value, property) {\n if ((typeof value !== "object" || value === null || Array.isArray(value)) && typeof value !== "function") {\n return false;\n }\n return typeof value[property] === "function";\n}\nfunction attachFilesToMessage(input) {\n if (!input.attachments?.length) return input.message;\n const files = input.attachments.map((attachment) => `- ${attachment.path}`).join("\\n");\n return `${input.message}\n\nFiles available in the sandbox:\n${files}`;\n}\nfunction isCoalescedPiEvent(value) {\n if (typeof value !== "object" || value === null || nodeUtilTypes.isProxy(value)) {\n return false;\n }\n const event = value;\n if (readPiLifecycleProperty(event, "type") !== "message_update") return false;\n const assistantEvent = readPiLifecycleProperty(\n event,\n "assistantMessageEvent"\n );\n if (!isRecord5(assistantEvent) || nodeUtilTypes.isProxy(assistantEvent)) {\n return false;\n }\n const assistantEventType = readPiLifecycleProperty(assistantEvent, "type");\n return typeof assistantEventType === "string" && assistantEventType.endsWith("_delta");\n}\nfunction assertPiSdkModule(value) {\n if (!isRecord5(value) || !hasCallableProperty(value.ModelRuntime, "create") || !hasCallableProperty(value.SessionManager, "open") || !hasCallableProperty(value.SettingsManager, "inMemory") || typeof value.DefaultResourceLoader !== "function" || typeof value.createAgentSession !== "function") {\n throw new Error(\n "The configured Pi SDK module does not expose the required session API."\n );\n }\n}\nfunction assertPiSdkSession(value) {\n if (!isRecord5(value) || typeof value.sessionId !== "string" || typeof value.prompt !== "function" || typeof value.steer !== "function" || typeof value.abort !== "function" || typeof value.dispose !== "function" || typeof value.subscribe !== "function") {\n throw new Error("Pi createAgentSession returned an invalid session.");\n }\n}\nfunction assertPiSdkSessionManager(value) {\n const flushed = isRecord5(value) ? Object.getOwnPropertyDescriptor(value, "flushed") : void 0;\n if (!isRecord5(value) || flushed?.value !== true || typeof value._persist !== "function" || typeof value.getSessionFile !== "function") {\n throw new Error(\n "The configured Pi SDK SessionManager does not expose the pinned persistent-session API."\n );\n }\n}\nfunction boundedMetadataString(value) {\n if (value.length <= MAX_PI_EVENT_METADATA_STRING_LENGTH) return value;\n return `${value.slice(0, MAX_PI_EVENT_METADATA_STRING_LENGTH - 3)}...`;\n}\nfunction copyPiEventScalarMetadata(source, target) {\n if (nodeUtilTypes.isProxy(source)) return;\n for (const key of PI_EVENT_SCALAR_METADATA_KEYS) {\n const item = source[key];\n if (typeof item === "string") {\n target[key] = boundedMetadataString(item);\n } else if (item === null || typeof item === "boolean" || typeof item === "number" && Number.isFinite(item)) {\n target[key] = item;\n }\n }\n}\nfunction summarizePiEventMetadata(value) {\n if (!isRecord5(value) || nodeUtilTypes.isProxy(value)) return {};\n const summary = /* @__PURE__ */ Object.create(null);\n copyPiEventScalarMetadata(value, summary);\n for (const key of PI_EVENT_NESTED_METADATA_KEYS) {\n const item = value[key];\n if (!isRecord5(item) || nodeUtilTypes.isProxy(item)) continue;\n const nested = /* @__PURE__ */ Object.create(null);\n copyPiEventScalarMetadata(item, nested);\n if (Object.keys(nested).length > 0) summary[key] = nested;\n }\n for (const key of PI_EVENT_ARRAY_METADATA_KEYS) {\n const item = value[key];\n if (Array.isArray(item) && !nodeUtilTypes.isProxy(item)) {\n summary[`${key}Count`] = item.length;\n }\n }\n return summary;\n}\nfunction truncatedPiEvent(event, reason, redactor, originalPayloadBytes) {\n let metadata;\n try {\n metadata = redactJsonStrings(\n summarizePiEventMetadata(event),\n redactor\n );\n } catch {\n metadata = {};\n }\n const truncation = {\n truncated: true,\n reason,\n maxPayloadBytes: MAX_PERSISTED_PI_EVENT_PAYLOAD_BYTES,\n ...originalPayloadBytes === void 0 ? {} : { originalPayloadBytes }\n };\n const candidate = {\n ...metadata,\n neckbeardTruncation: truncation\n };\n if (Buffer.byteLength(JSON.stringify(candidate), "utf8") <= MAX_TRUNCATED_PI_EVENT_PAYLOAD_BYTES) {\n return candidate;\n }\n return {\n ...typeof metadata.type === "string" ? { type: metadata.type } : {},\n neckbeardTruncation: truncation\n };\n}\nfunction redactJsonStrings(value, redactor) {\n if (typeof value === "string") return redactor.redact(value);\n if (typeof value === "object" && value !== null && nodeUtilTypes.isProxy(value)) {\n return void 0;\n }\n if (Array.isArray(value))\n return value.map((item) => redactJsonStrings(item, redactor));\n if (!isRecord5(value)) return value;\n const redacted = /* @__PURE__ */ Object.create(null);\n for (const [key, item] of Object.entries(value)) {\n redacted[redactor.redact(key)] = redactJsonStrings(item, redactor);\n }\n return redacted;\n}\nvar PiEventTraversalLimitError = class extends Error {\n};\nvar PiEventSerializationError = class extends Error {\n};\nfunction consumePiEventTraversalNode(writer) {\n writer.visitedNodes += 1;\n if (writer.visitedNodes > MAX_PI_EVENT_TRAVERSAL_NODES) {\n throw new PiEventTraversalLimitError();\n }\n}\nfunction appendPiEventJson(writer, chunk) {\n const remainingBytes = MAX_PERSISTED_PI_EVENT_PAYLOAD_BYTES - writer.sizeBytes;\n if (chunk.length > remainingBytes) throw new PiEventTraversalLimitError();\n const chunkBytes = Buffer.byteLength(chunk, "utf8");\n if (chunkBytes > remainingBytes) throw new PiEventTraversalLimitError();\n writer.chunks.push(chunk);\n writer.sizeBytes += chunkBytes;\n}\nfunction appendRedactedPiEventString(writer, value) {\n const remainingBytes = MAX_PERSISTED_PI_EVENT_PAYLOAD_BYTES - writer.sizeBytes;\n if (value.length + 2 > remainingBytes)\n throw new PiEventTraversalLimitError();\n const redacted = writer.redactor.redact(value);\n if (redacted.length + 2 > remainingBytes)\n throw new PiEventTraversalLimitError();\n appendPiEventJson(writer, JSON.stringify(redacted));\n}\nfunction readPiEventProperty(value, key) {\n try {\n return Reflect.get(value, key);\n } catch {\n throw new PiEventSerializationError();\n }\n}\nfunction writePiEventJsonValue(writer, value, key, depth, applyToJson = true) {\n consumePiEventTraversalNode(writer);\n if (value === null) {\n appendPiEventJson(writer, "null");\n return true;\n }\n if (typeof value === "string") {\n appendRedactedPiEventString(writer, value);\n return true;\n }\n if (typeof value === "boolean") {\n appendPiEventJson(writer, value ? "true" : "false");\n return true;\n }\n if (typeof value === "number") {\n appendPiEventJson(writer, Number.isFinite(value) ? JSON.stringify(value) : "null");\n return true;\n }\n if (value === void 0 || typeof value === "function" || typeof value === "symbol") {\n return false;\n }\n if (typeof value === "bigint") {\n const boxed = Object(value);\n const toJSON = readPiEventProperty(boxed, "toJSON");\n if (typeof toJSON !== "function") throw new PiEventSerializationError();\n let normalized;\n try {\n normalized = Reflect.apply(toJSON, value, [key]);\n } catch {\n throw new PiEventSerializationError();\n }\n return writePiEventJsonValue(writer, normalized, key, depth, false);\n }\n if (typeof value !== "object") throw new PiEventSerializationError();\n if (depth > MAX_PI_EVENT_TRAVERSAL_DEPTH)\n throw new PiEventTraversalLimitError();\n if (nodeUtilTypes.isProxy(value)) throw new PiEventSerializationError();\n if (applyToJson) {\n const toJSON = readPiEventProperty(value, "toJSON");\n if (typeof toJSON === "function") {\n let normalized;\n try {\n normalized = Reflect.apply(toJSON, value, [key]);\n } catch {\n throw new PiEventSerializationError();\n }\n return writePiEventJsonValue(writer, normalized, key, depth, false);\n }\n }\n if (nodeUtilTypes.isNumberObject(value)) {\n return writePiEventJsonValue(writer, Number(value), key, depth, false);\n }\n if (nodeUtilTypes.isStringObject(value)) {\n return writePiEventJsonValue(writer, String(value), key, depth, false);\n }\n if (nodeUtilTypes.isBooleanObject(value)) {\n return writePiEventJsonValue(writer, Boolean(value.valueOf()), key, depth, false);\n }\n if (nodeUtilTypes.isBigIntObject(value)) {\n throw new PiEventSerializationError();\n }\n if (writer.activeObjects.has(value)) throw new PiEventSerializationError();\n writer.activeObjects.add(value);\n try {\n if (Array.isArray(value)) {\n appendPiEventJson(writer, "[");\n for (let index = 0; index < value.length; index += 1) {\n consumePiEventTraversalNode(writer);\n if (index > 0) appendPiEventJson(writer, ",");\n const item = readPiEventProperty(value, String(index));\n if (!writePiEventJsonValue(writer, item, String(index), depth + 1)) {\n appendPiEventJson(writer, "null");\n }\n }\n appendPiEventJson(writer, "]");\n return true;\n }\n appendPiEventJson(writer, "{");\n let wroteProperty = false;\n try {\n for (const property in value) {\n consumePiEventTraversalNode(writer);\n if (!Object.hasOwn(value, property)) continue;\n const item = readPiEventProperty(value, property);\n const checkpointChunks = writer.chunks.length;\n const checkpointBytes = writer.sizeBytes;\n if (wroteProperty) appendPiEventJson(writer, ",");\n appendRedactedPiEventString(writer, property);\n appendPiEventJson(writer, ":");\n if (writePiEventJsonValue(writer, item, property, depth + 1)) {\n wroteProperty = true;\n } else {\n writer.chunks.length = checkpointChunks;\n writer.sizeBytes = checkpointBytes;\n }\n }\n } catch (error) {\n if (error instanceof PiEventTraversalLimitError || error instanceof PiEventSerializationError) {\n throw error;\n }\n throw new PiEventSerializationError();\n }\n appendPiEventJson(writer, "}");\n return true;\n } finally {\n writer.activeObjects.delete(value);\n }\n}\nfunction serializeBoundedPiEvent(event, redactor) {\n const writer = {\n chunks: [],\n activeObjects: /* @__PURE__ */ new WeakSet(),\n redactor,\n sizeBytes: 0,\n visitedNodes: 0\n };\n if (!writePiEventJsonValue(writer, event, "", 0)) {\n throw new PiEventSerializationError();\n }\n return writer.chunks.join("");\n}\nfunction jsonSafePiEvent(event, redactor) {\n try {\n return JSON.parse(serializeBoundedPiEvent(event, redactor));\n } catch (error) {\n if (error instanceof PiEventTraversalLimitError) {\n return truncatedPiEvent(event, "payload_exceeded_limit", redactor);\n }\n return truncatedPiEvent(event, "payload_not_json_serializable", redactor);\n }\n}\nfunction finiteNonnegative(value) {\n return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;\n}\nfunction nonnegativeInteger(value) {\n return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0;\n}\nfunction usageFromAssistantMessage(message) {\n if (!message || !isRecord5(message.usage)) return void 0;\n const usage = message.usage;\n const inputTokens = nonnegativeInteger(usage.input);\n const outputTokens = nonnegativeInteger(usage.output);\n const cacheReadTokens = nonnegativeInteger(usage.cacheRead);\n const cacheWriteTokens = nonnegativeInteger(usage.cacheWrite);\n const reportedTotal = nonnegativeInteger(usage.totalTokens);\n const calculatedTotal = inputTokens + outputTokens + cacheReadTokens + cacheWriteTokens;\n const totalTokens = reportedTotal || (Number.isSafeInteger(calculatedTotal) ? calculatedTotal : Number.MAX_SAFE_INTEGER);\n const totalCost = isRecord5(usage.cost) ? finiteNonnegative(usage.cost.total) : 0;\n return {\n inputTokens,\n outputTokens,\n cacheReadTokens,\n cacheWriteTokens,\n totalTokens,\n ...totalCost === 0 ? {} : { costUsd: totalCost }\n };\n}\nfunction lastAssistantMessage(messages) {\n if (!Array.isArray(messages) || nodeUtilTypes.isProxy(messages)) return null;\n const minimumIndex = Math.max(\n 0,\n messages.length - MAX_PI_EVENT_LIFECYCLE_MESSAGE_SCAN\n );\n for (let index = messages.length - 1; index >= minimumIndex; index -= 1) {\n const message = boundedAssistantMessage(\n readPiLifecycleProperty(messages, String(index))\n );\n if (message?.role === "assistant") return message;\n }\n return null;\n}\nfunction boundedLifecycleString(value) {\n return value.length <= MAX_PI_EVENT_LIFECYCLE_STRING_LENGTH ? value : `${value.slice(0, MAX_PI_EVENT_LIFECYCLE_STRING_LENGTH - 3)}...`;\n}\nfunction readPiLifecycleProperty(value, property) {\n try {\n let current = value;\n for (let depth = 0; current !== null && depth < 4; depth += 1) {\n if (nodeUtilTypes.isProxy(current)) return void 0;\n const descriptor = Object.getOwnPropertyDescriptor(current, property);\n if (descriptor) {\n return "value" in descriptor ? descriptor.value : void 0;\n }\n current = Object.getPrototypeOf(current);\n }\n return void 0;\n } catch {\n return void 0;\n }\n}\nfunction boundedAssistantMessage(value) {\n if (!isRecord5(value) || nodeUtilTypes.isProxy(value)) return null;\n const bounded = /* @__PURE__ */ Object.create(null);\n for (const property of ["role", "stopReason", "errorMessage"]) {\n const item = readPiLifecycleProperty(value, property);\n if (typeof item === "string") bounded[property] = boundedLifecycleString(item);\n }\n const usage = readPiLifecycleProperty(value, "usage");\n if (isRecord5(usage) && !nodeUtilTypes.isProxy(usage)) {\n const boundedUsage = /* @__PURE__ */ Object.create(null);\n for (const property of [\n "input",\n "output",\n "cacheRead",\n "cacheWrite",\n "totalTokens"\n ]) {\n const item = readPiLifecycleProperty(usage, property);\n if (typeof item === "number" && Number.isFinite(item)) {\n boundedUsage[property] = item;\n }\n }\n const cost = readPiLifecycleProperty(usage, "cost");\n if (isRecord5(cost) && !nodeUtilTypes.isProxy(cost)) {\n const total = readPiLifecycleProperty(cost, "total");\n if (typeof total === "number" && Number.isFinite(total)) {\n boundedUsage.cost = { total };\n }\n }\n bounded.usage = boundedUsage;\n }\n return bounded;\n}\nfunction boundedLifecycleFailure(value) {\n let isError = false;\n try {\n isError = value instanceof Error;\n } catch {\n return new Error("Pi turn failed.");\n }\n if (isError && typeof value === "object" && value !== null) {\n const record = value;\n const message = readPiLifecycleProperty(record, "message");\n const name = readPiLifecycleProperty(record, "name");\n const stack = readPiLifecycleProperty(record, "stack");\n const bounded = new Error(\n typeof message === "string" ? boundedLifecycleString(message) : "Pi turn failed."\n );\n if (typeof name === "string") {\n bounded.name = boundedLifecycleString(name);\n }\n if (typeof stack === "string") {\n bounded.stack = boundedLifecycleString(stack);\n }\n return bounded;\n }\n if (typeof value === "string") return boundedLifecycleString(value);\n return new Error("Pi turn failed.");\n}\nvar PiSdkHarnessAdapter = class {\n constructor(config, executionGate = new SupervisorExecutionGate(), redactor = new SensitiveValueRedactor(), dependencies = {}) {\n this.config = config;\n this.executionGate = executionGate;\n this.redactor = redactor;\n this.dependencies = dependencies;\n assertSupervisorHarnessPathOwnership(\n config.stateDir,\n config.harness.sessionPath,\n config.harness.agentDir\n );\n this.resourceSnapshotManager = new PiResourceSnapshotManager(\n {\n agentDir: config.harness.agentDir ?? join4(config.stateDir, "pi/agent"),\n stateDir: config.stateDir,\n stateDurabilityAnchor: config.stateDurabilityAnchor,\n attemptId: config.attemptId\n },\n dependencies\n );\n }\n config;\n executionGate;\n redactor;\n dependencies;\n name = "pi-sdk";\n state = "idle";\n listeners = /* @__PURE__ */ new Set();\n session = null;\n unsubscribe = null;\n startPromise = null;\n stopPromise = null;\n activeTurn = null;\n eventQueue = [];\n eventQueueBytes = 0;\n eventPump = null;\n eventFailure = null;\n commandApplied = /* @__PURE__ */ new Set();\n commandAppliedWaiters = /* @__PURE__ */ new Map();\n resourceSnapshotManager;\n sessionDirectory = null;\n sessionFile = null;\n sessionHistoryFailure = null;\n subscribe(listener) {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n async start() {\n this.executionGate.throwIfClosed();\n if (this.state === "running") return;\n if (this.startPromise) return this.startPromise;\n if (this.state !== "idle") {\n throw new Error(`Pi cannot start while harness state is ${this.state}.`);\n }\n const starting = this.startSession();\n this.startPromise = starting;\n try {\n await starting;\n } finally {\n if (this.startPromise === starting) this.startPromise = null;\n }\n }\n async prompt(input) {\n this.executionGate.throwIfClosed();\n await this.start();\n this.executionGate.throwIfClosed();\n const session = this.session;\n if (!session) throw new Error("Pi SDK session is unavailable.");\n if (this.activeTurn || session.isStreaming) {\n throw new Error(\n "Pi already has an active turn; use a steer command instead."\n );\n }\n await this.assertSessionHistoryPromptCapacity();\n this.executionGate.throwIfClosed();\n const turn = {\n commandId: input.commandId,\n run: null,\n terminalTask: null,\n terminalClaim: null,\n terminalFinalized: false,\n started: false,\n latestAssistantMessage: null\n };\n this.activeTurn = turn;\n let preflightSettled = false;\n let preflightAccepted = false;\n let resolvePreflight;\n let rejectPreflight;\n const preflight = new Promise((resolveAccepted, rejectAccepted) => {\n resolvePreflight = resolveAccepted;\n rejectPreflight = rejectAccepted;\n });\n let run;\n try {\n this.assertSessionHistoryPromptCapacitySync();\n this.executionGate.throwIfClosed();\n run = session.prompt(attachFilesToMessage(input), {\n preflightResult: (disposition) => {\n if (preflightSettled) return;\n preflightSettled = true;\n if (disposition !== false) {\n preflightAccepted = true;\n resolvePreflight();\n } else {\n rejectPreflight(\n new Error("Pi rejected the prompt before acceptance.")\n );\n }\n }\n });\n } catch (error) {\n if (this.activeTurn === turn) this.activeTurn = null;\n throw error;\n }\n const tracked = run.then(\n async () => {\n if (!preflightSettled) {\n preflightSettled = true;\n rejectPreflight(\n new Error("Pi completed before reporting prompt preflight.")\n );\n }\n if (preflightAccepted) await this.finishTurn(turn);\n },\n async (error) => {\n if (!preflightSettled) {\n preflightSettled = true;\n rejectPreflight(errorFromUnknown(error));\n }\n if (preflightAccepted) await this.finishTurn(turn, error);\n }\n ).finally(() => {\n if (!preflightAccepted || turn.terminalFinalized || turn.terminalClaim === "shutdown") {\n this.releaseTurn(turn);\n }\n });\n turn.run = tracked;\n void tracked.catch(() => void 0);\n await preflight;\n }\n async steer(input) {\n this.executionGate.throwIfClosed();\n const session = this.session;\n const turn = this.activeTurn;\n if (!session || !turn?.run || !session.isStreaming) {\n throw new Error(\n "Pi is not running an active turn; steering cannot be queued."\n );\n }\n await this.assertSessionHistoryPromptCapacity();\n this.assertSessionHistoryPromptCapacitySync();\n this.executionGate.throwIfClosed();\n await session.steer(attachFilesToMessage(input));\n }\n async cancel(reason, commandId) {\n await this.cancelForCommand(reason, commandId);\n }\n async cancelForCommand(reason, commandId) {\n if (!this.claimStop()) return false;\n await this.abortClaimedStop(reason, commandId);\n return true;\n }\n claimStop() {\n this.executionGate.throwIfClosed();\n const session = this.session;\n const turn = this.activeTurn;\n if (!session || !turn?.run) return false;\n return this.claimTerminal(turn, "stopped");\n }\n async abortClaimedStop(reason, commandId) {\n const session = this.session;\n const turn = this.activeTurn;\n if (!session || !turn?.run || turn.terminalClaim !== "stopped") {\n throw new Error(\n "Pi stop must be claimed before aborting the active turn."\n );\n }\n let abort;\n try {\n this.executionGate.throwIfClosed();\n abort = session.abort();\n } catch (error) {\n this.failHarness("Pi failed to abort the active turn.", error);\n throw error;\n }\n const safeReason = reason === void 0 ? void 0 : sanitizeSupervisorReason(this.redactor.redact(reason));\n const terminalTask = abort.then(async () => {\n await turn.run?.catch(() => void 0);\n await this.drainEvents();\n await this.syncSessionHistory();\n if (commandId) await this.waitForCommandApplied(commandId);\n const usage = usageFromAssistantMessage(turn.latestAssistantMessage);\n await this.enqueueEvent({\n type: "lifecycle",\n event: {\n kind: "turn_stopped",\n commandId: turn.commandId,\n ...safeReason === void 0 ? {} : { reason: safeReason },\n ...usage === void 0 ? {} : { usage }\n }\n });\n }).catch((error) => {\n if (!this.executionGate.isClosed && !this.eventFailure) {\n this.failHarness("Pi cancellation could not be finalized.", error);\n }\n throw error;\n }).finally(() => {\n turn.terminalFinalized = true;\n this.forgetCommandApplication(turn.commandId);\n this.forgetCommandApplication(commandId);\n this.releaseTurn(turn);\n });\n turn.terminalTask = terminalTask;\n void terminalTask.catch(() => void 0);\n await abort;\n }\n confirmCommandApplied(commandId) {\n if (this.executionGate.closure) {\n this.commandAppliedWaiters.get(commandId)?.reject(this.executionGate.closure.error);\n this.commandAppliedWaiters.delete(commandId);\n return;\n }\n this.commandApplied.add(commandId);\n this.commandAppliedWaiters.get(commandId)?.resolve();\n this.commandAppliedWaiters.delete(commandId);\n }\n stop(reason = "supervisor_shutdown") {\n const safeReason = sanitizeSupervisorReason(this.redactor.redact(reason));\n this.executionGate.close("shutdown", safeReason);\n if (this.stopPromise) return this.stopPromise;\n const stopping = this.stopSession();\n this.stopPromise = stopping;\n return stopping;\n }\n async startSession() {\n this.state = "starting";\n let candidateSession = null;\n let candidateUnsubscribe = null;\n try {\n const sessionDirectory = await ensureDescriptorBoundDirectory(\n this.config.stateDurabilityAnchor,\n dirname3(this.config.harness.sessionPath)\n );\n this.sessionDirectory = sessionDirectory;\n await this.dependencies.afterSessionDirectoryBound?.(\n dirname3(this.config.harness.sessionPath)\n );\n this.sessionFile = await preparePiSessionFile(\n sessionDirectory,\n basename(this.config.harness.sessionPath),\n this.config.harness.sessionPath\n );\n this.executionGate.throwIfClosed();\n await mkdir3(this.config.workspaceDir, { recursive: true });\n await assertWorkspaceIsolated(\n this.config.workspaceDir,\n this.config.stateDir\n );\n this.executionGate.throwIfClosed();\n await this.resourceSnapshotManager.prepare();\n const agentDir = this.resourceSnapshotManager.runtimeAgentDir;\n const authPath = this.resourceSnapshotManager.runtimeAuthPath;\n this.executionGate.throwIfClosed();\n const provider = this.config.harness.provider;\n const providerCredentialEnv = this.config.harness.providerCredentialEnv;\n const providerCredential = providerCredentialEnv === void 0 ? void 0 : process.env[providerCredentialEnv];\n if (providerCredentialEnv !== void 0 && !providerCredential?.trim()) {\n throw new Error(\n `Pi provider credential ${providerCredentialEnv} must be non-empty.`\n );\n }\n if (providerCredentialEnv !== void 0)\n delete process.env[providerCredentialEnv];\n this.redactor.capture(providerCredential);\n const sdk = await import(this.config.harness.moduleSpecifier);\n this.executionGate.throwIfClosed();\n assertPiSdkModule(sdk);\n if (sdk.VERSION !== this.config.harness.expectedVersion) {\n throw new Error(\n `Pi SDK version mismatch: expected ${this.config.harness.expectedVersion}, received ${String(\n sdk.VERSION\n )}.`\n );\n }\n await this.resourceSnapshotManager.validateRuntimeAuth();\n this.executionGate.throwIfClosed();\n await this.dependencies.beforeModelRuntimeCreate?.(authPath);\n await this.resourceSnapshotManager.validateRuntimeAuth();\n this.executionGate.throwIfClosed();\n const modelRuntime = await sdk.ModelRuntime.create({\n authPath,\n modelsPath: null\n });\n this.executionGate.throwIfClosed();\n if (provider && providerCredential) {\n await modelRuntime.setRuntimeApiKey(provider, providerCredential, {\n allowNetwork: false\n });\n this.executionGate.throwIfClosed();\n }\n this.executionGate.throwIfClosed();\n const sessionFile = this.sessionFile;\n if (sessionFile === null) {\n throw new Error("Pi session storage is not descriptor-bound.");\n }\n const sessionManager = await withPiSessionFileReady(\n sessionDirectory,\n basename(this.config.harness.sessionPath),\n sessionFile,\n this.config.harness.sessionPath,\n () => {\n this.executionGate.throwIfClosed();\n assertPiSessionHistoryReadyForSdkOpen(\n sessionFile,\n this.config.harness.sessionPath\n );\n return sdk.SessionManager.open(\n this.boundSessionFilePath(),\n descriptorBoundDirectoryPath(sessionDirectory),\n this.config.workspaceDir\n );\n }\n );\n assertPiSdkSessionManager(sessionManager);\n this.installSessionHistoryWriteGuard(sessionManager);\n await this.syncSessionHistory();\n const model = provider && this.config.harness.model ? modelRuntime.getModel(provider, this.config.harness.model) : void 0;\n if (this.config.harness.provider && this.config.harness.model && !model) {\n throw new Error(\n `Pi model ${this.config.harness.provider}/${this.config.harness.model} was not found.`\n );\n }\n const settingsManager = sdk.SettingsManager.inMemory(\n {},\n { projectTrusted: false }\n );\n const createResourceLoader = (snapshotAgentDir) => new sdk.DefaultResourceLoader({\n cwd: this.config.workspaceDir,\n agentDir: snapshotAgentDir,\n settingsManager\n });\n const resourceLoader = this.resourceSnapshotManager.createResourceLoader(\n createResourceLoader\n );\n await resourceLoader.reload();\n this.executionGate.throwIfClosed();\n const result = await sdk.createAgentSession({\n cwd: this.config.workspaceDir,\n agentDir,\n modelRuntime,\n resourceLoader,\n settingsManager,\n sessionManager,\n ...model === void 0 ? {} : { model },\n ...this.config.harness.thinking === void 0 ? {} : { thinkingLevel: this.config.harness.thinking }\n });\n assertPiSdkSession(result.session);\n candidateSession = result.session;\n await this.syncSessionHistory();\n this.executionGate.throwIfClosed();\n candidateUnsubscribe = candidateSession.subscribe(\n (event) => this.onPiEvent(event)\n );\n this.executionGate.throwIfClosed();\n this.session = candidateSession;\n this.unsubscribe = candidateUnsubscribe;\n candidateSession = null;\n candidateUnsubscribe = null;\n this.state = "running";\n await this.enqueueEvent({ type: "started" });\n this.executionGate.throwIfClosed();\n } catch (error) {\n candidateUnsubscribe?.();\n candidateSession?.dispose();\n this.disposePublishedSession();\n await this.resourceSnapshotManager.close().catch(() => void 0);\n await this.closeSessionStorage().catch(() => void 0);\n if (this.state !== "stopping")\n this.state = "exited";\n if (!this.executionGate.isClosed) {\n this.executionGate.close(\n "startup_failed",\n "Pi SDK session initialization failed.",\n error\n );\n }\n throw error;\n }\n }\n async stopSession() {\n if (this.state !== "exited") this.state = "stopping";\n const closureError = this.executionGate.closure?.error ?? new Error("Supervisor execution was stopped.");\n const turn = this.activeTurn;\n if (turn) this.claimTerminal(turn, "shutdown");\n this.rejectCommandAppliedWaiters(closureError);\n let failure = null;\n try {\n await withTimeout(\n this.settleHarnessForStop(),\n this.config.harness.stopGraceMs,\n "Timed out while stopping the Pi SDK session."\n );\n } catch (error) {\n failure = errorFromUnknown(error);\n }\n try {\n this.disposePublishedSession();\n } catch (error) {\n failure ??= errorFromUnknown(error);\n }\n const closingSnapshots = this.resourceSnapshotManager.close();\n void closingSnapshots.catch(() => void 0);\n try {\n await withTimeout(\n closingSnapshots,\n this.config.harness.stopGraceMs,\n "Timed out while releasing Pi resource snapshots."\n );\n } catch (error) {\n failure ??= errorFromUnknown(error);\n }\n try {\n await this.closeSessionStorage();\n } catch (error) {\n failure ??= errorFromUnknown(error);\n }\n this.activeTurn = null;\n this.commandApplied.clear();\n this.commandAppliedWaiters.clear();\n this.state = "exited";\n try {\n await withTimeout(\n (async () => {\n await this.drainEvents();\n if (!this.eventFailure) {\n await this.enqueueEvent({\n type: "exit",\n result: { exitCode: 0, signal: null }\n });\n }\n })(),\n this.config.harness.stopGraceMs,\n "Timed out while draining Pi SDK lifecycle events."\n );\n } catch (error) {\n failure ??= errorFromUnknown(error);\n }\n if (this.eventFailure) failure ??= this.eventFailure;\n if (failure) throw failure;\n }\n async settleHarnessForStop() {\n await this.startPromise?.catch(() => void 0);\n const session = this.session;\n const turn = this.activeTurn;\n if (!session || !turn?.run) return;\n this.claimTerminal(turn, "shutdown");\n await session.abort();\n await turn.run.catch(() => void 0);\n await turn.terminalTask?.catch(() => void 0);\n await this.syncSessionHistory();\n }\n onPiEvent(event) {\n const turn = this.activeTurn;\n const boundedEvent = isRecord5(event) && !nodeUtilTypes.isProxy(event) ? event : null;\n const eventType = boundedEvent === null ? void 0 : readPiLifecycleProperty(boundedEvent, "type");\n if (turn && boundedEvent) {\n if (eventType === "turn_end") {\n turn.latestAssistantMessage = boundedAssistantMessage(\n readPiLifecycleProperty(boundedEvent, "message")\n ) ?? turn.latestAssistantMessage;\n } else if (eventType === "agent_end") {\n turn.latestAssistantMessage = lastAssistantMessage(\n readPiLifecycleProperty(boundedEvent, "messages")\n ) ?? turn.latestAssistantMessage;\n }\n }\n const safeEvent = jsonSafePiEvent(event, this.redactor);\n this.queueEvent(\n { type: "event", payload: safeEvent },\n isCoalescedPiEvent(safeEvent)\n );\n if (turn && eventType === "agent_start" && !turn.started) {\n turn.started = true;\n this.queueEvent({\n type: "lifecycle",\n event: { kind: "turn_started", commandId: turn.commandId }\n });\n }\n }\n async finishTurn(turn, failure) {\n if (!this.claimTerminal(turn, "natural")) return;\n try {\n await this.waitForCommandApplied(turn.commandId);\n await this.drainEvents();\n await this.syncSessionHistory();\n if (!turn.started) {\n turn.started = true;\n await this.enqueueEvent({\n type: "lifecycle",\n event: { kind: "turn_started", commandId: turn.commandId }\n });\n }\n const message = turn.latestAssistantMessage;\n const rawStopReason = message && typeof message.stopReason === "string" ? message.stopReason : void 0;\n const stopReason = rawStopReason === void 0 ? void 0 : sanitizeSupervisorReason(\n this.redactor.redact(boundedLifecycleString(rawStopReason))\n );\n const usage = usageFromAssistantMessage(message);\n const errorMessage = message && typeof message.errorMessage === "string" ? message.errorMessage : void 0;\n if (failure !== void 0 || rawStopReason === "error" || rawStopReason === "aborted") {\n await this.enqueueEvent({\n type: "lifecycle",\n event: {\n kind: "turn_failed",\n commandId: turn.commandId,\n ...stopReason === void 0 ? {} : { stopReason },\n error: this.redactor.serialize(\n boundedLifecycleFailure(\n failure ?? errorMessage ?? `Pi turn ended with stop reason ${String(stopReason)}.`\n )\n ),\n ...usage === void 0 ? {} : { usage }\n }\n });\n } else {\n await this.enqueueEvent({\n type: "lifecycle",\n event: {\n kind: "turn_completed",\n commandId: turn.commandId,\n ...stopReason === void 0 ? {} : { stopReason },\n ...usage === void 0 ? {} : { usage }\n }\n });\n }\n } finally {\n turn.terminalFinalized = true;\n this.forgetCommandApplication(turn.commandId);\n this.releaseTurn(turn);\n }\n }\n forgetCommandApplication(commandId) {\n if (commandId === void 0) return;\n this.commandApplied.delete(commandId);\n this.commandAppliedWaiters.delete(commandId);\n }\n claimTerminal(turn, claim) {\n if (this.activeTurn !== turn || turn.terminalClaim) return false;\n turn.terminalClaim = claim;\n return true;\n }\n releaseTurn(turn) {\n if (this.activeTurn === turn) this.activeTurn = null;\n }\n waitForCommandApplied(commandId) {\n if (this.commandApplied.has(commandId)) return Promise.resolve();\n if (this.executionGate.closure)\n return Promise.reject(this.executionGate.closure.error);\n const existing = this.commandAppliedWaiters.get(commandId);\n if (existing) return existing.promise;\n let resolveApplied;\n let rejectApplied;\n const promise = new Promise((resolve2, reject) => {\n resolveApplied = resolve2;\n rejectApplied = reject;\n });\n this.commandAppliedWaiters.set(commandId, {\n promise,\n resolve: resolveApplied,\n reject: rejectApplied\n });\n return promise;\n }\n rejectCommandAppliedWaiters(error) {\n for (const waiter of this.commandAppliedWaiters.values())\n waiter.reject(error);\n this.commandAppliedWaiters.clear();\n }\n async syncSessionHistory() {\n try {\n const file = this.sessionFile;\n const directory = this.sessionDirectory;\n if (file === null || directory === null) {\n throw new Error("Pi session storage is not descriptor-bound.");\n }\n if (this.sessionHistoryFailure) throw this.sessionHistoryFailure;\n await this.revalidateSessionHistoryFile();\n await file.sync();\n await syncDescriptorBoundDirectory(directory);\n await this.dependencies.afterSessionHistoryDurabilitySync?.(\n this.config.harness.sessionPath\n );\n const stats = await this.revalidateSessionHistoryFile();\n if (this.sessionHistoryFailure) throw this.sessionHistoryFailure;\n assertPiSessionHistorySize(\n stats,\n SUPERVISOR_MAX_PI_SESSION_HISTORY_BYTES,\n "above",\n "exceeds"\n );\n } catch (error) {\n this.failHarness("Pi session history could not be made durable.", error);\n throw error;\n }\n }\n async assertSessionHistoryPromptCapacity() {\n const stats = await this.revalidateSessionHistoryFile();\n assertPiSessionHistorySize(\n stats,\n SUPERVISOR_PI_SESSION_HISTORY_PROMPT_LIMIT_BYTES,\n "at_or_above",\n "has reached"\n );\n await this.dependencies.afterSessionHistoryAdmissionRevalidation?.(\n this.config.harness.sessionPath\n );\n }\n assertSessionHistoryPromptCapacitySync() {\n const file = this.sessionFile;\n if (file === null) {\n throw new Error("Pi session storage is not descriptor-bound.");\n }\n assertPiSessionHistorySize(\n fstatSync(file.fd, { bigint: true }),\n SUPERVISOR_PI_SESSION_HISTORY_PROMPT_LIMIT_BYTES,\n "at_or_above",\n "has reached"\n );\n }\n async revalidateSessionHistoryFile() {\n const file = this.sessionFile;\n const directory = this.sessionDirectory;\n if (file === null || directory === null) {\n throw new Error("Pi session storage is not descriptor-bound.");\n }\n let stats = null;\n await withRevalidatedPrivateRegularFile(\n file,\n () => openPiSessionFile(\n directory,\n basename(this.config.harness.sessionPath),\n this.config.harness.sessionPath,\n constants2.O_RDONLY\n ),\n () => {\n stats = fstatSync(file.fd, { bigint: true });\n },\n {\n failureMessage: `Pi session path ${this.config.harness.sessionPath} must remain the process-owned single-link private regular file bound at startup.`\n }\n );\n if (stats === null) {\n throw new Error("Pi session storage could not be revalidated.");\n }\n return stats;\n }\n installSessionHistoryWriteGuard(sessionManager) {\n this.assertSessionManagerUsesBoundHistory(sessionManager);\n this.assertSessionManagerIsAppendOnly(sessionManager);\n const adapter = this;\n sessionManager._persist = function guardedPiSessionPersist(entry) {\n try {\n adapter.assertSessionManagerUsesBoundHistory(sessionManager);\n adapter.assertSessionManagerIsAppendOnly(sessionManager);\n const serialized = JSON.stringify(entry);\n if (typeof serialized !== "string") {\n throw new Error("Pi attempted to persist a non-JSON session entry.");\n }\n adapter.assertSessionManagerUsesBoundHistory(sessionManager);\n adapter.assertSessionManagerIsAppendOnly(sessionManager);\n const line = Buffer.from(`${serialized}\n`, "utf8");\n const beforeBytes = adapter.assertSessionHistoryWriteCapacity(\n line.byteLength\n );\n adapter.appendSessionHistoryLine(line, beforeBytes);\n adapter.dependencies.afterSessionHistoryAppend?.(\n adapter.config.harness.sessionPath\n );\n adapter.assertSessionManagerUsesBoundHistory(sessionManager);\n adapter.assertSessionManagerIsAppendOnly(sessionManager);\n const afterBytes = adapter.assertSessionHistoryWriteCapacity(0);\n if (afterBytes !== beforeBytes + BigInt(line.byteLength)) {\n throw new Error(\n "Pi session history append did not produce its exact expected size."\n );\n }\n } catch (error) {\n throw adapter.failSessionHistoryPersistence(error);\n }\n };\n }\n assertSessionManagerUsesBoundHistory(sessionManager) {\n if (sessionManager.getSessionFile() !== this.boundSessionFilePath()) {\n throw new Error(\n "Pi SessionManager must keep using the descriptor-bound session history path."\n );\n }\n }\n assertSessionManagerIsAppendOnly(sessionManager) {\n if (Object.getOwnPropertyDescriptor(sessionManager, "flushed")?.value !== true) {\n throw new Error(\n "Pi SessionManager left its pinned append-only persistence state."\n );\n }\n }\n assertSessionHistoryWriteCapacity(entryBytes) {\n const file = this.sessionFile;\n if (file === null) {\n throw new Error("Pi session storage is not descriptor-bound.");\n }\n const stats = fstatSync(file.fd, { bigint: true });\n const maximumBytes = BigInt(SUPERVISOR_MAX_PI_SESSION_HISTORY_BYTES);\n if (stats.size + BigInt(entryBytes) > maximumBytes) {\n throw piSessionHistoryLimitError(\n SUPERVISOR_MAX_PI_SESSION_HISTORY_BYTES,\n "would exceed"\n );\n }\n return stats.size;\n }\n appendSessionHistoryLine(line, start) {\n const file = this.sessionFile;\n if (file === null) {\n throw new Error("Pi session storage is not descriptor-bound.");\n }\n const position = Number(start);\n let written = 0;\n while (written < line.byteLength) {\n const bytesWritten = writeSync(\n file.fd,\n line,\n written,\n line.byteLength - written,\n position + written\n );\n if (bytesWritten <= 0) {\n throw new Error("Pi session history append made no forward progress.");\n }\n written += bytesWritten;\n }\n }\n failSessionHistoryPersistence(error) {\n const failure = errorFromUnknown(error);\n this.sessionHistoryFailure ??= failure;\n this.failHarness("Pi session history persistence failed.", failure);\n return failure;\n }\n boundSessionFilePath() {\n const file = this.sessionFile;\n if (file === null) {\n throw new Error("Pi session storage is not descriptor-bound.");\n }\n return descriptorBoundDirectoryPath({ handle: file });\n }\n async closeSessionStorage() {\n const file = this.sessionFile;\n const directory = this.sessionDirectory;\n this.sessionFile = null;\n this.sessionDirectory = null;\n let failure;\n await file?.close().catch((error) => {\n failure ??= error;\n });\n await directory?.handle.close().catch((error) => {\n failure ??= error;\n });\n if (failure !== void 0) throw failure;\n }\n queueEvent(event, coalescible = false) {\n if (this.eventFailure) return;\n try {\n this.stageEvent({\n event,\n sizeBytes: Buffer.byteLength(JSON.stringify(event), "utf8"),\n coalescible\n });\n } catch (error) {\n this.latchEventFailure(errorFromUnknown(error));\n }\n }\n enqueueEvent(event) {\n if (this.eventFailure) return Promise.reject(this.eventFailure);\n const sizeBytes = Buffer.byteLength(JSON.stringify(event), "utf8");\n const persisted = new Promise((resolvePersisted, rejectPersisted) => {\n try {\n this.stageEvent({\n event,\n sizeBytes,\n coalescible: false,\n resolve: resolvePersisted,\n reject: rejectPersisted\n });\n } catch (error) {\n rejectPersisted(errorFromUnknown(error));\n }\n });\n void persisted.catch(() => void 0);\n return persisted;\n }\n stageEvent(entry) {\n if (this.eventFailure) throw this.eventFailure;\n const last = this.eventQueue.at(-1);\n if (entry.coalescible && last?.coalescible && !last.inFlight) {\n this.eventQueueBytes += entry.sizeBytes - last.sizeBytes;\n last.event = entry.event;\n last.sizeBytes = entry.sizeBytes;\n } else {\n this.eventQueue.push(entry);\n this.eventQueueBytes += entry.sizeBytes;\n }\n if (this.eventQueue.length > MAX_PENDING_HARNESS_EVENTS || this.eventQueueBytes > MAX_PENDING_HARNESS_EVENT_BYTES) {\n const failure = new Error(\n "Pi event delivery exceeded its bounded pending queue."\n );\n this.latchEventFailure(failure);\n throw failure;\n }\n this.startEventPump();\n }\n startEventPump() {\n if (this.eventPump || this.eventFailure || this.eventQueue.length === 0)\n return;\n const pumping = this.pumpEvents();\n this.eventPump = pumping;\n void pumping.catch((error) => {\n this.latchEventFailure(errorFromUnknown(error));\n }).finally(() => {\n if (this.eventPump === pumping) this.eventPump = null;\n if (!this.eventFailure && this.eventQueue.length > 0)\n this.startEventPump();\n });\n }\n async pumpEvents() {\n while (this.eventQueue.length > 0) {\n if (this.eventFailure) throw this.eventFailure;\n const entry = this.eventQueue[0];\n if (!entry) return;\n entry.inFlight = true;\n try {\n await this.emit(entry.event);\n entry.resolve?.();\n } catch (error) {\n const failure = errorFromUnknown(error);\n entry.reject?.(failure);\n throw failure;\n } finally {\n if (!this.eventFailure && this.eventQueue[0] === entry) {\n this.eventQueue.shift();\n this.eventQueueBytes -= entry.sizeBytes;\n }\n }\n }\n }\n async drainEvents() {\n while (true) {\n if (this.eventFailure) throw this.eventFailure;\n const pumping = this.eventPump;\n if (pumping) await pumping.catch(() => void 0);\n if (this.eventFailure) throw this.eventFailure;\n if (!this.eventPump && this.eventQueue.length === 0) return;\n this.startEventPump();\n }\n }\n latchEventFailure(error) {\n if (this.eventFailure) return;\n this.eventFailure = error;\n const pending = this.eventQueue.splice(0);\n this.eventQueueBytes = 0;\n for (const entry of pending) entry.reject?.(error);\n this.executionGate.close(\n "persistence_failed",\n "A harness event listener failed; durable event delivery cannot continue.",\n error\n );\n this.rejectCommandAppliedWaiters(error);\n queueMicrotask(() => {\n void this.stop("harness_event_persistence_failed").catch(() => void 0);\n });\n }\n failHarness(reason, error) {\n const failure = errorFromUnknown(error);\n this.executionGate.close("harness_failed", reason, failure);\n this.rejectCommandAppliedWaiters(failure);\n queueMicrotask(() => {\n void this.stop(reason).catch(() => void 0);\n });\n }\n disposePublishedSession() {\n const unsubscribe = this.unsubscribe;\n const session = this.session;\n this.unsubscribe = null;\n this.session = null;\n unsubscribe?.();\n session?.dispose();\n }\n async emit(event) {\n for (const listener of this.listeners) await listener(event);\n }\n};\n\n// src/supervisor/runtime-store.ts\nimport { randomUUID as randomUUID4 } from "node:crypto";\nimport { constants as fsConstants3 } from "node:fs";\nvar STORE_DISK_FORMAT_VERSION = 2;\nvar LEGACY_SUPERVISOR_RUNTIME_VERSION = 1;\nvar OUTBOX_COMPACTION_MIN_RECLAIMED_EVENTS = 64;\nvar OUTBOX_COMPACTION_MIN_RECLAIMED_BYTES = 4 * 1024 * 1024;\nvar METADATA_FILE = "metadata.json";\nvar OUTBOX_FILE = "outbox.jsonl";\nvar COMMAND_LEDGER_FILE = "commands.jsonl";\nvar ACTIVE_TURN_FILE = "active-turn.json";\nvar DEFAULT_OUTBOX_CAPACITY = {\n maximumEvents: 8192,\n maximumBytes: 32 * 1024 * 1024,\n recoveryReserveEvents: 64,\n recoveryReserveBytes: 8 * 1024 * 1024\n};\nvar DEFAULT_COMMAND_LEDGER_CAPACITY = {\n maximumBytes: SUPERVISOR_MAX_COMMAND_LEDGER_BYTES,\n maximumRecords: SUPERVISOR_MAX_COMMAND_LEDGER_RECORDS,\n maximumDistinctCommands: SUPERVISOR_MAX_DISTINCT_COMMANDS,\n recoveryReserveBytes: SUPERVISOR_COMMAND_LEDGER_RECOVERY_BYTES,\n recoveryReserveRecords: SUPERVISOR_COMMAND_LEDGER_RECOVERY_RECORDS\n};\nfunction sanitizeStoredEvent(event) {\n if ((event.kind === "turn_completed" || event.kind === "turn_failed") && typeof event.stopReason === "string") {\n return { ...event, stopReason: sanitizeSupervisorReason(event.stopReason) };\n }\n if ((event.kind === "turn_stopped" || event.kind === "interrupted" || event.kind === "supervisor_stopping") && typeof event.reason === "string") {\n return { ...event, reason: sanitizeSupervisorReason(event.reason) };\n }\n return event;\n}\nfunction createSupervisorCommandIdentity(command) {\n return {\n commandId: command.commandId,\n commandSequence: command.commandSequence,\n commandKind: command.payload.kind,\n attemptId: command.attemptId,\n commandFingerprint: createSupervisorCommandFingerprint(command)\n };\n}\nfunction compareSupervisorCommandIdentity(left, right) {\n if (left.commandId !== right.commandId || left.commandSequence !== right.commandSequence || left.commandKind !== right.commandKind || left.attemptId !== right.attemptId) {\n return "mismatch";\n }\n if (left.commandFingerprint === void 0 || right.commandFingerprint === void 0) {\n return "unverifiable";\n }\n return left.commandFingerprint === right.commandFingerprint ? "match" : "mismatch";\n}\nvar DEFAULT_METADATA = {\n nextEventSequence: 1,\n lastAcknowledgedEventSequence: 0,\n lastAppliedCommandSequence: 0\n};\nvar StoreMutationConflictError = class extends Error {\n name = "StoreMutationConflictError";\n};\nfunction isRecord6(value) {\n return typeof value === "object" && value !== null && !Array.isArray(value);\n}\nfunction isNonNegativeInteger2(value) {\n return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;\n}\nfunction isPositiveInteger3(value) {\n return typeof value === "number" && Number.isSafeInteger(value) && value > 0;\n}\nfunction isStoredCommandId(value) {\n return isBoundedUtf8Identifier(value, SUPERVISOR_MAX_COMMAND_ID_LENGTH);\n}\nfunction isCanonicalTimestamp(value) {\n return typeof value === "string" && Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;\n}\nfunction parseStoredEvent(value) {\n if (isRecord6(value) && isRecord6(value.event)) {\n const sanitizedEvent = sanitizeStoredEvent(value.event);\n if (sanitizedEvent !== value.event) value = { ...value, event: sanitizedEvent };\n }\n if (!isRecord6(value) || value.type !== "event" || value.protocolVersion !== SUPERVISOR_PROTOCOL_VERSION || value.runtimeVersion !== LEGACY_SUPERVISOR_RUNTIME_VERSION && value.runtimeVersion !== SUPERVISOR_RUNTIME_VERSION || typeof value.sessionId !== "string" || value.sessionId.length === 0 || typeof value.runId !== "string" || value.runId.length === 0 || typeof value.attemptId !== "string" || value.attemptId.length === 0 || typeof value.eventId !== "string" || value.eventId.length === 0 || !isPositiveInteger3(value.attemptSequence) || !isCanonicalTimestamp(value.occurredAt) || value.durability !== "durable" && value.durability !== "coalesced" || !isSupervisorEvent(value.event)) {\n return null;\n }\n const frame = {\n ...value,\n runtimeVersion: SUPERVISOR_RUNTIME_VERSION\n };\n if (serializedFrameBytes(frame) >= SUPERVISOR_MAX_FRAME_BYTES) return null;\n return frame;\n}\nfunction parseStoredCommand(value) {\n if (!isRecord6(value) || !isStoredCommandId(value.commandId) || !isPositiveInteger3(value.commandSequence) || value.commandKind !== "prompt" && value.commandKind !== "steer" && value.commandKind !== "stop" || typeof value.attemptId !== "string" || value.attemptId.length === 0 || value.status !== "received" && value.status !== "applied" && value.status !== "failed" || !isCanonicalTimestamp(value.recordedAt) || value.commandFingerprint !== void 0 && !isSupervisorCommandFingerprint(value.commandFingerprint)) {\n return null;\n }\n return value;\n}\nfunction parseActiveTurn(value) {\n if (!isRecord6(value) || !isStoredCommandId(value.commandId) || typeof value.attemptId !== "string" || value.attemptId.length === 0 || typeof value.startedAt !== "string" || !isCanonicalTimestamp(value.startedAt) || value.stop !== void 0 && (!isRecord6(value.stop) || !isStoredCommandId(value.stop.commandId) || value.stop.reason !== void 0 && typeof value.stop.reason !== "string")) {\n return null;\n }\n return {\n commandId: value.commandId,\n attemptId: value.attemptId,\n startedAt: value.startedAt,\n ...value.stop === void 0 ? {} : {\n stop: {\n commandId: value.stop.commandId,\n ...value.stop.reason === void 0 ? {} : {\n reason: sanitizeSupervisorReason(value.stop.reason)\n }\n }\n }\n };\n}\nfunction parseOutboxCheckpoint(value) {\n if (!isRecord6(value) || value.recordType !== "outbox_checkpoint" || value.diskFormatVersion !== STORE_DISK_FORMAT_VERSION || typeof value.sessionId !== "string" || typeof value.runId !== "string" || typeof value.attemptId !== "string" || !isNonNegativeInteger2(value.acknowledgedEventSequence) || !isPositiveInteger3(value.nextEventSequence) || value.acknowledgedEventSequence >= value.nextEventSequence) {\n return null;\n }\n const recoveryFacts = value.recoveryFacts === void 0 ? void 0 : parseStoredRecoveryFacts(value.recoveryFacts, {\n allowMissingCommandApplications: true\n });\n if (recoveryFacts === null) return null;\n return {\n recordType: "outbox_checkpoint",\n diskFormatVersion: STORE_DISK_FORMAT_VERSION,\n sessionId: value.sessionId,\n runId: value.runId,\n attemptId: value.attemptId,\n acknowledgedEventSequence: value.acknowledgedEventSequence,\n nextEventSequence: value.nextEventSequence,\n ...recoveryFacts === void 0 ? {} : {\n recoveryFacts\n }\n };\n}\nfunction parseCommandOutcomeFact(value) {\n if (!isRecord6(value) || !isStoredCommandId(value.commandId) || !isPositiveInteger3(value.commandSequence) || !isPositiveInteger3(value.eventSequence)) {\n return null;\n }\n return value;\n}\nfunction parseTurnTerminalFact(value) {\n if (!isRecord6(value) || !isStoredCommandId(value.commandId) || !isPositiveInteger3(value.eventSequence) || value.kind !== "turn_completed" && value.kind !== "turn_failed" && value.kind !== "turn_stopped" || value.stopReason !== void 0 && typeof value.stopReason !== "string") {\n return null;\n }\n return {\n commandId: value.commandId,\n eventSequence: value.eventSequence,\n kind: value.kind,\n ...value.stopReason === void 0 ? {} : { stopReason: sanitizeSupervisorReason(value.stopReason) }\n };\n}\nfunction parseStoredRecoveryFacts(value, {\n allowMissingCommandApplications\n}) {\n if (!isRecord6(value)) return null;\n const commandApplicationCandidates = value.commandApplications === void 0 && allowMissingCommandApplications ? [] : value.commandApplications;\n if (!Array.isArray(commandApplicationCandidates) || !Array.isArray(value.commandFailures) || !Array.isArray(value.turnTerminals)) {\n return null;\n }\n const recoveryFacts = {\n commandApplications: [],\n commandFailures: [],\n turnTerminals: []\n };\n for (const candidate of commandApplicationCandidates) {\n const fact = parseCommandOutcomeFact(candidate);\n if (!fact) return null;\n recoveryFacts.commandApplications.push(fact);\n }\n for (const candidate of value.commandFailures) {\n const fact = parseCommandOutcomeFact(candidate);\n if (!fact) return null;\n recoveryFacts.commandFailures.push(fact);\n }\n for (const candidate of value.turnTerminals) {\n const fact = parseTurnTerminalFact(candidate);\n if (!fact) return null;\n recoveryFacts.turnTerminals.push(fact);\n }\n return recoveryFacts;\n}\nfunction sameCommandOutcomeFact(left, right) {\n return left.commandId === right.commandId && left.commandSequence === right.commandSequence && left.eventSequence === right.eventSequence;\n}\nfunction sameTurnTerminalFact(left, right) {\n return left.commandId === right.commandId && left.eventSequence === right.eventSequence && left.kind === right.kind && left.stopReason === right.stopReason;\n}\nfunction commandOutcomeFactKey(fact) {\n return JSON.stringify([fact.commandId, fact.commandSequence, fact.eventSequence]);\n}\nfunction turnTerminalFactKey(fact) {\n return JSON.stringify([\n fact.commandId,\n fact.eventSequence,\n fact.kind,\n fact.stopReason ?? null\n ]);\n}\nfunction parseAppendOnlyJsonLines(raw, name) {\n const values = [];\n const lines = raw.split("\\n");\n const finalLineMayBePartial = !raw.endsWith("\\n");\n for (let index = 0; index < lines.length; index += 1) {\n const line = lines[index];\n if (!line) continue;\n try {\n values.push(JSON.parse(line));\n } catch {\n if (finalLineMayBePartial && index === lines.length - 1) continue;\n throw new Error(`${name} contains malformed JSON before its crash-safe suffix.`);\n }\n }\n return values;\n}\nasync function readTextIfPresent(directory, name, maximumBytes, capacityName) {\n try {\n return await readBoundedRegularTextFileAt(directory, name, maximumBytes, capacityName);\n } catch (error) {\n if (error.code === "ENOENT") return null;\n throw error;\n }\n}\nasync function appendDurably(directory, name, value) {\n const handle = await openRegularFileAt(\n directory,\n name,\n fsConstants3.O_WRONLY | fsConstants3.O_APPEND | fsConstants3.O_CREAT,\n "Supervisor append-only journal",\n 384\n );\n try {\n await assertMutableJournalHandle(handle);\n await handle.writeFile(`${JSON.stringify(value)}\n`, "utf8");\n await handle.sync();\n } finally {\n await handle.close();\n }\n await syncDescriptorBoundDirectory(directory);\n}\nasync function repairPartialJsonLine(directory, name, raw) {\n if (!raw || raw.endsWith("\\n")) return;\n const finalLineStart = raw.lastIndexOf("\\n") + 1;\n const finalLineStartBytes = Buffer.byteLength(raw.slice(0, finalLineStart), "utf8");\n const finalLine = raw.slice(finalLineStart);\n let finalLineIsValid = false;\n try {\n JSON.parse(finalLine);\n finalLineIsValid = true;\n } catch {\n }\n const handle = await openRegularFileAt(\n directory,\n name,\n finalLineIsValid ? fsConstants3.O_WRONLY | fsConstants3.O_APPEND : fsConstants3.O_RDWR,\n "Supervisor append-only journal"\n );\n try {\n await assertMutableJournalHandle(handle);\n if (finalLineIsValid) await handle.writeFile("\\n", "utf8");\n else await handle.truncate(finalLineStartBytes);\n await handle.sync();\n } finally {\n await handle.close();\n }\n}\nasync function assertMutableJournalHandle(handle) {\n const processUid = typeof process.getuid === "function" ? BigInt(process.getuid()) : null;\n const stats = await handle.stat({ bigint: true });\n if (!stats.isFile() || processUid === null || stats.uid !== processUid || stats.nlink !== 1n) {\n throw new Error(\n "Supervisor append-only journal must be a process-owned single-link regular file."\n );\n }\n}\nasync function writeTextAtomically(directory, name, value) {\n const temporaryName = `${name}.${process.pid}.${randomUUID4()}.tmp`;\n let renamed = false;\n try {\n const handle = await openRegularFileAt(\n directory,\n temporaryName,\n fsConstants3.O_WRONLY | fsConstants3.O_CREAT | fsConstants3.O_EXCL,\n "Supervisor atomic-write temporary file",\n 384\n );\n try {\n await handle.writeFile(value, "utf8");\n await handle.sync();\n } finally {\n await handle.close();\n }\n await renameDescriptorBoundEntry(directory, temporaryName, directory, name);\n renamed = true;\n await syncDescriptorBoundDirectory(directory);\n } finally {\n if (!renamed) {\n await unlinkDescriptorBoundEntry(directory, temporaryName).catch(() => void 0);\n }\n }\n}\nasync function writeJsonAtomically(directory, name, value, maximumBytes, capacityName) {\n const serialized = `${JSON.stringify(value)}\n`;\n if (Buffer.byteLength(serialized, "utf8") > maximumBytes) {\n throw new Error(`${capacityName} exceeds its bounded on-disk capacity.`);\n }\n await writeTextAtomically(directory, name, serialized);\n}\nasync function unlinkDurably(directory, name) {\n const removed = await unlinkDescriptorBoundEntryIfPresent(directory, name);\n if (removed) await syncDescriptorBoundDirectory(directory);\n return removed;\n}\nfunction serializedFrameBytes(frame) {\n return Buffer.byteLength(`${JSON.stringify(frame)}\n`, "utf8");\n}\nfunction serializedRecordBytes(record) {\n return Buffer.byteLength(`${JSON.stringify(record)}\n`, "utf8");\n}\nfunction usesRecoveryOutboxReserve(event) {\n return event.kind === "supervisor_started" || event.kind === "command_applied" || event.kind === "command_failed" || event.kind === "turn_completed" || event.kind === "turn_failed" || event.kind === "turn_stopped" || event.kind === "interrupted" || event.kind === "supervisor_stopping";\n}\nfunction cloneActiveTurn(activeTurn) {\n if (!activeTurn) return null;\n return {\n ...activeTurn,\n ...activeTurn.stop === void 0 ? {} : { stop: { ...activeTurn.stop } }\n };\n}\nvar DiskSupervisorStore = class {\n constructor(config, outboxCapacity = DEFAULT_OUTBOX_CAPACITY, commandLedgerCapacity = DEFAULT_COMMAND_LEDGER_CAPACITY) {\n this.config = config;\n this.outboxCapacity = outboxCapacity;\n this.commandLedgerCapacity = commandLedgerCapacity;\n this.attemptDir = supervisorAttemptDataDirectory(config);\n }\n config;\n outboxCapacity;\n commandLedgerCapacity;\n attemptDir;\n attemptDirectoryIdentity = null;\n currentAttemptDirectory = null;\n metadata = { ...DEFAULT_METADATA };\n /** Contains only frames above the durable acknowledgement cursor. */\n events = [];\n commandsById = /* @__PURE__ */ new Map();\n commandIdsBySequence = /* @__PURE__ */ new Map();\n commandApplicationFacts = /* @__PURE__ */ new Map();\n commandFailureFacts = /* @__PURE__ */ new Map();\n turnTerminalFacts = /* @__PURE__ */ new Map();\n activeTurn = null;\n reclaimedEventCount = 0;\n reclaimedEventBytes = 0;\n requiresOutboxMigration = false;\n unacknowledgedEventBytes = 0;\n commandLedgerBytes = 0;\n commandLedgerRecords = 0;\n initialized = false;\n mutationFailure = null;\n mutationTail = Promise.resolve();\n async initialize() {\n await this.mutate(async () => {\n if (this.initialized) return;\n const attemptDirectory = this.requireCurrentAttemptDirectory();\n if (attemptDirectory.displayPath !== this.attemptDir) {\n throw new Error("Supervisor attempt storage resolved to an unexpected directory.");\n }\n const metadataRaw = await readTextIfPresent(\n attemptDirectory,\n METADATA_FILE,\n SUPERVISOR_MAX_STORE_METADATA_BYTES,\n "Supervisor metadata"\n );\n const metadataRecoveryFacts = this.loadMetadata(metadataRaw);\n const commandRaw = await readTextIfPresent(\n attemptDirectory,\n COMMAND_LEDGER_FILE,\n this.commandLedgerCapacity.maximumBytes + this.commandLedgerCapacity.recoveryReserveBytes,\n "Supervisor command ledger"\n );\n if (commandRaw) {\n this.loadCommandLedger(commandRaw);\n await repairPartialJsonLine(attemptDirectory, COMMAND_LEDGER_FILE, commandRaw);\n const ledgerHandle = await openRegularFileAt(\n attemptDirectory,\n COMMAND_LEDGER_FILE,\n fsConstants3.O_RDONLY,\n "Supervisor command ledger"\n );\n try {\n this.commandLedgerBytes = (await ledgerHandle.stat()).size;\n } finally {\n await ledgerHandle.close();\n }\n }\n const activeTurnRaw = await readTextIfPresent(\n attemptDirectory,\n ACTIVE_TURN_FILE,\n SUPERVISOR_MAX_ACTIVE_TURN_BYTES,\n "Supervisor active-turn marker"\n );\n if (activeTurnRaw !== null) {\n let activeTurn;\n try {\n activeTurn = parseActiveTurn(JSON.parse(activeTurnRaw));\n } catch {\n activeTurn = null;\n }\n if (!activeTurn || activeTurn.attemptId !== this.config.attemptId) {\n throw new Error(\n "Supervisor active-turn marker is malformed or belongs to another attempt."\n );\n }\n this.activeTurn = activeTurn;\n }\n const maximumJournalBytes = this.outboxCapacity.maximumBytes + this.outboxCapacity.recoveryReserveBytes + OUTBOX_COMPACTION_MIN_RECLAIMED_BYTES + SUPERVISOR_MAX_FRAME_BYTES;\n const outboxRaw = await readTextIfPresent(\n attemptDirectory,\n OUTBOX_FILE,\n maximumJournalBytes,\n "Supervisor outbox"\n );\n let loadedOutbox = { checkpoint: null, allEvents: [] };\n if (outboxRaw) {\n loadedOutbox = this.loadOutbox(outboxRaw);\n await repairPartialJsonLine(attemptDirectory, OUTBOX_FILE, outboxRaw);\n } else if (this.metadata.lastAcknowledgedEventSequence > 0 || this.metadata.nextEventSequence > 1) {\n throw new Error("Supervisor metadata references event history but its outbox is missing.");\n }\n this.rebuildAndBoundRecoveryFacts(metadataRecoveryFacts, loadedOutbox);\n this.initialized = true;\n await this.persistMetadata();\n await this.maybeCompactOutbox();\n }, true);\n }\n get lastAcknowledgedEventSequence() {\n return this.metadata.lastAcknowledgedEventSequence;\n }\n get lastAppliedCommandSequence() {\n return this.metadata.lastAppliedCommandSequence;\n }\n get lastEventSequence() {\n return this.metadata.nextEventSequence - 1;\n }\n get outboxDepth() {\n return this.events.length;\n }\n async appendEvent(event, durability = "durable") {\n return this.mutate(async () => {\n this.requireInitialized();\n const attemptSequence = this.metadata.nextEventSequence;\n const boundedEvent = sanitizeStoredEvent(event);\n const frame = {\n type: "event",\n protocolVersion: SUPERVISOR_PROTOCOL_VERSION,\n runtimeVersion: SUPERVISOR_RUNTIME_VERSION,\n sessionId: this.config.sessionId,\n runId: this.config.runId,\n attemptId: this.config.attemptId,\n eventId: createSupervisorEventId(this.config.attemptId, attemptSequence),\n attemptSequence,\n occurredAt: (/* @__PURE__ */ new Date()).toISOString(),\n durability,\n event: boundedEvent\n };\n const frameBytes = serializedFrameBytes(frame);\n if (frameBytes >= SUPERVISOR_MAX_FRAME_BYTES) {\n throw new Error(\n `Supervisor event frame exceeds the ${SUPERVISOR_MAX_FRAME_BYTES}-byte transport limit.`\n );\n }\n const usesReserve = usesRecoveryOutboxReserve(boundedEvent);\n const maximumEvents = this.outboxCapacity.maximumEvents + (usesReserve ? this.outboxCapacity.recoveryReserveEvents : 0);\n const maximumBytes = this.outboxCapacity.maximumBytes + (usesReserve ? this.outboxCapacity.recoveryReserveBytes : 0);\n if (this.events.length + 1 > maximumEvents || this.unacknowledgedEventBytes + frameBytes > maximumBytes) {\n throw new Error(\n "Supervisor unacknowledged outbox exceeded bounded capacity; gateway acknowledgement is required."\n );\n }\n await appendDurably(this.requireCurrentAttemptDirectory(), OUTBOX_FILE, frame);\n this.events.push(frame);\n this.unacknowledgedEventBytes += frameBytes;\n this.metadata.nextEventSequence += 1;\n this.noteRecoveryFact(frame);\n await this.persistMetadata();\n return frame;\n });\n }\n listEventsAfter(sequence, limit = Number.POSITIVE_INFINITY) {\n return this.events.filter((event) => event.attemptSequence > sequence).slice(0, Number.isFinite(limit) ? limit : void 0);\n }\n async acknowledgeEvents(sequence) {\n await this.mutate(async () => {\n this.requireInitialized();\n if (!isNonNegativeInteger2(sequence)) {\n throw new StoreMutationConflictError(\n "Event acknowledgement must be a nonnegative integer."\n );\n }\n const boundedSequence = Math.min(sequence, this.lastEventSequence);\n if (boundedSequence <= this.metadata.lastAcknowledgedEventSequence) return;\n const acknowledgedMetadata = {\n ...this.metadata,\n lastAcknowledgedEventSequence: boundedSequence\n };\n await this.persistMetadata(acknowledgedMetadata);\n this.metadata = acknowledgedMetadata;\n const retained = [];\n for (const frame of this.events) {\n if (frame.attemptSequence <= boundedSequence) {\n this.reclaimedEventCount += 1;\n const frameBytes = serializedFrameBytes(frame);\n this.reclaimedEventBytes += frameBytes;\n this.unacknowledgedEventBytes -= frameBytes;\n } else {\n retained.push(frame);\n }\n }\n this.events = retained;\n await this.maybeCompactOutbox();\n });\n }\n getCommand(commandId) {\n return this.commandsById.get(commandId);\n }\n getUnfinishedCommands() {\n return [...this.commandsById.values()].filter((command) => command.status === "received");\n }\n hasCommandFailureEvent(commandId) {\n return this.commandFailureFacts.has(commandId);\n }\n hasCommandApplicationEvent(commandId) {\n return this.commandApplicationFacts.has(commandId);\n }\n hasRecoveryTurnFailureEvent(commandId, stopReason) {\n const fact = this.turnTerminalFacts.get(commandId);\n return fact?.kind === "turn_failed" && fact.stopReason === stopReason;\n }\n hasTurnTerminalEvent(commandId) {\n return this.turnTerminalFacts.has(commandId);\n }\n async readActiveTurn() {\n await this.mutationTail;\n if (this.mutationFailure) throw this.mutationFailure;\n return cloneActiveTurn(this.activeTurn);\n }\n async recordActiveTurn(commandId) {\n await this.mutate(async () => {\n this.requireInitialized();\n if (this.activeTurn && this.activeTurn.commandId !== commandId) {\n throw new StoreMutationConflictError(\n `Active turn ${this.activeTurn.commandId} must finish before starting ${commandId}.`\n );\n }\n if (this.activeTurn) return;\n const activeTurn = {\n commandId,\n attemptId: this.config.attemptId,\n startedAt: (/* @__PURE__ */ new Date()).toISOString()\n };\n await writeJsonAtomically(\n this.requireCurrentAttemptDirectory(),\n ACTIVE_TURN_FILE,\n activeTurn,\n SUPERVISOR_MAX_ACTIVE_TURN_BYTES,\n "Supervisor active-turn marker"\n );\n this.activeTurn = activeTurn;\n });\n }\n async recordActiveTurnStop(commandId, reason) {\n await this.mutate(async () => {\n this.requireInitialized();\n const boundedReason = reason === void 0 ? void 0 : sanitizeSupervisorReason(reason);\n if (!this.activeTurn) return;\n if (this.activeTurn.stop) {\n if (this.activeTurn.stop.commandId === commandId && this.activeTurn.stop.reason === boundedReason) {\n return;\n }\n throw new StoreMutationConflictError(\n `Active turn stop is already owned by command ${this.activeTurn.stop.commandId}.`\n );\n }\n const activeTurn = {\n ...this.activeTurn,\n stop: {\n commandId,\n ...boundedReason === void 0 ? {} : { reason: boundedReason }\n }\n };\n await writeJsonAtomically(\n this.requireCurrentAttemptDirectory(),\n ACTIVE_TURN_FILE,\n activeTurn,\n SUPERVISOR_MAX_ACTIVE_TURN_BYTES,\n "Supervisor active-turn marker"\n );\n this.activeTurn = activeTurn;\n });\n }\n async clearActiveTurn(expectedCommandId) {\n await this.mutate(async () => {\n this.requireInitialized();\n if (expectedCommandId !== void 0 && this.activeTurn !== null && this.activeTurn.commandId !== expectedCommandId) {\n return;\n }\n const commandId = expectedCommandId ?? this.activeTurn?.commandId;\n await unlinkDurably(this.requireCurrentAttemptDirectory(), ACTIVE_TURN_FILE);\n this.activeTurn = null;\n if (commandId && this.turnTerminalFacts.delete(commandId)) await this.persistMetadata();\n });\n }\n async recordCommandReceived(command) {\n return this.mutate(async () => {\n this.requireInitialized();\n const { commandIdentity, existing } = this.validateCommandReplay(command);\n if (existing) return existing;\n const record = {\n ...commandIdentity,\n status: "received",\n recordedAt: (/* @__PURE__ */ new Date()).toISOString()\n };\n this.assertCommandLedgerCapacity(record, false, true);\n await appendDurably(this.requireCurrentAttemptDirectory(), COMMAND_LEDGER_FILE, record);\n this.commandLedgerBytes += serializedRecordBytes(record);\n this.commandLedgerRecords += 1;\n this.commandsById.set(record.commandId, record);\n this.commandIdsBySequence.set(record.commandSequence, record.commandId);\n return record;\n });\n }\n async completeCommand(command, status, error) {\n return this.mutate(async () => {\n this.requireInitialized();\n const { existing } = this.validateCommandReplay(command);\n if (!existing) {\n throw new StoreMutationConflictError(\n `Command ${command.commandId} must be durably received before completion.`\n );\n }\n return this.completeStoredCommandWithinMutation(existing, status, error);\n });\n }\n async completeStoredCommand(command, status, error) {\n return this.mutate(async () => {\n this.requireInitialized();\n const existing = this.commandsById.get(command.commandId);\n if (!existing) {\n throw new StoreMutationConflictError(`Command ${command.commandId} is not in the ledger.`);\n }\n this.assertMatchingStoredCommand(existing, command);\n return this.completeStoredCommandWithinMutation(existing, status, error);\n });\n }\n validateCommandReplay(command, options = {}) {\n this.requireInitialized();\n const commandIdentity = createSupervisorCommandIdentity(command);\n const existing = this.commandsById.get(command.commandId);\n if (existing) {\n this.assertMatchingCommandFrame(existing, commandIdentity, options.deferLegacyUnfinished);\n }\n const sequenceOwner = this.commandIdsBySequence.get(command.commandSequence);\n if (sequenceOwner && sequenceOwner !== command.commandId) {\n throw new StoreMutationConflictError(\n `Command sequence ${command.commandSequence} is already owned by ${sequenceOwner}.`\n );\n }\n return { commandIdentity, existing };\n }\n async advanceCommandCursor(sequence) {\n await this.mutate(async () => {\n this.requireInitialized();\n if (!isNonNegativeInteger2(sequence)) {\n throw new StoreMutationConflictError("Command cursor must be a nonnegative integer.");\n }\n if (sequence <= this.metadata.lastAppliedCommandSequence) return;\n const conflicting = [...this.commandsById.values()].find(\n (command) => command.status === "received" && command.commandSequence <= sequence\n );\n if (conflicting) {\n throw new StoreMutationConflictError(\n `Cannot advance the command cursor to ${sequence}; command ${conflicting.commandId} at sequence ${conflicting.commandSequence} is unfinished.`\n );\n }\n const advancedMetadata = {\n ...this.metadata,\n lastAppliedCommandSequence: sequence\n };\n await this.persistMetadata(advancedMetadata);\n this.metadata = advancedMetadata;\n });\n }\n mutate(operation, initializeStorage = false) {\n const mutation = this.mutationTail.then(async () => {\n if (this.mutationFailure) throw this.mutationFailure;\n let attemptDirectory = null;\n let operationFailed = false;\n try {\n if (initializeStorage && this.attemptDirectoryIdentity === null) {\n attemptDirectory = await openSupervisorAttemptStorage(this.config);\n this.attemptDirectoryIdentity = attemptDirectory.identity;\n } else if (this.attemptDirectoryIdentity !== null) {\n attemptDirectory = await bindDescriptorBoundDirectory(\n this.config.stateDurabilityAnchor,\n this.attemptDir,\n this.attemptDirectoryIdentity\n );\n }\n this.currentAttemptDirectory = attemptDirectory;\n return await operation();\n } catch (error) {\n operationFailed = true;\n if (!(error instanceof StoreMutationConflictError)) this.mutationFailure = error;\n throw error;\n } finally {\n this.currentAttemptDirectory = null;\n try {\n await attemptDirectory?.handle.close();\n } catch (error) {\n if (!operationFailed) {\n this.mutationFailure ??= error;\n throw error;\n }\n }\n }\n });\n this.mutationTail = mutation.then(\n () => void 0,\n () => void 0\n );\n return mutation;\n }\n requireCurrentAttemptDirectory() {\n if (this.currentAttemptDirectory === null) {\n throw new Error("Supervisor attempt storage is not descriptor-bound.");\n }\n return this.currentAttemptDirectory;\n }\n requireInitialized() {\n if (!this.initialized) {\n throw new StoreMutationConflictError("Supervisor store must be initialized before use.");\n }\n }\n loadMetadata(raw) {\n if (!raw) return null;\n let value;\n try {\n value = JSON.parse(raw);\n } catch {\n return null;\n }\n if (!isRecord6(value)) return null;\n const hasDiskFormatVersion = Object.hasOwn(value, "diskFormatVersion");\n if (hasDiskFormatVersion && value.diskFormatVersion !== STORE_DISK_FORMAT_VERSION) {\n throw new Error("Supervisor metadata uses an unsupported disk format version.");\n }\n const recoveryFacts = hasDiskFormatVersion ? parseStoredRecoveryFacts(value.recoveryFacts, {\n allowMissingCommandApplications: false\n }) : null;\n if (hasDiskFormatVersion && recoveryFacts === null) {\n throw new Error("Supervisor metadata contains invalid recovery facts.");\n }\n this.metadata = {\n nextEventSequence: isPositiveInteger3(value.nextEventSequence) ? value.nextEventSequence : DEFAULT_METADATA.nextEventSequence,\n lastAcknowledgedEventSequence: isNonNegativeInteger2(value.lastAcknowledgedEventSequence) ? value.lastAcknowledgedEventSequence : DEFAULT_METADATA.lastAcknowledgedEventSequence,\n lastAppliedCommandSequence: isNonNegativeInteger2(value.lastAppliedCommandSequence) ? value.lastAppliedCommandSequence : DEFAULT_METADATA.lastAppliedCommandSequence\n };\n if (!hasDiskFormatVersion) return null;\n return recoveryFacts;\n }\n loadCommandLedger(raw) {\n for (const value of parseAppendOnlyJsonLines(raw, "Supervisor command ledger")) {\n const command = parseStoredCommand(value);\n if (!command || command.attemptId !== this.config.attemptId) {\n throw new Error("Supervisor command ledger contains an invalid record.");\n }\n const sequenceOwner = this.commandIdsBySequence.get(command.commandSequence);\n if (sequenceOwner && sequenceOwner !== command.commandId) {\n throw new Error(\n `Supervisor command sequence ${command.commandSequence} has multiple owners.`\n );\n }\n const previous = this.commandsById.get(command.commandId);\n if (previous) {\n this.assertMatchingStoredCommand(previous, command, "disk");\n const validTransition = previous.status === "received" ? command.status !== "received" : command.status === previous.status;\n if (!validTransition) {\n throw new Error(\n `Supervisor command ${command.commandId} has an invalid on-disk status transition.`\n );\n }\n } else if (command.status !== "received") {\n throw new Error(\n `Supervisor command ${command.commandId} has an invalid on-disk status transition.`\n );\n }\n this.commandIdsBySequence.set(command.commandSequence, command.commandId);\n this.commandsById.set(command.commandId, command);\n this.commandLedgerRecords += 1;\n if (this.commandLedgerRecords > this.commandLedgerCapacity.maximumRecords + this.commandLedgerCapacity.recoveryReserveRecords) {\n throw new Error("Supervisor command ledger exceeds its bounded record capacity.");\n }\n }\n if (this.commandsById.size > this.commandLedgerCapacity.maximumDistinctCommands) {\n throw new Error("Supervisor command ledger exceeds its distinct-command capacity.");\n }\n let contiguousTerminalSequence = this.metadata.lastAppliedCommandSequence;\n while (contiguousTerminalSequence < Number.MAX_SAFE_INTEGER) {\n const commandId = this.commandIdsBySequence.get(contiguousTerminalSequence + 1);\n const command = commandId ? this.commandsById.get(commandId) : void 0;\n if (!command || command.status === "received") break;\n contiguousTerminalSequence += 1;\n }\n this.metadata.lastAppliedCommandSequence = contiguousTerminalSequence;\n }\n loadOutbox(raw) {\n let checkpoint = null;\n let journalRuntimeVersion = null;\n const allEvents = [];\n let sawEvent = false;\n let previousSequence = 0;\n for (const value of parseAppendOnlyJsonLines(raw, "Supervisor outbox")) {\n const candidateCheckpoint = parseOutboxCheckpoint(value);\n if (candidateCheckpoint) {\n if (checkpoint || sawEvent || !this.hasMatchingIdentity(candidateCheckpoint)) {\n throw new Error("Supervisor outbox contains an invalid compaction checkpoint.");\n }\n checkpoint = candidateCheckpoint;\n journalRuntimeVersion = SUPERVISOR_RUNTIME_VERSION;\n continue;\n }\n const event = parseStoredEvent(value);\n const storedRuntimeVersion = isRecord6(value) && (value.runtimeVersion === LEGACY_SUPERVISOR_RUNTIME_VERSION || value.runtimeVersion === SUPERVISOR_RUNTIME_VERSION) ? value.runtimeVersion : null;\n if (!event || storedRuntimeVersion === null || journalRuntimeVersion !== null && storedRuntimeVersion !== journalRuntimeVersion || !this.hasMatchingIdentity(event) || event.eventId !== createSupervisorEventId(this.config.attemptId, event.attemptSequence) || event.attemptSequence <= previousSequence) {\n throw new Error("Supervisor outbox contains an invalid or out-of-order event record.");\n }\n journalRuntimeVersion = storedRuntimeVersion;\n if (storedRuntimeVersion === LEGACY_SUPERVISOR_RUNTIME_VERSION) {\n this.requiresOutboxMigration = true;\n }\n if (checkpoint && event.attemptSequence <= checkpoint.acknowledgedEventSequence) {\n throw new Error("Supervisor compacted outbox retained an acknowledged event record.");\n }\n sawEvent = true;\n previousSequence = event.attemptSequence;\n allEvents.push(event);\n }\n const checkpointAcknowledgement = checkpoint?.acknowledgedEventSequence ?? 0;\n let expectedJournalSequence = checkpointAcknowledgement + 1;\n for (const event of allEvents) {\n if (event.attemptSequence !== expectedJournalSequence) {\n throw new Error(\n `Supervisor outbox is missing unacknowledged event sequence ${expectedJournalSequence}.`\n );\n }\n expectedJournalSequence += 1;\n }\n const lastJournalSequence = allEvents.at(-1)?.attemptSequence ?? 0;\n const checkpointNextSequence = checkpoint?.nextEventSequence ?? 1;\n const acknowledged = Math.max(\n this.metadata.lastAcknowledgedEventSequence,\n checkpointAcknowledgement\n );\n const nextSequence = Math.max(\n this.metadata.nextEventSequence,\n checkpointNextSequence,\n lastJournalSequence + 1,\n acknowledged + 1\n );\n if (!checkpoint && acknowledged > lastJournalSequence) {\n throw new Error("Supervisor metadata acknowledgement is beyond its legacy outbox history.");\n }\n if (checkpoint && acknowledged > checkpointAcknowledgement && acknowledged > lastJournalSequence) {\n throw new Error("Supervisor metadata acknowledgement is beyond its compacted outbox history.");\n }\n const retained = allEvents.filter((event) => event.attemptSequence > acknowledged);\n let expectedSequence = acknowledged + 1;\n for (const event of retained) {\n if (event.attemptSequence !== expectedSequence) {\n throw new Error(\n `Supervisor outbox is missing unacknowledged event sequence ${expectedSequence}.`\n );\n }\n expectedSequence += 1;\n }\n if (expectedSequence !== nextSequence) {\n throw new Error(\n `Supervisor outbox is missing unacknowledged event sequence ${expectedSequence}.`\n );\n }\n this.metadata.nextEventSequence = nextSequence;\n this.metadata.lastAcknowledgedEventSequence = acknowledged;\n this.events = retained;\n this.unacknowledgedEventBytes = retained.reduce(\n (total, event) => total + serializedFrameBytes(event),\n 0\n );\n const hardMaximumEvents = this.outboxCapacity.maximumEvents + this.outboxCapacity.recoveryReserveEvents;\n const hardMaximumBytes = this.outboxCapacity.maximumBytes + this.outboxCapacity.recoveryReserveBytes;\n if (this.events.length > hardMaximumEvents || this.unacknowledgedEventBytes > hardMaximumBytes) {\n throw new Error("Supervisor outbox exceeds its bounded unacknowledged capacity.");\n }\n const reclaimed = allEvents.filter((event) => event.attemptSequence <= acknowledged);\n this.reclaimedEventCount = reclaimed.length;\n this.reclaimedEventBytes = reclaimed.reduce(\n (total, event) => total + serializedFrameBytes(event),\n 0\n );\n return { checkpoint, allEvents };\n }\n rebuildAndBoundRecoveryFacts(metadataRecoveryFacts, loadedOutbox) {\n const { checkpoint, allEvents } = loadedOutbox;\n const eventsBySequence = new Map(\n allEvents.map((frame) => [frame.attemptSequence, frame])\n );\n const checkpointFacts = checkpoint?.recoveryFacts;\n const checkpointCommandApplicationKeys = new Set(\n checkpointFacts?.commandApplications.map(commandOutcomeFactKey)\n );\n const checkpointCommandFailureKeys = new Set(\n checkpointFacts?.commandFailures.map(commandOutcomeFactKey)\n );\n const checkpointTurnTerminalKeys = new Set(\n checkpointFacts?.turnTerminals.map(turnTerminalFactKey)\n );\n const metadataCommandApplicationKeys = new Set(\n metadataRecoveryFacts?.commandApplications.map(commandOutcomeFactKey)\n );\n const metadataCommandFailureKeys = new Set(\n metadataRecoveryFacts?.commandFailures.map(commandOutcomeFactKey)\n );\n const metadataTurnTerminalKeys = new Set(\n metadataRecoveryFacts?.turnTerminals.map(turnTerminalFactKey)\n );\n const invalidRecoveryFacts = () => {\n throw new Error(\n "Supervisor recovery facts do not match the durable ledger, cursors, and outbox history."\n );\n };\n const assertFactEvent = (eventSequence, matchesEvent, retainedByCheckpoint, retainedByMetadata) => {\n if (eventSequence >= this.metadata.nextEventSequence) invalidRecoveryFacts();\n const frame = eventsBySequence.get(eventSequence);\n if (frame) {\n if (!matchesEvent(frame)) invalidRecoveryFacts();\n return;\n }\n if (!checkpoint || eventSequence > checkpoint.acknowledgedEventSequence || !retainedByCheckpoint || metadataRecoveryFacts !== null && !retainedByMetadata) {\n invalidRecoveryFacts();\n }\n };\n const commandOutcomes = /* @__PURE__ */ new Map();\n const turnTerminals = /* @__PURE__ */ new Map();\n const factOwnersByEventSequence = /* @__PURE__ */ new Map();\n const assertUniqueEventOwner = (eventSequence, owner) => {\n const existing = factOwnersByEventSequence.get(eventSequence);\n if (existing !== void 0 && existing !== owner) invalidRecoveryFacts();\n factOwnersByEventSequence.set(eventSequence, owner);\n };\n const recordCommandOutcome = (kind, fact) => {\n const owner = `${kind}:${fact.commandId}:${fact.commandSequence}`;\n assertUniqueEventOwner(fact.eventSequence, owner);\n const existing = commandOutcomes.get(fact.commandId);\n if (existing && (existing.kind !== kind || !sameCommandOutcomeFact(existing.fact, fact))) {\n invalidRecoveryFacts();\n }\n commandOutcomes.set(fact.commandId, { kind, fact });\n };\n const acceptCommandOutcome = (kind, fact) => {\n const command = this.commandsById.get(fact.commandId);\n if (!command) return invalidRecoveryFacts();\n if (command.commandSequence !== fact.commandSequence) return invalidRecoveryFacts();\n if (command.status === "received" && command.commandSequence <= this.metadata.lastAppliedCommandSequence) {\n invalidRecoveryFacts();\n }\n if (command.status !== "received") return;\n const checkpointKeys = kind === "command_applied" ? checkpointCommandApplicationKeys : checkpointCommandFailureKeys;\n const metadataKeys = kind === "command_applied" ? metadataCommandApplicationKeys : metadataCommandFailureKeys;\n const factKey = commandOutcomeFactKey(fact);\n assertFactEvent(\n fact.eventSequence,\n (frame) => {\n const event = frame.event;\n return event.kind === kind && event.commandId === command.commandId && event.commandSequence === command.commandSequence && event.commandKind === command.commandKind;\n },\n checkpointKeys.has(factKey),\n metadataKeys.has(factKey)\n );\n recordCommandOutcome(kind, fact);\n };\n const acceptPhysicalCommandOutcome = (kind, fact, commandKind) => {\n const command = this.commandsById.get(fact.commandId);\n const matchingTerminalStatus = kind === "command_applied" ? "applied" : "failed";\n if (!command || command.commandSequence !== fact.commandSequence || command.commandKind !== commandKind || command.status !== "received" && command.status !== matchingTerminalStatus) {\n invalidRecoveryFacts();\n }\n recordCommandOutcome(kind, fact);\n };\n const acceptTurnTerminal = (fact) => {\n const command = this.commandsById.get(fact.commandId);\n if (!command) {\n if (this.activeTurn?.commandId === fact.commandId) return invalidRecoveryFacts();\n return;\n }\n if (command.commandKind !== "prompt") return invalidRecoveryFacts();\n if (command.status === "received" && command.commandSequence <= this.metadata.lastAppliedCommandSequence) {\n invalidRecoveryFacts();\n }\n const commandUnfinished = command.status === "received";\n const turnStillActive = this.activeTurn?.commandId === fact.commandId;\n if (!commandUnfinished && !turnStillActive) return;\n assertFactEvent(\n fact.eventSequence,\n (frame) => {\n const event = frame.event;\n return event.kind === fact.kind && event.commandId === command.commandId && (event.kind !== "turn_failed" || event.stopReason === fact.stopReason);\n },\n checkpointTurnTerminalKeys.has(turnTerminalFactKey(fact)),\n metadataTurnTerminalKeys.has(turnTerminalFactKey(fact))\n );\n const owner = `${fact.kind}:${fact.commandId}`;\n assertUniqueEventOwner(fact.eventSequence, owner);\n const existing = turnTerminals.get(fact.commandId);\n if (existing && !sameTurnTerminalFact(existing, fact)) invalidRecoveryFacts();\n turnTerminals.set(fact.commandId, fact);\n };\n for (const recoveryFacts of [metadataRecoveryFacts, checkpointFacts]) {\n if (!recoveryFacts) continue;\n for (const fact of recoveryFacts.commandApplications) {\n acceptCommandOutcome("command_applied", fact);\n }\n for (const fact of recoveryFacts.commandFailures) {\n acceptCommandOutcome("command_failed", fact);\n }\n for (const fact of recoveryFacts.turnTerminals) acceptTurnTerminal(fact);\n }\n for (const frame of allEvents) {\n const event = frame.event;\n if (event.kind === "command_applied" || event.kind === "command_failed") {\n acceptPhysicalCommandOutcome(\n event.kind,\n {\n commandId: event.commandId,\n commandSequence: event.commandSequence,\n eventSequence: frame.attemptSequence\n },\n event.commandKind\n );\n } else if ((event.kind === "turn_completed" || event.kind === "turn_failed" || event.kind === "turn_stopped") && event.commandId) {\n acceptTurnTerminal({\n commandId: event.commandId,\n eventSequence: frame.attemptSequence,\n kind: event.kind,\n ...event.kind === "turn_failed" && event.stopReason !== void 0 ? { stopReason: event.stopReason } : {}\n });\n }\n }\n this.commandApplicationFacts.clear();\n this.commandFailureFacts.clear();\n this.turnTerminalFacts.clear();\n for (const { kind, fact } of commandOutcomes.values()) {\n if (this.commandsById.get(fact.commandId)?.status !== "received") continue;\n if (kind === "command_applied") this.commandApplicationFacts.set(fact.commandId, fact);\n else this.commandFailureFacts.set(fact.commandId, fact);\n }\n for (const fact of turnTerminals.values()) {\n const commandUnfinished = this.commandsById.get(fact.commandId)?.status === "received";\n const turnStillActive = this.activeTurn?.commandId === fact.commandId;\n if (commandUnfinished || turnStillActive) this.turnTerminalFacts.set(fact.commandId, fact);\n }\n }\n noteRecoveryFact(frame) {\n const event = frame.event;\n if (event.kind === "command_applied" || event.kind === "command_failed") {\n const commandOutcomeFacts = event.kind === "command_applied" ? this.commandApplicationFacts : this.commandFailureFacts;\n if (this.commandsById.get(event.commandId)?.status === "received") {\n const existing = commandOutcomeFacts.get(event.commandId);\n if (!existing || frame.attemptSequence < existing.eventSequence) {\n commandOutcomeFacts.set(event.commandId, {\n commandId: event.commandId,\n commandSequence: event.commandSequence,\n eventSequence: frame.attemptSequence\n });\n }\n }\n return;\n }\n if ((event.kind === "turn_completed" || event.kind === "turn_failed" || event.kind === "turn_stopped") && event.commandId) {\n const commandUnfinished = this.commandsById.get(event.commandId)?.status === "received";\n const turnStillActive = this.activeTurn?.commandId === event.commandId;\n if (!commandUnfinished && !turnStillActive) return;\n const existing = this.turnTerminalFacts.get(event.commandId);\n if (!existing || frame.attemptSequence < existing.eventSequence) {\n this.turnTerminalFacts.set(event.commandId, {\n commandId: event.commandId,\n eventSequence: frame.attemptSequence,\n kind: event.kind,\n ...event.kind === "turn_failed" && event.stopReason !== void 0 ? { stopReason: event.stopReason } : {}\n });\n }\n }\n }\n assertMatchingCommandFrame(existing, commandIdentity, deferLegacyUnfinished = false) {\n const comparison = compareSupervisorCommandIdentity(existing, commandIdentity);\n if (comparison === "mismatch") {\n throw new StoreMutationConflictError(\n `Command ${commandIdentity.commandId} was replayed with different semantic content.`\n );\n }\n if (comparison === "unverifiable" && existing.status === "received" && !deferLegacyUnfinished) {\n throw new StoreMutationConflictError(\n `Legacy unfinished command ${commandIdentity.commandId} cannot be safely replayed.`\n );\n }\n }\n assertMatchingStoredCommand(existing, command, context = "completion") {\n const comparison = compareSupervisorCommandIdentity(existing, command);\n const mixedFingerprintPresence = existing.commandFingerprint === void 0 !== (command.commandFingerprint === void 0);\n if (comparison !== "mismatch" && !mixedFingerprintPresence) return;\n if (context === "disk") {\n throw new Error(`Supervisor command ${command.commandId} changed identity on disk.`);\n }\n throw new StoreMutationConflictError(\n `Command ${command.commandId} completion metadata does not match its receipt.`\n );\n }\n async completeStoredCommandWithinMutation(command, status, error) {\n if (command.status !== "received") {\n if (command.status === status) return command;\n throw new StoreMutationConflictError(\n `Command ${command.commandId} already has the ${command.status} outcome.`\n );\n }\n const record = {\n commandId: command.commandId,\n commandSequence: command.commandSequence,\n commandKind: command.commandKind,\n attemptId: command.attemptId,\n status,\n recordedAt: (/* @__PURE__ */ new Date()).toISOString(),\n ...command.commandFingerprint === void 0 ? {} : { commandFingerprint: command.commandFingerprint },\n ...error === void 0 ? {} : { error }\n };\n this.assertCommandLedgerCapacity(record, true, false);\n await appendDurably(this.requireCurrentAttemptDirectory(), COMMAND_LEDGER_FILE, record);\n this.commandLedgerBytes += serializedRecordBytes(record);\n this.commandLedgerRecords += 1;\n this.commandsById.set(record.commandId, record);\n this.commandIdsBySequence.set(record.commandSequence, record.commandId);\n if (record.commandSequence === this.metadata.lastAppliedCommandSequence + 1) {\n this.metadata.lastAppliedCommandSequence = record.commandSequence;\n while (true) {\n const nextId = this.commandIdsBySequence.get(this.metadata.lastAppliedCommandSequence + 1);\n const next = nextId ? this.commandsById.get(nextId) : void 0;\n if (!next || next.status === "received") break;\n this.metadata.lastAppliedCommandSequence += 1;\n }\n }\n this.commandApplicationFacts.delete(record.commandId);\n this.commandFailureFacts.delete(record.commandId);\n if (this.activeTurn?.commandId !== record.commandId) {\n this.turnTerminalFacts.delete(record.commandId);\n }\n await this.persistMetadata();\n return record;\n }\n assertCommandLedgerCapacity(record, usesRecoveryReserve, addsDistinctCommand) {\n const recordBytes = serializedRecordBytes(record);\n const maximumBytes = this.commandLedgerCapacity.maximumBytes + (usesRecoveryReserve ? this.commandLedgerCapacity.recoveryReserveBytes : 0);\n const maximumRecords = this.commandLedgerCapacity.maximumRecords + (usesRecoveryReserve ? this.commandLedgerCapacity.recoveryReserveRecords : 0);\n if (this.commandLedgerBytes + recordBytes > maximumBytes || this.commandLedgerRecords + 1 > maximumRecords || addsDistinctCommand && this.commandsById.size + 1 > this.commandLedgerCapacity.maximumDistinctCommands) {\n throw new Error("Supervisor command ledger exceeded bounded capacity.");\n }\n }\n hasMatchingIdentity(value) {\n return hasMatchingAttempt(this.config, value);\n }\n metadataForPersistence(metadata = this.metadata) {\n return {\n diskFormatVersion: STORE_DISK_FORMAT_VERSION,\n ...metadata,\n recoveryFacts: {\n commandApplications: [...this.commandApplicationFacts.values()].sort(\n (left, right) => left.eventSequence - right.eventSequence\n ),\n commandFailures: [...this.commandFailureFacts.values()].sort(\n (left, right) => left.eventSequence - right.eventSequence\n ),\n turnTerminals: [...this.turnTerminalFacts.values()].sort(\n (left, right) => left.eventSequence - right.eventSequence\n )\n }\n };\n }\n async persistMetadata(metadata = this.metadata) {\n await writeJsonAtomically(\n this.requireCurrentAttemptDirectory(),\n METADATA_FILE,\n this.metadataForPersistence(metadata),\n SUPERVISOR_MAX_STORE_METADATA_BYTES,\n "Supervisor metadata"\n );\n }\n shouldCompactOutbox() {\n if (this.requiresOutboxMigration) return true;\n if (this.metadata.lastAcknowledgedEventSequence === 0) return false;\n if (this.events.length === 0 && this.metadata.lastAcknowledgedEventSequence === this.lastEventSequence) {\n return true;\n }\n return this.reclaimedEventCount >= OUTBOX_COMPACTION_MIN_RECLAIMED_EVENTS || this.reclaimedEventBytes >= OUTBOX_COMPACTION_MIN_RECLAIMED_BYTES;\n }\n async maybeCompactOutbox() {\n if (!this.shouldCompactOutbox()) return;\n const checkpoint = {\n recordType: "outbox_checkpoint",\n diskFormatVersion: STORE_DISK_FORMAT_VERSION,\n sessionId: this.config.sessionId,\n runId: this.config.runId,\n attemptId: this.config.attemptId,\n acknowledgedEventSequence: this.metadata.lastAcknowledgedEventSequence,\n nextEventSequence: this.metadata.nextEventSequence,\n recoveryFacts: this.metadataForPersistence().recoveryFacts\n };\n const lines = [checkpoint, ...this.events].map((value) => JSON.stringify(value));\n await writeTextAtomically(\n this.requireCurrentAttemptDirectory(),\n OUTBOX_FILE,\n `${lines.join("\\n")}\n`\n );\n this.requiresOutboxMigration = false;\n this.reclaimedEventCount = 0;\n this.reclaimedEventBytes = 0;\n }\n};\n\n// src/supervisor/runtime.ts\nvar SUPERVISOR_SHUTDOWN_STOP_REASON = "supervisor_shutdown";\nfunction serializedCommandBytes(command) {\n return Buffer.byteLength(JSON.stringify(command), "utf8");\n}\nvar DEFAULT_DEPENDENCIES2 = {\n ...DEFAULT_GATEWAY_TRANSPORT_DEPENDENCIES\n};\nvar SupervisorCommandProcessor = class {\n constructor(config, store, harness, attachments, emit, executionGate, onFailure, redactor) {\n this.config = config;\n this.store = store;\n this.harness = harness;\n this.attachments = attachments;\n this.emit = emit;\n this.executionGate = executionGate;\n this.onFailure = onFailure;\n this.redactor = redactor;\n executionGate.signal.addEventListener(\n "abort",\n () => {\n this.clearPendingCommands();\n this.preparedResumeBatch = null;\n },\n { once: true }\n );\n }\n config;\n store;\n harness;\n attachments;\n emit;\n executionGate;\n onFailure;\n redactor;\n pending = /* @__PURE__ */ new Map();\n pendingByteLengths = /* @__PURE__ */ new Map();\n pendingBytes = 0;\n applying = /* @__PURE__ */ new Map();\n intakeTail = Promise.resolve();\n drainTask = null;\n nextResumeBatchToken = 1;\n preparedResumeBatch = null;\n async recoverUnfinishedCommands() {\n await this.finalizeInterruptedCommands({\n stopReason: SUPERVISOR_RECOVERY_STOP_REASON,\n message: "Supervisor restarted while Pi work was in flight; side-effect state is indeterminate."\n });\n }\n async finalizeGracefulShutdown() {\n await this.waitForQuiescence();\n await this.finalizeInterruptedCommands({\n stopReason: SUPERVISOR_SHUTDOWN_STOP_REASON,\n message: "Supervisor shut down while Pi work was in flight."\n });\n }\n async finalizeInterruptedCommands(options) {\n const unfinished = this.store.getUnfinishedCommands();\n const activeTurn = await this.store.readActiveTurn();\n const error = {\n name: "InterruptedCommandError",\n message: options.message\n };\n for (const command of unfinished) {\n const appliedByStopMarker = activeTurn?.stop?.commandId === command.commandId;\n if (appliedByStopMarker && !this.store.hasCommandApplicationEvent(command.commandId)) {\n await this.emit({\n kind: "command_applied",\n commandId: command.commandId,\n commandSequence: command.commandSequence,\n commandKind: command.commandKind\n });\n }\n if (!appliedByStopMarker && !this.store.hasCommandApplicationEvent(command.commandId) && !this.store.hasCommandFailureEvent(command.commandId)) {\n await this.emit({\n kind: "command_failed",\n commandId: command.commandId,\n commandSequence: command.commandSequence,\n commandKind: command.commandKind,\n error\n });\n }\n }\n if (activeTurn && !this.store.hasTurnTerminalEvent(activeTurn.commandId)) {\n if (activeTurn.stop) {\n await this.emit({\n kind: "turn_stopped",\n adapter: this.harness.name,\n commandId: activeTurn.commandId,\n ...activeTurn.stop.reason === void 0 ? {} : { reason: activeTurn.stop.reason }\n });\n } else {\n await this.emit({\n kind: "turn_failed",\n adapter: this.harness.name,\n commandId: activeTurn.commandId,\n stopReason: options.stopReason,\n error\n });\n }\n }\n for (const command of unfinished) {\n if (command.commandKind === "prompt" && command.commandId !== activeTurn?.commandId && !this.store.hasTurnTerminalEvent(command.commandId)) {\n await this.emit({\n kind: "turn_failed",\n adapter: this.harness.name,\n commandId: command.commandId,\n stopReason: options.stopReason,\n error\n });\n }\n if (this.store.hasCommandApplicationEvent(command.commandId) || activeTurn?.stop?.commandId === command.commandId) {\n await this.store.completeStoredCommand(command, "applied");\n } else {\n await this.store.completeStoredCommand(command, "failed", error);\n }\n }\n if (activeTurn) await this.store.clearActiveTurn(activeTurn.commandId);\n }\n async enqueue(command) {\n const intake = this.intakeTail.then(() => {\n const staged = this.snapshotPendingCommands();\n this.validateAndStage(command, staged);\n this.commitStagedCommands(staged);\n this.scheduleDrain();\n });\n this.intakeTail = intake.catch(() => void 0);\n await intake;\n }\n async prepareResumeBatch(commands, lastAppliedCommandSequence) {\n const intake = this.intakeTail.then(() => {\n this.preparedResumeBatch = null;\n const staged = {\n commands: /* @__PURE__ */ new Map(),\n byteLengths: /* @__PURE__ */ new Map(),\n totalBytes: 0\n };\n const effectiveCommandCursor = Math.max(\n lastAppliedCommandSequence,\n this.store.lastAppliedCommandSequence\n );\n try {\n for (const command of commands) {\n this.validateAndStage(command, staged, effectiveCommandCursor);\n }\n } catch (error) {\n this.scheduleDrain();\n throw error;\n }\n const token = this.nextResumeBatchToken;\n this.nextResumeBatchToken += 1;\n this.preparedResumeBatch = { token, staged };\n return token;\n });\n this.intakeTail = intake.then(() => void 0, () => void 0);\n return intake;\n }\n async commitResumeBatch(token, canCommit) {\n const intake = this.intakeTail.then(() => {\n const prepared = this.preparedResumeBatch;\n if (!prepared || prepared.token !== token || !canCommit()) return false;\n const durableCursor = this.store.lastAppliedCommandSequence;\n for (const sequence of prepared.staged.commands.keys()) {\n if (sequence > durableCursor) continue;\n const commandBytes = prepared.staged.byteLengths.get(sequence);\n if (commandBytes === void 0 || commandBytes > prepared.staged.totalBytes) {\n throw new Error("Prepared command byte accounting is inconsistent.");\n }\n prepared.staged.commands.delete(sequence);\n prepared.staged.byteLengths.delete(sequence);\n prepared.staged.totalBytes -= commandBytes;\n }\n this.preparedResumeBatch = null;\n this.commitStagedCommands(prepared.staged);\n this.scheduleDrain();\n return true;\n });\n this.intakeTail = intake.then(() => void 0, () => void 0);\n return intake;\n }\n async abortResumeBatch(token) {\n const intake = this.intakeTail.then(() => {\n if (this.preparedResumeBatch?.token !== token) return;\n this.preparedResumeBatch = null;\n this.scheduleDrain();\n });\n this.intakeTail = intake.catch(() => void 0);\n await intake;\n }\n close() {\n this.clearPendingCommands();\n this.preparedResumeBatch = null;\n }\n async waitForQuiescence() {\n while (true) {\n await this.intakeTail;\n const draining = this.drainTask;\n if (!draining) return;\n await draining.catch(() => void 0);\n if (this.drainTask === null) return;\n }\n }\n validateAndStage(command, staged, lastAppliedCommandSequence = this.store.lastAppliedCommandSequence) {\n const pendingCommands = staged.commands;\n this.executionGate.throwIfClosed();\n if (!hasMatchingAttempt(this.config, command)) {\n throw new Error("Command attempt identity does not match this supervisor.");\n }\n const commandIdentity = createSupervisorCommandIdentity(command);\n const applying = this.applying.get(command.commandId);\n if (applying) {\n if (compareSupervisorCommandIdentity(applying, commandIdentity) !== "match") {\n throw new Error(`Applying command ${command.commandId} was replayed with different metadata.`);\n }\n return;\n }\n for (const [applyingId, applyingCommand] of this.applying) {\n if (applyingCommand.commandSequence === command.commandSequence && applyingId !== command.commandId) {\n throw new Error(\n `Command sequence ${command.commandSequence} conflicts with applying command ${applyingId}.`\n );\n }\n }\n const { existing } = this.store.validateCommandReplay(command, {\n // Preserve the legacy recovery boundary: intake may stage an otherwise\n // matching v1 receipt, but the serialized record mutation still rejects\n // it before any attachment or harness side effect.\n deferLegacyUnfinished: true\n });\n if (existing?.status !== void 0 && existing.status !== "received") return;\n if (command.commandSequence <= lastAppliedCommandSequence) return;\n if (command.commandSequence - lastAppliedCommandSequence > SUPERVISOR_PENDING_COMMAND_SEQUENCE_WINDOW) {\n throw new Error(\n `Command sequence ${command.commandSequence} exceeds the pending sequence window.`\n );\n }\n const pendingAtSequence = pendingCommands.get(command.commandSequence);\n if (pendingAtSequence) {\n if (pendingAtSequence.commandId !== command.commandId) {\n throw new Error(\n `Pending command sequence ${command.commandSequence} conflicts with command ${pendingAtSequence.commandId}.`\n );\n }\n if (compareSupervisorCommandIdentity(\n createSupervisorCommandIdentity(pendingAtSequence),\n commandIdentity\n ) !== "match") {\n throw new Error(\n `Pending command ${command.commandId} was replayed with different metadata.`\n );\n }\n }\n for (const pending of pendingCommands.values()) {\n if (pending.commandId === command.commandId && compareSupervisorCommandIdentity(createSupervisorCommandIdentity(pending), commandIdentity) !== "match") {\n throw new Error(`Pending command ${command.commandId} was replayed with different metadata.`);\n }\n }\n const nextCount = pendingCommands.size + (pendingAtSequence ? 0 : 1);\n if (nextCount > SUPERVISOR_MAX_PENDING_COMMANDS) {\n throw new Error(\n `Pending command count exceeds the ${SUPERVISOR_MAX_PENDING_COMMANDS}-command limit.`\n );\n }\n const commandBytes = serializedCommandBytes(command);\n const previousBytes = pendingAtSequence ? staged.byteLengths.get(command.commandSequence) ?? serializedCommandBytes(pendingAtSequence) : 0;\n const nextBytes = staged.totalBytes - previousBytes + commandBytes;\n if (nextBytes > SUPERVISOR_MAX_PENDING_COMMAND_BYTES) {\n throw new Error(\n `Pending commands exceed the ${SUPERVISOR_MAX_PENDING_COMMAND_BYTES}-byte limit.`\n );\n }\n pendingCommands.set(command.commandSequence, command);\n staged.byteLengths.set(command.commandSequence, commandBytes);\n staged.totalBytes = nextBytes;\n }\n snapshotPendingCommands() {\n return {\n commands: new Map(this.pending),\n byteLengths: new Map(this.pendingByteLengths),\n totalBytes: this.pendingBytes\n };\n }\n commitStagedCommands(staged) {\n this.clearPendingCommands();\n for (const [sequence, command] of staged.commands) this.pending.set(sequence, command);\n for (const [sequence, byteLength] of staged.byteLengths) {\n this.pendingByteLengths.set(sequence, byteLength);\n }\n this.pendingBytes = staged.totalBytes;\n }\n clearPendingCommands() {\n this.pending.clear();\n this.pendingByteLengths.clear();\n this.pendingBytes = 0;\n }\n scheduleDrain() {\n if (this.drainTask || this.preparedResumeBatch || this.executionGate.isClosed) return;\n const draining = this.drain();\n this.drainTask = draining;\n void draining.catch((error) => {\n const closure = this.executionGate.closure;\n if (closure?.kind === "shutdown" || closure?.kind === "superseded") return;\n this.onFailure(errorFromUnknown(error));\n }).finally(() => {\n if (this.drainTask === draining) this.drainTask = null;\n if (!this.executionGate.isClosed && this.pending.has(this.store.lastAppliedCommandSequence + 1)) {\n this.scheduleDrain();\n }\n });\n }\n async drain() {\n while (true) {\n this.executionGate.throwIfClosed();\n if (this.preparedResumeBatch) return;\n const sequence = this.store.lastAppliedCommandSequence + 1;\n const command = this.pending.get(sequence);\n if (!command) return;\n const commandBytes = this.pendingByteLengths.get(sequence);\n if (commandBytes === void 0 || commandBytes > this.pendingBytes) {\n throw new Error("Pending command byte accounting is inconsistent.");\n }\n this.pending.delete(sequence);\n this.pendingByteLengths.delete(sequence);\n this.pendingBytes -= commandBytes;\n await this.apply(command);\n }\n }\n async apply(command) {\n if (this.applying.has(command.commandId)) return;\n this.applying.set(command.commandId, createSupervisorCommandIdentity(command));\n const existing = await this.store.recordCommandReceived(command);\n let stopClaimed = false;\n let stopFailure = null;\n try {\n if (existing.status !== "received") return;\n await this.emit({\n kind: "command_received",\n commandId: command.commandId,\n commandSequence: command.commandSequence,\n commandKind: command.payload.kind\n });\n this.executionGate.throwIfClosed();\n if (command.payload.kind === "prompt") {\n const attachments = await this.attachments.materialize(\n command.commandId,\n command.payload.attachments,\n this.executionGate.signal\n );\n this.executionGate.throwIfClosed();\n await this.store.recordActiveTurn(command.commandId);\n this.executionGate.throwIfClosed();\n this.executionGate.throwIfClosed();\n await this.harness.prompt({\n commandId: command.commandId,\n message: command.payload.message,\n attachments\n });\n } else if (command.payload.kind === "steer") {\n const attachments = await this.attachments.materialize(\n command.commandId,\n command.payload.attachments,\n this.executionGate.signal\n );\n this.executionGate.throwIfClosed();\n await this.harness.steer({\n commandId: command.commandId,\n message: command.payload.message,\n attachments\n });\n } else {\n const stopReason = command.payload.reason === void 0 ? void 0 : this.redactor.redact(command.payload.reason);\n stopClaimed = this.harness.claimStop();\n if (stopClaimed) {\n await this.store.recordActiveTurnStop(command.commandId, stopReason);\n try {\n this.executionGate.throwIfClosed();\n await this.harness.abortClaimedStop(stopReason, command.commandId);\n } catch (error) {\n stopFailure = errorFromUnknown(error);\n }\n }\n }\n await this.emit({\n kind: "command_applied",\n commandId: command.commandId,\n commandSequence: command.commandSequence,\n commandKind: command.payload.kind\n });\n await this.store.completeCommand(command, "applied");\n if (command.payload.kind === "prompt" || stopClaimed) {\n this.harness.confirmCommandApplied(command.commandId);\n }\n if (stopFailure) {\n const closure = this.executionGate.closure;\n if (closure?.kind !== "shutdown" && closure?.kind !== "superseded") {\n this.onFailure(stopFailure);\n }\n return;\n }\n } catch (error) {\n const closure = this.executionGate.closure;\n if (closure?.kind === "shutdown" || closure?.kind === "superseded") return;\n if (closure?.kind === "persistence_failed") throw closure.error;\n if (this.store.hasCommandApplicationEvent(command.commandId)) throw error;\n const serialized = this.redactor.serialize(error);\n await this.emit({\n kind: "command_failed",\n commandId: command.commandId,\n commandSequence: command.commandSequence,\n commandKind: command.payload.kind,\n error: serialized\n });\n if (command.payload.kind === "prompt" && !this.store.hasTurnTerminalEvent(command.commandId)) {\n await this.emit({\n kind: "turn_failed",\n adapter: this.harness.name,\n commandId: command.commandId,\n stopReason: "prompt_not_accepted",\n error: serialized\n });\n }\n await this.store.completeCommand(command, "failed", serialized);\n if (command.payload.kind === "prompt") {\n await this.store.clearActiveTurn(command.commandId);\n }\n if (closure) this.onFailure(closure.error);\n } finally {\n this.applying.delete(command.commandId);\n }\n }\n};\nvar SupervisorRuntime = class {\n constructor(config, dependencies = DEFAULT_DEPENDENCIES2, handoffEnvironment = {}) {\n this.config = config;\n this.redactor = new SensitiveValueRedactor(Object.values(handoffEnvironment));\n this.completion = new Promise((resolveCompletion, rejectCompletion) => {\n this.resolveCompletion = resolveCompletion;\n this.rejectCompletion = rejectCompletion;\n });\n void this.completion.catch(() => void 0);\n this.store = new DiskSupervisorStore(config);\n this.harness = new PiSdkHarnessAdapter(config, this.executionGate, this.redactor);\n this.attachments = new SupervisorAttachmentMaterializer(config, {\n ...dependencies.fetch === void 0 ? {} : { fetch: dependencies.fetch }\n });\n this.commands = new SupervisorCommandProcessor(\n config,\n this.store,\n this.harness,\n this.attachments,\n (event, durability) => this.emitEvent(event, durability),\n this.executionGate,\n (error) => this.failRuntime(error),\n this.redactor\n );\n this.transport = new SupervisorGatewayTransport(\n config,\n this.store,\n this.harness,\n this.commands,\n this.executionGate,\n this.redactor,\n {\n getCredential: () => this.credential,\n emitEvent: (event, durability) => this.emitEvent(event, durability),\n acceptSupersession: (reason) => this.acceptSupersession(reason),\n failRuntime: (error) => this.failRuntime(error),\n failTransport: (error) => this.failTransport(error)\n },\n dependencies\n );\n this.executionGate.signal.addEventListener(\n "abort",\n () => this.handleExecutionClosure(),\n { once: true }\n );\n }\n config;\n executionGate = new SupervisorExecutionGate();\n redactor;\n store;\n harness;\n attachments;\n commands;\n transport;\n completion;\n resolveCompletion;\n rejectCompletion;\n credential = null;\n stopped = false;\n superseded = false;\n stopPromise = null;\n fatalError = null;\n completionSettled = false;\n async start() {\n const credential = process.env[this.config.credentialEnv];\n if (!isSupervisorAttemptCredential(credential)) {\n throw new Error(\n `Supervisor credential ${this.config.credentialEnv} must be the canonical unpadded base64url encoding of ${SUPERVISOR_CREDENTIAL_BYTE_LENGTH} cryptographically random bytes (${SUPERVISOR_CREDENTIAL_ENCODED_LENGTH} characters).`\n );\n }\n this.credential = credential;\n this.redactor.capture(credential);\n delete process.env[this.config.credentialEnv];\n try {\n await this.store.initialize();\n await this.commands.recoverUnfinishedCommands();\n this.harness.subscribe(async (event) => {\n try {\n if (event.type === "started") {\n await this.emitEvent({\n kind: "harness_started",\n adapter: this.harness.name,\n pid: event.pid\n });\n } else if (event.type === "event") {\n await this.emitEvent(\n { kind: "harness_event", adapter: this.harness.name, payload: event.payload },\n isCoalescedPiEvent(event.payload) ? "coalesced" : "durable"\n );\n } else if (event.type === "lifecycle") {\n await this.emitEvent({\n ...event.event,\n adapter: this.harness.name\n });\n if ((event.event.kind === "turn_completed" || event.event.kind === "turn_failed" || event.event.kind === "turn_stopped") && event.event.commandId) {\n await this.store.clearActiveTurn(event.event.commandId);\n }\n } else if (event.type === "stderr") {\n await this.emitEvent({\n kind: "harness_stderr",\n adapter: this.harness.name,\n data: this.redactor.redact(event.data)\n });\n } else {\n await this.emitEvent({\n kind: "harness_exited",\n adapter: this.harness.name,\n exitCode: event.result.exitCode,\n signal: event.result.signal\n });\n }\n } catch (error) {\n const failure = errorFromUnknown(error);\n this.failRuntime(failure);\n throw failure;\n }\n });\n await this.emitEvent({\n kind: "supervisor_started",\n recovered: this.store.lastEventSequence > 0\n });\n this.transport.start();\n } catch (error) {\n const failure = errorFromUnknown(error);\n this.executionGate.close("startup_failed", "Supervisor startup failed.", failure);\n await this.attachments.close().catch(() => void 0);\n this.credential = null;\n throw failure;\n }\n }\n waitUntilStopped() {\n return this.completion;\n }\n serializeErrorForLog(error) {\n return this.redactor.serialize(error);\n }\n stop(reason = "supervisor_shutdown") {\n const safeReason = sanitizeSupervisorReason(this.redactor.redact(reason));\n this.executionGate.close(this.superseded ? "superseded" : "shutdown", safeReason);\n this.commands.close();\n if (this.stopPromise) return this.stopPromise;\n this.stopped = true;\n const stopping = this.stopRuntime(safeReason);\n this.stopPromise = stopping;\n void stopping.then(\n () => this.settleCompletion(),\n (error) => {\n this.fatalError ??= errorFromUnknown(error);\n this.settleCompletion();\n }\n );\n return stopping;\n }\n async stopRuntime(reason) {\n this.transport.beginShutdown();\n const stopEvent = this.fatalError ? Promise.resolve() : withTimeout(\n this.emitEvent({ kind: "supervisor_stopping", reason }),\n this.config.harness.stopGraceMs,\n "Timed out while persisting the supervisor shutdown event."\n );\n const harnessStop = this.harness.stop(reason);\n const commandQuiescence = withTimeout(\n this.commands.waitForQuiescence(),\n this.config.harness.stopGraceMs,\n "Timed out while waiting for supervisor commands to quiesce."\n );\n const results = await Promise.allSettled([stopEvent, harnessStop, commandQuiescence]);\n let rejected = results.find(\n (result) => result.status === "rejected"\n );\n if (!rejected && !this.fatalError && !this.superseded) {\n try {\n await withTimeout(\n this.commands.finalizeGracefulShutdown(),\n this.config.harness.stopGraceMs,\n "Timed out while finalizing interrupted supervisor commands."\n );\n } catch (error) {\n rejected = {\n status: "rejected",\n reason: error\n };\n }\n }\n try {\n await withTimeout(\n this.attachments.close(),\n this.config.harness.stopGraceMs,\n "Timed out while releasing descriptor-bound attachment storage."\n );\n } catch (error) {\n rejected ??= {\n status: "rejected",\n reason: error\n };\n }\n this.transport.finishShutdown({\n fatal: this.fatalError !== null,\n superseded: this.superseded\n });\n this.credential = null;\n if (this.fatalError) throw this.fatalError;\n if (rejected) throw errorFromUnknown(rejected.reason);\n }\n settleCompletion() {\n if (this.completionSettled) return;\n this.completionSettled = true;\n if (this.fatalError) this.rejectCompletion(this.fatalError);\n else this.resolveCompletion();\n }\n async emitEvent(event, durability = "durable") {\n try {\n await this.store.appendEvent(event, durability);\n this.transport.flushOutbox();\n } catch (error) {\n const failure = errorFromUnknown(error);\n this.failRuntime(failure);\n throw failure;\n }\n }\n failRuntime(error) {\n this.transitionToFatal(\n error,\n "persistence_failed",\n "Durable supervisor state could not be persisted.",\n true\n );\n }\n failTransport(error) {\n this.transitionToFatal(\n error,\n "runtime_failed",\n "Supervisor WebSocket construction failed.",\n false\n );\n }\n transitionToFatal(error, gateKind, gateMessage, failActiveConnection) {\n if (this.fatalError) return;\n this.fatalError = error;\n this.executionGate.close(gateKind, gateMessage, error);\n this.commands.close();\n if (failActiveConnection) this.transport.failActiveConnection();\n queueMicrotask(() => {\n void this.stop("fatal_supervisor_error").catch(() => void 0);\n });\n }\n handleExecutionClosure() {\n const closure = this.executionGate.closure;\n if (!closure || closure.kind === "shutdown" || closure.kind === "superseded" || closure.kind === "startup_failed" || this.fatalError) {\n return;\n }\n const cause = closure.error.cause;\n const failure = cause instanceof Error ? cause : closure.error;\n queueMicrotask(() => this.failRuntime(failure));\n }\n acceptSupersession(reason) {\n if (this.superseded || this.stopped) return;\n const safeReason = sanitizeSupervisorReason(this.redactor.redact(reason));\n this.superseded = true;\n this.executionGate.close("superseded", safeReason);\n this.commands.close();\n void this.stop(safeReason).catch(() => void 0);\n }\n};\n\n// src/supervisor/runtime-entry.ts\nvar INVALID_HANDOFF_ERROR = "Supervisor environment handoff is invalid.";\nvar DEFAULT_HANDOFF_DEPENDENCIES = {\n fstat: (fd) => fstatSync2(fd),\n read: (fd, buffer, offset, length, position) => readSync2(fd, buffer, offset, length, position),\n close: (fd) => closeSync(fd),\n truncate: (fd, length) => ftruncateSync(fd, length)\n};\nfunction parseSupervisorEnvironmentHandoff(source) {\n const handoff = deserializeSupervisorEnvironmentHandoff(source);\n if (!handoff.ok) throw new Error(INVALID_HANDOFF_ERROR);\n return handoff.environment;\n}\nfunction readSupervisorEnvironmentHandoff(dependencies) {\n const stats = dependencies.fstat(SUPERVISOR_ENVIRONMENT_FD);\n if (!stats.isFile() || !Number.isSafeInteger(stats.size) || stats.size <= 0 || stats.size > SUPERVISOR_ENVIRONMENT_MAX_BYTES) {\n throw new Error(INVALID_HANDOFF_ERROR);\n }\n const buffer = Buffer.alloc(SUPERVISOR_ENVIRONMENT_MAX_BYTES + 1);\n let offset = 0;\n while (offset < buffer.length) {\n const bytesRead = dependencies.read(\n SUPERVISOR_ENVIRONMENT_FD,\n buffer,\n offset,\n buffer.length - offset,\n null\n );\n if (!Number.isSafeInteger(bytesRead) || bytesRead < 0 || bytesRead > buffer.length - offset) {\n throw new Error(INVALID_HANDOFF_ERROR);\n }\n if (bytesRead === 0) break;\n offset += bytesRead;\n }\n if (offset === 0 || offset > SUPERVISOR_ENVIRONMENT_MAX_BYTES) {\n throw new Error(INVALID_HANDOFF_ERROR);\n }\n try {\n return new TextDecoder("utf-8", { fatal: true }).decode(buffer.subarray(0, offset));\n } catch {\n throw new Error(INVALID_HANDOFF_ERROR);\n }\n}\nfunction hydrateSupervisorEnvironmentFromHandoff(environment = process.env, dependencies = DEFAULT_HANDOFF_DEPENDENCIES, required = false) {\n const indicator = environment[SUPERVISOR_ENVIRONMENT_FD_ENV];\n if (indicator === void 0) {\n if (!required && environment[SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV] === void 0) {\n return /* @__PURE__ */ Object.create(null);\n }\n delete environment[SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV];\n throw new Error(INVALID_HANDOFF_ERROR);\n }\n delete environment[SUPERVISOR_ENVIRONMENT_FD_ENV];\n let hydrated;\n let failed = false;\n try {\n if (indicator !== String(SUPERVISOR_ENVIRONMENT_FD) || environment[SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV] !== void 0) {\n throw new Error(INVALID_HANDOFF_ERROR);\n }\n hydrated = parseSupervisorEnvironmentHandoff(\n readSupervisorEnvironmentHandoff(dependencies)\n );\n } catch {\n failed = true;\n } finally {\n delete environment[SUPERVISOR_ENVIRONMENT_PAYLOAD_ENV];\n try {\n dependencies.truncate(SUPERVISOR_ENVIRONMENT_FD, 0);\n } catch {\n failed = true;\n }\n try {\n dependencies.close(SUPERVISOR_ENVIRONMENT_FD);\n } catch {\n failed = true;\n }\n }\n if (failed || hydrated === void 0) throw new Error(INVALID_HANDOFF_ERROR);\n for (const [name, value] of Object.entries(hydrated)) environment[name] = value;\n return hydrated;\n}\nasync function loadConfig(path) {\n await access(path, fsConstants4.R_OK);\n const raw = await readFile(path, "utf8");\n return parseSupervisorRuntimeConfig(JSON.parse(raw));\n}\nvar processRuntime = null;\nvar processRedactor = new SensitiveValueRedactor();\nasync function main() {\n const handoffEnvironment = hydrateSupervisorEnvironmentFromHandoff(\n process.env,\n DEFAULT_HANDOFF_DEPENDENCIES,\n true\n );\n processRedactor.captureAll(Object.values(handoffEnvironment));\n const configPath = resolve(process.argv[2] ?? "neckbeard-supervisor.json");\n const config = await loadConfig(configPath);\n const runtime = new SupervisorRuntime(config, void 0, handoffEnvironment);\n processRuntime = runtime;\n await runtime.start();\n let shuttingDown = false;\n const shutdown = (signal) => {\n if (shuttingDown) return;\n shuttingDown = true;\n void runtime.stop(signal).catch(() => void 0);\n };\n process.on("SIGTERM", () => shutdown("SIGTERM"));\n process.on("SIGINT", () => shutdown("SIGINT"));\n await runtime.waitUntilStopped();\n}\nvar isMain = process.argv[1] ? pathToFileURL(resolve(process.argv[1])).href === import.meta.url : false;\nif (isMain) {\n main().catch((error) => {\n console.error(\n "[neckbeard-supervisor] failed to start",\n processRuntime?.serializeErrorForLog(error) ?? processRedactor.serialize(error)\n );\n process.exit(1);\n });\n}\nexport {\n PiSdkHarnessAdapter,\n SupervisorRuntime,\n hydrateSupervisorEnvironmentFromHandoff,\n parseSupervisorEnvironmentHandoff\n};\n';
23
23
 
24
24
  // src/supervisor/default-pi-package-lock.json
25
25
  var default_pi_package_lock_default = {
@@ -30,52 +30,17 @@ var default_pi_package_lock_default = {
30
30
  "": {
31
31
  name: "neckbeard-supervisor-runtime",
32
32
  dependencies: {
33
- "@earendil-works/pi-coding-agent": "0.83.0"
33
+ "@earendil-works/pi-coding-agent": "1.3.0"
34
34
  }
35
35
  },
36
- "node_modules/@earendil-works/pi-coding-agent": {
37
- version: "0.83.0",
38
- resolved: "https://registry.npmjs.org/@earendil-works/pi-coding-agent/-/pi-coding-agent-0.83.0.tgz",
39
- integrity: "sha512-uYhF+FsZxogoSX/AxBcUdiY+ZklubwaXyAoEGA2eQwsHcyEAhUYIKh/WLXe/a8+k8eTCmxb+ZN2Zo9mzQtzbWw==",
40
- hasShrinkwrap: true,
36
+ "node_modules/@anthropic-ai/sdk": {
37
+ version: "0.129.0",
38
+ resolved: "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.129.0.tgz",
39
+ integrity: "sha512-MH7LB20kNpGLUpPTe2OG5XvL/KhX8HUO9XyBaFjgFk6TLS4Xjt0VPIuMKywe7POKKPslX+QxSlVok9e+8kG5Nw==",
41
40
  license: "MIT",
42
41
  dependencies: {
43
- "@earendil-works/pi-agent-core": "^0.83.0",
44
- "@earendil-works/pi-ai": "^0.83.0",
45
- "@earendil-works/pi-tui": "^0.83.0",
46
- "@silvia-odwyer/photon-node": "0.3.4",
47
- chalk: "5.6.2",
48
- "cross-spawn": "7.0.6",
49
- diff: "8.0.4",
50
- glob: "13.0.6",
51
- "highlight.js": "10.7.3",
52
- "hosted-git-info": "9.0.3",
53
- ignore: "7.0.5",
54
- jiti: "2.7.0",
55
- minimatch: "10.2.5",
56
- "proper-lockfile": "4.1.2",
57
- semver: "7.8.0",
58
- typebox: "1.3.7",
59
- undici: "8.5.0",
60
- yaml: "2.9.0"
61
- },
62
- bin: {
63
- pi: "dist/cli.js"
64
- },
65
- engines: {
66
- node: ">=22.19.0"
67
- },
68
- optionalDependencies: {
69
- "@mariozechner/clipboard": "0.3.9"
70
- }
71
- },
72
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@anthropic-ai/sdk": {
73
- version: "0.91.1",
74
- resolved: "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.91.1.tgz",
75
- integrity: "sha512-LAmu761tSN9r66ixvmciswUj/ZC+1Q4iAfpedTfSVLeswRwnY3n2Nb6Tsk+cLPP28aLOPWeMgIuTuCcMC6W/iw==",
76
- license: "MIT",
77
- dependencies: {
78
- "json-schema-to-ts": "^3.1.1"
42
+ "json-schema-to-ts": "^3.1.1",
43
+ standardwebhooks: "^1.0.0"
79
44
  },
80
45
  bin: {
81
46
  "anthropic-ai-sdk": "bin/cli"
@@ -89,106 +54,41 @@ var default_pi_package_lock_default = {
89
54
  }
90
55
  }
91
56
  },
92
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-crypto/crc32": {
93
- version: "5.2.0",
94
- resolved: "https://registry.npmjs.org/@aws-crypto/crc32/-/crc32-5.2.0.tgz",
95
- integrity: "sha512-nLbCWqQNgUiwwtFsen1AdzAtvuLRsQS8rYgMuxCrdKf9kOssamGLuPwyTY9wyYblNr9+1XM8v6zoDTPPSIeANg==",
57
+ "node_modules/@aws-sdk/client-bedrock-runtime": {
58
+ version: "3.1127.0",
59
+ resolved: "https://registry.npmjs.org/@aws-sdk/client-bedrock-runtime/-/client-bedrock-runtime-3.1127.0.tgz",
60
+ integrity: "sha512-IDl/lrPb90aH+pZFHGNDmgH9nAUQj5PlZH1sJ3w7RikctyjHSnY3oNjZhrLoaBoQn/rNK0zsP6OHEqEhj2tdLA==",
96
61
  license: "Apache-2.0",
97
62
  dependencies: {
98
- "@aws-crypto/util": "^5.2.0",
99
- "@aws-sdk/types": "^3.222.0",
100
- tslib: "^2.6.2"
101
- },
102
- engines: {
103
- node: ">=16.0.0"
104
- }
105
- },
106
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-crypto/sha256-browser": {
107
- version: "5.2.0",
108
- resolved: "https://registry.npmjs.org/@aws-crypto/sha256-browser/-/sha256-browser-5.2.0.tgz",
109
- integrity: "sha512-AXfN/lGotSQwu6HNcEsIASo7kWXZ5HYWvfOmSNKDsEqC4OashTp8alTmaz+F7TC2L083SFv5RdB+qU3Vs1kZqw==",
110
- license: "Apache-2.0",
111
- dependencies: {
112
- "@aws-crypto/sha256-js": "^5.2.0",
113
- "@aws-crypto/supports-web-crypto": "^5.2.0",
114
- "@aws-crypto/util": "^5.2.0",
115
- "@aws-sdk/types": "^3.222.0",
116
- "@aws-sdk/util-locate-window": "^3.0.0",
117
- "@smithy/util-utf8": "^2.0.0",
118
- tslib: "^2.6.2"
119
- }
120
- },
121
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-crypto/sha256-js": {
122
- version: "5.2.0",
123
- resolved: "https://registry.npmjs.org/@aws-crypto/sha256-js/-/sha256-js-5.2.0.tgz",
124
- integrity: "sha512-FFQQyu7edu4ufvIZ+OadFpHHOt+eSTBaYaki44c+akjg7qZg9oOQeLlk77F6tSYqjDAFClrHJk9tMf0HdVyOvA==",
125
- license: "Apache-2.0",
126
- dependencies: {
127
- "@aws-crypto/util": "^5.2.0",
128
- "@aws-sdk/types": "^3.222.0",
129
- tslib: "^2.6.2"
130
- },
131
- engines: {
132
- node: ">=16.0.0"
133
- }
134
- },
135
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-crypto/supports-web-crypto": {
136
- version: "5.2.0",
137
- resolved: "https://registry.npmjs.org/@aws-crypto/supports-web-crypto/-/supports-web-crypto-5.2.0.tgz",
138
- integrity: "sha512-iAvUotm021kM33eCdNfwIN//F77/IADDSs58i+MDaOqFrVjZo9bAal0NK7HurRuWLLpF1iLX7gbWrjHjeo+YFg==",
139
- license: "Apache-2.0",
140
- dependencies: {
141
- tslib: "^2.6.2"
142
- }
143
- },
144
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-crypto/util": {
145
- version: "5.2.0",
146
- resolved: "https://registry.npmjs.org/@aws-crypto/util/-/util-5.2.0.tgz",
147
- integrity: "sha512-4RkU9EsI6ZpBve5fseQlGNUWKMa1RLPQ1dnjnQoe07ldfIzcsGb5hC5W0Dm7u423KWzawlrpbjXBrXCEv9zazQ==",
148
- license: "Apache-2.0",
149
- dependencies: {
150
- "@aws-sdk/types": "^3.222.0",
151
- "@smithy/util-utf8": "^2.0.0",
152
- tslib: "^2.6.2"
153
- }
154
- },
155
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/client-bedrock-runtime": {
156
- version: "3.1048.0",
157
- resolved: "https://registry.npmjs.org/@aws-sdk/client-bedrock-runtime/-/client-bedrock-runtime-3.1048.0.tgz",
158
- integrity: "sha512-u+NT61JZEkRFtpL0CAw1N1dwxnaLgwVXQl/zjJxTGgLyS/jTIdg2SdoEoCTHxgDyCnqa1HEi9QOoE9/pYRNpOQ==",
159
- license: "Apache-2.0",
160
- dependencies: {
161
- "@aws-crypto/sha256-browser": "5.2.0",
162
- "@aws-crypto/sha256-js": "5.2.0",
163
- "@aws-sdk/core": "^3.974.11",
164
- "@aws-sdk/credential-provider-node": "^3.972.42",
165
- "@aws-sdk/eventstream-handler-node": "^3.972.16",
166
- "@aws-sdk/middleware-eventstream": "^3.972.12",
167
- "@aws-sdk/middleware-websocket": "^3.972.19",
168
- "@aws-sdk/token-providers": "3.1048.0",
169
- "@aws-sdk/types": "^3.973.8",
170
- "@smithy/core": "^3.24.2",
171
- "@smithy/fetch-http-handler": "^5.4.2",
172
- "@smithy/node-http-handler": "^4.7.2",
173
- "@smithy/types": "^4.14.1",
63
+ "@aws-sdk/core": "^3.977.9",
64
+ "@aws-sdk/credential-provider-node": "^3.972.82",
65
+ "@aws-sdk/eventstream-handler-node": "^3.972.34",
66
+ "@aws-sdk/middleware-eventstream": "^3.972.29",
67
+ "@aws-sdk/middleware-websocket": "^3.972.52",
68
+ "@aws-sdk/token-providers": "3.1127.0",
69
+ "@aws-sdk/types": "^3.974.5",
70
+ "@smithy/core": "^3.33.3",
71
+ "@smithy/fetch-http-handler": "^5.7.2",
72
+ "@smithy/node-http-handler": "^4.11.3",
73
+ "@smithy/types": "^4.17.2",
174
74
  tslib: "^2.6.2"
175
75
  },
176
76
  engines: {
177
77
  node: ">=20.0.0"
178
78
  }
179
79
  },
180
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/core": {
181
- version: "3.974.11",
182
- resolved: "https://registry.npmjs.org/@aws-sdk/core/-/core-3.974.11.tgz",
183
- integrity: "sha512-QpnINq5FZH6EOaDEkmHdT7eUunbvD27pDNQypaWjFyYz7Zl1q3UCMQErBZxpmfGfI7MvI2TlK8KTkgNpv8b1ug==",
80
+ "node_modules/@aws-sdk/core": {
81
+ version: "3.978.3",
82
+ resolved: "https://registry.npmjs.org/@aws-sdk/core/-/core-3.978.3.tgz",
83
+ integrity: "sha512-nslpzUCTI9b2IQMWSd6mSAXldBexPc8rr0d3dXUutXYFLFaTdsHa2GD7sJdsn3PhyjK0O5K8ypd6zi+RXXPVlg==",
184
84
  license: "Apache-2.0",
185
85
  dependencies: {
186
- "@aws-sdk/types": "^3.973.8",
187
- "@aws-sdk/xml-builder": "^3.972.24",
188
- "@aws/lambda-invoke-store": "^0.2.2",
189
- "@smithy/core": "^3.24.2",
190
- "@smithy/signature-v4": "^5.4.2",
191
- "@smithy/types": "^4.14.1",
86
+ "@aws-sdk/types": "^3.974.6",
87
+ "@aws-sdk/xml-builder": "^3.972.41",
88
+ "@aws/lambda-invoke-store": "^0.3.0",
89
+ "@smithy/core": "^3.35.2",
90
+ "@smithy/signature-v4": "^5.7.4",
91
+ "@smithy/types": "^4.19.0",
192
92
  bowser: "^2.11.0",
193
93
  tslib: "^2.6.2"
194
94
  },
@@ -196,646 +96,482 @@ var default_pi_package_lock_default = {
196
96
  node: ">=20.0.0"
197
97
  }
198
98
  },
199
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/credential-provider-env": {
200
- version: "3.972.37",
201
- resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.972.37.tgz",
202
- integrity: "sha512-/jpPvEh6f7ntmIzf7dNxoNX6Q8vt8UpesCjbW6mFfk4V1NW6bIy9qxcQ6WbA8As5yQhsZOe+xeNd4xHX8kdY2Q==",
99
+ "node_modules/@aws-sdk/credential-provider-env": {
100
+ version: "3.972.74",
101
+ resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.972.74.tgz",
102
+ integrity: "sha512-rsRJcW2iFUhCgclyD6OSbMEaPl8Eu0qSeRZb2uuCK1ViZ66hl5wOe/p6Vr6MO3b+ydyKgFeqza2p6tZThvILlw==",
203
103
  license: "Apache-2.0",
204
104
  dependencies: {
205
- "@aws-sdk/core": "^3.974.11",
206
- "@aws-sdk/types": "^3.973.8",
207
- "@smithy/core": "^3.24.2",
208
- "@smithy/types": "^4.14.1",
105
+ "@aws-sdk/core": "^3.978.3",
106
+ "@aws-sdk/types": "^3.974.6",
107
+ "@smithy/core": "^3.35.2",
108
+ "@smithy/types": "^4.19.0",
209
109
  tslib: "^2.6.2"
210
110
  },
211
111
  engines: {
212
112
  node: ">=20.0.0"
213
113
  }
214
114
  },
215
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/credential-provider-http": {
216
- version: "3.972.39",
217
- resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.972.39.tgz",
218
- integrity: "sha512-pIgTpisWyWg7X1bUbzSjuUYosYTD0Ghz2M0hkSTmb3a6i3qV3uU+NYJPI/E2XSC0HcsZh5rsLPzeXrkb2DS0Cg==",
115
+ "node_modules/@aws-sdk/credential-provider-http": {
116
+ version: "3.972.76",
117
+ resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.972.76.tgz",
118
+ integrity: "sha512-pnKdh0Br7OJPj+7qKjzgTfDTFW0RhEMKXNDR2jv9CAM4oHuG/4z3hRh8KtutLfpmItuRtDbKBmwWkDqHwwAWXw==",
219
119
  license: "Apache-2.0",
220
120
  dependencies: {
221
- "@aws-sdk/core": "^3.974.11",
222
- "@aws-sdk/types": "^3.973.8",
223
- "@smithy/core": "^3.24.2",
224
- "@smithy/fetch-http-handler": "^5.4.2",
225
- "@smithy/node-http-handler": "^4.7.2",
226
- "@smithy/types": "^4.14.1",
121
+ "@aws-sdk/core": "^3.978.3",
122
+ "@aws-sdk/types": "^3.974.6",
123
+ "@smithy/core": "^3.35.2",
124
+ "@smithy/fetch-http-handler": "^5.8.0",
125
+ "@smithy/node-http-handler": "^4.12.1",
126
+ "@smithy/types": "^4.19.0",
227
127
  tslib: "^2.6.2"
228
128
  },
229
129
  engines: {
230
130
  node: ">=20.0.0"
231
131
  }
232
132
  },
233
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/credential-provider-ini": {
234
- version: "3.972.41",
235
- resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.972.41.tgz",
236
- integrity: "sha512-u2tyjaxJJzW8UtW4SM1ZcPMDwO6y+kV+llvou+Adts0FAKyzes5jG4izQN+KX3yE8ZROpS5y1LJ//xL2iSf76w==",
133
+ "node_modules/@aws-sdk/credential-provider-ini": {
134
+ version: "3.973.19",
135
+ resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.973.19.tgz",
136
+ integrity: "sha512-kcjvAxqQEV8yuwkX58RelNn3ne65o7JgRWf3Z/gVvbi7Xuw1qSDLJlatrLD76+40cmRxmNkLxBoyp/vAQChQ5g==",
237
137
  license: "Apache-2.0",
238
138
  dependencies: {
239
- "@aws-sdk/core": "^3.974.11",
240
- "@aws-sdk/credential-provider-env": "^3.972.37",
241
- "@aws-sdk/credential-provider-http": "^3.972.39",
242
- "@aws-sdk/credential-provider-login": "^3.972.41",
243
- "@aws-sdk/credential-provider-process": "^3.972.37",
244
- "@aws-sdk/credential-provider-sso": "^3.972.41",
245
- "@aws-sdk/credential-provider-web-identity": "^3.972.41",
246
- "@aws-sdk/nested-clients": "^3.997.9",
247
- "@aws-sdk/types": "^3.973.8",
248
- "@smithy/core": "^3.24.2",
249
- "@smithy/credential-provider-imds": "^4.3.2",
250
- "@smithy/types": "^4.14.1",
139
+ "@aws-sdk/core": "^3.978.3",
140
+ "@aws-sdk/credential-provider-env": "^3.972.74",
141
+ "@aws-sdk/credential-provider-http": "^3.972.76",
142
+ "@aws-sdk/credential-provider-login": "^3.972.81",
143
+ "@aws-sdk/credential-provider-process": "^3.972.74",
144
+ "@aws-sdk/credential-provider-sso": "^3.973.18",
145
+ "@aws-sdk/credential-provider-web-identity": "^3.972.80",
146
+ "@aws-sdk/nested-clients": "^3.997.48",
147
+ "@aws-sdk/types": "^3.974.6",
148
+ "@smithy/core": "^3.35.2",
149
+ "@smithy/credential-provider-imds": "^4.5.2",
150
+ "@smithy/types": "^4.19.0",
251
151
  tslib: "^2.6.2"
252
152
  },
253
153
  engines: {
254
154
  node: ">=20.0.0"
255
155
  }
256
156
  },
257
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/credential-provider-login": {
258
- version: "3.972.41",
259
- resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-login/-/credential-provider-login-3.972.41.tgz",
260
- integrity: "sha512-0LBitxXiAiaE5nlFPfpNIww/8FRY/I7WIndWsc9GmNFOM7cE1wNpVNQEGEk9Outg5l8xl+3vybxFyUy4l9q/LQ==",
157
+ "node_modules/@aws-sdk/credential-provider-login": {
158
+ version: "3.972.81",
159
+ resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-login/-/credential-provider-login-3.972.81.tgz",
160
+ integrity: "sha512-CeQHSbE2CnVdaHIJ/NayRaCecIER+Pm9faUPkmRATO54rCoMTEPSbVieGHzEwvm1dZM2HIs6qQZCznhayNTWJQ==",
261
161
  license: "Apache-2.0",
262
162
  dependencies: {
263
- "@aws-sdk/core": "^3.974.11",
264
- "@aws-sdk/nested-clients": "^3.997.9",
265
- "@aws-sdk/types": "^3.973.8",
266
- "@smithy/core": "^3.24.2",
267
- "@smithy/types": "^4.14.1",
163
+ "@aws-sdk/core": "^3.978.3",
164
+ "@aws-sdk/nested-clients": "^3.997.48",
165
+ "@aws-sdk/types": "^3.974.6",
166
+ "@smithy/core": "^3.35.2",
167
+ "@smithy/types": "^4.19.0",
268
168
  tslib: "^2.6.2"
269
169
  },
270
170
  engines: {
271
171
  node: ">=20.0.0"
272
172
  }
273
173
  },
274
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/credential-provider-node": {
275
- version: "3.972.42",
276
- resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.972.42.tgz",
277
- integrity: "sha512-D4oon2zbqqsWOJUM99Gm3/ZyJ0IJvTXVN3PyloGb3kQEyI36fjCZheZj422lAgTWWd6TSHgiImLt3RIaLdv3dQ==",
174
+ "node_modules/@aws-sdk/credential-provider-node": {
175
+ version: "3.972.86",
176
+ resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.972.86.tgz",
177
+ integrity: "sha512-WNttSyr6e8innPtBSty//CdnqJcgZN6eAbtw3v/CR2IObz6MYZEo8eusdtuCHJ2ujwFqC2bSPHVyhXGHx8HruQ==",
278
178
  license: "Apache-2.0",
279
179
  dependencies: {
280
- "@aws-sdk/credential-provider-env": "^3.972.37",
281
- "@aws-sdk/credential-provider-http": "^3.972.39",
282
- "@aws-sdk/credential-provider-ini": "^3.972.41",
283
- "@aws-sdk/credential-provider-process": "^3.972.37",
284
- "@aws-sdk/credential-provider-sso": "^3.972.41",
285
- "@aws-sdk/credential-provider-web-identity": "^3.972.41",
286
- "@aws-sdk/types": "^3.973.8",
287
- "@smithy/core": "^3.24.2",
288
- "@smithy/credential-provider-imds": "^4.3.2",
289
- "@smithy/types": "^4.14.1",
180
+ "@aws-sdk/credential-provider-env": "^3.972.74",
181
+ "@aws-sdk/credential-provider-http": "^3.972.76",
182
+ "@aws-sdk/credential-provider-ini": "^3.973.19",
183
+ "@aws-sdk/credential-provider-process": "^3.972.74",
184
+ "@aws-sdk/credential-provider-sso": "^3.973.18",
185
+ "@aws-sdk/credential-provider-web-identity": "^3.972.80",
186
+ "@aws-sdk/types": "^3.974.6",
187
+ "@smithy/core": "^3.35.2",
188
+ "@smithy/credential-provider-imds": "^4.5.2",
189
+ "@smithy/types": "^4.19.0",
290
190
  tslib: "^2.6.2"
291
191
  },
292
192
  engines: {
293
193
  node: ">=20.0.0"
294
194
  }
295
195
  },
296
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/credential-provider-process": {
297
- version: "3.972.37",
298
- resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.972.37.tgz",
299
- integrity: "sha512-7nVaHBUaWIddASYfVaA9O4D5ZVjewU3sCol9WqZPGfW0nR+0WqE0xHZnD/U2L33PlOB8KNXGKZ6wOES/QijKzg==",
196
+ "node_modules/@aws-sdk/credential-provider-process": {
197
+ version: "3.972.74",
198
+ resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.972.74.tgz",
199
+ integrity: "sha512-Yj6kZFJQdbR+PygTkqdVLPHHpdDpOS9GCYVcDCuweCRRig9LF24ELQBMfyUw1vspvrZJUfnOGVyMjhaL094ahw==",
300
200
  license: "Apache-2.0",
301
201
  dependencies: {
302
- "@aws-sdk/core": "^3.974.11",
303
- "@aws-sdk/types": "^3.973.8",
304
- "@smithy/core": "^3.24.2",
305
- "@smithy/types": "^4.14.1",
202
+ "@aws-sdk/core": "^3.978.3",
203
+ "@aws-sdk/types": "^3.974.6",
204
+ "@smithy/core": "^3.35.2",
205
+ "@smithy/types": "^4.19.0",
306
206
  tslib: "^2.6.2"
307
207
  },
308
208
  engines: {
309
209
  node: ">=20.0.0"
310
210
  }
311
211
  },
312
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/credential-provider-sso": {
313
- version: "3.972.41",
314
- resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.972.41.tgz",
315
- integrity: "sha512-IOWAWEHe5LkjSKkkUUX9ciV6Y1scHTsnfEkdt5yyC4Slrc7AGbkLPrpntjqh18ksJAMOaVhoBsO8p2WyTcY2wQ==",
212
+ "node_modules/@aws-sdk/credential-provider-sso": {
213
+ version: "3.973.18",
214
+ resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.973.18.tgz",
215
+ integrity: "sha512-FnpPhdY4qUGtX/8X6eKxh+uD+9Y19i9FYibgk4SBe0M935s9vocHkHzaxaMNk+YkHmvzgdu8cHA5SCoeU+kkew==",
316
216
  license: "Apache-2.0",
317
217
  dependencies: {
318
- "@aws-sdk/core": "^3.974.11",
319
- "@aws-sdk/nested-clients": "^3.997.9",
320
- "@aws-sdk/token-providers": "3.1048.0",
321
- "@aws-sdk/types": "^3.973.8",
322
- "@smithy/core": "^3.24.2",
323
- "@smithy/types": "^4.14.1",
218
+ "@aws-sdk/core": "^3.978.3",
219
+ "@aws-sdk/nested-clients": "^3.997.48",
220
+ "@aws-sdk/token-providers": "3.1150.0",
221
+ "@aws-sdk/types": "^3.974.6",
222
+ "@smithy/core": "^3.35.2",
223
+ "@smithy/types": "^4.19.0",
324
224
  tslib: "^2.6.2"
325
225
  },
326
226
  engines: {
327
227
  node: ">=20.0.0"
328
228
  }
329
229
  },
330
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/credential-provider-web-identity": {
331
- version: "3.972.41",
332
- resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.972.41.tgz",
333
- integrity: "sha512-mbACk9Yypa8nm4iGZLs0PofOXEcTDOUw6wDnsPXNDNSd2WNXs1tSo+6nc/fh0jLYdfVZThhBL98PHW4aXFsG5A==",
230
+ "node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers": {
231
+ version: "3.1150.0",
232
+ resolved: "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1150.0.tgz",
233
+ integrity: "sha512-wDU36ofhabZYu+d2KSriyDbwzxNoaOp+4dG0p3qkabk7HeALR5nIWyQbjoyJZLn3iqWkv/xNdyUfbfevDVDzzg==",
334
234
  license: "Apache-2.0",
335
235
  dependencies: {
336
- "@aws-sdk/core": "^3.974.11",
337
- "@aws-sdk/nested-clients": "^3.997.9",
338
- "@aws-sdk/types": "^3.973.8",
339
- "@smithy/core": "^3.24.2",
340
- "@smithy/types": "^4.14.1",
236
+ "@aws-sdk/core": "^3.978.3",
237
+ "@aws-sdk/nested-clients": "^3.997.48",
238
+ "@aws-sdk/types": "^3.974.6",
239
+ "@smithy/core": "^3.35.2",
240
+ "@smithy/types": "^4.19.0",
341
241
  tslib: "^2.6.2"
342
242
  },
343
243
  engines: {
344
244
  node: ">=20.0.0"
345
245
  }
346
246
  },
347
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/eventstream-handler-node": {
348
- version: "3.972.16",
349
- resolved: "https://registry.npmjs.org/@aws-sdk/eventstream-handler-node/-/eventstream-handler-node-3.972.16.tgz",
350
- integrity: "sha512-yedpPgKftqjU5SlPFHfqWpOw6xSCRieWRG1euWOlXn4WJxt2VX92VprCa2PpSOXjVCAeK6dTjW9eJRXVig9yGA==",
247
+ "node_modules/@aws-sdk/credential-provider-web-identity": {
248
+ version: "3.972.80",
249
+ resolved: "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.972.80.tgz",
250
+ integrity: "sha512-TJF25Ndwy2HxcVj6oxMgp8qVlJAawlExHYBXqhuC6Zt2m+A7WpdkjBD6QglNbiArlteYljZHEY3R7KKmno6ISA==",
351
251
  license: "Apache-2.0",
352
252
  dependencies: {
353
- "@aws-sdk/types": "^3.973.8",
354
- "@smithy/core": "^3.24.2",
355
- "@smithy/types": "^4.14.1",
253
+ "@aws-sdk/core": "^3.978.3",
254
+ "@aws-sdk/nested-clients": "^3.997.48",
255
+ "@aws-sdk/types": "^3.974.6",
256
+ "@smithy/core": "^3.35.2",
257
+ "@smithy/types": "^4.19.0",
356
258
  tslib: "^2.6.2"
357
259
  },
358
260
  engines: {
359
261
  node: ">=20.0.0"
360
262
  }
361
263
  },
362
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/middleware-eventstream": {
363
- version: "3.972.12",
364
- resolved: "https://registry.npmjs.org/@aws-sdk/middleware-eventstream/-/middleware-eventstream-3.972.12.tgz",
365
- integrity: "sha512-tHTHHCHNrq6XklQvlzHBDJG4Iuhh7NVPRdtmvP+nHFA+5sxPlIDzlAHHgfoYHGvT3NXP1yVP/L5c3opUn6T3Qg==",
264
+ "node_modules/@aws-sdk/eventstream-handler-node": {
265
+ version: "3.972.36",
266
+ resolved: "https://registry.npmjs.org/@aws-sdk/eventstream-handler-node/-/eventstream-handler-node-3.972.36.tgz",
267
+ integrity: "sha512-HFaKXA6ugPVvpR7W/3UT3hylWIPndqGMwduwNVrmGsRT5+OESHN8/ven4eeofraQF5Kxp8A8QgGVrv7iQsTRKQ==",
366
268
  license: "Apache-2.0",
367
269
  dependencies: {
368
- "@aws-sdk/types": "^3.973.8",
369
- "@smithy/core": "^3.24.2",
370
- "@smithy/types": "^4.14.1",
270
+ "@aws-sdk/types": "^3.974.6",
271
+ "@smithy/core": "^3.35.2",
272
+ "@smithy/types": "^4.19.0",
371
273
  tslib: "^2.6.2"
372
274
  },
373
275
  engines: {
374
276
  node: ">=20.0.0"
375
277
  }
376
278
  },
377
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/middleware-websocket": {
378
- version: "3.972.19",
379
- resolved: "https://registry.npmjs.org/@aws-sdk/middleware-websocket/-/middleware-websocket-3.972.19.tgz",
380
- integrity: "sha512-mkEhOGYozqKQkbFaVrjwr0faiwwZza1v5/jSY6Tucm3bD+uKTazIUH/4Yo6aMnQD2ua2W9cMP6s8mvwTcjtqHw==",
279
+ "node_modules/@aws-sdk/middleware-eventstream": {
280
+ version: "3.972.31",
281
+ resolved: "https://registry.npmjs.org/@aws-sdk/middleware-eventstream/-/middleware-eventstream-3.972.31.tgz",
282
+ integrity: "sha512-4yvdTVwPGKCnrwuwlYEmwLqQXKwk0unx3f/FvBi4FA9ruK/WGoPJyqfK7hOYurheIyQL44FR0ovgOHqvkfdpAQ==",
381
283
  license: "Apache-2.0",
382
284
  dependencies: {
383
- "@aws-sdk/core": "^3.974.11",
384
- "@aws-sdk/types": "^3.973.8",
385
- "@smithy/core": "^3.24.2",
386
- "@smithy/fetch-http-handler": "^5.4.2",
387
- "@smithy/signature-v4": "^5.4.2",
388
- "@smithy/types": "^4.14.1",
285
+ "@aws-sdk/types": "^3.974.6",
286
+ "@smithy/core": "^3.35.2",
287
+ "@smithy/types": "^4.19.0",
389
288
  tslib: "^2.6.2"
390
289
  },
391
290
  engines: {
392
- node: ">= 14.0.0"
291
+ node: ">=20.0.0"
393
292
  }
394
293
  },
395
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/nested-clients": {
396
- version: "3.997.9",
397
- resolved: "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.997.9.tgz",
398
- integrity: "sha512-jPR3rnmRI4hWYyzfmTGBr7NblMp8QYYeflHXba1H6+7CGrWVqWKQzaXFQ4qbExqPRsXN3T3L3JxFhr6aouXUGQ==",
294
+ "node_modules/@aws-sdk/middleware-websocket": {
295
+ version: "3.972.56",
296
+ resolved: "https://registry.npmjs.org/@aws-sdk/middleware-websocket/-/middleware-websocket-3.972.56.tgz",
297
+ integrity: "sha512-32d9EnnNM5UMwjVp/qnL0K4XYiZv+YlSbULI3BaoBdJvebAS6cD0bKfPJ7lzovN0qrelvmSh5jo/3tk0KoTuGQ==",
399
298
  license: "Apache-2.0",
400
299
  dependencies: {
401
- "@aws-crypto/sha256-browser": "5.2.0",
402
- "@aws-crypto/sha256-js": "5.2.0",
403
- "@aws-sdk/core": "^3.974.11",
404
- "@aws-sdk/signature-v4-multi-region": "^3.996.27",
405
- "@aws-sdk/types": "^3.973.8",
406
- "@smithy/core": "^3.24.2",
407
- "@smithy/fetch-http-handler": "^5.4.2",
408
- "@smithy/node-http-handler": "^4.7.2",
409
- "@smithy/types": "^4.14.1",
300
+ "@aws-sdk/core": "^3.978.3",
301
+ "@aws-sdk/types": "^3.974.6",
302
+ "@smithy/core": "^3.35.2",
303
+ "@smithy/fetch-http-handler": "^5.8.0",
304
+ "@smithy/signature-v4": "^5.7.4",
305
+ "@smithy/types": "^4.19.0",
410
306
  tslib: "^2.6.2"
411
307
  },
412
308
  engines: {
413
- node: ">=20.0.0"
309
+ node: ">= 14.0.0"
414
310
  }
415
311
  },
416
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/signature-v4-multi-region": {
417
- version: "3.996.27",
418
- resolved: "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.996.27.tgz",
419
- integrity: "sha512-0Phbz4t6HI3D3skxvG2uI+VWU034/nSIw1T8d+FPzzQG9EQTrw94o9mOKO2Gv3n3Oc8P7JD7RAUxkoneLWv5Eg==",
312
+ "node_modules/@aws-sdk/nested-clients": {
313
+ version: "3.997.48",
314
+ resolved: "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.997.48.tgz",
315
+ integrity: "sha512-B01jdXJtAW/XOiUzGdI2mz67WyEHbGEc9X6Euzw3bjLAa+txTqdZDER4X2FsIEcXzV2ABqudVZ5thali8tCCzQ==",
420
316
  license: "Apache-2.0",
421
317
  dependencies: {
422
- "@aws-sdk/types": "^3.973.8",
423
- "@smithy/core": "^3.24.2",
424
- "@smithy/signature-v4": "^5.4.2",
425
- "@smithy/types": "^4.14.1",
318
+ "@aws-sdk/core": "^3.978.3",
319
+ "@aws-sdk/signature-v4-multi-region": "^3.996.48",
320
+ "@aws-sdk/types": "^3.974.6",
321
+ "@smithy/core": "^3.35.2",
322
+ "@smithy/fetch-http-handler": "^5.8.0",
323
+ "@smithy/node-http-handler": "^4.12.1",
324
+ "@smithy/types": "^4.19.0",
426
325
  tslib: "^2.6.2"
427
326
  },
428
327
  engines: {
429
328
  node: ">=20.0.0"
430
329
  }
431
330
  },
432
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/token-providers": {
433
- version: "3.1048.0",
434
- resolved: "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1048.0.tgz",
435
- integrity: "sha512-k0y/GcuesuSfWyUM0WamrGyeZmltRYaPbHO82UDA6mZ/doB+FOHKutikPAtSXMn/hDz970cF+iRuuiYO9VEbAA==",
331
+ "node_modules/@aws-sdk/signature-v4-multi-region": {
332
+ version: "3.996.48",
333
+ resolved: "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.996.48.tgz",
334
+ integrity: "sha512-cFDXfEbXaGwbnpvR/DyqfxfjxpjXVRVthQLgkwvcfDS5u3+8G9WSj1X1Ag/pTRg/QOeOno1Tq3ycEdrKsCUcOA==",
436
335
  license: "Apache-2.0",
437
336
  dependencies: {
438
- "@aws-sdk/core": "^3.974.11",
439
- "@aws-sdk/nested-clients": "^3.997.9",
440
- "@aws-sdk/types": "^3.973.8",
441
- "@smithy/core": "^3.24.2",
442
- "@smithy/types": "^4.14.1",
337
+ "@aws-sdk/types": "^3.974.6",
338
+ "@smithy/signature-v4": "^5.7.4",
339
+ "@smithy/types": "^4.19.0",
443
340
  tslib: "^2.6.2"
444
341
  },
445
342
  engines: {
446
343
  node: ">=20.0.0"
447
344
  }
448
345
  },
449
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/types": {
450
- version: "3.973.8",
451
- resolved: "https://registry.npmjs.org/@aws-sdk/types/-/types-3.973.8.tgz",
452
- integrity: "sha512-gjlAdtHMbtR9X5iIhVUvbVcy55KnznpC6bkDUWW9z915bi0ckdUr5cjf16Kp6xq0bP5HBD2xzgbL9F9Quv5vUw==",
346
+ "node_modules/@aws-sdk/token-providers": {
347
+ version: "3.1127.0",
348
+ resolved: "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1127.0.tgz",
349
+ integrity: "sha512-Dv2TMWBshJ+tF6ahs2Sy5bh4Iabsd4GAQqVvE9XZmYmnoaVbpS2QKIKE/HRacc7bTtbjEEvP+laGzHvHlf1CiQ==",
453
350
  license: "Apache-2.0",
454
351
  dependencies: {
455
- "@smithy/types": "^4.14.1",
352
+ "@aws-sdk/core": "^3.977.9",
353
+ "@aws-sdk/nested-clients": "^3.997.44",
354
+ "@aws-sdk/types": "^3.974.5",
355
+ "@smithy/core": "^3.33.3",
356
+ "@smithy/types": "^4.17.2",
456
357
  tslib: "^2.6.2"
457
358
  },
458
359
  engines: {
459
360
  node: ">=20.0.0"
460
361
  }
461
362
  },
462
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/util-locate-window": {
463
- version: "3.965.5",
464
- resolved: "https://registry.npmjs.org/@aws-sdk/util-locate-window/-/util-locate-window-3.965.5.tgz",
465
- integrity: "sha512-WhlJNNINQB+9qtLtZJcpQdgZw3SCDCpXdUJP7cToGwHbCWCnRckGlc6Bx/OhWwIYFNAn+FIydY8SZ0QmVu3xTQ==",
363
+ "node_modules/@aws-sdk/types": {
364
+ version: "3.974.6",
365
+ resolved: "https://registry.npmjs.org/@aws-sdk/types/-/types-3.974.6.tgz",
366
+ integrity: "sha512-v/clNZzZnDxGyvpHMOGpJKVXFAExJzUNAAjaWGdcx8QAcXLGwTaOkw33p5SHAi0YAioK32xB3hWwOekRVfmfKg==",
466
367
  license: "Apache-2.0",
467
368
  dependencies: {
369
+ "@smithy/types": "^4.19.0",
468
370
  tslib: "^2.6.2"
469
371
  },
470
372
  engines: {
471
373
  node: ">=20.0.0"
472
374
  }
473
375
  },
474
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws-sdk/xml-builder": {
475
- version: "3.972.24",
476
- resolved: "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.972.24.tgz",
477
- integrity: "sha512-V8z5YcDPfsvzrBlj0xR1vhRtocblhYbqdreCJB/voGd4Sr5zjNAeWxexbnqVtskTJe0vFb5KMqbSL++ePl+zRw==",
376
+ "node_modules/@aws-sdk/xml-builder": {
377
+ version: "3.972.41",
378
+ resolved: "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.972.41.tgz",
379
+ integrity: "sha512-ctjVSyCMegrWfXlx6VqzSBFI6UqmQ5ZlnfMhdLIiWmhoH8UAQxSCP5N3OpG7X3k4LnS7ou74C4mt20+bfTW2aQ==",
478
380
  license: "Apache-2.0",
479
381
  dependencies: {
480
- "@nodable/entities": "2.1.0",
481
- "@smithy/types": "^4.14.1",
482
- "fast-xml-parser": "5.7.3",
382
+ "@smithy/types": "^4.19.0",
483
383
  tslib: "^2.6.2"
484
384
  },
485
385
  engines: {
486
386
  node: ">=20.0.0"
487
387
  }
488
388
  },
489
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@aws/lambda-invoke-store": {
490
- version: "0.2.4",
491
- resolved: "https://registry.npmjs.org/@aws/lambda-invoke-store/-/lambda-invoke-store-0.2.4.tgz",
492
- integrity: "sha512-iY8yvjE0y651BixKNPgmv1WrQc+GZ142sb0z4gYnChDDY2YqI4P/jsSopBWrKfAt7LOJAkOXt7rC/hms+WclQQ==",
389
+ "node_modules/@aws/lambda-invoke-store": {
390
+ version: "0.3.0",
391
+ resolved: "https://registry.npmjs.org/@aws/lambda-invoke-store/-/lambda-invoke-store-0.3.0.tgz",
392
+ integrity: "sha512-sl4Bm6yiMNYrZKkqqDFWN0UfnWhlS8ivKxrYl+6t0gCLrqr8y3B2IqZZbFRkfaVVp7C/baApyh71P+LeE1A2sQ==",
493
393
  license: "Apache-2.0",
494
394
  engines: {
495
395
  node: ">=18.0.0"
496
396
  }
497
397
  },
498
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@babel/runtime": {
499
- version: "7.29.2",
500
- resolved: "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.2.tgz",
501
- integrity: "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g==",
398
+ "node_modules/@babel/runtime": {
399
+ version: "7.29.10",
400
+ resolved: "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.10.tgz",
401
+ integrity: "sha512-NpugTzbKgGrNe45Ui32cN8vCFFMxVtP/9rtfwv0nP5FRDAjvYBxJcLVpYA9mr1jxP6cnIT7x9LUzuDTbWYYNRA==",
502
402
  license: "MIT",
503
403
  engines: {
504
404
  node: ">=6.9.0"
505
405
  }
506
406
  },
507
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@earendil-works/pi-agent-core": {
508
- version: "0.83.0",
509
- resolved: "https://registry.npmjs.org/@earendil-works/pi-agent-core/-/pi-agent-core-0.83.0.tgz",
407
+ "node_modules/@earendil-works/pi-agent-core": {
408
+ version: "1.3.0",
409
+ resolved: "https://registry.npmjs.org/@earendil-works/pi-agent-core/-/pi-agent-core-1.3.0.tgz",
410
+ integrity: "sha512-2jvpxZs47PFD5mSQb/yK0pGHJ5yO7Nu22u9mFjHbSLRgu62vZ9rupimDSIp4arnqOadyv0AWvYHtCSpFoJV7ag==",
510
411
  license: "MIT",
511
412
  dependencies: {
512
- "@earendil-works/pi-ai": "^0.83.0",
513
- diff: "8.0.4",
514
- ignore: "7.0.5",
515
- typebox: "1.3.7",
516
- yaml: "2.9.0"
413
+ "@earendil-works/pi-ai": "1.3.0",
414
+ typebox: "1.3.27"
517
415
  },
518
416
  engines: {
519
417
  node: ">=22.19.0"
520
- },
521
- integrity: "sha512-RorGp9OH5l3ElpuC5a5ZQ2eWcchZGXflXRzVGkV99y3y6tT+LLNyxoYIdVKvTKWEObwhExeQbTH0fI2tE4iX4g=="
418
+ }
522
419
  },
523
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@earendil-works/pi-ai": {
524
- version: "0.83.0",
525
- resolved: "https://registry.npmjs.org/@earendil-works/pi-ai/-/pi-ai-0.83.0.tgz",
420
+ "node_modules/@earendil-works/pi-ai": {
421
+ version: "1.3.0",
422
+ resolved: "https://registry.npmjs.org/@earendil-works/pi-ai/-/pi-ai-1.3.0.tgz",
423
+ integrity: "sha512-KaBI8x7q7sPoFUXICNGD9efHzDG+oRNwVvkA9jdIsSQWH1RjFssOlEGsbLtewUPPgCrvmz0l2KTgSLXTyj3acw==",
526
424
  license: "MIT",
527
425
  dependencies: {
528
- "@anthropic-ai/sdk": "0.91.1",
529
- "@aws-sdk/client-bedrock-runtime": "3.1048.0",
530
- "@google/genai": "1.52.0",
531
- "@mistralai/mistralai": "2.2.6",
532
- "@opentelemetry/api": "1.9.0",
533
- "@smithy/node-http-handler": "4.7.3",
534
- "http-proxy-agent": "7.0.2",
535
- "https-proxy-agent": "7.0.6",
536
- openai: "6.26.0",
426
+ "@anthropic-ai/sdk": "0.129.0",
427
+ "@aws-sdk/client-bedrock-runtime": "3.1127.0",
428
+ "@earendil-works/pi-telemetry": "1.3.0",
429
+ "@google/genai": "2.21.0",
430
+ "@smithy/node-http-handler": "4.12.1",
431
+ "http-proxy-agent": "9.1.0",
432
+ "https-proxy-agent": "9.1.0",
433
+ openai: "7.19.0",
537
434
  "partial-json": "0.1.7",
538
- typebox: "1.3.7"
435
+ typebox: "1.3.27"
539
436
  },
540
437
  bin: {
541
438
  "pi-ai": "dist/cli.js"
542
439
  },
543
440
  engines: {
544
441
  node: ">=22.19.0"
545
- },
546
- integrity: "sha512-m3IZD4g3er0V8TC9+Vpgw/sjTKqcJlkcIBy/JvsgRubuuik3tAVzyugUg4rVrShIkkOT69mEd34NEqKUIsl6JQ=="
442
+ }
547
443
  },
548
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@earendil-works/pi-tui": {
549
- version: "0.83.0",
550
- resolved: "https://registry.npmjs.org/@earendil-works/pi-tui/-/pi-tui-0.83.0.tgz",
444
+ "node_modules/@earendil-works/pi-codemode": {
445
+ version: "1.3.0",
446
+ resolved: "https://registry.npmjs.org/@earendil-works/pi-codemode/-/pi-codemode-1.3.0.tgz",
447
+ integrity: "sha512-2G9tmbsPhgzwfz7cmzJpbLSLqOx3eu22Gbzm+Wc3HqeZMjLQS4F3KfAabozVhv7uEjq3k2O1dZTHmhhWr2xbfQ==",
551
448
  license: "MIT",
552
449
  dependencies: {
553
- "get-east-asian-width": "1.6.0",
554
- marked: "18.0.5"
450
+ "quickjs-wasi": "3.6.2"
555
451
  },
556
452
  engines: {
557
453
  node: ">=22.19.0"
558
- },
559
- integrity: "sha512-IoYrb0rORjELmEpNtoCA/U8je3KopMkRAVJRdSzvXRvgb+Huo1gNh8Q5CSZvNOiYtDxJdj2tYZZHZ4B3+IN3hA=="
454
+ }
560
455
  },
561
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@google/genai": {
562
- version: "1.52.0",
563
- resolved: "https://registry.npmjs.org/@google/genai/-/genai-1.52.0.tgz",
564
- integrity: "sha512-gwSvbpiN/17O9TbsqSsE/OzZcpv5Fo4RQjdngGgogtuB9RsyJ8ZHhX5KjHj1bp5N9snN2eK8LDGXSaWW2hof8Q==",
565
- hasInstallScript: true,
566
- license: "Apache-2.0",
456
+ "node_modules/@earendil-works/pi-coding-agent": {
457
+ version: "1.3.0",
458
+ resolved: "https://registry.npmjs.org/@earendil-works/pi-coding-agent/-/pi-coding-agent-1.3.0.tgz",
459
+ integrity: "sha512-V/WoCjA2hQSe3QLWIUB24cTRdtEdeLiIzkDqU5RMXV6VWuD+KGZnzVBMhglwdnQTySkehZsjt8a3g6Jd2g4nnw==",
460
+ license: "MIT",
567
461
  dependencies: {
568
- "google-auth-library": "^10.3.0",
569
- "p-retry": "^4.6.2",
570
- protobufjs: "^7.5.4",
571
- ws: "^8.18.0"
572
- },
573
- engines: {
574
- node: ">=20.0.0"
462
+ "@earendil-works/pi-agent-core": "1.3.0",
463
+ "@earendil-works/pi-ai": "1.3.0",
464
+ "@earendil-works/pi-codemode": "1.3.0",
465
+ "@earendil-works/pi-mcp": "1.3.0",
466
+ "@earendil-works/pi-tui": "1.3.0",
467
+ "@silvia-odwyer/photon-node": "0.3.4",
468
+ "brace-expansion": "5.0.12",
469
+ chalk: "6.0.0",
470
+ "cross-spawn": "7.0.6",
471
+ diff: "8.0.4",
472
+ "grok-mermaid": "0.2.3",
473
+ "highlight.js": "10.7.3",
474
+ "hosted-git-info": "9.0.3",
475
+ ignore: "7.0.8",
476
+ jiti: "2.7.0",
477
+ minimatch: "10.2.6",
478
+ "proper-lockfile": "4.1.2",
479
+ "quickjs-wasi": "3.6.2",
480
+ semver: "7.8.5",
481
+ typebox: "1.3.27",
482
+ undici: "8.10.2",
483
+ yaml: "2.9.0"
575
484
  },
576
- peerDependencies: {
577
- "@modelcontextprotocol/sdk": "^1.25.2"
485
+ bin: {
486
+ pi: "dist/bundle/cli.js"
578
487
  },
579
- peerDependenciesMeta: {
580
- "@modelcontextprotocol/sdk": {
581
- optional: true
582
- }
583
- }
584
- },
585
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@mariozechner/clipboard": {
586
- version: "0.3.9",
587
- resolved: "https://registry.npmjs.org/@mariozechner/clipboard/-/clipboard-0.3.9.tgz",
588
- integrity: "sha512-ABnA53mdfkGZwOFUdZNv2S0CWGO/EIuPj8Vv9xmBFmSYg/qFc7ihO6q5FcQjvoE67kZpWkEc4AhD6B/os04yuA==",
589
- license: "MIT",
590
- optional: true,
591
- engines: {
592
- node: ">= 10"
593
- },
594
- optionalDependencies: {
595
- "@mariozechner/clipboard-darwin-arm64": "0.3.9",
596
- "@mariozechner/clipboard-darwin-universal": "0.3.9",
597
- "@mariozechner/clipboard-darwin-x64": "0.3.9",
598
- "@mariozechner/clipboard-linux-arm64-gnu": "0.3.9",
599
- "@mariozechner/clipboard-linux-arm64-musl": "0.3.9",
600
- "@mariozechner/clipboard-linux-riscv64-gnu": "0.3.9",
601
- "@mariozechner/clipboard-linux-x64-gnu": "0.3.9",
602
- "@mariozechner/clipboard-linux-x64-musl": "0.3.9",
603
- "@mariozechner/clipboard-win32-arm64-msvc": "0.3.9",
604
- "@mariozechner/clipboard-win32-x64-msvc": "0.3.9"
605
- }
606
- },
607
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@mariozechner/clipboard-darwin-arm64": {
608
- version: "0.3.9",
609
- resolved: "https://registry.npmjs.org/@mariozechner/clipboard-darwin-arm64/-/clipboard-darwin-arm64-0.3.9.tgz",
610
- integrity: "sha512-BfgV7vCEWZwJwZJw03r6bP5+tf0iI/ANuQYCxi9RNn7FrWB3yzGuMKCrNLRl6V761vXRdL8+OqZ0wd4TqlsNOQ==",
611
- cpu: [
612
- "arm64"
613
- ],
614
- license: "MIT",
615
- optional: true,
616
- os: [
617
- "darwin"
618
- ],
619
- engines: {
620
- node: ">= 10"
621
- }
622
- },
623
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@mariozechner/clipboard-darwin-universal": {
624
- version: "0.3.9",
625
- resolved: "https://registry.npmjs.org/@mariozechner/clipboard-darwin-universal/-/clipboard-darwin-universal-0.3.9.tgz",
626
- integrity: "sha512-BGGR4iA9Z2shAjI65eI5xtyb3LYNlDW9X3gxKxDbqtbnREohsrqznov6zpKoIrsRWpzlYVEdKphS7ksJ0/ndSQ==",
627
- license: "MIT",
628
- optional: true,
629
- os: [
630
- "darwin"
631
- ],
632
- engines: {
633
- node: ">= 10"
634
- }
635
- },
636
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@mariozechner/clipboard-darwin-x64": {
637
- version: "0.3.9",
638
- resolved: "https://registry.npmjs.org/@mariozechner/clipboard-darwin-x64/-/clipboard-darwin-x64-0.3.9.tgz",
639
- integrity: "sha512-4kURmCbS6nt8uYhtmWpUcJWyPHfmAr5dTpXD1nO3pIfa+TSQ9DbrGOYCKH+aEFW47XhQ4Vp8ZTszie+wfFvDKg==",
640
- cpu: [
641
- "x64"
642
- ],
643
- license: "MIT",
644
- optional: true,
645
- os: [
646
- "darwin"
647
- ],
648
- engines: {
649
- node: ">= 10"
650
- }
651
- },
652
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@mariozechner/clipboard-linux-arm64-gnu": {
653
- version: "0.3.9",
654
- resolved: "https://registry.npmjs.org/@mariozechner/clipboard-linux-arm64-gnu/-/clipboard-linux-arm64-gnu-0.3.9.tgz",
655
- integrity: "sha512-g59OkUGP2DDfCOIKypHeYgv2M55u/cKvXa5dSxFbEJ34XvIQMdcVmpKCkGUro3ZgefXiGVdwguvTMQGpHWzIXw==",
656
- cpu: [
657
- "arm64"
658
- ],
659
- license: "MIT",
660
- optional: true,
661
- os: [
662
- "linux"
663
- ],
664
- engines: {
665
- node: ">= 10"
666
- }
667
- },
668
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@mariozechner/clipboard-linux-arm64-musl": {
669
- version: "0.3.9",
670
- resolved: "https://registry.npmjs.org/@mariozechner/clipboard-linux-arm64-musl/-/clipboard-linux-arm64-musl-0.3.9.tgz",
671
- integrity: "sha512-AGuJdgKsmJdm4Pych7kv3sqe591ERRaAHW3xjLooiFzn8J+PxUyof++7YZrB5Y5tpnTO+K18Og3taj2NpluCRQ==",
672
- cpu: [
673
- "arm64"
674
- ],
675
- license: "MIT",
676
- optional: true,
677
- os: [
678
- "linux"
679
- ],
680
- engines: {
681
- node: ">= 10"
682
- }
683
- },
684
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@mariozechner/clipboard-linux-riscv64-gnu": {
685
- version: "0.3.9",
686
- resolved: "https://registry.npmjs.org/@mariozechner/clipboard-linux-riscv64-gnu/-/clipboard-linux-riscv64-gnu-0.3.9.tgz",
687
- integrity: "sha512-DXBEAiuMpk7dhS1a9NzNxVAFi1vaKoPu7rQNgY8LIDLGrK3lnIp3nT10DUum+PKVJoJppIP+NAA8IZe4DMNDPw==",
688
- cpu: [
689
- "riscv64"
690
- ],
691
- license: "MIT",
692
- optional: true,
693
- os: [
694
- "linux"
695
- ],
696
- engines: {
697
- node: ">= 10"
698
- }
699
- },
700
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@mariozechner/clipboard-linux-x64-gnu": {
701
- version: "0.3.9",
702
- resolved: "https://registry.npmjs.org/@mariozechner/clipboard-linux-x64-gnu/-/clipboard-linux-x64-gnu-0.3.9.tgz",
703
- integrity: "sha512-WORrMLd6EpElEME7JRKfSaY34nW1P5LbdgK5YNCS1ncG2LqmITsSMEJ8nh2mpvxb3TxqbOOKgY7k9eMJYlW9Mw==",
704
- cpu: [
705
- "x64"
706
- ],
707
- license: "MIT",
708
- optional: true,
709
- os: [
710
- "linux"
711
- ],
712
488
  engines: {
713
- node: ">= 10"
489
+ node: ">=22.19.0"
714
490
  }
715
491
  },
716
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@mariozechner/clipboard-linux-x64-musl": {
717
- version: "0.3.9",
718
- resolved: "https://registry.npmjs.org/@mariozechner/clipboard-linux-x64-musl/-/clipboard-linux-x64-musl-0.3.9.tgz",
719
- integrity: "sha512-/DHn+1DrfL6oRaPPWXaOKvonFFrni666fxd+zFqiQEfvBH0tsHVWjq9iqBk0oDp0qaPA72lIMy5BptxISBEhZQ==",
720
- cpu: [
721
- "x64"
722
- ],
492
+ "node_modules/@earendil-works/pi-mcp": {
493
+ version: "1.3.0",
494
+ resolved: "https://registry.npmjs.org/@earendil-works/pi-mcp/-/pi-mcp-1.3.0.tgz",
495
+ integrity: "sha512-lbktLplmdGamM2t460Q0ziNEfpUEHDTVNf79g/AialJ3XZ+SHgNqa/OJXRR+fU+GV/l+gBhRPcyP8XkQlv8Avw==",
723
496
  license: "MIT",
724
- optional: true,
725
- os: [
726
- "linux"
727
- ],
497
+ dependencies: {
498
+ "cross-spawn": "7.0.6"
499
+ },
728
500
  engines: {
729
- node: ">= 10"
501
+ node: ">=22.19.0"
730
502
  }
731
503
  },
732
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@mariozechner/clipboard-win32-arm64-msvc": {
733
- version: "0.3.9",
734
- resolved: "https://registry.npmjs.org/@mariozechner/clipboard-win32-arm64-msvc/-/clipboard-win32-arm64-msvc-0.3.9.tgz",
735
- integrity: "sha512-O5FHD3ErkMwMhNzAfu3ggy0ug4z7btZuoQgwwxlzPrwV2bxlD6WDpqBY4NCgICAgZdDKdp+loUEKVAVt8aYnhQ==",
736
- cpu: [
737
- "arm64"
738
- ],
504
+ "node_modules/@earendil-works/pi-telemetry": {
505
+ version: "1.3.0",
506
+ resolved: "https://registry.npmjs.org/@earendil-works/pi-telemetry/-/pi-telemetry-1.3.0.tgz",
507
+ integrity: "sha512-ERGZr+aXjNJzoUbB7ZzHVH3g5otzMHjHLs2Fyizm12By5X+gBEhod9cJXFOk13S7M8a29Am+Mq21zm73mRJFLg==",
739
508
  license: "MIT",
740
- optional: true,
741
- os: [
742
- "win32"
743
- ],
744
509
  engines: {
745
- node: ">= 10"
510
+ node: ">=22.19.0"
746
511
  }
747
512
  },
748
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@mariozechner/clipboard-win32-x64-msvc": {
749
- version: "0.3.9",
750
- resolved: "https://registry.npmjs.org/@mariozechner/clipboard-win32-x64-msvc/-/clipboard-win32-x64-msvc-0.3.9.tgz",
751
- integrity: "sha512-ihQC3EufqEY81vhXBgVBtK4prL+wc62zJsSvxrgz7K1hsdt6OObz6v9p3Rn1OG3GJksTTKMJF0u/guMISHPhSA==",
752
- cpu: [
753
- "x64"
754
- ],
513
+ "node_modules/@earendil-works/pi-tui": {
514
+ version: "1.3.0",
515
+ resolved: "https://registry.npmjs.org/@earendil-works/pi-tui/-/pi-tui-1.3.0.tgz",
516
+ integrity: "sha512-AlKvEwEWyVtnuw7SVb4N/mUhlfIohyFslUNWarZVdLHHSdt3ca5EhMLwTzblBpDpaofSz+f+tAHie6CfxVrWKA==",
755
517
  license: "MIT",
756
- optional: true,
757
- os: [
758
- "win32"
759
- ],
518
+ dependencies: {
519
+ "get-east-asian-width": "1.6.0",
520
+ marked: "18.0.11"
521
+ },
760
522
  engines: {
761
- node: ">= 10"
523
+ node: ">=22.19.0"
762
524
  }
763
525
  },
764
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@mistralai/mistralai": {
765
- version: "2.2.6",
766
- resolved: "https://registry.npmjs.org/@mistralai/mistralai/-/mistralai-2.2.6.tgz",
767
- integrity: "sha512-W8pX7zHxjJvMIpw8JMxeJEleapXX0Q9NPszdNzqkM3MIEoIGPObdodujj+WHteXEvGfaP/AMwlNyRfEzSY6dQQ==",
526
+ "node_modules/@google/genai": {
527
+ version: "2.21.0",
528
+ resolved: "https://registry.npmjs.org/@google/genai/-/genai-2.21.0.tgz",
529
+ integrity: "sha512-+PDtco2/Z0ONdzCGekCoCT+O1VJS9xJQNN4XzQpXG/t3El/SWWMkCWlFRO1KmivOHPa4Q0VjUYu1HBKCZ/v33Q==",
530
+ hasInstallScript: true,
768
531
  license: "Apache-2.0",
769
532
  dependencies: {
770
- "@opentelemetry/semantic-conventions": "^1.40.0",
771
- ws: "^8.18.0",
772
- zod: "^3.25.0 || ^4.0.0",
773
- "zod-to-json-schema": "^3.25.0"
533
+ "google-auth-library": "^10.3.0",
534
+ "p-retry": "^4.6.2",
535
+ protobufjs: "^7.5.4",
536
+ ws: "^8.18.0"
537
+ },
538
+ engines: {
539
+ node: ">=20.0.0"
774
540
  },
775
541
  peerDependencies: {
776
- "@opentelemetry/api": "^1.9.0"
542
+ "@modelcontextprotocol/sdk": "^1.25.2"
777
543
  },
778
544
  peerDependenciesMeta: {
779
- "@opentelemetry/api": {
545
+ "@modelcontextprotocol/sdk": {
780
546
  optional: true
781
547
  }
782
548
  }
783
549
  },
784
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@nodable/entities": {
785
- version: "2.1.0",
786
- resolved: "https://registry.npmjs.org/@nodable/entities/-/entities-2.1.0.tgz",
787
- integrity: "sha512-nyT7T3nbMyBI/lvr6L5TyWbFJAI9FTgVRakNoBqCD+PmID8DzFrrNdLLtHMwMszOtqZa8PAOV24ZqDnQrhQINA==",
788
- funding: [
789
- {
790
- type: "github",
791
- url: "https://github.com/sponsors/nodable"
792
- }
793
- ],
794
- license: "MIT"
795
- },
796
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@opentelemetry/api": {
797
- version: "1.9.0",
798
- resolved: "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.0.tgz",
799
- integrity: "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==",
800
- license: "Apache-2.0",
801
- engines: {
802
- node: ">=8.0.0"
803
- }
804
- },
805
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@opentelemetry/semantic-conventions": {
806
- version: "1.41.1",
807
- resolved: "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.41.1.tgz",
808
- integrity: "sha512-/UhIkaZgPutTFmQ7RnIJGgDXZmtEJ7Dvi86xNTFWcnRxVRNk/aotsqDJYeEvDP+FSMB2SdW+pQzNMcWP0rwuNA==",
809
- license: "Apache-2.0",
810
- engines: {
811
- node: ">=14"
812
- }
813
- },
814
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@protobufjs/aspromise": {
550
+ "node_modules/@protobufjs/aspromise": {
815
551
  version: "1.1.2",
816
552
  resolved: "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz",
817
553
  integrity: "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==",
818
554
  license: "BSD-3-Clause"
819
555
  },
820
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@protobufjs/base64": {
556
+ "node_modules/@protobufjs/base64": {
821
557
  version: "1.1.2",
822
558
  resolved: "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz",
823
559
  integrity: "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==",
824
560
  license: "BSD-3-Clause"
825
561
  },
826
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@protobufjs/codegen": {
562
+ "node_modules/@protobufjs/codegen": {
827
563
  version: "2.0.5",
828
564
  resolved: "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz",
829
565
  integrity: "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==",
830
566
  license: "BSD-3-Clause"
831
567
  },
832
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@protobufjs/eventemitter": {
568
+ "node_modules/@protobufjs/eventemitter": {
833
569
  version: "1.1.1",
834
570
  resolved: "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz",
835
571
  integrity: "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==",
836
572
  license: "BSD-3-Clause"
837
573
  },
838
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@protobufjs/fetch": {
574
+ "node_modules/@protobufjs/fetch": {
839
575
  version: "1.1.1",
840
576
  resolved: "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz",
841
577
  integrity: "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==",
@@ -844,122 +580,109 @@ var default_pi_package_lock_default = {
844
580
  "@protobufjs/aspromise": "^1.1.1"
845
581
  }
846
582
  },
847
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@protobufjs/float": {
583
+ "node_modules/@protobufjs/float": {
848
584
  version: "1.0.2",
849
585
  resolved: "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz",
850
586
  integrity: "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==",
851
587
  license: "BSD-3-Clause"
852
588
  },
853
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@protobufjs/path": {
589
+ "node_modules/@protobufjs/path": {
854
590
  version: "1.1.2",
855
591
  resolved: "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz",
856
592
  integrity: "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==",
857
593
  license: "BSD-3-Clause"
858
594
  },
859
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@protobufjs/pool": {
595
+ "node_modules/@protobufjs/pool": {
860
596
  version: "1.1.0",
861
597
  resolved: "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz",
862
598
  integrity: "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==",
863
599
  license: "BSD-3-Clause"
864
600
  },
865
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@protobufjs/utf8": {
866
- version: "1.1.1",
867
- resolved: "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.1.tgz",
868
- integrity: "sha512-oOAWABowe8EAbMyWKM0tYDKi8Yaox52D+HWZhAIJqQXbqe0xI/GV7FhLWqlEKreMkfDjshR5FKgi3mnle0h6Eg==",
601
+ "node_modules/@protobufjs/utf8": {
602
+ version: "1.1.2",
603
+ resolved: "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.2.tgz",
604
+ integrity: "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==",
869
605
  license: "BSD-3-Clause"
870
606
  },
871
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@silvia-odwyer/photon-node": {
607
+ "node_modules/@silvia-odwyer/photon-node": {
872
608
  version: "0.3.4",
873
609
  resolved: "https://registry.npmjs.org/@silvia-odwyer/photon-node/-/photon-node-0.3.4.tgz",
874
610
  integrity: "sha512-bnly4BKB3KDTFxrUIcgCLbaeVVS8lrAkri1pEzskpmxu9MdfGQTy8b8EgcD83ywD3RPMsIulY8xJH5Awa+t9fA==",
875
611
  license: "Apache-2.0"
876
612
  },
877
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@smithy/core": {
878
- version: "3.24.3",
879
- resolved: "https://registry.npmjs.org/@smithy/core/-/core-3.24.3.tgz",
880
- integrity: "sha512-Ep/7tPamGY8mgESE3LyLKtxJyy6U52WWAqr/3wial47Sj4u3PiIF73AOGI27UyLy9duTkhZbgzodOfLV4TduZg==",
613
+ "node_modules/@smithy/core": {
614
+ version: "3.36.0",
615
+ resolved: "https://registry.npmjs.org/@smithy/core/-/core-3.36.0.tgz",
616
+ integrity: "sha512-3hJiwG1F5t1SoXqp/yOCmYXziyx7ZVqF63S5W6YU201e/qwVaHPex+E/3vvyY9a3ORq/b+BydeNZpP2saQ9X2g==",
881
617
  license: "Apache-2.0",
882
618
  dependencies: {
883
- "@aws-crypto/crc32": "5.2.0",
884
- "@smithy/types": "^4.14.2",
619
+ "@smithy/types": "^4.19.0",
885
620
  tslib: "^2.6.2"
886
621
  },
887
622
  engines: {
888
623
  node: ">=18.0.0"
889
624
  }
890
625
  },
891
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@smithy/credential-provider-imds": {
892
- version: "4.3.3",
893
- resolved: "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.3.3.tgz",
894
- integrity: "sha512-I2Bti0DKFo2IJyN28ijCsx51BAumEYR4/1yZ1FXyBygy9MqbnMqCev4JPth/MbpRfBSRAX35hITSnAdJRo1u5w==",
626
+ "node_modules/@smithy/credential-provider-imds": {
627
+ version: "4.5.2",
628
+ resolved: "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.5.2.tgz",
629
+ integrity: "sha512-A9uSdn72ozbRUSit0eib0TW7nXuNPlaeM0zcGkJ+nE6tFcSDbnmtwoxbTCFBukVQcszDAyvsd7+rTduPTXpygg==",
895
630
  license: "Apache-2.0",
896
631
  dependencies: {
897
- "@smithy/core": "^3.24.3",
898
- "@smithy/types": "^4.14.2",
632
+ "@smithy/core": "^3.33.2",
633
+ "@smithy/types": "^4.17.2",
899
634
  tslib: "^2.6.2"
900
635
  },
901
636
  engines: {
902
637
  node: ">=18.0.0"
903
638
  }
904
639
  },
905
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@smithy/fetch-http-handler": {
906
- version: "5.4.3",
907
- resolved: "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.4.3.tgz",
908
- integrity: "sha512-F+DRf8IJazRJgYog2A/yJK7eYVc0rqTlRzO+5ZxjJd4WkZoKz0IJRncf7G6t1pdVT3kryJcwuTFhN1c5m6N47A==",
640
+ "node_modules/@smithy/fetch-http-handler": {
641
+ version: "5.8.0",
642
+ resolved: "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.8.0.tgz",
643
+ integrity: "sha512-ycSJu3tFAQ4v04CBB0agqFMVsSQ1iG3yw+SpgxRqKfaURpQD4CZ8Wn0zPMmSnOuTpTh65Vz+EA0rMrw089wvkA==",
909
644
  license: "Apache-2.0",
910
645
  dependencies: {
911
- "@smithy/core": "^3.24.3",
912
- "@smithy/types": "^4.14.2",
646
+ "@smithy/core": "^3.33.3",
647
+ "@smithy/types": "^4.18.0",
913
648
  tslib: "^2.6.2"
914
649
  },
915
650
  engines: {
916
651
  node: ">=18.0.0"
917
652
  }
918
653
  },
919
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@smithy/is-array-buffer": {
920
- version: "2.2.0",
921
- resolved: "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-2.2.0.tgz",
922
- integrity: "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA==",
923
- license: "Apache-2.0",
924
- dependencies: {
925
- tslib: "^2.6.2"
926
- },
927
- engines: {
928
- node: ">=14.0.0"
929
- }
930
- },
931
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@smithy/node-http-handler": {
932
- version: "4.7.3",
933
- resolved: "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.7.3.tgz",
934
- integrity: "sha512-/jPhevcTFPMVl6KNjbaI47iOg1zxC7IsnX4PQDGVZKMFceOXtB8IEYaB7a9VvkP/3oC60WzTeKocvSI7vLT0vA==",
654
+ "node_modules/@smithy/node-http-handler": {
655
+ version: "4.12.1",
656
+ resolved: "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.12.1.tgz",
657
+ integrity: "sha512-ThMkboGeONWXAelq9FvGsuJC4rOi+qyC4/zhUF58xYpxUg5sQKx2VXZYJmtNjr4dSuBJ1HeJXETQILCz3wOHvw==",
935
658
  license: "Apache-2.0",
936
659
  dependencies: {
937
- "@smithy/core": "^3.24.3",
938
- "@smithy/types": "^4.14.2",
660
+ "@smithy/core": "^3.33.3",
661
+ "@smithy/types": "^4.18.0",
939
662
  tslib: "^2.6.2"
940
663
  },
941
664
  engines: {
942
665
  node: ">=18.0.0"
943
666
  }
944
667
  },
945
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@smithy/signature-v4": {
946
- version: "5.4.3",
947
- resolved: "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.4.3.tgz",
948
- integrity: "sha512-53+75QuPl6DL+ct6vVEB51FDO5oulXr20TPV46VvJZg76lIlXNWfxi8j+G2V/t0I2qxCBOa3vX/8bmjrpFVo9g==",
668
+ "node_modules/@smithy/signature-v4": {
669
+ version: "5.7.4",
670
+ resolved: "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.7.4.tgz",
671
+ integrity: "sha512-tHy0K0VtqNd5Y7Y41h0a0Lhh0L1GzC08dTWg0F7vRJWFtTENg7IZikf3wQkanYIRdb7ngoIPMTmqgUi401fEeQ==",
949
672
  license: "Apache-2.0",
950
673
  dependencies: {
951
- "@smithy/core": "^3.24.3",
952
- "@smithy/types": "^4.14.2",
674
+ "@smithy/core": "^3.35.0",
675
+ "@smithy/types": "^4.19.0",
953
676
  tslib: "^2.6.2"
954
677
  },
955
678
  engines: {
956
679
  node: ">=18.0.0"
957
680
  }
958
681
  },
959
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@smithy/types": {
960
- version: "4.14.2",
961
- resolved: "https://registry.npmjs.org/@smithy/types/-/types-4.14.2.tgz",
962
- integrity: "sha512-P+otAxbV4CqBybp7EkcJCrig63yE2E7PuNVOmilVMRcx/O+QDzGULTrKsq4DV13gSfak9ObPrWaHl/9bL5YcWw==",
682
+ "node_modules/@smithy/types": {
683
+ version: "4.19.0",
684
+ resolved: "https://registry.npmjs.org/@smithy/types/-/types-4.19.0.tgz",
685
+ integrity: "sha512-r7jh49VJxGerfAcTQA6gXcKc+98zOp/tqRwzYjgOE+iSQsP6cEU1hq2QzbuipmP68QtYdY9wKEhiCQZIzHgZ4Q==",
963
686
  license: "Apache-2.0",
964
687
  dependencies: {
965
688
  tslib: "^2.6.2"
@@ -968,51 +691,37 @@ var default_pi_package_lock_default = {
968
691
  node: ">=18.0.0"
969
692
  }
970
693
  },
971
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@smithy/util-buffer-from": {
972
- version: "2.2.0",
973
- resolved: "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-2.2.0.tgz",
974
- integrity: "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA==",
975
- license: "Apache-2.0",
976
- dependencies: {
977
- "@smithy/is-array-buffer": "^2.2.0",
978
- tslib: "^2.6.2"
979
- },
980
- engines: {
981
- node: ">=14.0.0"
982
- }
983
- },
984
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@smithy/util-utf8": {
985
- version: "2.3.0",
986
- resolved: "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-2.3.0.tgz",
987
- integrity: "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A==",
988
- license: "Apache-2.0",
989
- dependencies: {
990
- "@smithy/util-buffer-from": "^2.2.0",
991
- tslib: "^2.6.2"
992
- },
993
- engines: {
994
- node: ">=14.0.0"
995
- }
694
+ "node_modules/@stablelib/base64": {
695
+ version: "1.0.1",
696
+ resolved: "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz",
697
+ integrity: "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==",
698
+ license: "MIT"
996
699
  },
997
- "node_modules/@earendil-works/pi-coding-agent/node_modules/@types/node": {
998
- version: "22.19.19",
999
- resolved: "https://registry.npmjs.org/@types/node/-/node-22.19.19.tgz",
1000
- integrity: "sha512-dyh/xO2Fh5bYrfWaaqGrRQQGkNdmYw6AmaAUvYeUMNTWQtvb796ikLdmTchRmOlOiIJ1TDXfWgVx1QkUlQ6Hew==",
700
+ "node_modules/@types/node": {
701
+ version: "26.6.5",
702
+ resolved: "https://registry.npmjs.org/@types/node/-/node-26.6.5.tgz",
703
+ integrity: "sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==",
1001
704
  license: "MIT",
1002
705
  dependencies: {
1003
- "undici-types": "~6.21.0"
706
+ "undici-types": "~8.9.0"
1004
707
  }
1005
708
  },
1006
- "node_modules/@earendil-works/pi-coding-agent/node_modules/agent-base": {
1007
- version: "7.1.4",
1008
- resolved: "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
1009
- integrity: "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",
709
+ "node_modules/@types/retry": {
710
+ version: "0.12.0",
711
+ resolved: "https://registry.npmjs.org/@types/retry/-/retry-0.12.0.tgz",
712
+ integrity: "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==",
713
+ license: "MIT"
714
+ },
715
+ "node_modules/agent-base": {
716
+ version: "9.0.0",
717
+ resolved: "https://registry.npmjs.org/agent-base/-/agent-base-9.0.0.tgz",
718
+ integrity: "sha512-TQf59BsZnytt8GdJKLPfUZ54g/iaUL2OWDSFCCvMOhsHduDQxO8xC4PNeyIkVcA5KwL2phPSv0douC0fgWzmnA==",
1010
719
  license: "MIT",
1011
720
  engines: {
1012
- node: ">= 14"
721
+ node: ">= 20"
1013
722
  }
1014
723
  },
1015
- "node_modules/@earendil-works/pi-coding-agent/node_modules/balanced-match": {
724
+ "node_modules/balanced-match": {
1016
725
  version: "4.0.4",
1017
726
  resolved: "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",
1018
727
  integrity: "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",
@@ -1021,7 +730,7 @@ var default_pi_package_lock_default = {
1021
730
  node: "18 || 20 || >=22"
1022
731
  }
1023
732
  },
1024
- "node_modules/@earendil-works/pi-coding-agent/node_modules/base64-js": {
733
+ "node_modules/base64-js": {
1025
734
  version: "1.5.1",
1026
735
  resolved: "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
1027
736
  integrity: "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
@@ -1041,7 +750,7 @@ var default_pi_package_lock_default = {
1041
750
  ],
1042
751
  license: "MIT"
1043
752
  },
1044
- "node_modules/@earendil-works/pi-coding-agent/node_modules/bignumber.js": {
753
+ "node_modules/bignumber.js": {
1045
754
  version: "9.3.1",
1046
755
  resolved: "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.3.1.tgz",
1047
756
  integrity: "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==",
@@ -1050,43 +759,43 @@ var default_pi_package_lock_default = {
1050
759
  node: "*"
1051
760
  }
1052
761
  },
1053
- "node_modules/@earendil-works/pi-coding-agent/node_modules/bowser": {
762
+ "node_modules/bowser": {
1054
763
  version: "2.14.1",
1055
764
  resolved: "https://registry.npmjs.org/bowser/-/bowser-2.14.1.tgz",
1056
765
  integrity: "sha512-tzPjzCxygAKWFOJP011oxFHs57HzIhOEracIgAePE4pqB3LikALKnSzUyU4MGs9/iCEUuHlAJTjTc5M+u7YEGg==",
1057
766
  license: "MIT"
1058
767
  },
1059
- "node_modules/@earendil-works/pi-coding-agent/node_modules/brace-expansion": {
1060
- version: "5.0.7",
1061
- resolved: "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.7.tgz",
1062
- integrity: "sha512-7oFy703dxfY3/NLxC1fh2SUCQ0H9rmAY+5EpDVfXjUTTs+HEwR2nYaqLv+GWcTsumwxPfiz6CzCNkwXwBUwqCA==",
768
+ "node_modules/brace-expansion": {
769
+ version: "5.0.12",
770
+ resolved: "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz",
771
+ integrity: "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==",
1063
772
  license: "MIT",
1064
773
  dependencies: {
1065
774
  "balanced-match": "^4.0.2"
1066
775
  },
1067
776
  engines: {
1068
- node: "18 || 20 || >=22"
777
+ node: "20 || >=22"
1069
778
  }
1070
779
  },
1071
- "node_modules/@earendil-works/pi-coding-agent/node_modules/buffer-equal-constant-time": {
780
+ "node_modules/buffer-equal-constant-time": {
1072
781
  version: "1.0.1",
1073
782
  resolved: "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
1074
783
  integrity: "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",
1075
784
  license: "BSD-3-Clause"
1076
785
  },
1077
- "node_modules/@earendil-works/pi-coding-agent/node_modules/chalk": {
1078
- version: "5.6.2",
1079
- resolved: "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz",
1080
- integrity: "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==",
786
+ "node_modules/chalk": {
787
+ version: "6.0.0",
788
+ resolved: "https://registry.npmjs.org/chalk/-/chalk-6.0.0.tgz",
789
+ integrity: "sha512-2uNTXIuTTxk7ciZgAU1BQcgnchcG0xXnrs6jzkQfj9SsRa9M2s5zE8WT96hS6KmG4MzWHSrvH43DF1m4XRkrFg==",
1081
790
  license: "MIT",
1082
791
  engines: {
1083
- node: "^12.17.0 || ^14.13 || >=16.0.0"
792
+ node: ">=22"
1084
793
  },
1085
794
  funding: {
1086
795
  url: "https://github.com/chalk/chalk"
1087
796
  }
1088
797
  },
1089
- "node_modules/@earendil-works/pi-coding-agent/node_modules/cross-spawn": {
798
+ "node_modules/cross-spawn": {
1090
799
  version: "7.0.6",
1091
800
  resolved: "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
1092
801
  integrity: "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
@@ -1100,7 +809,7 @@ var default_pi_package_lock_default = {
1100
809
  node: ">= 8"
1101
810
  }
1102
811
  },
1103
- "node_modules/@earendil-works/pi-coding-agent/node_modules/data-uri-to-buffer": {
812
+ "node_modules/data-uri-to-buffer": {
1104
813
  version: "4.0.1",
1105
814
  resolved: "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz",
1106
815
  integrity: "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==",
@@ -1109,7 +818,7 @@ var default_pi_package_lock_default = {
1109
818
  node: ">= 12"
1110
819
  }
1111
820
  },
1112
- "node_modules/@earendil-works/pi-coding-agent/node_modules/debug": {
821
+ "node_modules/debug": {
1113
822
  version: "4.4.3",
1114
823
  resolved: "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
1115
824
  integrity: "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
@@ -1126,7 +835,7 @@ var default_pi_package_lock_default = {
1126
835
  }
1127
836
  }
1128
837
  },
1129
- "node_modules/@earendil-works/pi-coding-agent/node_modules/diff": {
838
+ "node_modules/diff": {
1130
839
  version: "8.0.4",
1131
840
  resolved: "https://registry.npmjs.org/diff/-/diff-8.0.4.tgz",
1132
841
  integrity: "sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw==",
@@ -1135,7 +844,7 @@ var default_pi_package_lock_default = {
1135
844
  node: ">=0.3.1"
1136
845
  }
1137
846
  },
1138
- "node_modules/@earendil-works/pi-coding-agent/node_modules/ecdsa-sig-formatter": {
847
+ "node_modules/ecdsa-sig-formatter": {
1139
848
  version: "1.0.11",
1140
849
  resolved: "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
1141
850
  integrity: "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",
@@ -1144,50 +853,19 @@ var default_pi_package_lock_default = {
1144
853
  "safe-buffer": "^5.0.1"
1145
854
  }
1146
855
  },
1147
- "node_modules/@earendil-works/pi-coding-agent/node_modules/extend": {
856
+ "node_modules/extend": {
1148
857
  version: "3.0.2",
1149
858
  resolved: "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",
1150
859
  integrity: "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",
1151
860
  license: "MIT"
1152
861
  },
1153
- "node_modules/@earendil-works/pi-coding-agent/node_modules/fast-xml-builder": {
1154
- version: "1.2.0",
1155
- resolved: "https://registry.npmjs.org/fast-xml-builder/-/fast-xml-builder-1.2.0.tgz",
1156
- integrity: "sha512-00aAWieqff+ZJhsXA4g1g7M8k+7AYoMUUHF+/zFb5U6Uv/P0Vl4QZo84/IcufzYalLuEj9928bXN9PbbFzMF0Q==",
1157
- funding: [
1158
- {
1159
- type: "github",
1160
- url: "https://github.com/sponsors/NaturalIntelligence"
1161
- }
1162
- ],
1163
- license: "MIT",
1164
- dependencies: {
1165
- "path-expression-matcher": "^1.5.0",
1166
- "xml-naming": "^0.1.0"
1167
- }
862
+ "node_modules/fast-sha256": {
863
+ version: "1.3.0",
864
+ resolved: "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz",
865
+ integrity: "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==",
866
+ license: "Unlicense"
1168
867
  },
1169
- "node_modules/@earendil-works/pi-coding-agent/node_modules/fast-xml-parser": {
1170
- version: "5.7.3",
1171
- resolved: "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.7.3.tgz",
1172
- integrity: "sha512-C0AaNuC+mscy6vrAQKAc/rMq+zAPHodfHGZu4sGVehvAQt/JLG1O5zEcYcXSY5zSqr4YVgxsB+pHXTq0i7eDlg==",
1173
- funding: [
1174
- {
1175
- type: "github",
1176
- url: "https://github.com/sponsors/NaturalIntelligence"
1177
- }
1178
- ],
1179
- license: "MIT",
1180
- dependencies: {
1181
- "@nodable/entities": "^2.1.0",
1182
- "fast-xml-builder": "^1.1.7",
1183
- "path-expression-matcher": "^1.5.0",
1184
- strnum: "^2.2.3"
1185
- },
1186
- bin: {
1187
- fxparser: "src/cli/cli.js"
1188
- }
1189
- },
1190
- "node_modules/@earendil-works/pi-coding-agent/node_modules/fetch-blob": {
868
+ "node_modules/fetch-blob": {
1191
869
  version: "3.2.0",
1192
870
  resolved: "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz",
1193
871
  integrity: "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==",
@@ -1210,7 +888,7 @@ var default_pi_package_lock_default = {
1210
888
  node: "^12.20 || >= 14.13"
1211
889
  }
1212
890
  },
1213
- "node_modules/@earendil-works/pi-coding-agent/node_modules/formdata-polyfill": {
891
+ "node_modules/formdata-polyfill": {
1214
892
  version: "4.0.10",
1215
893
  resolved: "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz",
1216
894
  integrity: "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==",
@@ -1222,10 +900,10 @@ var default_pi_package_lock_default = {
1222
900
  node: ">=12.20.0"
1223
901
  }
1224
902
  },
1225
- "node_modules/@earendil-works/pi-coding-agent/node_modules/gaxios": {
1226
- version: "7.1.4",
1227
- resolved: "https://registry.npmjs.org/gaxios/-/gaxios-7.1.4.tgz",
1228
- integrity: "sha512-bTIgTsM2bWn3XklZISBTQX7ZSddGW+IO3bMdGaemHZ3tbqExMENHLx6kKZ/KlejgrMtj8q7wBItt51yegqalrA==",
903
+ "node_modules/gaxios": {
904
+ version: "7.3.1",
905
+ resolved: "https://registry.npmjs.org/gaxios/-/gaxios-7.3.1.tgz",
906
+ integrity: "sha512-kB3rzJV7d9juLZh8/56QTXCwQfxyhdOMdyYk1HdQKFtF8TJTDTZQJtixWIwXdE9Jji91mC41DUNpjleo4L4eAQ==",
1229
907
  license: "Apache-2.0",
1230
908
  dependencies: {
1231
909
  extend: "^3.0.2",
@@ -1236,7 +914,29 @@ var default_pi_package_lock_default = {
1236
914
  node: ">=18"
1237
915
  }
1238
916
  },
1239
- "node_modules/@earendil-works/pi-coding-agent/node_modules/gcp-metadata": {
917
+ "node_modules/gaxios/node_modules/agent-base": {
918
+ version: "7.1.4",
919
+ resolved: "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
920
+ integrity: "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",
921
+ license: "MIT",
922
+ engines: {
923
+ node: ">= 14"
924
+ }
925
+ },
926
+ "node_modules/gaxios/node_modules/https-proxy-agent": {
927
+ version: "7.0.6",
928
+ resolved: "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
929
+ integrity: "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
930
+ license: "MIT",
931
+ dependencies: {
932
+ "agent-base": "^7.1.2",
933
+ debug: "4"
934
+ },
935
+ engines: {
936
+ node: ">= 14"
937
+ }
938
+ },
939
+ "node_modules/gcp-metadata": {
1240
940
  version: "8.1.2",
1241
941
  resolved: "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-8.1.2.tgz",
1242
942
  integrity: "sha512-zV/5HKTfCeKWnxG0Dmrw51hEWFGfcF2xiXqcA3+J90WDuP0SvoiSO5ORvcBsifmx/FoIjgQN3oNOGaQ5PhLFkg==",
@@ -1250,7 +950,7 @@ var default_pi_package_lock_default = {
1250
950
  node: ">=18"
1251
951
  }
1252
952
  },
1253
- "node_modules/@earendil-works/pi-coding-agent/node_modules/get-east-asian-width": {
953
+ "node_modules/get-east-asian-width": {
1254
954
  version: "1.6.0",
1255
955
  resolved: "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.6.0.tgz",
1256
956
  integrity: "sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA==",
@@ -1262,27 +962,10 @@ var default_pi_package_lock_default = {
1262
962
  url: "https://github.com/sponsors/sindresorhus"
1263
963
  }
1264
964
  },
1265
- "node_modules/@earendil-works/pi-coding-agent/node_modules/glob": {
1266
- version: "13.0.6",
1267
- resolved: "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz",
1268
- integrity: "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==",
1269
- license: "BlueOak-1.0.0",
1270
- dependencies: {
1271
- minimatch: "^10.2.2",
1272
- minipass: "^7.1.3",
1273
- "path-scurry": "^2.0.2"
1274
- },
1275
- engines: {
1276
- node: "18 || 20 || >=22"
1277
- },
1278
- funding: {
1279
- url: "https://github.com/sponsors/isaacs"
1280
- }
1281
- },
1282
- "node_modules/@earendil-works/pi-coding-agent/node_modules/google-auth-library": {
1283
- version: "10.6.2",
1284
- resolved: "https://registry.npmjs.org/google-auth-library/-/google-auth-library-10.6.2.tgz",
1285
- integrity: "sha512-e27Z6EThmVNNvtYASwQxose/G57rkRuaRbQyxM2bvYLLX/GqWZ5chWq2EBoUchJbCc57eC9ArzO5wMsEmWftCw==",
965
+ "node_modules/google-auth-library": {
966
+ version: "10.9.1",
967
+ resolved: "https://registry.npmjs.org/google-auth-library/-/google-auth-library-10.9.1.tgz",
968
+ integrity: "sha512-i1ydyHrqcIxXkWh/uBmVkzCvIuq5yiK2ATndIe5XxKholrG/MTYP9xGYka4sQhrbIAgGjL2B6NOE7rFaiF3fXw==",
1286
969
  license: "Apache-2.0",
1287
970
  dependencies: {
1288
971
  "base64-js": "^1.3.0",
@@ -1296,7 +979,7 @@ var default_pi_package_lock_default = {
1296
979
  node: ">=18"
1297
980
  }
1298
981
  },
1299
- "node_modules/@earendil-works/pi-coding-agent/node_modules/google-logging-utils": {
982
+ "node_modules/google-logging-utils": {
1300
983
  version: "1.1.3",
1301
984
  resolved: "https://registry.npmjs.org/google-logging-utils/-/google-logging-utils-1.1.3.tgz",
1302
985
  integrity: "sha512-eAmLkjDjAFCVXg7A1unxHsLf961m6y17QFqXqAXGj/gVkKFrEICfStRfwUlGNfeCEjNRa32JEWOUTlYXPyyKvA==",
@@ -1305,13 +988,22 @@ var default_pi_package_lock_default = {
1305
988
  node: ">=14"
1306
989
  }
1307
990
  },
1308
- "node_modules/@earendil-works/pi-coding-agent/node_modules/graceful-fs": {
991
+ "node_modules/graceful-fs": {
1309
992
  version: "4.2.11",
1310
993
  resolved: "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
1311
994
  integrity: "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
1312
995
  license: "ISC"
1313
996
  },
1314
- "node_modules/@earendil-works/pi-coding-agent/node_modules/highlight.js": {
997
+ "node_modules/grok-mermaid": {
998
+ version: "0.2.3",
999
+ resolved: "https://registry.npmjs.org/grok-mermaid/-/grok-mermaid-0.2.3.tgz",
1000
+ integrity: "sha512-/4KopAbsjvuRP9MdPtlDjOHUmUVEohOX73JNcsWpzAtFxh+bq5+Dhb6gzvRieLDwIPQIR3/vy8V1NNTuz4Zsmg==",
1001
+ license: "Apache-2.0",
1002
+ engines: {
1003
+ node: ">=18"
1004
+ }
1005
+ },
1006
+ "node_modules/highlight.js": {
1315
1007
  version: "10.7.3",
1316
1008
  resolved: "https://registry.npmjs.org/highlight.js/-/highlight.js-10.7.3.tgz",
1317
1009
  integrity: "sha512-tzcUFauisWKNHaRkN4Wjl/ZA07gENAjFl3J/c480dprkGTg5EQstgaNFqBfUqCq54kZRIEcreTsAgF/m2quD7A==",
@@ -1320,7 +1012,7 @@ var default_pi_package_lock_default = {
1320
1012
  node: "*"
1321
1013
  }
1322
1014
  },
1323
- "node_modules/@earendil-works/pi-coding-agent/node_modules/hosted-git-info": {
1015
+ "node_modules/hosted-git-info": {
1324
1016
  version: "9.0.3",
1325
1017
  resolved: "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-9.0.3.tgz",
1326
1018
  integrity: "sha512-Hc+ghLoSt6QaYZUv0WBiIvmMDZuZZ7oaDvdH8MbfOO4lOsxdXLEvuC6ePoGs9H1X9oCLyq6+NVN0MKqD+ydxyg==",
@@ -1332,48 +1024,50 @@ var default_pi_package_lock_default = {
1332
1024
  node: "^20.17.0 || >=22.9.0"
1333
1025
  }
1334
1026
  },
1335
- "node_modules/@earendil-works/pi-coding-agent/node_modules/http-proxy-agent": {
1336
- version: "7.0.2",
1337
- resolved: "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",
1338
- integrity: "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==",
1027
+ "node_modules/http-proxy-agent": {
1028
+ version: "9.1.0",
1029
+ resolved: "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-9.1.0.tgz",
1030
+ integrity: "sha512-2NxoveTT58mjYT4n3RPTEfCZGLMbidoO8XEieXfpSYxu+PQJ1qpx4ypwH6N+uF9twBPIvRRgvkvW5HUTYWENig==",
1339
1031
  license: "MIT",
1340
1032
  dependencies: {
1341
- "agent-base": "^7.1.0",
1342
- debug: "^4.3.4"
1033
+ "agent-base": "9.0.0",
1034
+ debug: "^4.3.4",
1035
+ "proxy-agent-negotiate": "1.1.0"
1343
1036
  },
1344
1037
  engines: {
1345
- node: ">= 14"
1038
+ node: ">= 20"
1346
1039
  }
1347
1040
  },
1348
- "node_modules/@earendil-works/pi-coding-agent/node_modules/https-proxy-agent": {
1349
- version: "7.0.6",
1350
- resolved: "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
1351
- integrity: "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
1041
+ "node_modules/https-proxy-agent": {
1042
+ version: "9.1.0",
1043
+ resolved: "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-9.1.0.tgz",
1044
+ integrity: "sha512-ag87y7cJJ9/3+GxFr8Oy4O5faDsGRGnBGsJj/YjOSsSx/5eadKLYTMPlzuR6obgoCDDm0abAAZitXXQkMOPSpA==",
1352
1045
  license: "MIT",
1353
1046
  dependencies: {
1354
- "agent-base": "^7.1.2",
1355
- debug: "4"
1047
+ "agent-base": "9.0.0",
1048
+ debug: "^4.3.4",
1049
+ "proxy-agent-negotiate": "1.1.0"
1356
1050
  },
1357
1051
  engines: {
1358
- node: ">= 14"
1052
+ node: ">= 20"
1359
1053
  }
1360
1054
  },
1361
- "node_modules/@earendil-works/pi-coding-agent/node_modules/ignore": {
1362
- version: "7.0.5",
1363
- resolved: "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz",
1364
- integrity: "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==",
1055
+ "node_modules/ignore": {
1056
+ version: "7.0.8",
1057
+ resolved: "https://registry.npmjs.org/ignore/-/ignore-7.0.8.tgz",
1058
+ integrity: "sha512-YYNsSlXBjMk92SKnkwvB5LOVSa6OznlFUGcsvrFgNJbJCd0M1XKeFVRc8ZByeCqz32FivYNHJVooLmdqrmvp/Q==",
1365
1059
  license: "MIT",
1366
1060
  engines: {
1367
1061
  node: ">= 4"
1368
1062
  }
1369
1063
  },
1370
- "node_modules/@earendil-works/pi-coding-agent/node_modules/isexe": {
1064
+ "node_modules/isexe": {
1371
1065
  version: "2.0.0",
1372
1066
  resolved: "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
1373
1067
  integrity: "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
1374
1068
  license: "ISC"
1375
1069
  },
1376
- "node_modules/@earendil-works/pi-coding-agent/node_modules/jiti": {
1070
+ "node_modules/jiti": {
1377
1071
  version: "2.7.0",
1378
1072
  resolved: "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz",
1379
1073
  integrity: "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==",
@@ -1382,7 +1076,7 @@ var default_pi_package_lock_default = {
1382
1076
  jiti: "lib/jiti-cli.mjs"
1383
1077
  }
1384
1078
  },
1385
- "node_modules/@earendil-works/pi-coding-agent/node_modules/json-bigint": {
1079
+ "node_modules/json-bigint": {
1386
1080
  version: "1.0.0",
1387
1081
  resolved: "https://registry.npmjs.org/json-bigint/-/json-bigint-1.0.0.tgz",
1388
1082
  integrity: "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==",
@@ -1391,7 +1085,7 @@ var default_pi_package_lock_default = {
1391
1085
  "bignumber.js": "^9.0.0"
1392
1086
  }
1393
1087
  },
1394
- "node_modules/@earendil-works/pi-coding-agent/node_modules/json-schema-to-ts": {
1088
+ "node_modules/json-schema-to-ts": {
1395
1089
  version: "3.1.1",
1396
1090
  resolved: "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz",
1397
1091
  integrity: "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==",
@@ -1404,7 +1098,7 @@ var default_pi_package_lock_default = {
1404
1098
  node: ">=16"
1405
1099
  }
1406
1100
  },
1407
- "node_modules/@earendil-works/pi-coding-agent/node_modules/jwa": {
1101
+ "node_modules/jwa": {
1408
1102
  version: "2.0.1",
1409
1103
  resolved: "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz",
1410
1104
  integrity: "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==",
@@ -1415,7 +1109,7 @@ var default_pi_package_lock_default = {
1415
1109
  "safe-buffer": "^5.0.1"
1416
1110
  }
1417
1111
  },
1418
- "node_modules/@earendil-works/pi-coding-agent/node_modules/jws": {
1112
+ "node_modules/jws": {
1419
1113
  version: "4.0.1",
1420
1114
  resolved: "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz",
1421
1115
  integrity: "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==",
@@ -1425,25 +1119,25 @@ var default_pi_package_lock_default = {
1425
1119
  "safe-buffer": "^5.0.1"
1426
1120
  }
1427
1121
  },
1428
- "node_modules/@earendil-works/pi-coding-agent/node_modules/long": {
1122
+ "node_modules/long": {
1429
1123
  version: "5.3.2",
1430
1124
  resolved: "https://registry.npmjs.org/long/-/long-5.3.2.tgz",
1431
1125
  integrity: "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==",
1432
1126
  license: "Apache-2.0"
1433
1127
  },
1434
- "node_modules/@earendil-works/pi-coding-agent/node_modules/lru-cache": {
1435
- version: "11.4.0",
1436
- resolved: "https://registry.npmjs.org/lru-cache/-/lru-cache-11.4.0.tgz",
1437
- integrity: "sha512-W+R+kFL4HgVxONq2bhXPi3bGpzGe/yEhVOp233qw9wCRtgncJ15P3bC+e4zZMu4Cq7d+WAJjXGW0uUkifhcatA==",
1128
+ "node_modules/lru-cache": {
1129
+ version: "11.5.3",
1130
+ resolved: "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz",
1131
+ integrity: "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==",
1438
1132
  license: "BlueOak-1.0.0",
1439
1133
  engines: {
1440
1134
  node: "20 || >=22"
1441
1135
  }
1442
1136
  },
1443
- "node_modules/@earendil-works/pi-coding-agent/node_modules/marked": {
1444
- version: "18.0.5",
1445
- resolved: "https://registry.npmjs.org/marked/-/marked-18.0.5.tgz",
1446
- integrity: "sha512-S6GcvALHg6K4ohtu4E7x0a1AqhAjp6cV8KhLSyN9qVapnzJkusVBxZRcIU9AeYsbe6P1hKDusSbEOzGyyuce6w==",
1137
+ "node_modules/marked": {
1138
+ version: "18.0.11",
1139
+ resolved: "https://registry.npmjs.org/marked/-/marked-18.0.11.tgz",
1140
+ integrity: "sha512-HnslJfsZkRPBDJRHvVtAaWlZHEpSu7u8LgQuJCELjRKuWR+hpq4A7sLq3p8HaI9ypVoXDXxV34CsQJEe1+J5Aw==",
1447
1141
  license: "MIT",
1448
1142
  bin: {
1449
1143
  marked: "bin/marked.js"
@@ -1452,13 +1146,13 @@ var default_pi_package_lock_default = {
1452
1146
  node: ">= 20"
1453
1147
  }
1454
1148
  },
1455
- "node_modules/@earendil-works/pi-coding-agent/node_modules/minimatch": {
1456
- version: "10.2.5",
1457
- resolved: "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz",
1458
- integrity: "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==",
1149
+ "node_modules/minimatch": {
1150
+ version: "10.2.6",
1151
+ resolved: "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz",
1152
+ integrity: "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==",
1459
1153
  license: "BlueOak-1.0.0",
1460
1154
  dependencies: {
1461
- "brace-expansion": "^5.0.5"
1155
+ "brace-expansion": "^5.0.8"
1462
1156
  },
1463
1157
  engines: {
1464
1158
  node: "18 || 20 || >=22"
@@ -1467,22 +1161,13 @@ var default_pi_package_lock_default = {
1467
1161
  url: "https://github.com/sponsors/isaacs"
1468
1162
  }
1469
1163
  },
1470
- "node_modules/@earendil-works/pi-coding-agent/node_modules/minipass": {
1471
- version: "7.1.3",
1472
- resolved: "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz",
1473
- integrity: "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==",
1474
- license: "BlueOak-1.0.0",
1475
- engines: {
1476
- node: ">=16 || 14 >=14.17"
1477
- }
1478
- },
1479
- "node_modules/@earendil-works/pi-coding-agent/node_modules/ms": {
1164
+ "node_modules/ms": {
1480
1165
  version: "2.1.3",
1481
1166
  resolved: "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
1482
1167
  integrity: "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
1483
1168
  license: "MIT"
1484
1169
  },
1485
- "node_modules/@earendil-works/pi-coding-agent/node_modules/node-domexception": {
1170
+ "node_modules/node-domexception": {
1486
1171
  version: "1.0.0",
1487
1172
  resolved: "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz",
1488
1173
  integrity: "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==",
@@ -1502,7 +1187,7 @@ var default_pi_package_lock_default = {
1502
1187
  node: ">=10.5.0"
1503
1188
  }
1504
1189
  },
1505
- "node_modules/@earendil-works/pi-coding-agent/node_modules/node-fetch": {
1190
+ "node_modules/node-fetch": {
1506
1191
  version: "3.3.2",
1507
1192
  resolved: "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz",
1508
1193
  integrity: "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==",
@@ -1520,19 +1205,35 @@ var default_pi_package_lock_default = {
1520
1205
  url: "https://opencollective.com/node-fetch"
1521
1206
  }
1522
1207
  },
1523
- "node_modules/@earendil-works/pi-coding-agent/node_modules/openai": {
1524
- version: "6.26.0",
1525
- resolved: "https://registry.npmjs.org/openai/-/openai-6.26.0.tgz",
1526
- integrity: "sha512-zd23dbWTjiJ6sSAX6s0HrCZi41JwTA1bQVs0wLQPZ2/5o2gxOJA5wh7yOAUgwYybfhDXyhwlpeQf7Mlgx8EOCA==",
1208
+ "node_modules/openai": {
1209
+ version: "7.19.0",
1210
+ resolved: "https://registry.npmjs.org/openai/-/openai-7.19.0.tgz",
1211
+ integrity: "sha512-MX2s3u2L5racTO0CC/SWpCOasJQBCJrqLKXK+l82cAhdeF8mPMBEe/gxMm0ZFa2xpKpOFLRjxv5afYEZbBXmbQ==",
1527
1212
  license: "Apache-2.0",
1528
- bin: {
1529
- openai: "bin/cli"
1213
+ engines: {
1214
+ node: ">=22.0.0"
1530
1215
  },
1531
1216
  peerDependencies: {
1532
- ws: "^8.18.0",
1217
+ "@aws-sdk/credential-provider-node": ">=3.972.0 <4",
1218
+ "@smithy/hash-node": ">=4.3.0 <5",
1219
+ "@smithy/signature-v4": ">=5.4.0 <6",
1220
+ undici: ">=5 <9",
1221
+ ws: "^8.21.0",
1533
1222
  zod: "^3.25 || ^4.0"
1534
1223
  },
1535
1224
  peerDependenciesMeta: {
1225
+ "@aws-sdk/credential-provider-node": {
1226
+ optional: true
1227
+ },
1228
+ "@smithy/hash-node": {
1229
+ optional: true
1230
+ },
1231
+ "@smithy/signature-v4": {
1232
+ optional: true
1233
+ },
1234
+ undici: {
1235
+ optional: true
1236
+ },
1536
1237
  ws: {
1537
1238
  optional: true
1538
1239
  },
@@ -1541,7 +1242,7 @@ var default_pi_package_lock_default = {
1541
1242
  }
1542
1243
  }
1543
1244
  },
1544
- "node_modules/@earendil-works/pi-coding-agent/node_modules/p-retry": {
1245
+ "node_modules/p-retry": {
1545
1246
  version: "4.6.2",
1546
1247
  resolved: "https://registry.npmjs.org/p-retry/-/p-retry-4.6.2.tgz",
1547
1248
  integrity: "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ==",
@@ -1554,34 +1255,13 @@ var default_pi_package_lock_default = {
1554
1255
  node: ">=8"
1555
1256
  }
1556
1257
  },
1557
- "node_modules/@earendil-works/pi-coding-agent/node_modules/p-retry/node_modules/@types/retry": {
1558
- version: "0.12.0",
1559
- resolved: "https://registry.npmjs.org/@types/retry/-/retry-0.12.0.tgz",
1560
- integrity: "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==",
1561
- license: "MIT"
1562
- },
1563
- "node_modules/@earendil-works/pi-coding-agent/node_modules/partial-json": {
1258
+ "node_modules/partial-json": {
1564
1259
  version: "0.1.7",
1565
1260
  resolved: "https://registry.npmjs.org/partial-json/-/partial-json-0.1.7.tgz",
1566
1261
  integrity: "sha512-Njv/59hHaokb/hRUjce3Hdv12wd60MtM9Z5Olmn+nehe0QDAsRtRbJPvJ0Z91TusF0SuZRIvnM+S4l6EIP8leA==",
1567
1262
  license: "MIT"
1568
1263
  },
1569
- "node_modules/@earendil-works/pi-coding-agent/node_modules/path-expression-matcher": {
1570
- version: "1.5.0",
1571
- resolved: "https://registry.npmjs.org/path-expression-matcher/-/path-expression-matcher-1.5.0.tgz",
1572
- integrity: "sha512-cbrerZV+6rvdQrrD+iGMcZFEiiSrbv9Tfdkvnusy6y0x0GKBXREFg/Y65GhIfm0tnLntThhzCnfKwp1WRjeCyQ==",
1573
- funding: [
1574
- {
1575
- type: "github",
1576
- url: "https://github.com/sponsors/NaturalIntelligence"
1577
- }
1578
- ],
1579
- license: "MIT",
1580
- engines: {
1581
- node: ">=14.0.0"
1582
- }
1583
- },
1584
- "node_modules/@earendil-works/pi-coding-agent/node_modules/path-key": {
1264
+ "node_modules/path-key": {
1585
1265
  version: "3.1.1",
1586
1266
  resolved: "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
1587
1267
  integrity: "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
@@ -1590,23 +1270,7 @@ var default_pi_package_lock_default = {
1590
1270
  node: ">=8"
1591
1271
  }
1592
1272
  },
1593
- "node_modules/@earendil-works/pi-coding-agent/node_modules/path-scurry": {
1594
- version: "2.0.2",
1595
- resolved: "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz",
1596
- integrity: "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==",
1597
- license: "BlueOak-1.0.0",
1598
- dependencies: {
1599
- "lru-cache": "^11.0.0",
1600
- minipass: "^7.1.2"
1601
- },
1602
- engines: {
1603
- node: "18 || 20 || >=22"
1604
- },
1605
- funding: {
1606
- url: "https://github.com/sponsors/isaacs"
1607
- }
1608
- },
1609
- "node_modules/@earendil-works/pi-coding-agent/node_modules/proper-lockfile": {
1273
+ "node_modules/proper-lockfile": {
1610
1274
  version: "4.1.2",
1611
1275
  resolved: "https://registry.npmjs.org/proper-lockfile/-/proper-lockfile-4.1.2.tgz",
1612
1276
  integrity: "sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==",
@@ -1617,7 +1281,7 @@ var default_pi_package_lock_default = {
1617
1281
  "signal-exit": "^3.0.2"
1618
1282
  }
1619
1283
  },
1620
- "node_modules/@earendil-works/pi-coding-agent/node_modules/proper-lockfile/node_modules/retry": {
1284
+ "node_modules/proper-lockfile/node_modules/retry": {
1621
1285
  version: "0.12.0",
1622
1286
  resolved: "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz",
1623
1287
  integrity: "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==",
@@ -1626,10 +1290,10 @@ var default_pi_package_lock_default = {
1626
1290
  node: ">= 4"
1627
1291
  }
1628
1292
  },
1629
- "node_modules/@earendil-works/pi-coding-agent/node_modules/protobufjs": {
1630
- version: "7.6.5",
1631
- resolved: "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.5.tgz",
1632
- integrity: "sha512-/FPD0nUc9jH6rfFjji9IBqOz4pcSE3CsT1m7Ep6Mdb0LxSUMj8hgl6GomOvZzpNpAqqGaXA0P3VSrZLFzIhQrw==",
1293
+ "node_modules/protobufjs": {
1294
+ version: "7.6.6",
1295
+ resolved: "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.6.tgz",
1296
+ integrity: "sha512-dYDWdjSl5RNb7SgPxGQcRU+GtvP7s2fpkrY0r432PcOIaZ0/rBcxEZnQN67iJhFuQiVw754JDoPruPCNdGsbjg==",
1633
1297
  hasInstallScript: true,
1634
1298
  license: "BSD-3-Clause",
1635
1299
  dependencies: {
@@ -1649,7 +1313,30 @@ var default_pi_package_lock_default = {
1649
1313
  node: ">=12.0.0"
1650
1314
  }
1651
1315
  },
1652
- "node_modules/@earendil-works/pi-coding-agent/node_modules/retry": {
1316
+ "node_modules/proxy-agent-negotiate": {
1317
+ version: "1.1.0",
1318
+ resolved: "https://registry.npmjs.org/proxy-agent-negotiate/-/proxy-agent-negotiate-1.1.0.tgz",
1319
+ integrity: "sha512-N8IBcM3UgCVzz2L2Lqv8DVntDnnC8/hiV4nEDUPkqq72TPUgYWjQc+bdZlBPZK9LzPAvOY//gAt0S0DApoOXWQ==",
1320
+ license: "MIT",
1321
+ engines: {
1322
+ node: ">= 20"
1323
+ },
1324
+ peerDependencies: {
1325
+ kerberos: "^2.0.0"
1326
+ },
1327
+ peerDependenciesMeta: {
1328
+ kerberos: {
1329
+ optional: true
1330
+ }
1331
+ }
1332
+ },
1333
+ "node_modules/quickjs-wasi": {
1334
+ version: "3.6.2",
1335
+ resolved: "https://registry.npmjs.org/quickjs-wasi/-/quickjs-wasi-3.6.2.tgz",
1336
+ integrity: "sha512-FCqGtGOrMgzUiIrMNMA2YnsOxCNwo31dzqXvclXUC6xeT35NJLKXQJsvbeCTjvoFAwZgEAPg8U6+KAPDGXn8Mg==",
1337
+ license: "MIT"
1338
+ },
1339
+ "node_modules/retry": {
1653
1340
  version: "0.13.1",
1654
1341
  resolved: "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz",
1655
1342
  integrity: "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==",
@@ -1658,7 +1345,7 @@ var default_pi_package_lock_default = {
1658
1345
  node: ">= 4"
1659
1346
  }
1660
1347
  },
1661
- "node_modules/@earendil-works/pi-coding-agent/node_modules/safe-buffer": {
1348
+ "node_modules/safe-buffer": {
1662
1349
  version: "5.2.1",
1663
1350
  resolved: "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
1664
1351
  integrity: "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
@@ -1678,10 +1365,10 @@ var default_pi_package_lock_default = {
1678
1365
  ],
1679
1366
  license: "MIT"
1680
1367
  },
1681
- "node_modules/@earendil-works/pi-coding-agent/node_modules/semver": {
1682
- version: "7.8.0",
1683
- resolved: "https://registry.npmjs.org/semver/-/semver-7.8.0.tgz",
1684
- integrity: "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==",
1368
+ "node_modules/semver": {
1369
+ version: "7.8.5",
1370
+ resolved: "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
1371
+ integrity: "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
1685
1372
  license: "ISC",
1686
1373
  bin: {
1687
1374
  semver: "bin/semver.js"
@@ -1690,7 +1377,7 @@ var default_pi_package_lock_default = {
1690
1377
  node: ">=10"
1691
1378
  }
1692
1379
  },
1693
- "node_modules/@earendil-works/pi-coding-agent/node_modules/shebang-command": {
1380
+ "node_modules/shebang-command": {
1694
1381
  version: "2.0.0",
1695
1382
  resolved: "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
1696
1383
  integrity: "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
@@ -1702,7 +1389,7 @@ var default_pi_package_lock_default = {
1702
1389
  node: ">=8"
1703
1390
  }
1704
1391
  },
1705
- "node_modules/@earendil-works/pi-coding-agent/node_modules/shebang-regex": {
1392
+ "node_modules/shebang-regex": {
1706
1393
  version: "3.0.0",
1707
1394
  resolved: "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
1708
1395
  integrity: "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
@@ -1711,58 +1398,56 @@ var default_pi_package_lock_default = {
1711
1398
  node: ">=8"
1712
1399
  }
1713
1400
  },
1714
- "node_modules/@earendil-works/pi-coding-agent/node_modules/signal-exit": {
1401
+ "node_modules/signal-exit": {
1715
1402
  version: "3.0.7",
1716
1403
  resolved: "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz",
1717
1404
  integrity: "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==",
1718
1405
  license: "ISC"
1719
1406
  },
1720
- "node_modules/@earendil-works/pi-coding-agent/node_modules/strnum": {
1721
- version: "2.3.0",
1722
- resolved: "https://registry.npmjs.org/strnum/-/strnum-2.3.0.tgz",
1723
- integrity: "sha512-ums3KNd42PGyx5xaoVTO1mjU1bH3NpY4vsrVlnv9PNGqQj8wd7rJ6nEypLrJ7z5vxK5RP0yMLo6J/Gsm62DI5Q==",
1724
- funding: [
1725
- {
1726
- type: "github",
1727
- url: "https://github.com/sponsors/NaturalIntelligence"
1728
- }
1729
- ],
1730
- license: "MIT"
1407
+ "node_modules/standardwebhooks": {
1408
+ version: "1.1.1",
1409
+ resolved: "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.1.1.tgz",
1410
+ integrity: "sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ==",
1411
+ license: "MIT",
1412
+ dependencies: {
1413
+ "@stablelib/base64": "^1.0.0",
1414
+ "fast-sha256": "^1.3.0"
1415
+ }
1731
1416
  },
1732
- "node_modules/@earendil-works/pi-coding-agent/node_modules/ts-algebra": {
1417
+ "node_modules/ts-algebra": {
1733
1418
  version: "2.0.0",
1734
1419
  resolved: "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz",
1735
1420
  integrity: "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==",
1736
1421
  license: "MIT"
1737
1422
  },
1738
- "node_modules/@earendil-works/pi-coding-agent/node_modules/tslib": {
1423
+ "node_modules/tslib": {
1739
1424
  version: "2.8.1",
1740
1425
  resolved: "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
1741
1426
  integrity: "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
1742
1427
  license: "0BSD"
1743
1428
  },
1744
- "node_modules/@earendil-works/pi-coding-agent/node_modules/typebox": {
1745
- version: "1.3.7",
1746
- resolved: "https://registry.npmjs.org/typebox/-/typebox-1.3.7.tgz",
1747
- integrity: "sha512-meKuifc33Pccx0O6PdIzYMq3Og8zvP4TIi/a+Bw3AEMZMxOD0+RHGQvpglEe6Zdy3wZ8nqn/j95h8LUZLk/6Hg==",
1429
+ "node_modules/typebox": {
1430
+ version: "1.3.27",
1431
+ resolved: "https://registry.npmjs.org/typebox/-/typebox-1.3.27.tgz",
1432
+ integrity: "sha512-zu+jc1pcy4UiNThxikUr36f0Rybk9PEeCg/NE6adeWr/SKsdNO4EzZHYRDlv2YCVAfj3Odq3dESSo/jNyoBXzA==",
1748
1433
  license: "MIT"
1749
1434
  },
1750
- "node_modules/@earendil-works/pi-coding-agent/node_modules/undici": {
1751
- version: "8.5.0",
1752
- resolved: "https://registry.npmjs.org/undici/-/undici-8.5.0.tgz",
1753
- integrity: "sha512-xamtWoB1EshgjpmlXd7GGm2VfdDtw1+rD8uhry8pSNW3If6S8E0m2T2+orSKeZXEn/aPJMviCpDBA65WJt8zhg==",
1435
+ "node_modules/undici": {
1436
+ version: "8.10.2",
1437
+ resolved: "https://registry.npmjs.org/undici/-/undici-8.10.2.tgz",
1438
+ integrity: "sha512-/y4/bH9YNU5hi9NIrpOuvGXFcxrj3CMrV+/AYpowAYTpHn8gX/XPFjNy766FPoYY0miQhdW977JFWKGNhBdwyQ==",
1754
1439
  license: "MIT",
1755
1440
  engines: {
1756
1441
  node: ">=22.19.0"
1757
1442
  }
1758
1443
  },
1759
- "node_modules/@earendil-works/pi-coding-agent/node_modules/undici-types": {
1760
- version: "6.21.0",
1761
- resolved: "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
1762
- integrity: "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
1444
+ "node_modules/undici-types": {
1445
+ version: "8.9.0",
1446
+ resolved: "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
1447
+ integrity: "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
1763
1448
  license: "MIT"
1764
1449
  },
1765
- "node_modules/@earendil-works/pi-coding-agent/node_modules/web-streams-polyfill": {
1450
+ "node_modules/web-streams-polyfill": {
1766
1451
  version: "3.3.3",
1767
1452
  resolved: "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz",
1768
1453
  integrity: "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==",
@@ -1771,7 +1456,7 @@ var default_pi_package_lock_default = {
1771
1456
  node: ">= 8"
1772
1457
  }
1773
1458
  },
1774
- "node_modules/@earendil-works/pi-coding-agent/node_modules/which": {
1459
+ "node_modules/which": {
1775
1460
  version: "2.0.2",
1776
1461
  resolved: "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
1777
1462
  integrity: "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
@@ -1786,10 +1471,10 @@ var default_pi_package_lock_default = {
1786
1471
  node: ">= 8"
1787
1472
  }
1788
1473
  },
1789
- "node_modules/@earendil-works/pi-coding-agent/node_modules/ws": {
1790
- version: "8.21.0",
1791
- resolved: "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",
1792
- integrity: "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",
1474
+ "node_modules/ws": {
1475
+ version: "8.22.0",
1476
+ resolved: "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz",
1477
+ integrity: "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==",
1793
1478
  license: "MIT",
1794
1479
  engines: {
1795
1480
  node: ">=10.0.0"
@@ -1807,22 +1492,7 @@ var default_pi_package_lock_default = {
1807
1492
  }
1808
1493
  }
1809
1494
  },
1810
- "node_modules/@earendil-works/pi-coding-agent/node_modules/xml-naming": {
1811
- version: "0.1.0",
1812
- resolved: "https://registry.npmjs.org/xml-naming/-/xml-naming-0.1.0.tgz",
1813
- integrity: "sha512-k8KO9hrMyNk6tUWqUfkTEZbezRRpONVOzUTnc97VnCvyj6Tf9lyUR9EDAIeiVLv56jsMcoXEwjW8Kv5yPY52lw==",
1814
- funding: [
1815
- {
1816
- type: "github",
1817
- url: "https://github.com/sponsors/NaturalIntelligence"
1818
- }
1819
- ],
1820
- license: "MIT",
1821
- engines: {
1822
- node: ">=16.0.0"
1823
- }
1824
- },
1825
- "node_modules/@earendil-works/pi-coding-agent/node_modules/yaml": {
1495
+ "node_modules/yaml": {
1826
1496
  version: "2.9.0",
1827
1497
  resolved: "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz",
1828
1498
  integrity: "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==",
@@ -1836,31 +1506,13 @@ var default_pi_package_lock_default = {
1836
1506
  funding: {
1837
1507
  url: "https://github.com/sponsors/eemeli"
1838
1508
  }
1839
- },
1840
- "node_modules/@earendil-works/pi-coding-agent/node_modules/zod": {
1841
- version: "3.25.76",
1842
- resolved: "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
1843
- integrity: "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
1844
- license: "MIT",
1845
- funding: {
1846
- url: "https://github.com/sponsors/colinhacks"
1847
- }
1848
- },
1849
- "node_modules/@earendil-works/pi-coding-agent/node_modules/zod-to-json-schema": {
1850
- version: "3.25.2",
1851
- resolved: "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz",
1852
- integrity: "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==",
1853
- license: "ISC",
1854
- peerDependencies: {
1855
- zod: "^3.25.28 || ^4"
1856
- }
1857
1509
  }
1858
1510
  }
1859
1511
  };
1860
1512
 
1861
1513
  // src/supervisor/package-lock-policy.mjs
1862
1514
  var DEFAULT_PI_SDK_MODULE = "@earendil-works/pi-coding-agent";
1863
- var DEFAULT_PI_SDK_VERSION = "0.83.0";
1515
+ var DEFAULT_PI_SDK_VERSION = "1.3.0";
1864
1516
  function createSupervisorPackageManifest(moduleSpecifier = DEFAULT_PI_SDK_MODULE, expectedVersion = DEFAULT_PI_SDK_VERSION) {
1865
1517
  return {
1866
1518
  name: "neckbeard-supervisor-runtime",