@tangle-network/agent-runtime 0.175.0 → 0.177.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/dist/{activation-CsdJWRXX.js → activation-XVI_z1g3.js} +3 -3
- package/dist/{activation-CsdJWRXX.js.map → activation-XVI_z1g3.js.map} +1 -1
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +2 -2
- package/dist/{authoring-DsLNInAz.js → authoring-bXmPNfCI.js} +2 -2
- package/dist/{authoring-DsLNInAz.js.map → authoring-bXmPNfCI.js.map} +1 -1
- package/dist/candidate-execution/index.js +4 -4
- package/dist/{candidate-execution-BbMbyhgC.js → candidate-execution-fBNUyWyE.js} +10 -4
- package/dist/candidate-execution-fBNUyWyE.js.map +1 -0
- package/dist/{conversation-7XGKoDM6.js → conversation-BREx2hi-.js} +3 -3
- package/dist/{conversation-7XGKoDM6.js.map → conversation-BREx2hi-.js.map} +1 -1
- package/dist/conversation.d.ts +1 -1
- package/dist/conversation.js +1 -1
- package/dist/coordination-driver-xO1tkxy-.js +3063 -0
- package/dist/coordination-driver-xO1tkxy-.js.map +1 -0
- package/dist/durable-file-g3YdfEh4.js +131 -0
- package/dist/durable-file-g3YdfEh4.js.map +1 -0
- package/dist/durable.d.ts +2 -2
- package/dist/durable.js +1 -1
- package/dist/{environment-provider-DWjbGH8W.d.ts → environment-provider-5E82esWE.d.ts} +6 -3
- package/dist/{environment-provider-Bn3652YU.js → environment-provider-DKyMWQJd.js} +121 -17
- package/dist/environment-provider-DKyMWQJd.js.map +1 -0
- package/dist/environment-provider.d.ts +1 -1
- package/dist/environment-provider.js +1 -1
- package/dist/{graph-BbeHgLXH.js → graph-DwJXa1Ph.js} +3 -3
- package/dist/graph-DwJXa1Ph.js.map +1 -0
- package/dist/graph.d.ts +3 -3
- package/dist/graph.js +4 -4
- package/dist/{improvement-cycle-DKGDCukL.js → improvement-cycle-eiSv6aH4.js} +5 -5
- package/dist/{improvement-cycle-DKGDCukL.js.map → improvement-cycle-eiSv6aH4.js.map} +1 -1
- package/dist/{index-CIhkH7mq.d.ts → index-BnAiQVLD.d.ts} +290 -29
- package/dist/{index-CFMB9ux3.d.ts → index-Bs0uhf-y.d.ts} +2 -2
- package/dist/{index-Dk5X9eKg.d.ts → index-C9XTLVP1.d.ts} +4 -4
- package/dist/index.d.ts +7 -7
- package/dist/index.js +13 -13
- package/dist/intelligence.d.ts +4 -4
- package/dist/intelligence.js +6 -6
- package/dist/kernel.d.ts +6 -6
- package/dist/kernel.js +13 -11
- package/dist/{knowledge-BaAX0HVu.js → knowledge-Bmtj_7u7.js} +5 -5
- package/dist/{knowledge-BaAX0HVu.js.map → knowledge-Bmtj_7u7.js.map} +1 -1
- package/dist/knowledge.d.ts +1 -1
- package/dist/knowledge.js +1 -1
- package/dist/{loop-runner-bin-DRYApMiu.d.ts → loop-runner-bin-ChS5deJ0.d.ts} +3 -3
- package/dist/{loop-runner-bin-D63Tytdk.js → loop-runner-bin-GTN5wqCt.js} +3 -3
- package/dist/{loop-runner-bin-D63Tytdk.js.map → loop-runner-bin-GTN5wqCt.js.map} +1 -1
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/{materialization-Ct3I4wu3.js → materialization-CekWK6OO.js} +5 -3
- package/dist/materialization-CekWK6OO.js.map +1 -0
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.d.ts +3 -3
- package/dist/mcp/index.js +5 -4
- package/dist/mcp/index.js.map +1 -1
- package/dist/{openai-tools-BBgjWYNw.js → openai-tools-BBj1QGJp.js} +2 -2
- package/dist/{openai-tools-BBgjWYNw.js.map → openai-tools-BBj1QGJp.js.map} +1 -1
- package/dist/{prepare-BAyaNoZu.js → prepare-Tip-2ZoZ.js} +2 -2
- package/dist/{prepare-BAyaNoZu.js.map → prepare-Tip-2ZoZ.js.map} +1 -1
- package/dist/primeintellect/index.d.ts +1 -1
- package/dist/{protected-model-port-T2UWrDNQ.js → protected-model-port-Dd3a1SRm.js} +2 -2
- package/dist/{protected-model-port-T2UWrDNQ.js.map → protected-model-port-Dd3a1SRm.js.map} +1 -1
- package/dist/provision-supervisor-zA__ayUX.js +1020 -0
- package/dist/provision-supervisor-zA__ayUX.js.map +1 -0
- package/dist/{redact-DvLf4x1m.d.ts → redact-DkRLcSiE.d.ts} +3 -3
- package/dist/run-layout-Cd_l2XWV.js +645 -0
- package/dist/run-layout-Cd_l2XWV.js.map +1 -0
- package/dist/{runtime-D5u1M6T5.d.ts → runtime-B2eZ76kG.d.ts} +3 -3
- package/dist/{runtime-CojgP-hr.js → runtime-CJNlF5wM.js} +16 -1095
- package/dist/runtime-CJNlF5wM.js.map +1 -0
- package/dist/{spawn-journal-Tgvp5VS5.js → spawn-journal--N8Ten1q.js} +3 -1
- package/dist/{spawn-journal-Tgvp5VS5.js.map → spawn-journal--N8Ten1q.js.map} +1 -1
- package/dist/{stream-agent-turn-DxQ3GOuR.d.ts → stream-agent-turn-ByY8po9W.d.ts} +2 -2
- package/dist/{stream-agent-turn-CKIpCbSq.js → stream-agent-turn-CPj9SqVm.js} +2 -2
- package/dist/{stream-agent-turn-CKIpCbSq.js.map → stream-agent-turn-CPj9SqVm.js.map} +1 -1
- package/dist/{structural-rollout-BUYA61iV.js → structural-rollout-BeAUK7Ta.js} +4 -4
- package/dist/{structural-rollout-BUYA61iV.js.map → structural-rollout-BeAUK7Ta.js.map} +1 -1
- package/dist/{supervise-Ci0RfWQF.js → supervise-HsRKOlKY.js} +405 -3374
- package/dist/supervise-HsRKOlKY.js.map +1 -0
- package/dist/{supervisor-Bt1XLCVq.js → supervisor-ChLgoYhG.js} +1620 -33
- package/dist/supervisor-ChLgoYhG.js.map +1 -0
- package/dist/testing.d.ts +2 -2
- package/dist/testing.js +13 -12
- package/dist/testing.js.map +1 -1
- package/dist/{top-app-3rYfFPTW.js → top-app-DIBApkt1.js} +25 -9
- package/dist/top-app-DIBApkt1.js.map +1 -0
- package/dist/tui/bin.js +1 -1
- package/dist/tui/index.d.ts +9 -1
- package/dist/tui/index.js +3 -2
- package/dist/{types-DjVO-p7R.d.ts → types-a2ZZUl80.d.ts} +25 -2
- package/dist/{workspace-archive-B0Hqp2eJ.js → workspace-archive-DOZAeeKU.js} +2 -2
- package/dist/{workspace-archive-B0Hqp2eJ.js.map → workspace-archive-DOZAeeKU.js.map} +1 -1
- package/package.json +5 -4
- package/dist/candidate-execution-BbMbyhgC.js.map +0 -1
- package/dist/environment-provider-Bn3652YU.js.map +0 -1
- package/dist/graph-BbeHgLXH.js.map +0 -1
- package/dist/materialization-Ct3I4wu3.js.map +0 -1
- package/dist/run-layout-C2jgwsCq.js +0 -393
- package/dist/run-layout-C2jgwsCq.js.map +0 -1
- package/dist/runtime-CojgP-hr.js.map +0 -1
- package/dist/supervise-Ci0RfWQF.js.map +0 -1
- package/dist/supervisor-Bt1XLCVq.js.map +0 -1
- package/dist/top-app-3rYfFPTW.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"materialization-Ct3I4wu3.js","names":[],"sources":["../src/runtime/turn-input.ts","../src/runtime/retained-run-binding.ts","../src/runtime/supervise/materialization.ts"],"sourcesContent":["import {\n AgentExactRunControlRefSchema,\n type ContextTransferRequest,\n type InputPart,\n} from '@tangle-network/agent-interface'\nimport type { AgentTurnInput } from '@tangle-network/agent-interface/environment-provider'\nimport type { PromptInputPart, PromptOptions } from '@tangle-network/sandbox'\n\n/**\n * Copy only fields that describe a new provider turn.\n *\n * Session, replay, continuation, and transfer coordinates are runtime-owned\n * and are injected by the caller that owns that lifecycle. Keeping this copy\n * explicit also makes JavaScript callers subject to the same boundary.\n */\nexport function freshTurnInput(\n input: AgentTurnInput,\n runtime: {\n readonly turnId: string\n readonly detach: true\n readonly sessionId?: string\n readonly executionId?: string\n readonly contextTransfer?: ContextTransferRequest\n },\n): AgentTurnInput {\n const fresh: AgentTurnInput = {\n ...(input.prompt === undefined ? {} : { prompt: input.prompt }),\n ...(input.parts === undefined ? {} : { parts: input.parts }),\n ...(input.model === undefined ? {} : { model: input.model }),\n ...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }),\n ...(input.context === undefined ? {} : { context: input.context }),\n ...(input.interactions === undefined ? {} : { interactions: input.interactions }),\n ...(input.providerOptions === undefined ? {} : { providerOptions: input.providerOptions }),\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n turnId: runtime.turnId,\n detach: runtime.detach,\n ...(runtime.sessionId === undefined ? {} : { sessionId: runtime.sessionId }),\n ...(runtime.executionId === undefined ? {} : { executionId: runtime.executionId }),\n ...(runtime.contextTransfer === undefined ? {} : { contextTransfer: runtime.contextTransfer }),\n }\n return fresh\n}\n\n/** Project canonical turn parts onto the Sandbox prompt vocabulary once. */\nexport function promptFromAgentTurnInput(input: AgentTurnInput): string | PromptInputPart[] {\n if (input.parts !== undefined) return input.parts.map(promptPartFromInputPart)\n return input.prompt ?? providerMessageText(input.providerOptions) ?? ''\n}\n\n/** Project canonical turn controls onto the Sandbox prompt options once. */\nexport function promptOptionsFromAgentTurnInput(input: AgentTurnInput): PromptOptions {\n const providerBackend =\n input.providerOptions?.backend &&\n typeof input.providerOptions.backend === 'object' &&\n !Array.isArray(input.providerOptions.backend)\n ? (input.providerOptions.backend as NonNullable<PromptOptions['backend']>)\n : undefined\n const backend = {\n ...(providerBackend ?? {}),\n ...(input.interactions === undefined ? {} : { interactions: input.interactions }),\n }\n const runControlRef =\n input.controlRef === undefined\n ? undefined\n : AgentExactRunControlRefSchema.parse(input.controlRef)\n return {\n ...(input.sessionId === undefined ? {} : { sessionId: input.sessionId }),\n ...(input.model === undefined ? {} : { model: input.model }),\n ...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }),\n ...(input.context === undefined ? {} : { context: input.context }),\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n ...(input.executionId === undefined ? {} : { executionId: input.executionId }),\n ...(input.lastEventId === undefined ? {} : { lastEventId: input.lastEventId }),\n ...(input.turnId === undefined ? {} : { turnId: input.turnId }),\n ...(input.detach === undefined ? {} : { detach: input.detach }),\n ...(runControlRef === undefined ? {} : { runControlRef }),\n ...(Object.keys(backend).length === 0 ? {} : { backend }),\n }\n}\n\n/** Read a text fallback from provider-specific conversation options. */\nexport function providerMessageText(\n providerOptions: Record<string, unknown> | undefined,\n): string | undefined {\n const messages = providerOptions?.messages\n if (!Array.isArray(messages)) return undefined\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index]\n if (!message || typeof message !== 'object' || Array.isArray(message)) continue\n if (!('role' in message) || message.role !== 'user') continue\n if (!('content' in message)) continue\n if (typeof message.content === 'string') return message.content\n }\n return undefined\n}\n\nfunction promptPartFromInputPart(part: InputPart): PromptInputPart {\n if (part.type === 'text' || part.type === 'image') return part\n if (part.content !== undefined || part.path !== undefined) {\n throw new Error(\n 'Sandbox file prompt parts require a URL; inline content and local paths are not representable',\n )\n }\n if (!part.filename || !part.url) {\n throw new Error('Sandbox file prompt parts require both filename and URL')\n }\n return {\n type: 'file',\n filename: part.filename,\n ...(part.mediaType === undefined ? {} : { mediaType: part.mediaType }),\n url: part.url,\n }\n}\n","import {\n type AgentExactRunControlRef,\n AgentExactRunControlRefSchema,\n type AgentRunCancellationAcknowledgement,\n AgentRunCancellationAcknowledgementSchema,\n type AgentRunCancellationRequest,\n AgentRunCancellationRequestSchema,\n agentRunCancellationAcknowledgementMatchesRequest,\n agentRunCancellationRequestDigest,\n canonicalCandidateDigest,\n type InteractionResponseCommand,\n type NativeContextBoundaryProof,\n type StreamEvent,\n} from '@tangle-network/agent-interface'\nimport type {\n AgentEnvironment,\n AgentEnvironmentEvent,\n AgentSession,\n AgentSessionStatus,\n AgentTurnResult,\n} from '@tangle-network/agent-interface/environment-provider'\n\nexport function exactSession(\n environment: AgentEnvironment,\n controlRef: AgentExactRunControlRef,\n): { session: AgentSession; controlRef: AgentExactRunControlRef } {\n if (environment.id !== controlRef.environmentId || environment.provider !== controlRef.provider) {\n throw new Error('provider reconstructed a different retained environment')\n }\n if (!environment.session || !controlRef.sessionId) {\n throw new Error('retained run control requires a provider session id')\n }\n const session = environment.session(controlRef.sessionId, { controlRef })\n if (session.id !== controlRef.sessionId) {\n throw new Error('provider reconstructed a different session')\n }\n if (session.controlRef === undefined) {\n throw new Error('provider session did not return its provider-owned run control reference')\n }\n const currentControlRef = AgentExactRunControlRefSchema.parse(session.controlRef)\n if (!sameControlCoordinates(currentControlRef, controlRef)) {\n throw new Error('provider session reconstructed a different retained session')\n }\n if (canonicalCandidateDigest(currentControlRef) !== canonicalCandidateDigest(controlRef)) {\n throw new Error('provider session did not retain the exact run control reference')\n }\n return { session, controlRef: currentControlRef }\n}\n\nexport function sameControlCoordinates(\n left: AgentExactRunControlRef,\n right: AgentExactRunControlRef,\n): boolean {\n return canonicalCandidateDigest(left) === canonicalCandidateDigest(right)\n}\n\nexport function freezeControlRef(controlRef: AgentExactRunControlRef): AgentExactRunControlRef {\n return Object.freeze({ ...AgentExactRunControlRefSchema.parse(controlRef) })\n}\n\nexport function copyControlRef(controlRef: AgentExactRunControlRef): AgentExactRunControlRef {\n return { ...controlRef }\n}\n\nexport function exactControlRef(\n candidate: unknown,\n expected: { provider: string; environmentId: string; sessionId: string },\n): AgentExactRunControlRef {\n if (!candidate) throw new Error('provider dispatch returned no durable run control reference')\n const controlRef = AgentExactRunControlRefSchema.parse(candidate)\n if (\n controlRef.provider !== expected.provider ||\n controlRef.environmentId !== expected.environmentId ||\n controlRef.sessionId !== expected.sessionId\n ) {\n throw new Error('provider dispatch returned control coordinates for another run')\n }\n return controlRef\n}\n\nexport function exactContinuedControlRef(\n candidate: AgentExactRunControlRef,\n initial: AgentExactRunControlRef,\n): AgentExactRunControlRef {\n const controlRef = AgentExactRunControlRefSchema.parse(candidate)\n if (\n controlRef.provider !== initial.provider ||\n controlRef.environmentId !== initial.environmentId ||\n controlRef.sessionId !== initial.sessionId\n ) {\n throw new Error('provider continuation advanced to another retained session')\n }\n if (controlRef.runId === initial.runId && controlRef.executionId === initial.executionId) {\n throw new Error('provider continuation did not return a new exact run execution')\n }\n return controlRef\n}\n\nexport function assertInteractionBinding(\n controlRef: AgentExactRunControlRef,\n command: InteractionResponseCommand,\n): void {\n // This digest identifies the interaction request, not the retained turn.\n // The provider validates it against its durable interaction record.\n if (\n command.binding.runId !== controlRef.runId ||\n command.binding.provider !== controlRef.provider ||\n command.binding.environmentId !== controlRef.environmentId ||\n command.binding.sessionId !== controlRef.sessionId ||\n command.binding.executionId !== controlRef.executionId\n ) {\n throw new Error('interaction response command does not target this retained run')\n }\n}\n\nexport function assertBoundaryBinding(\n controlRef: AgentExactRunControlRef,\n proof: NativeContextBoundaryProof,\n): void {\n if (\n proof.runId !== controlRef.runId ||\n proof.provider !== controlRef.provider ||\n proof.environmentId !== controlRef.environmentId ||\n proof.sessionId !== controlRef.sessionId ||\n proof.executionId !== controlRef.executionId ||\n proof.requestDigest !== controlRef.requestDigest\n ) {\n throw new Error('native context proof does not identify this retained run')\n }\n}\n\nexport function assertSequence(value: unknown, label: string): asserts value is number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {\n throw new Error(`${label} must be a non-negative safe integer`)\n }\n}\n\nexport function assertResultBinding(\n controlRef: AgentExactRunControlRef,\n result: AgentTurnResult,\n): void {\n if (result.sessionId !== controlRef.sessionId) {\n throw new Error('provider returned a result for another retained session')\n }\n const metadata = result.metadata\n if (controlRef.executionId !== undefined && metadata?.executionId !== controlRef.executionId) {\n throw new Error('provider returned a result for another retained execution')\n }\n if (metadata?.runId !== controlRef.runId) {\n throw new Error('provider returned a result for another retained run')\n }\n if (metadata?.requestDigest !== controlRef.requestDigest) {\n throw new Error('provider returned a result for another retained request')\n }\n}\n\ninterface ExactCancelOptions {\n readonly signal?: AbortSignal\n}\n\nexport class RetainedRunProviderContractError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'RetainedRunProviderContractError'\n }\n}\n\nexport function cancellationRequest(\n controlRef: AgentExactRunControlRef,\n operationId: string,\n reason?: string,\n): AgentRunCancellationRequest {\n const material = {\n operationId,\n run: AgentExactRunControlRefSchema.parse(controlRef),\n ...(reason === undefined ? {} : { reason }),\n }\n return AgentRunCancellationRequestSchema.parse({\n ...material,\n requestDigest: agentRunCancellationRequestDigest(material),\n })\n}\n\nexport async function exactSessionCancel(\n session: AgentSession,\n request: AgentRunCancellationRequest,\n options: ExactCancelOptions,\n): Promise<AgentRunCancellationAcknowledgement> {\n if (!session.cancelRun) {\n throw new Error('provider session does not expose durable cancellation operations')\n }\n let acknowledgement: unknown\n try {\n acknowledgement = await awaitAbortable(\n Promise.resolve().then(() => session.cancelRun!(request, options)),\n options.signal,\n )\n } catch (error) {\n if (error instanceof RetainedRunProviderContractError) throw error\n throw error\n }\n let exactAcknowledgement: AgentRunCancellationAcknowledgement\n try {\n exactAcknowledgement = AgentRunCancellationAcknowledgementSchema.parse(acknowledgement)\n } catch {\n throw new RetainedRunProviderContractError(\n 'provider returned an invalid retained cancellation acknowledgement',\n )\n }\n if (!agentRunCancellationAcknowledgementMatchesRequest(request, exactAcknowledgement)) {\n throw new RetainedRunProviderContractError(\n 'provider returned a retained cancellation acknowledgement for another request',\n )\n }\n return exactAcknowledgement\n}\n\nexport function hasDurableCancel(session: AgentSession): boolean {\n return typeof session.cancelRun === 'function'\n}\n\nexport async function awaitAbortable<T>(\n work: PromiseLike<T>,\n signal: AbortSignal | undefined,\n): Promise<T> {\n if (signal === undefined) return await work\n if (signal.aborted) {\n void Promise.resolve(work).catch(() => undefined)\n throw abortError(signal.reason)\n }\n return await new Promise<T>((resolve, reject) => {\n let settled = false\n const cleanup = () => signal.removeEventListener('abort', onAbort)\n const onAbort = () => {\n queueMicrotask(() => {\n if (settled) return\n settled = true\n cleanup()\n reject(abortError(signal.reason))\n })\n }\n signal.addEventListener('abort', onAbort, { once: true })\n Promise.resolve(work).then(\n (value) => {\n if (settled) return\n settled = true\n cleanup()\n resolve(value)\n },\n (error) => {\n if (settled) return\n settled = true\n cleanup()\n reject(error)\n },\n )\n })\n}\n\nexport async function exactSessionResult(session: AgentSession): Promise<AgentTurnResult> {\n return session.result()\n}\n\nexport function assertEventBinding(\n source: AgentEnvironmentEvent,\n controlRef: AgentExactRunControlRef,\n): void {\n const transport = isRecord(source) ? source : undefined\n const payload = isRecord(source.data) ? source.data : undefined\n const providerEvent = isRecord(source.providerEvent) ? source.providerEvent : undefined\n const bindings = [\n { value: transport, checkSessionId: true },\n {\n value: payload,\n // The canonical session.updated payload identifies the harness-native chat.\n // It is event content, not the retained provider session coordinate.\n checkSessionId: source.type !== 'session.updated',\n },\n { value: providerEvent, checkSessionId: true },\n ]\n for (const { value, checkSessionId } of bindings) {\n if (value === undefined) continue\n if (value.runId !== undefined && value.runId !== controlRef.runId) {\n throw new Error('provider returned an event for another retained run')\n }\n if (value.executionId !== undefined && value.executionId !== controlRef.executionId) {\n throw new Error('provider returned an event for another retained execution')\n }\n if (\n checkSessionId &&\n value.sessionId !== undefined &&\n value.sessionId !== controlRef.sessionId\n ) {\n throw new Error('provider returned an event for another retained session')\n }\n }\n}\n\n/** Validate the nested coordinates carried by a canonical interaction request. */\nexport function assertCanonicalEventBinding(\n controlRef: AgentExactRunControlRef,\n event: StreamEvent,\n): void {\n if (event.type !== 'interaction') return\n const binding = event.request.binding\n if (\n binding.runId !== controlRef.runId ||\n binding.provider !== controlRef.provider ||\n binding.environmentId !== controlRef.environmentId ||\n binding.sessionId !== controlRef.sessionId ||\n binding.executionId !== controlRef.executionId ||\n binding.interactionId !== event.request.id\n ) {\n throw new Error('provider returned an interaction for another retained execution')\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nexport function assertStableText(value: string, label: string): void {\n if (value.length === 0 || value.trim() !== value) {\n throw new Error(`${label} must be non-empty and have no outer whitespace`)\n }\n}\n\nexport function abortError(reason: unknown): Error {\n const error = new Error(\n reason instanceof Error ? reason.message : reason === undefined ? 'aborted' : String(reason),\n )\n error.name = 'AbortError'\n return error\n}\n\nexport function assertWaitDuration(value: number, label: string): void {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error(`${label} must be a non-negative safe integer`)\n }\n}\n\n/**\n * Whether a session can still change state.\n *\n * Exhaustive over `AgentSessionStatus` by construction: the map below is `satisfies\n * Record<AgentSessionStatus, boolean>`, so a member added upstream fails to compile here instead of\n * being silently classified as non-terminal. Written as a boolean chain, `stopped` was missing —\n * and a `status({ waitMs })` call on an already-stopped session then polled every 25 ms for the\n * whole wait before returning the answer it already had at the first snapshot.\n *\n * `unknown` is deliberately NOT terminal: it says the provider could not tell us, which is the one\n * state where continuing to poll is the point. That differs from\n * `sandboxSessionStatusFromAgentSessionStatus`, which projects `unknown` to `failed` because a run\n * RESULT must never claim success without proof — a different question about the same word.\n */\nconst sessionStatusIsTerminal = {\n pending: false,\n provisioning: false,\n running: false,\n unknown: false,\n stopped: true,\n completed: true,\n cancelled: true,\n failed: true,\n expired: true,\n} satisfies Record<AgentSessionStatus, boolean>\n\nexport function isTerminalSessionStatus(status: AgentSessionStatus | null): boolean {\n return status !== null && sessionStatusIsTerminal[status]\n}\n\nexport function delay(ms: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) return Promise.reject(abortError(signal.reason))\n return new Promise((resolveDelay, rejectDelay) => {\n const timer = setTimeout(finish, ms)\n function finish() {\n signal?.removeEventListener('abort', onAbort)\n resolveDelay()\n }\n function onAbort() {\n clearTimeout(timer)\n signal?.removeEventListener('abort', onAbort)\n rejectDelay(abortError(signal?.reason))\n }\n signal?.addEventListener('abort', onAbort, { once: true })\n })\n}\n","import { randomUUID } from 'node:crypto'\nimport {\n agentProfileSchema,\n canonicalAgentProfileDigest,\n canonicalCandidateDigest,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { ValidationError } from '../../errors'\nimport { detachedSnapshot } from './snapshot'\nimport type {\n ExecutionBindingReceipt,\n Executor,\n ExecutorExecutionBinding,\n ExecutorMaterialization,\n ProfileMaterializationReceipt,\n ProviderModelAttemptEvidence,\n ProviderModelExecutionEvidence,\n Runtime,\n UnknownMaterializationReason,\n} from './types'\n\ntype RuntimeOwnedExecutorMaterialization =\n | {\n readonly kind: 'known'\n readonly declaration: ExecutorMaterialization\n readonly binding?: ExecutorExecutionBinding\n }\n | {\n /** A Runtime-owned external executor whose exact launch is known, but whose remote\n * materializer has not yet returned its terminal acknowledgement. This private state lets\n * Runtime validate the planned authority before execution without presenting it as proof\n * that the remote process actually used that plan. */\n readonly kind: 'pending'\n readonly runtime: Runtime\n readonly declaration: ExecutorMaterialization\n readonly binding: ExecutorExecutionBinding\n }\n | { readonly kind: 'deferred'; readonly runtime: Runtime }\n\ninterface RuntimeOwnedExecutorMaterializationRef {\n current: RuntimeOwnedExecutorMaterialization\n}\n\nconst runtimeOwnedExecutorMaterializations = new WeakMap<\n object,\n RuntimeOwnedExecutorMaterializationRef\n>()\nconst runtimeOwnedScopeOwners = new WeakMap<object, Runtime>()\nconst runtimeOwnedExecutorProviderEvidenceState = new WeakMap<\n object,\n {\n readonly attempts: Array<{\n readonly observations: string[]\n identityConflict?: boolean\n providerDispatch?: 'not_started'\n }>\n }\n>()\nconst runtimeOwnedDriveHarnessProviderEvidenceState = new WeakMap<\n object,\n ProviderModelExecutionEvidence\n>()\n\ninterface KnownReceiptInput {\n readonly authoredProfileDigest: Sha256Digest\n readonly runtime: Runtime\n readonly declaration: ExecutorMaterialization\n}\n\ninterface UnknownReceiptInput {\n readonly authoredProfileDigest?: Sha256Digest\n readonly runtime: Runtime\n readonly reason: UnknownMaterializationReason\n}\n\nconst declarationKeys = new Set([\n 'effectiveProfile',\n 'backend',\n 'model',\n 'execution',\n 'materializer',\n 'plan',\n 'platformAttachments',\n])\n\n/**\n * Bind a declaration to a runtime-owned executor without putting an attestable method on the\n * public Executor interface. This module is not a package export: arbitrary caller executors stay\n * unknown even if they add a lookalike `materialization()` property.\n */\nexport function attestRuntimeOwnedExecutor<Out>(\n executor: Executor<Out>,\n declaration: ExecutorMaterialization,\n binding?: ExecutorExecutionBinding,\n): Executor<Out> {\n runtimeOwnedExecutorMaterializations.set(executor as object, {\n current: Object.freeze({\n kind: 'known',\n declaration: detachedSnapshot(declaration, 'runtime-owned executor materialization'),\n ...(binding === undefined\n ? {}\n : {\n binding: detachedSnapshot(binding, 'runtime-owned executor execution binding'),\n }),\n }),\n })\n ensureProviderEvidenceState(executor)\n return executor\n}\n\n/** Brand an external Runtime executor whose exact remote materialization is provable only after\n * its terminal protocol acknowledgement. The declaration is a planned authority check, never a\n * known receipt; callers must finalize this same object after validating the acknowledgement. */\nexport function attestRuntimeOwnedPendingExecutor<Out>(\n executor: Executor<Out>,\n runtime: Runtime,\n declaration: ExecutorMaterialization,\n binding: ExecutorExecutionBinding,\n): Executor<Out> {\n runtimeOwnedExecutorMaterializations.set(executor as object, {\n current: Object.freeze({\n kind: 'pending',\n runtime,\n declaration: detachedSnapshot(declaration, 'pending executor materialization'),\n binding: detachedSnapshot(binding, 'pending executor execution binding'),\n }),\n })\n return executor\n}\n\n/** Replace a private pending brand with terminally acknowledged evidence. A caller-owned executor\n * cannot enter this path because only this module can create the pending WeakMap entry. */\nexport function finalizeRuntimeOwnedPendingExecutor<Out>(\n executor: Executor<Out>,\n declaration: ExecutorMaterialization,\n binding: ExecutorExecutionBinding,\n): Executor<Out> {\n const ref = runtimeOwnedExecutorMaterializations.get(executor as object)\n if (ref?.current.kind !== 'pending' || ref.current.runtime !== executor.runtime) {\n throw new ValidationError(\n 'executor materialization: terminal acknowledgement has no matching Runtime-owned pending executor',\n )\n }\n ref.current = Object.freeze({\n kind: 'known',\n declaration: detachedSnapshot(declaration, 'runtime-owned executor materialization'),\n binding: detachedSnapshot(binding, 'runtime-owned executor execution binding'),\n })\n return executor\n}\n\n/** Mark a runtime-owned orchestration executor whose exact leaf declaration is published through\n * its private nested Scope before the first backend inference. Arbitrary executors cannot opt in. */\nexport function attestRuntimeOwnedDeferredExecutor<Out>(\n executor: Executor<Out>,\n runtime: Runtime,\n): Executor<Out> {\n runtimeOwnedExecutorMaterializations.set(executor as object, {\n current: Object.freeze({ kind: 'deferred', runtime }),\n })\n return executor\n}\n\n/** Preserve the runtime-owned attestation when a trusted wrapper changes result semantics only. */\nexport function inheritRuntimeOwnedExecutorAttestation<In, Out>(\n source: Executor<In>,\n wrapper: Executor<Out>,\n): Executor<Out> {\n const ref = runtimeOwnedExecutorMaterializations.get(source as object)\n if (ref !== undefined) {\n runtimeOwnedExecutorMaterializations.set(wrapper as object, ref)\n }\n const providerState = ensureProviderEvidenceState(source)\n runtimeOwnedExecutorProviderEvidenceState.set(wrapper as object, providerState)\n return wrapper\n}\n\nfunction ensureProviderEvidenceState<Out>(executor: Executor<Out>): {\n readonly attempts: Array<{\n readonly observations: string[]\n identityConflict?: boolean\n providerDispatch?: 'not_started'\n }>\n} {\n const existing = runtimeOwnedExecutorProviderEvidenceState.get(executor as object)\n if (existing !== undefined) return existing\n const state = { attempts: [] }\n runtimeOwnedExecutorProviderEvidenceState.set(executor as object, state)\n return state\n}\n\n/** Read a declaration only when Runtime itself branded this exact executor object. */\nexport function runtimeOwnedExecutorMaterialization<Out>(\n executor: Executor<Out>,\n): ExecutorMaterialization | undefined {\n const attestation = runtimeOwnedExecutorMaterializations.get(executor as object)?.current\n return attestation?.kind === 'known' ? attestation.declaration : undefined\n}\n\n/** Read one attempt binding only from the private brand on this exact executor object. */\nexport function runtimeOwnedExecutorExecutionBinding<Out>(\n executor: Executor<Out>,\n): ExecutorExecutionBinding | undefined {\n const attestation = runtimeOwnedExecutorMaterializations.get(executor as object)?.current\n return attestation?.kind === 'known' ? attestation.binding : undefined\n}\n\n/** Read a planned external declaration only for Runtime's private pending brand. This is useful for\n * pre-execution authority checks, but must never be turned into a known durable receipt. */\nexport function runtimeOwnedPendingExecutorMaterialization<Out>(executor: Executor<Out>):\n | {\n readonly runtime: Runtime\n readonly declaration: ExecutorMaterialization\n readonly binding: ExecutorExecutionBinding\n }\n | undefined {\n const attestation = runtimeOwnedExecutorMaterializations.get(executor as object)?.current\n return attestation?.kind === 'pending'\n ? {\n runtime: attestation.runtime,\n declaration: attestation.declaration,\n binding: attestation.binding,\n }\n : undefined\n}\n\n/** Read the expected leaf runtime only for a privately branded deferred orchestration executor. */\nexport function runtimeOwnedDeferredExecutorRuntime<Out>(\n executor: Executor<Out>,\n): Runtime | undefined {\n const attestation = runtimeOwnedExecutorMaterializations.get(executor as object)?.current\n return attestation?.kind === 'deferred' ? attestation.runtime : undefined\n}\n\n/** Propagate trust from a built-in driver adapter to the Agent and recursive executor it owns. */\nexport function attestRuntimeOwnedScopeOwner<T extends object>(owner: T, runtime: Runtime): T {\n runtimeOwnedScopeOwners.set(owner, runtime)\n return owner\n}\n\n/** Return a built-in scope owner's expected concrete leaf runtime; caller-owned functions/Agents\n * deliberately have no entry even if they add lookalike fields. */\nexport function runtimeOwnedScopeOwnerRuntime(owner: object): Runtime | undefined {\n return runtimeOwnedScopeOwners.get(owner)\n}\n\n/** Mark one provider inference attempt on a Runtime-owned executor. */\nexport function recordRuntimeOwnedProviderAttemptStart<Out>(executor: Executor<Out>): void {\n const state = ensureProviderEvidenceState(executor)\n state.attempts.push({ observations: [] })\n}\n\n/** Mark the current attempt as rejected before provider dispatch.\n *\n * The caller may use this only after consuming the Router-owned\n * `provider_dispatch: \"not_started\"` fact. Any other error stays an empty,\n * unknown attempt and must not be upgraded here.\n */\nexport function recordRuntimeOwnedProviderDispatchNotStarted<Out>(executor: Executor<Out>): void {\n const state = ensureProviderEvidenceState(executor)\n const attempt = state.attempts.at(-1)\n if (attempt === undefined) {\n throw new ValidationError('provider dispatch rejection arrived before an attempt started')\n }\n if (attempt.observations.length > 0 || attempt.identityConflict === true) {\n throw new ValidationError(\n 'provider dispatch rejection arrived after provider identity evidence was observed',\n )\n }\n attempt.providerDispatch = 'not_started'\n}\n\n/** Record a trusted served model on the current provider attempt. */\nexport function recordRuntimeOwnedProviderModel<Out>(executor: Executor<Out>, model: string): void {\n const state = runtimeOwnedExecutorProviderEvidenceState.get(executor as object)\n const attempt = state?.attempts.at(-1)\n if (attempt === undefined) {\n throw new ValidationError('provider model observation arrived before an attempt started')\n }\n if (attempt.observations.at(-1) !== model) attempt.observations.push(model)\n}\n\n/** Convert process-local provider observations into a frozen, replayable evidence value. */\nexport function runtimeOwnedExecutorProviderEvidence<Out>(\n executor: Executor<Out>,\n): ProviderModelExecutionEvidence | undefined {\n const state = runtimeOwnedExecutorProviderEvidenceState.get(executor as object)\n if (state === undefined || state.attempts.length === 0) return undefined\n const attempts: ReadonlyArray<ProviderModelAttemptEvidence> = Object.freeze(\n state.attempts.map((attempt) =>\n Object.freeze({\n observations: Object.freeze([...attempt.observations]),\n ...(attempt.identityConflict ? { identityConflict: true } : {}),\n ...(attempt.providerDispatch === 'not_started'\n ? { providerDispatch: 'not_started' as const }\n : {}),\n }),\n ),\n )\n const models = Object.freeze([...new Set(attempts.flatMap((attempt) => attempt.observations))])\n const missing = attempts.some(\n (attempt) => attempt.observations.length === 0 && attempt.providerDispatch !== 'not_started',\n )\n const conflict = attempts.some((attempt) => attempt.identityConflict === true)\n const served = attempts.some((attempt) => attempt.observations.length > 0)\n return Object.freeze(\n missing || conflict || !served\n ? {\n status: 'unknown' as const,\n attempts,\n models,\n reason: conflict\n ? ('provider-model-conflict' as const)\n : ('provider-model-missing' as const),\n }\n : { status: 'known' as const, attempts, models },\n )\n}\n\n/** Mark the current provider attempt unusable after conflicting served identity metadata. */\nexport function recordRuntimeOwnedProviderIdentityConflict<Out>(executor: Executor<Out>): void {\n const state = ensureProviderEvidenceState(executor)\n const attempt = state.attempts.at(-1)\n if (attempt === undefined) {\n throw new ValidationError('provider identity conflict arrived before an attempt started')\n }\n attempt.identityConflict = true\n}\n\n/** Attach one executor's provider evidence to a Runtime-owned root drive for final projection. */\nexport function recordRuntimeOwnedDriveHarnessProviderEvidence(\n owner: object,\n evidence: ProviderModelExecutionEvidence | undefined,\n): void {\n if (evidence === undefined) return\n const prior = runtimeOwnedDriveHarnessProviderEvidenceState.get(owner)\n if (prior === undefined) {\n runtimeOwnedDriveHarnessProviderEvidenceState.set(owner, evidence)\n return\n }\n const attempts = Object.freeze([...prior.attempts, ...evidence.attempts])\n const models = Object.freeze([...new Set([...prior.models, ...evidence.models])])\n const missing = attempts.some(\n (attempt) => attempt.observations.length === 0 && attempt.providerDispatch !== 'not_started',\n )\n const conflict = attempts.some((attempt) => attempt.identityConflict === true)\n const served = attempts.some((attempt) => attempt.observations.length > 0)\n runtimeOwnedDriveHarnessProviderEvidenceState.set(\n owner,\n Object.freeze(\n missing || conflict || !served\n ? {\n status: 'unknown' as const,\n attempts,\n models,\n reason: conflict\n ? ('provider-model-conflict' as const)\n : ('provider-model-missing' as const),\n }\n : { status: 'known' as const, attempts, models },\n ),\n )\n}\n\n/** Read provider evidence recorded by a Runtime-owned root drive. */\nexport function runtimeOwnedDriveHarnessProviderEvidence(\n owner: object,\n): ProviderModelExecutionEvidence | undefined {\n return runtimeOwnedDriveHarnessProviderEvidenceState.get(owner)\n}\n\n/** Build one kernel-owned known receipt from a data-only executor declaration. */\nexport function knownMaterializationReceipt(\n input: KnownReceiptInput,\n): ProfileMaterializationReceipt {\n const declaration = detachedSnapshot(input.declaration, 'executor materialization')\n assertExactDeclaration(declaration)\n const effectiveProfile = agentProfileSchema.safeParse(declaration.effectiveProfile)\n if (!effectiveProfile.success) {\n throw new ValidationError('executor materialization: effectiveProfile must be an AgentProfile')\n }\n assertNonEmpty(declaration.backend, 'backend')\n assertNonEmpty(declaration.materializer, 'materializer')\n assertNonEmpty(declaration.execution?.kind, 'execution.kind')\n assertNonEmpty(declaration.execution?.id, 'execution.id')\n assertModel(declaration.model)\n\n let effectiveProfileDigest: Sha256Digest\n let materializationPlanDigest: Sha256Digest\n let platformAttachmentsDigest: Sha256Digest | undefined\n try {\n effectiveProfileDigest = canonicalAgentProfileDigest(effectiveProfile.data)\n materializationPlanDigest = canonicalCandidateDigest(jsonWireSnapshot(declaration.plan))\n platformAttachmentsDigest =\n declaration.platformAttachments === undefined\n ? undefined\n : canonicalCandidateDigest(jsonWireSnapshot(declaration.platformAttachments))\n } catch (error) {\n throw new ValidationError(\n 'executor materialization: profile, plan, and attachments must be finite RFC 8785 JSON',\n { cause: error },\n )\n }\n\n return Object.freeze({\n status: 'known' as const,\n authoredProfileDigest: input.authoredProfileDigest,\n effectiveProfileDigest,\n materializationPlanDigest,\n ...(platformAttachmentsDigest === undefined ? {} : { platformAttachmentsDigest }),\n runtime: input.runtime,\n backend: declaration.backend,\n model: declaration.model,\n execution: declaration.execution,\n materializer: declaration.materializer,\n })\n}\n\n/** Build an explicit unknown receipt without fabricating any executor-owned identity. */\nexport function unknownMaterializationReceipt(\n input: UnknownReceiptInput,\n): ProfileMaterializationReceipt {\n return Object.freeze({\n status: 'unknown' as const,\n ...(input.authoredProfileDigest === undefined\n ? {}\n : { authoredProfileDigest: input.authoredProfileDigest }),\n runtime: input.runtime,\n reason: input.reason,\n })\n}\n\n/** Mint a process-unique attempt id before executor construction. */\nexport function newExecutionAttemptId(nodeId: string): string {\n return `${nodeId}:attempt:${randomUUID()}`\n}\n\n/** Build the immutable safe receipt for a full, transient execution binding. */\nexport function knownExecutionBindingReceipt(\n materialization: ProfileMaterializationReceipt,\n bindingInput: ExecutorExecutionBinding,\n): ExecutionBindingReceipt {\n const binding = detachedSnapshot(bindingInput, 'executor execution binding')\n assertNonEmpty(binding.attemptId, 'binding.attemptId')\n assertSafeDescriptor(binding.descriptor)\n let materializationReceiptDigest: Sha256Digest\n let bindingDigest: Sha256Digest\n try {\n materializationReceiptDigest = canonicalCandidateDigest(materialization)\n // Bind the exact JSON document a backend receives. Optional AgentProfile fields are represented\n // as `undefined` in memory but omitted by JSON transport; normalize that one distinction while\n // rejecting every non-finite/non-data value instead of silently coercing it.\n bindingDigest = canonicalCandidateDigest(jsonWireSnapshot(binding.binding))\n } catch (error) {\n throw new ValidationError('executor binding must be finite RFC 8785 JSON', { cause: error })\n }\n return Object.freeze({\n status: 'known' as const,\n attemptId: binding.attemptId,\n materializationReceiptDigest,\n bindingDigest,\n descriptor: binding.descriptor,\n })\n}\n\n/** Preserve an attempt boundary even when its caller-owned transport cannot be attested. */\nexport function unknownExecutionBindingReceipt(\n materialization: ProfileMaterializationReceipt,\n attemptId: string,\n reason: UnknownMaterializationReason,\n): ExecutionBindingReceipt {\n assertNonEmpty(attemptId, 'binding.attemptId')\n return Object.freeze({\n status: 'unknown' as const,\n attemptId,\n materializationReceiptDigest: canonicalCandidateDigest(materialization),\n reason,\n })\n}\n\n/** Derive an authored-profile digest without turning non-canonical input into a fake identity. */\nexport function authoredProfileDigest(profile: unknown): Sha256Digest | undefined {\n try {\n return canonicalAgentProfileDigest(agentProfileSchema.parse(profile))\n } catch {\n return undefined\n }\n}\n\nfunction assertExactDeclaration(value: ExecutorMaterialization): void {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new ValidationError('executor materialization: declaration must be an object')\n }\n const unknown = Object.keys(value).filter((key) => !declarationKeys.has(key))\n if (unknown.length > 0) {\n throw new ValidationError(\n `executor materialization: unknown declaration fields: ${unknown.sort().join(', ')}`,\n )\n }\n if (!Object.hasOwn(value, 'plan')) {\n throw new ValidationError('executor materialization: plan is required')\n }\n}\n\nfunction assertModel(model: ExecutorMaterialization['model']): void {\n if (typeof model !== 'object' || model === null || Array.isArray(model)) {\n throw new ValidationError('executor materialization: model must be a known/unknown identity')\n }\n const keys = Object.keys(model).sort()\n if (model.status === 'known') {\n if (keys.join(',') !== 'id,status') {\n throw new ValidationError('executor materialization: known model accepts only status and id')\n }\n assertNonEmpty(model.id, 'model.id')\n return\n }\n if (model.status === 'unknown') {\n if (keys.join(',') !== 'reason,status') {\n throw new ValidationError(\n 'executor materialization: unknown model accepts only status and reason',\n )\n }\n assertNonEmpty(model.reason, 'model.reason')\n return\n }\n throw new ValidationError('executor materialization: model.status must be known or unknown')\n}\n\nfunction assertNonEmpty(value: unknown, field: string): asserts value is string {\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new ValidationError(`executor materialization: ${field} must be a non-empty string`)\n }\n}\n\nfunction assertSafeDescriptor(descriptor: ExecutorExecutionBinding['descriptor']): void {\n if (typeof descriptor !== 'object' || descriptor === null || Array.isArray(descriptor)) {\n throw new ValidationError('executor binding: descriptor must be an object')\n }\n for (const [key, value] of Object.entries(descriptor)) {\n if (/(url|uri|token|key|secret|bearer|credential|authorization)/i.test(key)) {\n throw new ValidationError(`executor binding: unsafe descriptor key ${JSON.stringify(key)}`)\n }\n if (\n value !== null &&\n typeof value !== 'string' &&\n typeof value !== 'number' &&\n typeof value !== 'boolean'\n ) {\n throw new ValidationError(\n `executor binding: descriptor ${JSON.stringify(key)} must be scalar`,\n )\n }\n if (typeof value === 'string' && (value.includes('://') || value.includes('@'))) {\n throw new ValidationError(\n `executor binding: descriptor ${JSON.stringify(key)} contains transport or credential text`,\n )\n }\n }\n}\n\nfunction jsonWireSnapshot(value: unknown, path = '$'): unknown {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return value\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) {\n throw new ValidationError(`executor binding: ${path} must be finite`)\n }\n return value\n }\n if (Array.isArray(value)) {\n return value.map((item, index) => {\n if (item === undefined) {\n throw new ValidationError(`executor binding: ${path}[${index}] cannot be undefined`)\n }\n return jsonWireSnapshot(item, `${path}[${index}]`)\n })\n }\n if (typeof value !== 'object' || value === null) {\n throw new ValidationError(`executor binding: ${path} must be JSON data`)\n }\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) {\n throw new ValidationError(`executor binding: ${path} must be a plain object`)\n }\n const out: Record<string, unknown> = {}\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) {\n if (item === undefined) continue\n out[key] = jsonWireSnapshot(item, `${path}.${key}`)\n }\n return out\n}\n\n/**\n * The provider-identity evidence for ONE attempt, from the served model alone. `unknown` with a\n * `provider-model-missing` reason when the attempt produced no model, because an attempt that\n * cannot name what served it is not evidence that nothing did.\n */\nexport function providerAttemptEvidence(model: string | undefined): ProviderModelExecutionEvidence {\n const attempts = Object.freeze([\n Object.freeze({ observations: Object.freeze(model === undefined ? [] : [model]) }),\n ])\n const models = Object.freeze(model === undefined ? [] : [model])\n return Object.freeze(\n model === undefined\n ? { status: 'unknown' as const, attempts, models, reason: 'provider-model-missing' as const }\n : { status: 'known' as const, attempts, models },\n )\n}\n"],"mappings":";;;;;;;;;;;;AAeA,SAAgB,eACd,OACA,SAOgB;CAgBhB,OAAO;EAdL,GAAI,MAAM,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,MAAM,OAAO;EAC7D,GAAI,MAAM,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,MAAM,MAAM;EAC1D,GAAI,MAAM,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,MAAM,MAAM;EAC1D,GAAI,MAAM,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,WAAW,MAAM,UAAU;EACtE,GAAI,MAAM,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,MAAM,QAAQ;EAChE,GAAI,MAAM,iBAAiB,KAAA,IAAY,CAAC,IAAI,EAAE,cAAc,MAAM,aAAa;EAC/E,GAAI,MAAM,oBAAoB,KAAA,IAAY,CAAC,IAAI,EAAE,iBAAiB,MAAM,gBAAgB;EACxF,GAAI,MAAM,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,MAAM,OAAO;EAC7D,QAAQ,QAAQ;EAChB,QAAQ,QAAQ;EAChB,GAAI,QAAQ,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,WAAW,QAAQ,UAAU;EAC1E,GAAI,QAAQ,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,aAAa,QAAQ,YAAY;EAChF,GAAI,QAAQ,oBAAoB,KAAA,IAAY,CAAC,IAAI,EAAE,iBAAiB,QAAQ,gBAAgB;CAEnF;AAC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Y,OAAO,eAAe,KAAK;CAC7C,IAAI,cAAc,OAAO,aAAa,cAAc,MAClD,MAAM,IAAI,gBAAgB,qBAAqB,KAAK,wBAAwB;CAE9E,MAAM,MAA+B,CAAC;CACtC,KAAK,MAAM,CAAC,KAAK,SAAS,OAAO,QAAQ,KAAgC,GAAG;EAC1E,IAAI,SAAS,KAAA,GAAW;EACxB,IAAI,OAAO,iBAAiB,MAAM,GAAG,KAAK,GAAG,KAAK;CACpD;CACA,OAAO;AACT;;;;;;AAOA,SAAgB,wBAAwB,OAA2D;CACjG,MAAM,WAAW,OAAO,OAAO,CAC7B,OAAO,OAAO,EAAE,cAAc,OAAO,OAAO,UAAU,KAAA,IAAY,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,CACnF,CAAC;CACD,MAAM,SAAS,OAAO,OAAO,UAAU,KAAA,IAAY,CAAC,IAAI,CAAC,KAAK,CAAC;CAC/D,OAAO,OAAO,OACZ,UAAU,KAAA,IACN;EAAE,QAAQ;EAAoB;EAAU;EAAQ,QAAQ;CAAkC,IAC1F;EAAE,QAAQ;EAAkB;EAAU;CAAO,CACnD;AACF"}
|
|
@@ -1,393 +0,0 @@
|
|
|
1
|
-
import { randomUUID } from "node:crypto";
|
|
2
|
-
import { join, resolve } from "node:path";
|
|
3
|
-
import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
4
|
-
//#region src/runtime/supervise/run-layout.ts
|
|
5
|
-
/**
|
|
6
|
-
* The on-disk supervisor-run layout: `<root>/.agent/supervisor/<id>`.
|
|
7
|
-
*
|
|
8
|
-
* This is the durable, cross-process face of a supervisor run — the counterpart to the in-process
|
|
9
|
-
* `Inbox` seam in `./inbox`. A run persists its state under one directory so that any OTHER process
|
|
10
|
-
* can find it after the fact: `@tangle-network/traces` reads exactly this layout via
|
|
11
|
-
* `traces analyze --supervisor-run-dir`, a restarted host can rehydrate a run it no longer holds
|
|
12
|
-
* handles to, and a human can steer a live worker by appending one NDJSON line. Until now the
|
|
13
|
-
* layout was defined only in the unpublished `loops` repo (`src/supervisor-control.ts`) — a
|
|
14
|
-
* published reader depending on an unpublished writer's convention — so the contract is promoted
|
|
15
|
-
* here, names preserved.
|
|
16
|
-
*
|
|
17
|
-
* `.agent` is the one dot-dir for ALL agent-owned state (skills already write
|
|
18
|
-
* `.agent/hypotheses/`, `.agent/skill-runs.jsonl`); supervisor runs live beside them rather than
|
|
19
|
-
* under a product-branded dir. Runs written by older writers used `.loops/supervisor/<id>` —
|
|
20
|
-
* readers that must see those keep a legacy fallback; this writer never creates `.loops` again.
|
|
21
|
-
*
|
|
22
|
-
* Layout, relative to `supervisorRunDir(root, id)`:
|
|
23
|
-
*
|
|
24
|
-
* workers/<label>.inbox.ndjson down-leg steer/answer requests for one worker (durable inbox);
|
|
25
|
-
* each line is a {@link WorkerSteerRequest}
|
|
26
|
-
* workers/<label>.ndjson best-effort per-worker control-event log (delivery bookkeeping)
|
|
27
|
-
* cancellations/requests.ndjson worker-scoped cancel requests (durable inbox); each line is a
|
|
28
|
-
* {@link WorkerCancelRequest}
|
|
29
|
-
* cancellations/<opId>.json the acknowledgement for one cancel operation — a
|
|
30
|
-
* {@link WorkerCancellation} written ONLY by the runtime
|
|
31
|
-
* acknowledger in the OWNING manager's turn loop: exact node
|
|
32
|
-
* ids route to the manager that parents them (any depth);
|
|
33
|
-
* label/profile-name references to the root manager alone
|
|
34
|
-
* cancellations/run.request.json the run-scoped cancel request — one {@link RunCancelRequest},
|
|
35
|
-
* the whole RUN rather than one worker
|
|
36
|
-
* cancellations/run.json the acknowledgement for the run-scoped request — a
|
|
37
|
-
* {@link RunCancellation} written ONLY by the runtime (the root
|
|
38
|
-
* manager issues the abort; the `supervise()` settle path records
|
|
39
|
-
* what the run actually did)
|
|
40
|
-
*
|
|
41
|
-
* Reads are tolerant by contract: a partial trailing line (a writer mid-append) or a corrupt line
|
|
42
|
-
* never poisons the rest of the file — later valid lines still matter.
|
|
43
|
-
*
|
|
44
|
-
* Promoted from `loops/src/supervisor-control.ts`. The one deliberate difference: the loops version
|
|
45
|
-
* resolved a worker id to its label through the run journal before writing a steer; that resolution
|
|
46
|
-
* stays with the caller (it is journal-format-specific), so `writeWorkerSteer` here takes the worker
|
|
47
|
-
* LABEL directly.
|
|
48
|
-
*
|
|
49
|
-
* @experimental
|
|
50
|
-
*/
|
|
51
|
-
/** The root every supervisor run of one workspace lives under. */
|
|
52
|
-
function supervisorRunsRoot(rootDir) {
|
|
53
|
-
return join(resolve(rootDir), ".agent", "supervisor");
|
|
54
|
-
}
|
|
55
|
-
/** The run directory every artifact of one supervisor run lives under. */
|
|
56
|
-
function supervisorRunDir(rootDir, id) {
|
|
57
|
-
return join(supervisorRunsRoot(rootDir), id);
|
|
58
|
-
}
|
|
59
|
-
/**
|
|
60
|
-
* Where a pre-rename writer put the same run (`<root>/.loops/supervisor/<id>`). Readers that must
|
|
61
|
-
* see historical runs check {@link supervisorRunDir} first and fall back to this; nothing writes
|
|
62
|
-
* here anymore.
|
|
63
|
-
*/
|
|
64
|
-
function legacySupervisorRunDir(rootDir, id) {
|
|
65
|
-
return join(legacySupervisorRunsRoot(rootDir), id);
|
|
66
|
-
}
|
|
67
|
-
/**
|
|
68
|
-
* The pre-rename runs root (`<root>/.loops/supervisor`). Only readers that ENUMERATE historical
|
|
69
|
-
* runs need this — the per-id form is {@link legacySupervisorRunDir}. Nothing writes here.
|
|
70
|
-
*/
|
|
71
|
-
function legacySupervisorRunsRoot(rootDir) {
|
|
72
|
-
return join(resolve(rootDir), ".loops", "supervisor");
|
|
73
|
-
}
|
|
74
|
-
/** A worker label reduced to a safe filename stem. Empty labels get a stable fallback. */
|
|
75
|
-
function safeWorkerFile(label) {
|
|
76
|
-
const safe = label.replace(/[^A-Za-z0-9._-]/g, "_");
|
|
77
|
-
return safe.length > 0 ? safe : "worker";
|
|
78
|
-
}
|
|
79
|
-
/** The directory holding every per-worker file of one run (inboxes and control-event logs). */
|
|
80
|
-
function supervisorWorkersDir(eventDir) {
|
|
81
|
-
return join(eventDir, "workers");
|
|
82
|
-
}
|
|
83
|
-
/** The durable inbox file for one worker of one run. */
|
|
84
|
-
function workerInboxFile(rootDir, supervisorId, worker) {
|
|
85
|
-
return workerInboxFileFromEventDir(supervisorRunDir(rootDir, supervisorId), worker);
|
|
86
|
-
}
|
|
87
|
-
/** Same, addressed from an already-known run directory (the reader's usual entry point). */
|
|
88
|
-
function workerInboxFileFromEventDir(eventDir, worker) {
|
|
89
|
-
return join(supervisorWorkersDir(eventDir), `${safeWorkerFile(worker)}.inbox.ndjson`);
|
|
90
|
-
}
|
|
91
|
-
/**
|
|
92
|
-
* The best-effort control-event log for one worker (`workers/<label>.ndjson`) — delivery
|
|
93
|
-
* bookkeeping for steers, plus whatever lifecycle events a writer chooses to append. Distinct from
|
|
94
|
-
* the inbox: the inbox is the durable down-leg queue, this is the record of what happened to it.
|
|
95
|
-
*/
|
|
96
|
-
function workerControlLogFile(eventDir, worker) {
|
|
97
|
-
return join(supervisorWorkersDir(eventDir), `${safeWorkerFile(worker)}.ndjson`);
|
|
98
|
-
}
|
|
99
|
-
/**
|
|
100
|
-
* Durably append one steer request to a worker's inbox and log the delivery attempt.
|
|
101
|
-
*
|
|
102
|
-
* The inbox append is the durable act; the control-event log is best-effort bookkeeping and may
|
|
103
|
-
* silently fail without voiding the steer.
|
|
104
|
-
*/
|
|
105
|
-
function writeWorkerSteer(rootDir, supervisorId, worker, message, source = "human") {
|
|
106
|
-
const trimmed = message.trim();
|
|
107
|
-
if (!trimmed) throw new Error("steer message is empty");
|
|
108
|
-
const dir = supervisorRunDir(rootDir, supervisorId);
|
|
109
|
-
mkdirSync(supervisorWorkersDir(dir), { recursive: true });
|
|
110
|
-
const request = {
|
|
111
|
-
id: randomUUID(),
|
|
112
|
-
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
113
|
-
source,
|
|
114
|
-
worker,
|
|
115
|
-
message: trimmed
|
|
116
|
-
};
|
|
117
|
-
const file = workerInboxFile(rootDir, supervisorId, worker);
|
|
118
|
-
appendFileSync(file, `${JSON.stringify(request)}\n`, "utf8");
|
|
119
|
-
appendWorkerControlEvent(dir, worker, {
|
|
120
|
-
kind: "message",
|
|
121
|
-
direction: "down",
|
|
122
|
-
source,
|
|
123
|
-
requestId: request.id,
|
|
124
|
-
message: trimmed,
|
|
125
|
-
queued: true,
|
|
126
|
-
delivered: false
|
|
127
|
-
});
|
|
128
|
-
return {
|
|
129
|
-
worker,
|
|
130
|
-
file,
|
|
131
|
-
request
|
|
132
|
-
};
|
|
133
|
-
}
|
|
134
|
-
/** Read every valid steer request in a worker's inbox. Corrupt or partial lines are skipped. */
|
|
135
|
-
function readWorkerSteerRequests(eventDir, worker) {
|
|
136
|
-
const file = workerInboxFileFromEventDir(eventDir, worker);
|
|
137
|
-
if (!existsSync(file)) return [];
|
|
138
|
-
const out = [];
|
|
139
|
-
let raw = "";
|
|
140
|
-
try {
|
|
141
|
-
raw = readFileSync(file, "utf8");
|
|
142
|
-
} catch {
|
|
143
|
-
return out;
|
|
144
|
-
}
|
|
145
|
-
for (const line of raw.split("\n")) {
|
|
146
|
-
const trimmed = line.trim();
|
|
147
|
-
if (!trimmed) continue;
|
|
148
|
-
try {
|
|
149
|
-
const parsed = JSON.parse(trimmed);
|
|
150
|
-
if (isWorkerSteerRequest(parsed)) out.push(parsed);
|
|
151
|
-
} catch {}
|
|
152
|
-
}
|
|
153
|
-
return out;
|
|
154
|
-
}
|
|
155
|
-
/** The directory holding every cancellation artifact of one run (request inbox + acknowledgements). */
|
|
156
|
-
function workerCancellationsDir(eventDir) {
|
|
157
|
-
return join(eventDir, "cancellations");
|
|
158
|
-
}
|
|
159
|
-
/** The durable cancel-request inbox of one run — one NDJSON line per {@link WorkerCancelRequest}. */
|
|
160
|
-
function workerCancelRequestsFile(eventDir) {
|
|
161
|
-
return join(workerCancellationsDir(eventDir), "requests.ndjson");
|
|
162
|
-
}
|
|
163
|
-
/**
|
|
164
|
-
* The acknowledgement file for one cancel operation. The filename is a sanitized stem of the
|
|
165
|
-
* `operationId`; the record inside carries the exact id, and readers verify it so two distinct
|
|
166
|
-
* ids that sanitize to one stem fail loud instead of answering for each other.
|
|
167
|
-
*/
|
|
168
|
-
function workerCancellationFile(eventDir, operationId) {
|
|
169
|
-
return join(workerCancellationsDir(eventDir), `${safeOperationFile(operationId)}.json`);
|
|
170
|
-
}
|
|
171
|
-
function safeOperationFile(operationId) {
|
|
172
|
-
const safe = operationId.replace(/[^A-Za-z0-9._-]/g, "_");
|
|
173
|
-
if (safe.length === 0) throw new Error("cancel operationId is empty");
|
|
174
|
-
return safe;
|
|
175
|
-
}
|
|
176
|
-
/** Read every valid cancel request in the run's cancellation inbox. Corrupt lines are skipped. */
|
|
177
|
-
function readWorkerCancelRequests(eventDir) {
|
|
178
|
-
const file = workerCancelRequestsFile(eventDir);
|
|
179
|
-
if (!existsSync(file)) return [];
|
|
180
|
-
const out = [];
|
|
181
|
-
let raw = "";
|
|
182
|
-
try {
|
|
183
|
-
raw = readFileSync(file, "utf8");
|
|
184
|
-
} catch {
|
|
185
|
-
return out;
|
|
186
|
-
}
|
|
187
|
-
for (const line of raw.split("\n")) {
|
|
188
|
-
const trimmed = line.trim();
|
|
189
|
-
if (!trimmed) continue;
|
|
190
|
-
try {
|
|
191
|
-
const parsed = JSON.parse(trimmed);
|
|
192
|
-
if (isWorkerCancelRequest(parsed)) out.push(parsed);
|
|
193
|
-
} catch {}
|
|
194
|
-
}
|
|
195
|
-
return out;
|
|
196
|
-
}
|
|
197
|
-
/**
|
|
198
|
-
* Read the acknowledgement for one cancel operation. `undefined` when the runtime has not
|
|
199
|
-
* answered. A record whose stored `operationId` differs from the requested one is a filename
|
|
200
|
-
* collision between two sanitized ids — fail loud rather than return another operation's answer.
|
|
201
|
-
*/
|
|
202
|
-
function readWorkerCancellation(eventDir, operationId) {
|
|
203
|
-
const file = workerCancellationFile(eventDir, operationId);
|
|
204
|
-
if (!existsSync(file)) return void 0;
|
|
205
|
-
const parsed = JSON.parse(readFileSync(file, "utf8"));
|
|
206
|
-
if (parsed.operationId !== operationId) throw new Error(`cancel acknowledgement collision: '${file}' holds operation '${parsed.operationId}', not '${operationId}' — use operation ids that stay distinct after filename sanitization`);
|
|
207
|
-
return parsed;
|
|
208
|
-
}
|
|
209
|
-
/**
|
|
210
|
-
* Durably write one acknowledgement record. Write-then-rename, so a concurrent reader sees the
|
|
211
|
-
* prior complete record or the new complete record, never a partial file.
|
|
212
|
-
*
|
|
213
|
-
* @internal The runtime acknowledger is the only intended writer; clients read via
|
|
214
|
-
* {@link readWorkerCancellation} or {@link cancelWorker}.
|
|
215
|
-
*/
|
|
216
|
-
function writeWorkerCancellation(eventDir, record) {
|
|
217
|
-
mkdirSync(workerCancellationsDir(eventDir), { recursive: true });
|
|
218
|
-
const file = workerCancellationFile(eventDir, record.operationId);
|
|
219
|
-
const tmp = `${file}.${randomUUID()}.tmp`;
|
|
220
|
-
writeFileSync(tmp, `${JSON.stringify(record, null, 2)}\n`, "utf8");
|
|
221
|
-
renameSync(tmp, file);
|
|
222
|
-
}
|
|
223
|
-
/**
|
|
224
|
-
* Request the cancellation of ONE worker, idempotently, and return the operation's current
|
|
225
|
-
* durable state.
|
|
226
|
-
*
|
|
227
|
-
* The write half of the acknowledged-cancellation contract (`writeWorkerSteer` is the steer
|
|
228
|
-
* analog): append the request to the run's cancellation inbox, where the OWNING manager's
|
|
229
|
-
* acknowledger (its turn loop — the root for label/profile references, the parent manager for an
|
|
230
|
-
* exact node id at any depth) applies it — aborting exactly that worker's subtree and recording
|
|
231
|
-
* what it proved. This function never applies the cancellation itself; writing a
|
|
232
|
-
* request file is not an acknowledgement.
|
|
233
|
-
*
|
|
234
|
-
* Idempotency is a lookup: when an acknowledgement for `operationId` already exists, it is
|
|
235
|
-
* returned AS-IS and nothing is appended — repeating one operation can never apply twice. A
|
|
236
|
-
* request the runtime has not answered yet returns `effect: 'unknown'` (never a success); call
|
|
237
|
-
* again with the same `operationId` — or `readWorkerCancellation` — to read the acknowledged
|
|
238
|
-
* result after a reconnect.
|
|
239
|
-
*/
|
|
240
|
-
function cancelWorker(eventDir, worker, operationId, options = {}) {
|
|
241
|
-
const ref = worker.trim();
|
|
242
|
-
if (!ref) throw new Error("cancelWorker: worker reference is empty");
|
|
243
|
-
const opId = operationId.trim();
|
|
244
|
-
if (!opId) throw new Error("cancelWorker: operationId is empty");
|
|
245
|
-
const acknowledged = readWorkerCancellation(eventDir, opId);
|
|
246
|
-
if (acknowledged) return acknowledged;
|
|
247
|
-
const source = options.source ?? "human";
|
|
248
|
-
const pending = readWorkerCancelRequests(eventDir).find((r) => r.operationId === opId);
|
|
249
|
-
const request = pending ?? {
|
|
250
|
-
operationId: opId,
|
|
251
|
-
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
252
|
-
source,
|
|
253
|
-
worker: ref,
|
|
254
|
-
...options.reason === void 0 ? {} : { reason: options.reason }
|
|
255
|
-
};
|
|
256
|
-
if (!pending) {
|
|
257
|
-
mkdirSync(workerCancellationsDir(eventDir), { recursive: true });
|
|
258
|
-
appendFileSync(workerCancelRequestsFile(eventDir), `${JSON.stringify(request)}\n`, "utf8");
|
|
259
|
-
appendWorkerControlEvent(eventDir, ref, {
|
|
260
|
-
kind: "cancel-request",
|
|
261
|
-
operationId: opId,
|
|
262
|
-
source,
|
|
263
|
-
queued: true,
|
|
264
|
-
...options.reason === void 0 ? {} : { reason: options.reason }
|
|
265
|
-
});
|
|
266
|
-
}
|
|
267
|
-
return {
|
|
268
|
-
operationId: opId,
|
|
269
|
-
worker: request.worker,
|
|
270
|
-
effect: "unknown",
|
|
271
|
-
requestedAt: request.at,
|
|
272
|
-
observedAt: request.at,
|
|
273
|
-
...request.reason === void 0 ? {} : { reason: request.reason },
|
|
274
|
-
detail: "request queued; no runtime acknowledger has answered yet",
|
|
275
|
-
terminated: []
|
|
276
|
-
};
|
|
277
|
-
}
|
|
278
|
-
/** The run-scoped cancel request file of one run — one {@link RunCancelRequest}. */
|
|
279
|
-
function runCancelRequestFile(eventDir) {
|
|
280
|
-
return join(workerCancellationsDir(eventDir), "run.request.json");
|
|
281
|
-
}
|
|
282
|
-
/** The run-scoped acknowledgement file of one run — one {@link RunCancellation}. */
|
|
283
|
-
function runCancellationFile(eventDir) {
|
|
284
|
-
return join(workerCancellationsDir(eventDir), "run.json");
|
|
285
|
-
}
|
|
286
|
-
/** Read the run-scoped cancel request, or `undefined` when none was written. */
|
|
287
|
-
function readRunCancelRequest(eventDir) {
|
|
288
|
-
const file = runCancelRequestFile(eventDir);
|
|
289
|
-
if (!existsSync(file)) return void 0;
|
|
290
|
-
const parsed = JSON.parse(readFileSync(file, "utf8"));
|
|
291
|
-
if (!isRunCancelRequest(parsed)) throw new Error(`run cancel request '${file}' is not a complete RunCancelRequest`);
|
|
292
|
-
return parsed;
|
|
293
|
-
}
|
|
294
|
-
/**
|
|
295
|
-
* Read the acknowledgement for the run-scoped cancel operation. `undefined` when the runtime has
|
|
296
|
-
* not answered. A record holding a DIFFERENT `operationId` belongs to another operation on the
|
|
297
|
-
* same run — fail loud rather than answer for it.
|
|
298
|
-
*/
|
|
299
|
-
function readRunCancellation(eventDir, operationId) {
|
|
300
|
-
const file = runCancellationFile(eventDir);
|
|
301
|
-
if (!existsSync(file)) return void 0;
|
|
302
|
-
const parsed = JSON.parse(readFileSync(file, "utf8"));
|
|
303
|
-
if (parsed.operationId !== operationId) throw new Error(`run cancel acknowledgement '${file}' holds operation '${parsed.operationId}', not '${operationId}' — one run carries one run-scoped cancel operation`);
|
|
304
|
-
return parsed;
|
|
305
|
-
}
|
|
306
|
-
/**
|
|
307
|
-
* Durably write the run-scoped acknowledgement. Write-then-rename, so a concurrent reader sees the
|
|
308
|
-
* prior complete record or the new complete record, never a partial file.
|
|
309
|
-
*
|
|
310
|
-
* @internal The runtime is the only intended writer; clients read via {@link readRunCancellation}
|
|
311
|
-
* or {@link cancelRun}.
|
|
312
|
-
*/
|
|
313
|
-
function writeRunCancellation(eventDir, record) {
|
|
314
|
-
mkdirSync(workerCancellationsDir(eventDir), { recursive: true });
|
|
315
|
-
const file = runCancellationFile(eventDir);
|
|
316
|
-
const tmp = `${file}.${randomUUID()}.tmp`;
|
|
317
|
-
writeFileSync(tmp, `${JSON.stringify(record, null, 2)}\n`, "utf8");
|
|
318
|
-
renameSync(tmp, file);
|
|
319
|
-
}
|
|
320
|
-
/**
|
|
321
|
-
* Request the cancellation of the WHOLE run, idempotently, and return the operation's current
|
|
322
|
-
* durable state.
|
|
323
|
-
*
|
|
324
|
-
* The run-scoped twin of {@link cancelWorker}: write the request into the run's cancellation
|
|
325
|
-
* directory, where the run's own root manager applies it — aborting the root through the one
|
|
326
|
-
* cascade controller the run already has, so every live worker comes down with it. This function
|
|
327
|
-
* never applies the cancellation itself; writing a request file is not an acknowledgement.
|
|
328
|
-
*
|
|
329
|
-
* Idempotency is a lookup: when an acknowledgement for `operationId` already exists it is returned
|
|
330
|
-
* AS-IS and nothing is written. A request the runtime has not answered yet returns
|
|
331
|
-
* `effect: 'unknown'` (never a success); call again with the same `operationId` — or
|
|
332
|
-
* {@link readRunCancellation} — to read the acknowledged result after a reconnect.
|
|
333
|
-
*
|
|
334
|
-
* A run carries ONE run-scoped operation: a second request under a different `operationId` throws
|
|
335
|
-
* rather than silently replacing the pending one, because both would claim the same single abort.
|
|
336
|
-
*/
|
|
337
|
-
function cancelRun(eventDir, operationId, options = {}) {
|
|
338
|
-
const opId = operationId.trim();
|
|
339
|
-
if (!opId) throw new Error("cancelRun: operationId is empty");
|
|
340
|
-
const acknowledged = readRunCancellation(eventDir, opId);
|
|
341
|
-
if (acknowledged) return acknowledged;
|
|
342
|
-
const pending = readRunCancelRequest(eventDir);
|
|
343
|
-
if (pending !== void 0 && pending.operationId !== opId) throw new Error(`cancelRun: run cancel '${pending.operationId}' is already pending for this run; read it with readRunCancellation instead of issuing '${opId}'`);
|
|
344
|
-
const source = options.source ?? "human";
|
|
345
|
-
const request = pending ?? {
|
|
346
|
-
operationId: opId,
|
|
347
|
-
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
348
|
-
source,
|
|
349
|
-
...options.reason === void 0 ? {} : { reason: options.reason }
|
|
350
|
-
};
|
|
351
|
-
if (pending === void 0) {
|
|
352
|
-
mkdirSync(workerCancellationsDir(eventDir), { recursive: true });
|
|
353
|
-
writeFileSync(runCancelRequestFile(eventDir), `${JSON.stringify(request, null, 2)}\n`, "utf8");
|
|
354
|
-
appendWorkerControlEvent(eventDir, "run", {
|
|
355
|
-
kind: "run-cancel-request",
|
|
356
|
-
operationId: opId,
|
|
357
|
-
source,
|
|
358
|
-
queued: true,
|
|
359
|
-
...options.reason === void 0 ? {} : { reason: options.reason }
|
|
360
|
-
});
|
|
361
|
-
}
|
|
362
|
-
return {
|
|
363
|
-
operationId: opId,
|
|
364
|
-
effect: "unknown",
|
|
365
|
-
requestedAt: request.at,
|
|
366
|
-
observedAt: request.at,
|
|
367
|
-
...request.reason === void 0 ? {} : { reason: request.reason },
|
|
368
|
-
detail: "request queued; no runtime acknowledger has answered yet"
|
|
369
|
-
};
|
|
370
|
-
}
|
|
371
|
-
function isRunCancelRequest(value) {
|
|
372
|
-
return typeof value.operationId === "string" && value.operationId.length > 0 && typeof value.at === "string" && typeof value.source === "string" && (value.reason === void 0 || typeof value.reason === "string");
|
|
373
|
-
}
|
|
374
|
-
function isWorkerCancelRequest(value) {
|
|
375
|
-
return typeof value.operationId === "string" && value.operationId.length > 0 && typeof value.at === "string" && typeof value.source === "string" && typeof value.worker === "string" && value.worker.length > 0 && (value.reason === void 0 || typeof value.reason === "string");
|
|
376
|
-
}
|
|
377
|
-
function appendWorkerControlEvent(eventDir, label, event) {
|
|
378
|
-
try {
|
|
379
|
-
mkdirSync(supervisorWorkersDir(eventDir), { recursive: true });
|
|
380
|
-
appendFileSync(workerControlLogFile(eventDir, label), `${JSON.stringify({
|
|
381
|
-
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
382
|
-
label,
|
|
383
|
-
...event
|
|
384
|
-
})}\n`, "utf8");
|
|
385
|
-
} catch {}
|
|
386
|
-
}
|
|
387
|
-
function isWorkerSteerRequest(value) {
|
|
388
|
-
return typeof value.id === "string" && typeof value.at === "string" && typeof value.source === "string" && typeof value.worker === "string" && typeof value.message === "string" && value.message.trim().length > 0;
|
|
389
|
-
}
|
|
390
|
-
//#endregion
|
|
391
|
-
export { writeWorkerCancellation as C, writeRunCancellation as S, workerCancellationFile as _, readRunCancelRequest as a, workerInboxFile as b, readWorkerCancellation as c, runCancellationFile as d, safeWorkerFile as f, workerCancelRequestsFile as g, supervisorWorkersDir as h, legacySupervisorRunsRoot as i, readWorkerSteerRequests as l, supervisorRunsRoot as m, cancelWorker as n, readRunCancellation as o, supervisorRunDir as p, legacySupervisorRunDir as r, readWorkerCancelRequests as s, cancelRun as t, runCancelRequestFile as u, workerCancellationsDir as v, writeWorkerSteer as w, workerInboxFileFromEventDir as x, workerControlLogFile as y };
|
|
392
|
-
|
|
393
|
-
//# sourceMappingURL=run-layout-C2jgwsCq.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"run-layout-C2jgwsCq.js","names":[],"sources":["../src/runtime/supervise/run-layout.ts"],"sourcesContent":["/**\n * The on-disk supervisor-run layout: `<root>/.agent/supervisor/<id>`.\n *\n * This is the durable, cross-process face of a supervisor run — the counterpart to the in-process\n * `Inbox` seam in `./inbox`. A run persists its state under one directory so that any OTHER process\n * can find it after the fact: `@tangle-network/traces` reads exactly this layout via\n * `traces analyze --supervisor-run-dir`, a restarted host can rehydrate a run it no longer holds\n * handles to, and a human can steer a live worker by appending one NDJSON line. Until now the\n * layout was defined only in the unpublished `loops` repo (`src/supervisor-control.ts`) — a\n * published reader depending on an unpublished writer's convention — so the contract is promoted\n * here, names preserved.\n *\n * `.agent` is the one dot-dir for ALL agent-owned state (skills already write\n * `.agent/hypotheses/`, `.agent/skill-runs.jsonl`); supervisor runs live beside them rather than\n * under a product-branded dir. Runs written by older writers used `.loops/supervisor/<id>` —\n * readers that must see those keep a legacy fallback; this writer never creates `.loops` again.\n *\n * Layout, relative to `supervisorRunDir(root, id)`:\n *\n * workers/<label>.inbox.ndjson down-leg steer/answer requests for one worker (durable inbox);\n * each line is a {@link WorkerSteerRequest}\n * workers/<label>.ndjson best-effort per-worker control-event log (delivery bookkeeping)\n * cancellations/requests.ndjson worker-scoped cancel requests (durable inbox); each line is a\n * {@link WorkerCancelRequest}\n * cancellations/<opId>.json the acknowledgement for one cancel operation — a\n * {@link WorkerCancellation} written ONLY by the runtime\n * acknowledger in the OWNING manager's turn loop: exact node\n * ids route to the manager that parents them (any depth);\n * label/profile-name references to the root manager alone\n * cancellations/run.request.json the run-scoped cancel request — one {@link RunCancelRequest},\n * the whole RUN rather than one worker\n * cancellations/run.json the acknowledgement for the run-scoped request — a\n * {@link RunCancellation} written ONLY by the runtime (the root\n * manager issues the abort; the `supervise()` settle path records\n * what the run actually did)\n *\n * Reads are tolerant by contract: a partial trailing line (a writer mid-append) or a corrupt line\n * never poisons the rest of the file — later valid lines still matter.\n *\n * Promoted from `loops/src/supervisor-control.ts`. The one deliberate difference: the loops version\n * resolved a worker id to its label through the run journal before writing a steer; that resolution\n * stays with the caller (it is journal-format-specific), so `writeWorkerSteer` here takes the worker\n * LABEL directly.\n *\n * @experimental\n */\n\nimport { randomUUID } from 'node:crypto'\nimport {\n appendFileSync,\n existsSync,\n mkdirSync,\n readFileSync,\n renameSync,\n writeFileSync,\n} from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport type { RetainedRunEffect } from '../retained-run-types'\n\n/** One durable down-leg request appended to a worker's inbox file. */\nexport interface WorkerSteerRequest {\n readonly id: string\n /** ISO timestamp of the append. */\n readonly at: string\n /** Who asked — 'human', a brain label, a tool name. Provenance, not authorization. */\n readonly source: string\n /** The worker LABEL the request targets (already resolved by the caller). */\n readonly worker: string\n readonly message: string\n}\n\n/** One durable worker-scoped cancel request appended to the run's cancellation inbox. */\nexport interface WorkerCancelRequest {\n /** Caller-minted stable operation identifier — the idempotency key of the whole operation. */\n readonly operationId: string\n /** ISO timestamp of the append. */\n readonly at: string\n /** Who asked — 'human', a brain label, a tool name. Provenance, not authorization. */\n readonly source: string\n /** The worker the request targets: a workerId (node id — routed to the owning manager at any\n * depth), or a profile name or spawn label (resolved by the root manager against its direct\n * children only). */\n readonly worker: string\n readonly reason?: string\n}\n\n/**\n * The durable acknowledgement state for one worker-scoped cancel operation, keyed by\n * `operationId`. The runtime acknowledger is the ONLY writer; `cancelWorker` only reads it.\n *\n * `effect` reuses the retained-run vocabulary ({@link RetainedRunEffect}) so the runtime has one\n * spelling of the four cancellation states:\n * - `'unknown'` — not yet resolved by the runtime (also what `cancelWorker` returns for\n * a request no acknowledger has answered), or — terminally, with the\n * run-over detail — an abort was issued but the run ended before the\n * termination could be observed. Never a success.\n * - `'cancel_requested'` — the runtime issued the worker's abort; termination not yet proven.\n * - `'cancelled'` — the worker reached a terminal `down` state on the settle path.\n * - `'not_live'` — the worker was not live to cancel (already settled, it settled\n * `done` despite the abort, or the run ended before the request was\n * ever applied). Never a success of THIS operation.\n *\n * Expiry is run end: the owning manager's final pass closes every still-open request it owns\n * (`not_live` never applied, `unknown` issued-but-unproven), so a pending request cannot outlive\n * its run and abort a future spawn that happens to reuse a label.\n */\nexport interface WorkerCancellation {\n readonly operationId: string\n /** The worker reference exactly as requested. */\n readonly worker: string\n readonly effect: RetainedRunEffect\n /** ISO timestamp of the original request. */\n readonly requestedAt: string\n /** ISO timestamp of the runtime's most recent observation of this operation. */\n readonly observedAt: string\n /** The node id the acknowledger resolved `worker` to, once resolved. */\n readonly workerId?: string\n /** The caller's reason, carried verbatim from the request. */\n readonly reason?: string\n /** The runtime's explanation of how it arrived at `effect`. */\n readonly detail?: string\n /**\n * Every node id this operation PROVED terminated: the requested worker plus each descendant of\n * its subtree observed to reach a terminal `down`/`cancelled` journal record at or after the\n * abort was ISSUED — the acknowledger's own `observedAt` on the `cancel_requested` record\n * (runtime clock), never the client's `requestedAt` (a cancelled lead cascades to its subtree\n * by design — the scope signal chain — so the acknowledgement names the set, not one id).\n * Proven at acknowledgement time; post-abort causation is approximate: a descendant that died\n * of its own cause after the abort is indistinguishable from the cascade and may be included,\n * a late teardown journal joins the set on a later pass while the manager still runs, and one\n * still absent at run end is absent from the set. Grows monotonically; empty until termination\n * is proven.\n */\n readonly terminated: ReadonlyArray<string>\n}\n\n/** One durable run-scoped cancel request: cancel the WHOLE run, not one worker. */\nexport interface RunCancelRequest {\n /** Caller-minted stable operation identifier — the idempotency key of the whole operation. */\n readonly operationId: string\n /** ISO timestamp of the write. */\n readonly at: string\n /** Who asked — 'human', a brain label, a tool name. Provenance, not authorization. */\n readonly source: string\n readonly reason?: string\n}\n\n/**\n * The durable acknowledgement state for the run-scoped cancel operation, keyed by `operationId`.\n * The runtime is the ONLY writer; {@link cancelRun} only reads it.\n *\n * `effect` is the same {@link RetainedRunEffect} vocabulary the worker-scoped and retained-run\n * paths use, so the runtime has one spelling of the four cancellation states:\n * - `'unknown'` — no runtime has answered yet. Never a success.\n * - `'cancel_requested'` — the root manager issued the run's cascading abort; the run's terminal\n * state is not yet observed.\n * - `'cancelled'` — the run reached its terminal state ABORTED after that request.\n * - `'not_live'` — the run was not live to cancel: it settled on its own despite the\n * request, or it ended before the request was applied.\n */\nexport interface RunCancellation {\n readonly operationId: string\n readonly effect: RetainedRunEffect\n /** ISO timestamp of the original request. */\n readonly requestedAt: string\n /** ISO timestamp of the runtime's most recent observation of this operation. */\n readonly observedAt: string\n /** The caller's reason, carried verbatim from the request. */\n readonly reason?: string\n /** The runtime's explanation of how it arrived at `effect`. */\n readonly detail?: string\n}\n\n/** The root every supervisor run of one workspace lives under. */\nexport function supervisorRunsRoot(rootDir: string): string {\n return join(resolve(rootDir), '.agent', 'supervisor')\n}\n\n/** The run directory every artifact of one supervisor run lives under. */\nexport function supervisorRunDir(rootDir: string, id: string): string {\n return join(supervisorRunsRoot(rootDir), id)\n}\n\n/**\n * Where a pre-rename writer put the same run (`<root>/.loops/supervisor/<id>`). Readers that must\n * see historical runs check {@link supervisorRunDir} first and fall back to this; nothing writes\n * here anymore.\n */\nexport function legacySupervisorRunDir(rootDir: string, id: string): string {\n return join(legacySupervisorRunsRoot(rootDir), id)\n}\n\n/**\n * The pre-rename runs root (`<root>/.loops/supervisor`). Only readers that ENUMERATE historical\n * runs need this — the per-id form is {@link legacySupervisorRunDir}. Nothing writes here.\n */\nexport function legacySupervisorRunsRoot(rootDir: string): string {\n return join(resolve(rootDir), '.loops', 'supervisor')\n}\n\n/** A worker label reduced to a safe filename stem. Empty labels get a stable fallback. */\nexport function safeWorkerFile(label: string): string {\n const safe = label.replace(/[^A-Za-z0-9._-]/g, '_')\n return safe.length > 0 ? safe : 'worker'\n}\n\n/** The directory holding every per-worker file of one run (inboxes and control-event logs). */\nexport function supervisorWorkersDir(eventDir: string): string {\n return join(eventDir, 'workers')\n}\n\n/** The durable inbox file for one worker of one run. */\nexport function workerInboxFile(rootDir: string, supervisorId: string, worker: string): string {\n return workerInboxFileFromEventDir(supervisorRunDir(rootDir, supervisorId), worker)\n}\n\n/** Same, addressed from an already-known run directory (the reader's usual entry point). */\nexport function workerInboxFileFromEventDir(eventDir: string, worker: string): string {\n return join(supervisorWorkersDir(eventDir), `${safeWorkerFile(worker)}.inbox.ndjson`)\n}\n\n/**\n * The best-effort control-event log for one worker (`workers/<label>.ndjson`) — delivery\n * bookkeeping for steers, plus whatever lifecycle events a writer chooses to append. Distinct from\n * the inbox: the inbox is the durable down-leg queue, this is the record of what happened to it.\n */\nexport function workerControlLogFile(eventDir: string, worker: string): string {\n return join(supervisorWorkersDir(eventDir), `${safeWorkerFile(worker)}.ndjson`)\n}\n\n/**\n * Durably append one steer request to a worker's inbox and log the delivery attempt.\n *\n * The inbox append is the durable act; the control-event log is best-effort bookkeeping and may\n * silently fail without voiding the steer.\n */\nexport function writeWorkerSteer(\n rootDir: string,\n supervisorId: string,\n worker: string,\n message: string,\n source = 'human',\n): { worker: string; file: string; request: WorkerSteerRequest } {\n const trimmed = message.trim()\n if (!trimmed) throw new Error('steer message is empty')\n const dir = supervisorRunDir(rootDir, supervisorId)\n mkdirSync(supervisorWorkersDir(dir), { recursive: true })\n const request: WorkerSteerRequest = {\n id: randomUUID(),\n at: new Date().toISOString(),\n source,\n worker,\n message: trimmed,\n }\n const file = workerInboxFile(rootDir, supervisorId, worker)\n appendFileSync(file, `${JSON.stringify(request)}\\n`, 'utf8')\n appendWorkerControlEvent(dir, worker, {\n kind: 'message',\n direction: 'down',\n source,\n requestId: request.id,\n message: trimmed,\n queued: true,\n delivered: false,\n })\n return { worker, file, request }\n}\n\n/** Read every valid steer request in a worker's inbox. Corrupt or partial lines are skipped. */\nexport function readWorkerSteerRequests(eventDir: string, worker: string): WorkerSteerRequest[] {\n const file = workerInboxFileFromEventDir(eventDir, worker)\n if (!existsSync(file)) return []\n const out: WorkerSteerRequest[] = []\n let raw = ''\n try {\n raw = readFileSync(file, 'utf8')\n } catch {\n return out\n }\n for (const line of raw.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed) continue\n try {\n const parsed = JSON.parse(trimmed) as Partial<WorkerSteerRequest>\n if (isWorkerSteerRequest(parsed)) out.push(parsed)\n } catch {\n // Ignore partial or corrupt input lines; later valid lines still matter.\n }\n }\n return out\n}\n\n/** The directory holding every cancellation artifact of one run (request inbox + acknowledgements). */\nexport function workerCancellationsDir(eventDir: string): string {\n return join(eventDir, 'cancellations')\n}\n\n/** The durable cancel-request inbox of one run — one NDJSON line per {@link WorkerCancelRequest}. */\nexport function workerCancelRequestsFile(eventDir: string): string {\n return join(workerCancellationsDir(eventDir), 'requests.ndjson')\n}\n\n/**\n * The acknowledgement file for one cancel operation. The filename is a sanitized stem of the\n * `operationId`; the record inside carries the exact id, and readers verify it so two distinct\n * ids that sanitize to one stem fail loud instead of answering for each other.\n */\nexport function workerCancellationFile(eventDir: string, operationId: string): string {\n return join(workerCancellationsDir(eventDir), `${safeOperationFile(operationId)}.json`)\n}\n\nfunction safeOperationFile(operationId: string): string {\n const safe = operationId.replace(/[^A-Za-z0-9._-]/g, '_')\n if (safe.length === 0) throw new Error('cancel operationId is empty')\n return safe\n}\n\n/** Read every valid cancel request in the run's cancellation inbox. Corrupt lines are skipped. */\nexport function readWorkerCancelRequests(eventDir: string): WorkerCancelRequest[] {\n const file = workerCancelRequestsFile(eventDir)\n if (!existsSync(file)) return []\n const out: WorkerCancelRequest[] = []\n let raw = ''\n try {\n raw = readFileSync(file, 'utf8')\n } catch {\n return out\n }\n for (const line of raw.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed) continue\n try {\n const parsed = JSON.parse(trimmed) as Partial<WorkerCancelRequest>\n if (isWorkerCancelRequest(parsed)) out.push(parsed)\n } catch {\n // Ignore partial or corrupt input lines; later valid lines still matter.\n }\n }\n return out\n}\n\n/**\n * Read the acknowledgement for one cancel operation. `undefined` when the runtime has not\n * answered. A record whose stored `operationId` differs from the requested one is a filename\n * collision between two sanitized ids — fail loud rather than return another operation's answer.\n */\nexport function readWorkerCancellation(\n eventDir: string,\n operationId: string,\n): WorkerCancellation | undefined {\n const file = workerCancellationFile(eventDir, operationId)\n if (!existsSync(file)) return undefined\n const parsed = JSON.parse(readFileSync(file, 'utf8')) as WorkerCancellation\n if (parsed.operationId !== operationId) {\n throw new Error(\n `cancel acknowledgement collision: '${file}' holds operation '${parsed.operationId}', ` +\n `not '${operationId}' — use operation ids that stay distinct after filename sanitization`,\n )\n }\n return parsed\n}\n\n/**\n * Durably write one acknowledgement record. Write-then-rename, so a concurrent reader sees the\n * prior complete record or the new complete record, never a partial file.\n *\n * @internal The runtime acknowledger is the only intended writer; clients read via\n * {@link readWorkerCancellation} or {@link cancelWorker}.\n */\nexport function writeWorkerCancellation(eventDir: string, record: WorkerCancellation): void {\n const dir = workerCancellationsDir(eventDir)\n mkdirSync(dir, { recursive: true })\n const file = workerCancellationFile(eventDir, record.operationId)\n const tmp = `${file}.${randomUUID()}.tmp`\n writeFileSync(tmp, `${JSON.stringify(record, null, 2)}\\n`, 'utf8')\n renameSync(tmp, file)\n}\n\n/**\n * Request the cancellation of ONE worker, idempotently, and return the operation's current\n * durable state.\n *\n * The write half of the acknowledged-cancellation contract (`writeWorkerSteer` is the steer\n * analog): append the request to the run's cancellation inbox, where the OWNING manager's\n * acknowledger (its turn loop — the root for label/profile references, the parent manager for an\n * exact node id at any depth) applies it — aborting exactly that worker's subtree and recording\n * what it proved. This function never applies the cancellation itself; writing a\n * request file is not an acknowledgement.\n *\n * Idempotency is a lookup: when an acknowledgement for `operationId` already exists, it is\n * returned AS-IS and nothing is appended — repeating one operation can never apply twice. A\n * request the runtime has not answered yet returns `effect: 'unknown'` (never a success); call\n * again with the same `operationId` — or `readWorkerCancellation` — to read the acknowledged\n * result after a reconnect.\n */\nexport function cancelWorker(\n eventDir: string,\n worker: string,\n operationId: string,\n options: { readonly reason?: string; readonly source?: string } = {},\n): WorkerCancellation {\n const ref = worker.trim()\n if (!ref) throw new Error('cancelWorker: worker reference is empty')\n const opId = operationId.trim()\n if (!opId) throw new Error('cancelWorker: operationId is empty')\n const acknowledged = readWorkerCancellation(eventDir, opId)\n if (acknowledged) return acknowledged\n const source = options.source ?? 'human'\n const pending = readWorkerCancelRequests(eventDir).find((r) => r.operationId === opId)\n const request: WorkerCancelRequest = pending ?? {\n operationId: opId,\n at: new Date().toISOString(),\n source,\n worker: ref,\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n }\n if (!pending) {\n mkdirSync(workerCancellationsDir(eventDir), { recursive: true })\n appendFileSync(workerCancelRequestsFile(eventDir), `${JSON.stringify(request)}\\n`, 'utf8')\n appendWorkerControlEvent(eventDir, ref, {\n kind: 'cancel-request',\n operationId: opId,\n source,\n queued: true,\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n })\n }\n return {\n operationId: opId,\n worker: request.worker,\n effect: 'unknown',\n requestedAt: request.at,\n observedAt: request.at,\n ...(request.reason === undefined ? {} : { reason: request.reason }),\n detail: 'request queued; no runtime acknowledger has answered yet',\n terminated: [],\n }\n}\n\n/** The run-scoped cancel request file of one run — one {@link RunCancelRequest}. */\nexport function runCancelRequestFile(eventDir: string): string {\n return join(workerCancellationsDir(eventDir), 'run.request.json')\n}\n\n/** The run-scoped acknowledgement file of one run — one {@link RunCancellation}. */\nexport function runCancellationFile(eventDir: string): string {\n return join(workerCancellationsDir(eventDir), 'run.json')\n}\n\n/** Read the run-scoped cancel request, or `undefined` when none was written. */\nexport function readRunCancelRequest(eventDir: string): RunCancelRequest | undefined {\n const file = runCancelRequestFile(eventDir)\n if (!existsSync(file)) return undefined\n const parsed = JSON.parse(readFileSync(file, 'utf8')) as Partial<RunCancelRequest>\n if (!isRunCancelRequest(parsed)) {\n throw new Error(`run cancel request '${file}' is not a complete RunCancelRequest`)\n }\n return parsed\n}\n\n/**\n * Read the acknowledgement for the run-scoped cancel operation. `undefined` when the runtime has\n * not answered. A record holding a DIFFERENT `operationId` belongs to another operation on the\n * same run — fail loud rather than answer for it.\n */\nexport function readRunCancellation(\n eventDir: string,\n operationId: string,\n): RunCancellation | undefined {\n const file = runCancellationFile(eventDir)\n if (!existsSync(file)) return undefined\n const parsed = JSON.parse(readFileSync(file, 'utf8')) as RunCancellation\n if (parsed.operationId !== operationId) {\n throw new Error(\n `run cancel acknowledgement '${file}' holds operation '${parsed.operationId}', not ` +\n `'${operationId}' — one run carries one run-scoped cancel operation`,\n )\n }\n return parsed\n}\n\n/**\n * Durably write the run-scoped acknowledgement. Write-then-rename, so a concurrent reader sees the\n * prior complete record or the new complete record, never a partial file.\n *\n * @internal The runtime is the only intended writer; clients read via {@link readRunCancellation}\n * or {@link cancelRun}.\n */\nexport function writeRunCancellation(eventDir: string, record: RunCancellation): void {\n const dir = workerCancellationsDir(eventDir)\n mkdirSync(dir, { recursive: true })\n const file = runCancellationFile(eventDir)\n const tmp = `${file}.${randomUUID()}.tmp`\n writeFileSync(tmp, `${JSON.stringify(record, null, 2)}\\n`, 'utf8')\n renameSync(tmp, file)\n}\n\n/**\n * Request the cancellation of the WHOLE run, idempotently, and return the operation's current\n * durable state.\n *\n * The run-scoped twin of {@link cancelWorker}: write the request into the run's cancellation\n * directory, where the run's own root manager applies it — aborting the root through the one\n * cascade controller the run already has, so every live worker comes down with it. This function\n * never applies the cancellation itself; writing a request file is not an acknowledgement.\n *\n * Idempotency is a lookup: when an acknowledgement for `operationId` already exists it is returned\n * AS-IS and nothing is written. A request the runtime has not answered yet returns\n * `effect: 'unknown'` (never a success); call again with the same `operationId` — or\n * {@link readRunCancellation} — to read the acknowledged result after a reconnect.\n *\n * A run carries ONE run-scoped operation: a second request under a different `operationId` throws\n * rather than silently replacing the pending one, because both would claim the same single abort.\n */\nexport function cancelRun(\n eventDir: string,\n operationId: string,\n options: { readonly reason?: string; readonly source?: string } = {},\n): RunCancellation {\n const opId = operationId.trim()\n if (!opId) throw new Error('cancelRun: operationId is empty')\n const acknowledged = readRunCancellation(eventDir, opId)\n if (acknowledged) return acknowledged\n const pending = readRunCancelRequest(eventDir)\n if (pending !== undefined && pending.operationId !== opId) {\n throw new Error(\n `cancelRun: run cancel '${pending.operationId}' is already pending for this run; ` +\n `read it with readRunCancellation instead of issuing '${opId}'`,\n )\n }\n const source = options.source ?? 'human'\n const request: RunCancelRequest = pending ?? {\n operationId: opId,\n at: new Date().toISOString(),\n source,\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n }\n if (pending === undefined) {\n mkdirSync(workerCancellationsDir(eventDir), { recursive: true })\n writeFileSync(runCancelRequestFile(eventDir), `${JSON.stringify(request, null, 2)}\\n`, 'utf8')\n appendWorkerControlEvent(eventDir, 'run', {\n kind: 'run-cancel-request',\n operationId: opId,\n source,\n queued: true,\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n })\n }\n return {\n operationId: opId,\n effect: 'unknown',\n requestedAt: request.at,\n observedAt: request.at,\n ...(request.reason === undefined ? {} : { reason: request.reason }),\n detail: 'request queued; no runtime acknowledger has answered yet',\n }\n}\n\nfunction isRunCancelRequest(value: Partial<RunCancelRequest>): value is RunCancelRequest {\n return (\n typeof value.operationId === 'string' &&\n value.operationId.length > 0 &&\n typeof value.at === 'string' &&\n typeof value.source === 'string' &&\n (value.reason === undefined || typeof value.reason === 'string')\n )\n}\n\nfunction isWorkerCancelRequest(value: Partial<WorkerCancelRequest>): value is WorkerCancelRequest {\n return (\n typeof value.operationId === 'string' &&\n value.operationId.length > 0 &&\n typeof value.at === 'string' &&\n typeof value.source === 'string' &&\n typeof value.worker === 'string' &&\n value.worker.length > 0 &&\n (value.reason === undefined || typeof value.reason === 'string')\n )\n}\n\nfunction appendWorkerControlEvent(\n eventDir: string,\n label: string,\n event: Record<string, unknown>,\n): void {\n try {\n mkdirSync(supervisorWorkersDir(eventDir), { recursive: true })\n appendFileSync(\n workerControlLogFile(eventDir, label),\n `${JSON.stringify({ at: new Date().toISOString(), label, ...event })}\\n`,\n 'utf8',\n )\n } catch {\n // Control logging is best-effort; the inbox write above is the durable part.\n }\n}\n\nfunction isWorkerSteerRequest(value: Partial<WorkerSteerRequest>): value is WorkerSteerRequest {\n return (\n typeof value.id === 'string' &&\n typeof value.at === 'string' &&\n typeof value.source === 'string' &&\n typeof value.worker === 'string' &&\n typeof value.message === 'string' &&\n value.message.trim().length > 0\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8KA,SAAgB,mBAAmB,SAAyB;CAC1D,OAAO,KAAK,QAAQ,OAAO,GAAG,UAAU,YAAY;AACtD;;AAGA,SAAgB,iBAAiB,SAAiB,IAAoB;CACpE,OAAO,KAAK,mBAAmB,OAAO,GAAG,EAAE;AAC7C;;;;;;AAOA,SAAgB,uBAAuB,SAAiB,IAAoB;CAC1E,OAAO,KAAK,yBAAyB,OAAO,GAAG,EAAE;AACnD;;;;;AAMA,SAAgB,yBAAyB,SAAyB;CAChE,OAAO,KAAK,QAAQ,OAAO,GAAG,UAAU,YAAY;AACtD;;AAGA,SAAg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