@tangle-network/agent-runtime 6.0.5 → 6.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +4 -0
- package/dist/{activation-kpRQffeo.js → activation-D2fc3d4p.js} +2 -2
- package/dist/{activation-kpRQffeo.js.map → activation-D2fc3d4p.js.map} +1 -1
- package/dist/agent.js +2 -2
- package/dist/{coordination-manager-ds4pn4IC.js → coordination-manager-CJ-qVHwc.js} +2 -2
- package/dist/{coordination-manager-ds4pn4IC.js.map → coordination-manager-CJ-qVHwc.js.map} +1 -1
- package/dist/{delegate-B2Z1CueR.js → delegate-B7XsdzB5.js} +2 -2
- package/dist/{delegate-B2Z1CueR.js.map → delegate-B7XsdzB5.js.map} +1 -1
- package/dist/durable.js +4 -4
- package/dist/{graph-flrNgUfu.js → graph-DyU1try5.js} +4 -4
- package/dist/{graph-flrNgUfu.js.map → graph-DyU1try5.js.map} +1 -1
- package/dist/{improve-DEkdGeQV.js → improve-BTyWlALh.js} +5 -5
- package/dist/{improve-DEkdGeQV.js.map → improve-BTyWlALh.js.map} +1 -1
- package/dist/index.js +7 -7
- package/dist/intelligence.js +3 -3
- package/dist/kernel.js +10 -10
- package/dist/{loop-runner-CrEq3gmu.js → loop-runner-BwOcyOhb.js} +2 -2
- package/dist/{loop-runner-CrEq3gmu.js.map → loop-runner-BwOcyOhb.js.map} +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/bin.js +2 -2
- package/dist/mcp/index.js +4 -4
- package/dist/{provision-supervisor-CuX82sFT.js → provision-supervisor-jR8FxV0u.js} +3 -3
- package/dist/{provision-supervisor-CuX82sFT.js.map → provision-supervisor-jR8FxV0u.js.map} +1 -1
- package/dist/{run-state-Dt-v0Fr8.js → run-state-D4R8gEFv.js} +2 -2
- package/dist/{run-state-Dt-v0Fr8.js.map → run-state-D4R8gEFv.js.map} +1 -1
- package/dist/{runtime-BNSsSOZ7.js → runtime-BNJMiodu.js} +10 -10
- package/dist/{runtime-BNSsSOZ7.js.map → runtime-BNJMiodu.js.map} +1 -1
- package/dist/{search-executor-CpQIJAdh.js → search-executor-LTYs04Ua.js} +2 -2
- package/dist/{search-executor-CpQIJAdh.js.map → search-executor-LTYs04Ua.js.map} +1 -1
- package/dist/{server-umzSNbPI.js → server-BqD2MOmF.js} +2 -2
- package/dist/{server-umzSNbPI.js.map → server-BqD2MOmF.js.map} +1 -1
- package/dist/{structural-rollout-B8PkKbfv.js → structural-rollout-BKliAKV6.js} +2 -2
- package/dist/{structural-rollout-B8PkKbfv.js.map → structural-rollout-BKliAKV6.js.map} +1 -1
- package/dist/{supervise-B3hzcqVU.js → supervise-B5GVxYGQ.js} +3 -3
- package/dist/{supervise-B3hzcqVU.js.map → supervise-B5GVxYGQ.js.map} +1 -1
- package/dist/{supervisor-DpWSUrwB.js → supervisor-Buv6rd8h.js} +19 -18
- package/dist/supervisor-Buv6rd8h.js.map +1 -0
- package/dist/testing.js +11 -11
- package/dist/tui/index.js +1 -1
- package/package.json +1 -1
- package/dist/supervisor-DpWSUrwB.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provision-supervisor-CuX82sFT.js","names":[],"sources":["../src/runtime/retained-interactive-control.ts","../src/runtime/supervise/interactive-executor.ts","../src/runtime/supervise/interactive-worker.ts","../src/runtime/supervise/provision-supervisor.ts"],"sourcesContent":["import type { AgentInteractiveSessionControlClaim } from '@tangle-network/agent-interface'\nimport {\n agentInteractiveSessionControlClaimRequestDigest,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport {\n acceptedInteractiveControl,\n offerInteractiveControl,\n prepareInteractiveDelegation,\n} from './retained-interactive-delegation'\nimport type { RetainedInteractiveRunHandle } from './retained-interactive-types'\nimport { abortError } from './util'\n\nconst MAX_GENERATION_CONFLICTS = 8\n\n/** Input for acquiring write authority over one exact interactive process. @stable */\nexport interface ClaimRetainedInteractiveControlOptions {\n readonly handle: RetainedInteractiveRunHandle\n readonly holderId: string\n /** Last known provider generation. Zero discovers the current generation safely. */\n readonly expectedGeneration?: number\n readonly signal?: AbortSignal\n /** Explicit full-control delegation within private local Runtime state. The accepted claim\n * retains the real holder identity and grants attach/input/resize, prompt and stop authority. */\n readonly delegation?: 'offer' | 'accept'\n}\n\n/**\n * Acquire provider-issued write authority without reading authority from status.\n *\n * A new coordinator starts at generation zero. If another claim already exists,\n * the provider returns its public generation and this helper retries one new\n * compare-and-swap operation. Every generation has a deterministic operation\n * identifier, so retrying after an ambiguous response cannot create two claims.\n * @stable\n */\nexport async function claimRetainedInteractiveControl(\n options: ClaimRetainedInteractiveControlOptions,\n): Promise<AgentInteractiveSessionControlClaim> {\n if (options.signal?.aborted) throw abortError(options.signal.reason)\n const expected = options.expectedGeneration ?? 0\n if (!Number.isSafeInteger(expected) || expected < 0) {\n throw new Error('interactive control expectedGeneration must be a non-negative integer')\n }\n if (options.delegation === 'offer') await prepareInteractiveDelegation(options.handle)\n if (options.delegation === 'accept') {\n const delegated = await acceptedInteractiveControl(options.handle)\n if (options.signal?.aborted) throw abortError(options.signal.reason)\n if (delegated) return delegated\n }\n let generation = expected\n for (let conflict = 0; conflict <= MAX_GENERATION_CONFLICTS; conflict += 1) {\n if (options.signal?.aborted) throw abortError(options.signal.reason)\n const material = {\n operationId: controlClaimOperationId(options.handle, options.holderId, generation),\n ref: options.handle.ref,\n holderId: options.holderId,\n expectedGeneration: generation,\n }\n const acknowledgement = await options.handle.claimControl(\n {\n ...material,\n requestDigest: agentInteractiveSessionControlClaimRequestDigest(material),\n },\n options.signal === undefined ? undefined : { signal: options.signal },\n )\n if (acknowledgement.status === 'accepted' || acknowledgement.status === 'replayed') {\n const control = acknowledgement.control\n if (control === undefined) {\n throw new Error('provider accepted interactive control without returning its claim')\n }\n if (Date.parse(control.expiresAt) <= Date.now()) {\n throw new Error('provider returned an expired interactive control claim')\n }\n if (options.delegation === 'offer') await offerInteractiveControl(options.handle, control)\n return control\n }\n if (\n acknowledgement.status !== 'conflict' ||\n acknowledgement.conflictReason !== 'generation_mismatch'\n ) {\n throw new Error(\n acknowledgement.status === 'unknown'\n ? 'interactive control claim outcome is unknown; retry the same acquisition'\n : 'interactive control claim operation conflicts with different request material',\n )\n }\n const current = acknowledgement.currentGeneration\n if (current === undefined || current <= generation) {\n throw new Error('provider returned a non-advancing interactive control generation')\n }\n generation = current\n }\n throw new Error('interactive control changed too often to acquire safely')\n}\n\nfunction controlClaimOperationId(\n handle: RetainedInteractiveRunHandle,\n holderId: string,\n expectedGeneration: number,\n): string {\n const digest = canonicalCandidateDigest({\n kind: 'retained-interactive-control-claim.v1',\n ref: handle.ref,\n holderId,\n expectedGeneration,\n })\n return `interactive-claim-${digest.slice('sha256:'.length, 'sha256:'.length + 40)}`\n}\n","/**\n * The executor behind one interactive worker: starts the provider's retained interactive process,\n * polls it to exit, relays steers as prompts, and stops and releases it exactly once.\n */\n\nimport {\n type AgentInteractiveSessionPromptCommand,\n type AgentInteractiveSessionStatus,\n type AgentInteractiveSessionStopAcknowledgement,\n type AgentInteractiveSessionStopCommand,\n type AgentProfile,\n agentInteractiveSessionPromptRequestDigest,\n agentInteractiveSessionStopRequestDigest,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport type {\n AgentEnvironment,\n AgentEnvironmentProvider,\n} from '@tangle-network/agent-interface/environment-provider'\nimport { contentAddress } from '../../durable/content-address'\nimport type { WorkerSpawnContext } from '../../mcp/tools/coordination-contracts'\nimport { startRetainedInteractiveRun } from '../retained-interactive'\nimport { claimRetainedInteractiveControl } from '../retained-interactive-control'\nimport { destroyInteractiveEnvironment, environmentGone } from '../retained-interactive-lifecycle'\nimport type { RetainedInteractiveRunHandle } from '../retained-interactive-types'\nimport { retainedCreateMaterial } from '../retained-run-intent'\nimport type { RetainedInteractiveAdmission } from '../retained-run-types'\nimport { sleep } from '../util'\nimport { linkAbort, signalAbortError } from './abortable'\nimport { createInbox, failPendingAfter } from './inbox'\nimport type { InteractiveAdmissionWriter } from './interactive-admission'\nimport type {\n InteractiveWorkerEnvironment,\n InteractiveWorkerOptions,\n InteractiveWorkerResult,\n} from './interactive-worker'\nimport {\n attestRuntimeOwnedPendingExecutor,\n finalizeRuntimeOwnedPendingExecutor,\n newExecutionAttemptId,\n} from './materialization'\nimport { concreteProfileModel } from './model-policy'\nimport { detachedSnapshot } from './snapshot'\nimport { taskToPrompt } from './task-prompt'\nimport type {\n Executor,\n ExecutorCancellation,\n ExecutorResult,\n HeldEnvironment,\n Runtime,\n Spend,\n UsageEvent,\n WorkerInteractiveSession,\n} from './types'\n\nconst INTERACTIVE_TEARDOWN_TIMEOUT_MS = 30_000\n\nexport interface InteractiveExecutorInput {\n readonly provider: AgentEnvironmentProvider\n readonly profile: AgentProfile\n readonly context?: WorkerSpawnContext\n readonly environment?: InteractiveWorkerEnvironment\n readonly environmentKey: string\n readonly interactiveKey: (task: unknown) => string\n readonly holderId: (task: unknown) => string\n readonly initialPrompt?: InteractiveWorkerOptions['initialPrompt']\n readonly cwd?: string\n readonly cols?: number\n readonly rows?: number\n readonly runtime: Runtime\n readonly pollIntervalMs?: number\n readonly destroyEnvironmentOnTeardown?: boolean\n readonly executionAttemptId?: string\n readonly nodeId?: string\n readonly admission: InteractiveAdmissionWriter\n}\n\n/** The one record an interactive executor reads and writes across start, poll, steer, stop and teardown. */\ninterface InteractiveRun {\n readonly input: InteractiveExecutorInput\n readonly attemptId: string\n readonly localController: AbortController\n readonly inbox: ReturnType<typeof createInbox>\n readonly planned: PlannedDeclaration\n readonly stopOperations: Map<string, Promise<ExecutorCancellation>>\n readonly memoryAdmissions: Map<string, RetainedInteractiveAdmission>\n readonly ready: Promise<WorkerInteractiveSession>\n readonly resolveReady: (session: WorkerInteractiveSession) => void\n executor: Executor<InteractiveWorkerResult>\n handle: RetainedInteractiveRunHandle | undefined\n createdEnvironment: AgentEnvironment | undefined\n environmentId: string | undefined\n artifact: ExecutorResult<InteractiveWorkerResult> | undefined\n activeLink: ReturnType<typeof linkAbort> | undefined\n startPromise: Promise<RetainedInteractiveRunHandle> | undefined\n executeStarted: boolean\n teardownComplete: boolean\n teardownPromise: Promise<{ destroyed: boolean }> | undefined\n flushChain: Promise<void>\n controlError: unknown\n}\n\ntype PlannedDeclaration = ReturnType<typeof plannedDeclarationOf>\n\nconst descriptorOf = (input: InteractiveExecutorInput) =>\n ({\n kind: 'interactive-session',\n provider: input.provider.name,\n transport: 'agent-environment',\n }) as const\n\nfunction plannedDeclarationOf(input: InteractiveExecutorInput) {\n const declaredEnvironment = input.environment\n ? retainedCreateMaterial({\n ...input.environment,\n profile: input.profile,\n idempotencyKey: input.environmentKey,\n })\n : null\n const profileModel = concreteProfileModel(input.profile)\n return {\n effectiveProfile: input.profile,\n backend: input.provider.name,\n model: profileModel\n ? { status: 'known' as const, id: profileModel }\n : { status: 'unknown' as const, reason: 'provider selected the model' },\n execution: { kind: 'interactive-session', id: input.nodeId ?? input.environmentKey },\n materializer: 'retained-interactive-provider',\n plan: {\n kind: 'retained-interactive-provider',\n provider: input.provider.name,\n environment: declaredEnvironment,\n environmentIdempotencyKey: input.environmentKey,\n destroyEnvironmentOnTeardown: input.destroyEnvironmentOnTeardown !== false,\n },\n }\n}\n\nexport function interactiveExecutor(\n input: InteractiveExecutorInput,\n): Executor<InteractiveWorkerResult> {\n const attemptId =\n input.executionAttemptId ?? newExecutionAttemptId(input.nodeId ?? input.environmentKey)\n let resolveReady!: (session: WorkerInteractiveSession) => void\n const ready = new Promise<WorkerInteractiveSession>((resolve) => {\n resolveReady = resolve\n })\n const run: InteractiveRun = {\n input,\n attemptId,\n localController: new AbortController(),\n inbox: createInbox(),\n planned: plannedDeclarationOf(input),\n stopOperations: new Map(),\n memoryAdmissions: new Map(),\n ready,\n resolveReady,\n executor: undefined as unknown as Executor<InteractiveWorkerResult>,\n handle: undefined,\n createdEnvironment: undefined,\n environmentId: undefined,\n artifact: undefined,\n activeLink: undefined,\n startPromise: undefined,\n executeStarted: false,\n teardownComplete: false,\n teardownPromise: undefined,\n flushChain: Promise.resolve(),\n controlError: undefined,\n }\n run.executor = interactiveSurface(run)\n attestRuntimeOwnedPendingExecutor(run.executor, input.runtime, run.planned, {\n attemptId,\n binding: {\n provider: input.provider.name,\n environmentIdempotencyKey: input.environmentKey,\n nodeId: input.nodeId ?? null,\n },\n descriptor: descriptorOf(input),\n })\n return run.executor\n}\n\nfunction interactiveSurface(run: InteractiveRun): Executor<InteractiveWorkerResult> {\n const { input } = run\n return {\n runtime: input.runtime,\n teardownTimeoutMs: INTERACTIVE_TEARDOWN_TIMEOUT_MS,\n execute(task, signal): AsyncIterable<UsageEvent> {\n if (run.executeStarted || run.teardownComplete || run.teardownPromise !== undefined) {\n throw new Error('workerFromInteractiveProvider: execute() may only be called once')\n }\n run.executeStarted = true\n run.startPromise = startInteractive(run, task, signal)\n return failPendingAfter(run.inbox, runInteractive(run, signal))\n },\n deliver(message: unknown): boolean {\n if (run.teardownComplete || run.teardownPromise !== undefined) return false\n const accepted = run.inbox.deliver(message)\n if (accepted) void flushInbox(run)\n return accepted\n },\n interactive(): WorkerInteractiveSession {\n return run.handle\n ? { status: 'available', handle: run.handle }\n : { status: 'unavailable', reason: 'interactive-session-not-started' }\n },\n interactiveReady(): Promise<WorkerInteractiveSession> {\n return run.ready\n },\n async cancel(request): Promise<ExecutorCancellation> {\n const existing = run.stopOperations.get(request.operationId)\n if (existing) return existing\n const operation = stopInteractive(run, request.operationId, request.reason, request.signal)\n const tracked = operation.then((result) => {\n if (\n result.status === 'unknown' &&\n run.stopOperations.get(request.operationId) === tracked\n ) {\n run.stopOperations.delete(request.operationId)\n }\n return result\n })\n run.stopOperations.set(request.operationId, tracked)\n return tracked\n },\n teardown(grace): Promise<{ destroyed: boolean }> {\n void grace\n if (run.teardownComplete) return Promise.resolve({ destroyed: true })\n if (run.teardownPromise !== undefined) return run.teardownPromise\n const pending = teardownInteractive(run)\n run.teardownPromise = pending.then(\n (result) => {\n run.teardownComplete = true\n return result\n },\n (error) => {\n run.teardownPromise = undefined\n throw error\n },\n )\n return run.teardownPromise\n },\n heldEnvironments(): ReadonlyArray<HeldEnvironment> {\n if (run.teardownComplete || input.destroyEnvironmentOnTeardown === false) return []\n const held =\n run.createdEnvironment?.id ?? run.environmentId ?? run.handle?.ref.run.environmentId\n return held === undefined ? [] : [{ provider: input.provider.name, environmentId: held }]\n },\n resultArtifact(): ExecutorResult<InteractiveWorkerResult> {\n if (!run.artifact) {\n throw new Error(\n 'workerFromInteractiveProvider: resultArtifact() read before execution settled',\n )\n }\n return run.artifact\n },\n }\n}\n\nfunction initialPromptFor(input: InteractiveExecutorInput, task: unknown): string {\n const initialPrompt =\n typeof input.initialPrompt === 'function'\n ? input.initialPrompt(task, {\n provider: input.provider.name,\n profile: input.profile,\n ...(input.context === undefined ? {} : { context: input.context }),\n task,\n ...(input.nodeId === undefined ? {} : { nodeId: input.nodeId }),\n })\n : (input.initialPrompt ?? taskToPrompt(task))\n if (typeof initialPrompt !== 'string') {\n throw new Error('workerFromInteractiveProvider: initialPrompt must return a string')\n }\n return initialPrompt\n}\n\n/** Keep each admission phase's first snapshot in memory and refuse a retry that changes it. */\nasync function recordAdmission(\n run: InteractiveRun,\n admission: RetainedInteractiveAdmission,\n): Promise<void> {\n run.environmentId =\n admission.phase === 'interactive_environment' ? admission.environmentId : run.environmentId\n const existing = run.memoryAdmissions.get(admission.phase)\n if (existing !== undefined) {\n if (canonicalCandidateDigest(existing) !== canonicalCandidateDigest(admission)) {\n throw new Error(`interactive admission phase '${admission.phase}' changed across retry`)\n }\n } else {\n run.memoryAdmissions.set(admission.phase, detachedSnapshot(admission, 'interactive admission'))\n }\n await run.input.admission(admission)\n}\n\nasync function startInteractive(\n run: InteractiveRun,\n task: unknown,\n signal: AbortSignal,\n): Promise<RetainedInteractiveRunHandle> {\n const { input } = run\n try {\n run.activeLink = linkAbort(signal, run.localController.signal)\n const initialPrompt = initialPromptFor(input, task)\n const interactiveIdempotencyKey = input.interactiveKey(task)\n const started = await startRetainedInteractiveRun({\n provider: {\n ...input.provider,\n async create(environmentInput): Promise<AgentEnvironment> {\n const environment = await input.provider.create!(environmentInput)\n run.createdEnvironment = environment\n return environment\n },\n },\n environment: {\n ...(input.environment ?? {}),\n profile: input.profile,\n idempotencyKey: input.environmentKey,\n },\n interactiveIdempotencyKey,\n ...(initialPrompt.length === 0 ? {} : { initialPrompt }),\n ...(input.cwd === undefined ? {} : { cwd: input.cwd }),\n ...(input.cols === undefined ? {} : { cols: input.cols }),\n ...(input.rows === undefined ? {} : { rows: input.rows }),\n onAdmission: (admission) => recordAdmission(run, admission),\n signal: run.activeLink.signal,\n })\n finalizeRuntimeOwnedPendingExecutor(\n run.executor,\n {\n ...run.planned,\n execution: { kind: 'interactive-session', id: started.ref.run.executionId },\n plan: {\n ...run.planned.plan,\n environmentId: started.ref.run.environmentId,\n interactiveIdempotencyKey,\n },\n },\n {\n attemptId: run.attemptId,\n binding: {\n provider: input.provider.name,\n ref: started.ref,\n environmentId: started.ref.run.environmentId,\n },\n descriptor: descriptorOf(input),\n },\n )\n run.handle = started\n run.resolveReady({ status: 'available', handle: started })\n void flushInbox(run)\n return started\n } catch (error) {\n run.resolveReady({ status: 'unavailable', reason: unavailableReason(error) })\n run.activeLink?.release()\n throw error\n }\n}\n\nasync function* runInteractive(\n run: InteractiveRun,\n signal: AbortSignal,\n): AsyncIterable<UsageEvent> {\n const { input, localController } = run\n const startedAt = Date.now()\n try {\n const current = await run.startPromise\n if (current === undefined) {\n throw new Error('workerFromInteractiveProvider: interactive start did not begin')\n }\n yield { kind: 'iteration' }\n // Native TUI sessions do not expose a complete turn receipt. These zero counters are an\n // observed floor and the explicit false markers keep the run's accounting honest.\n yield { kind: 'tokens', input: 0, output: 0, tokensKnown: false }\n yield { kind: 'cost', usd: 0, usdKnown: false, provenance: 'uncaptured' }\n let status: AgentInteractiveSessionStatus | undefined\n for (;;) {\n if (signal.aborted || localController.signal.aborted) {\n throw signalAbortError(\n signal.aborted ? signal : localController.signal,\n 'interactive execution aborted',\n )\n }\n status = await current.status({ signal: run.activeLink?.signal })\n await run.flushChain\n if (run.controlError !== undefined) throw controlErrorValue(run.controlError)\n if (status.state !== 'running') break\n await sleep(input.pollIntervalMs ?? 100, run.activeLink?.signal)\n }\n const finished = status\n const output: InteractiveWorkerResult = {\n provider: input.provider.name,\n environmentId: current.ref.run.environmentId,\n sessionId: current.ref.run.sessionId,\n executionId: current.ref.run.executionId,\n state: finished?.state === 'exited' ? 'exited' : 'unknown',\n ref: current.ref,\n ...(finished?.state === 'exited' && finished.reason ? { reason: finished.reason } : {}),\n ...(finished?.state === 'exited' && finished.exitCode !== undefined\n ? { exitCode: finished.exitCode }\n : {}),\n ...(finished?.state === 'exited' && finished.exitSignal !== undefined\n ? { exitSignal: finished.exitSignal }\n : {}),\n }\n const spent: Spend = {\n iterations: 1,\n tokens: { input: 0, output: 0 },\n tokensKnown: false,\n usd: 0,\n usdKnown: false,\n ms: Date.now() - startedAt,\n }\n run.artifact = {\n outRef: contentAddress(output),\n out: output,\n spent,\n }\n } finally {\n run.activeLink?.release()\n }\n}\n\nasync function flushInbox(run: InteractiveRun): Promise<void> {\n run.flushChain = run.flushChain.then(async () => {\n const handle = run.handle\n if (!handle) return\n const lease = run.inbox.take()\n try {\n const messages = lease.messages\n if (messages.length === 0) return\n const prompt = run.inbox.fold(messages)\n const operationId = `interactive-prompt-${canonicalCandidateDigest({\n ref: handle.ref,\n prompt,\n }).slice('sha256:'.length)}`\n const control = await claimRetainedInteractiveControl({\n handle,\n holderId: run.input.holderId(undefined),\n })\n const material = {\n operationId,\n ref: handle.ref,\n control,\n prompt,\n }\n const command: AgentInteractiveSessionPromptCommand = {\n ...material,\n requestDigest: agentInteractiveSessionPromptRequestDigest(material),\n }\n await handle.sendPrompt(command)\n for (const message of messages) lease.commit(operationId, message.id)\n } catch (error) {\n lease.release()\n run.controlError ??= error\n }\n })\n await run.flushChain\n}\n\nasync function stopInteractive(\n run: InteractiveRun,\n operationId: string,\n reason?: string,\n signal?: AbortSignal,\n): Promise<ExecutorCancellation> {\n const observedAt = new Date().toISOString()\n const handle = run.handle\n if (!handle) {\n run.localController.abort(reason ?? 'interactive cancellation requested')\n return {\n status: 'unknown',\n effect: 'cancel_requested',\n observedAt,\n detail: 'interactive process has not published a provider reference',\n }\n }\n try {\n const control = await claimRetainedInteractiveControl({\n handle,\n holderId: run.input.holderId(undefined),\n signal,\n })\n const material = { operationId, ref: handle.ref, control }\n const command: AgentInteractiveSessionStopCommand = {\n ...material,\n requestDigest: agentInteractiveSessionStopRequestDigest(material),\n }\n const acknowledgement = await handle.stop(\n command,\n signal === undefined ? undefined : { signal },\n )\n run.localController.abort(reason ?? 'interactive cancellation requested')\n return cancellationFromAcknowledgement(acknowledgement, observedAt)\n } catch (error) {\n run.localController.abort(reason ?? 'interactive cancellation requested')\n return {\n status: 'unknown',\n effect: 'cancel_requested',\n observedAt,\n detail: error instanceof Error ? error.message : String(error),\n evidence: { operationId },\n }\n }\n}\n\nasync function teardownInteractive(run: InteractiveRun): Promise<{ destroyed: boolean }> {\n run.localController.abort('interactive worker teardown')\n run.activeLink?.release()\n await run.startPromise?.catch(() => undefined)\n if (run.handle) {\n const status = await safeStatus(run.handle)\n if (status?.state === 'running') {\n const operationId = `interactive-teardown-${canonicalCandidateDigest(run.handle.ref).slice(\n 'sha256:'.length,\n )}`\n const cancellation = await stopInteractive(run, operationId, 'interactive worker teardown')\n if (cancellation.status === 'rejected' || cancellation.status === 'unknown') {\n throw new Error(cancellation.detail ?? 'interactive teardown was not acknowledged')\n }\n }\n }\n await destroyEnvironment(run)\n return { destroyed: true }\n}\n\nasync function destroyEnvironment(run: InteractiveRun): Promise<void> {\n const { input } = run\n if (input.destroyEnvironmentOnTeardown === false) return\n if (run.createdEnvironment !== undefined) {\n await destroyConfirmed(input.provider, run.createdEnvironment)\n return\n }\n if (!input.provider.get) return\n // The exact provider reference is durable and remains available even when the admission\n // callback was interrupted after the environment was created. Use it as the cleanup identity\n // so an aborted provider signal cannot turn a real environment into an unconfirmed leak.\n const cleanupEnvironmentId = run.environmentId ?? run.handle?.ref.run.environmentId\n if (!cleanupEnvironmentId) return\n const environment = await input.provider.get(cleanupEnvironmentId)\n if (environment !== undefined && environment !== null) {\n await destroyConfirmed(input.provider, environment)\n }\n}\n\nasync function destroyConfirmed(\n provider: AgentEnvironmentProvider,\n environment: AgentEnvironment,\n): Promise<void> {\n try {\n await destroyInteractiveEnvironment(environment)\n } catch (error) {\n // A delete whose answer was lost fails not-found on every later attempt; the provider's\n // lookup confirming the environment gone is the destroy's confirmation.\n if (!(await environmentGone(provider, environment.id))) throw error\n }\n}\n\nfunction unavailableReason(\n error: unknown,\n): 'provider-has-no-interactive-contract' | 'interactive-binding-stale' {\n const message = error instanceof Error ? error.message : String(error)\n return message.includes('interactive') || message.includes('Interactive')\n ? 'provider-has-no-interactive-contract'\n : 'interactive-binding-stale'\n}\n\nfunction cancellationFromAcknowledgement(\n acknowledgement: AgentInteractiveSessionStopAcknowledgement,\n observedAt: string,\n): ExecutorCancellation {\n const status =\n acknowledgement.status === 'accepted' || acknowledgement.status === 'replayed'\n ? 'accepted'\n : acknowledgement.status === 'conflict'\n ? 'rejected'\n : 'unknown'\n const effect =\n acknowledgement.effect === 'stopped'\n ? 'cancelled'\n : acknowledgement.effect === 'not_live'\n ? 'not_live'\n : acknowledgement.effect === 'stop_requested'\n ? 'cancel_requested'\n : 'unknown'\n return {\n status,\n effect,\n observedAt,\n ...(acknowledgement.message === undefined ? {} : { detail: acknowledgement.message }),\n evidence: {\n operationId: acknowledgement.operationId,\n requestDigest: acknowledgement.requestDigest,\n providerStatus: acknowledgement.status,\n providerEffect: acknowledgement.effect,\n },\n }\n}\n\nfunction controlErrorValue(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error))\n}\n\nasync function safeStatus(\n handle: RetainedInteractiveRunHandle,\n): Promise<AgentInteractiveSessionStatus | undefined> {\n let timer: ReturnType<typeof setTimeout> | undefined\n const timeout = new Promise<undefined>((resolve) => {\n timer = setTimeout(() => resolve(undefined), 100)\n timer.unref?.()\n })\n try {\n // A provider environment created with the worker's abort signal may reject or hang all\n // subsequent calls after the scope begins teardown. Keep status best-effort and let the fresh\n // environment lookup below prove release without spending the teardown acknowledgement window\n // on a stale connection.\n return await Promise.race([handle.status(), timeout])\n } catch {\n return undefined\n } finally {\n if (timer !== undefined) clearTimeout(timer)\n }\n}\n","/**\n * Runtime-owned worker seam for a provider's native interactive coding-agent process. It composes\n * the retained-interactive lifecycle, adding no second stream, replay buffer, session id or\n * cancellation protocol: the provider owns process state; Scope owns the worker, journal, budget\n * and local control inbox.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport {\n type AgentInteractiveSessionRef,\n type AgentProfile,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport type {\n AgentEnvironmentProvider,\n CreateAgentEnvironmentInput,\n} from '@tangle-network/agent-interface/environment-provider'\nimport type { MakeWorkerAgent, WorkerSpawnContext } from '../../mcp/tools/coordination-contracts'\nimport type { RetainedInteractiveAdmission } from '../retained-run-types'\nimport { executableAgentProfileSnapshot } from './executable-spec'\nimport {\n type InteractiveAdmissionWriter,\n interactiveAdmissionSeamKey,\n} from './interactive-admission'\nimport { interactiveExecutor } from './interactive-executor'\nimport { detachedSnapshot } from './snapshot'\nimport type { Agent, AgentSpec, Executor, ExecutorContext, Runtime } from './types'\n\n/** Environment fields supplied to every interactive worker after Runtime adds the exact profile. */\nexport type InteractiveWorkerEnvironment = Omit<\n CreateAgentEnvironmentInput,\n 'profile' | 'idempotencyKey' | 'signal'\n>\n\n/** Native interactive worker output. Provider usage is intentionally not fabricated. */\nexport interface InteractiveWorkerResult {\n readonly provider: string\n readonly environmentId: string\n readonly sessionId: string\n readonly executionId: string\n readonly state: 'exited' | 'unknown'\n readonly ref: AgentInteractiveSessionRef\n readonly reason?: string\n readonly exitCode?: number\n readonly exitSignal?: string\n}\n\n/** Configuration shared by every worker produced by `workerFromInteractiveProvider`. */\nexport interface InteractiveWorkerOptions {\n /** Provider create fields. Runtime supplies `profile`, the two idempotency keys, and `signal`. */\n readonly environment?: InteractiveWorkerEnvironment\n /** Stable environment identity override. Defaults to a digest of the exact worker assignment. */\n readonly environmentIdempotencyKey?: (input: InteractiveWorkerKeyInput) => string\n /** Stable interactive-session identity override. Defaults to a digest of assignment and task. */\n readonly interactiveIdempotencyKey?: (input: InteractiveWorkerKeyInput) => string\n /** Provider holder id used only while the worker sends a steer or stop command. */\n readonly holderId?: string | ((input: InteractiveWorkerKeyInput) => string)\n /** Initial prompt override. The exact worker task is the default prompt. */\n readonly initialPrompt?: string | ((task: unknown, input: InteractiveWorkerKeyInput) => string)\n readonly cwd?: string\n readonly cols?: number\n readonly rows?: number\n /** Runtime tag written into tree snapshots. Defaults to the provider name. */\n readonly runtime?: Runtime\n /** Poll delay used while waiting for the provider's native process to exit. */\n readonly pollIntervalMs?: number\n /** Destroy the provider environment after the process is terminal. Defaults to true. */\n readonly destroyEnvironmentOnTeardown?: boolean\n}\n\n/** Stable input available to key and holder functions. */\nexport interface InteractiveWorkerKeyInput {\n readonly provider: string\n readonly profile: AgentProfile\n readonly context?: WorkerSpawnContext\n readonly task?: unknown\n readonly nodeId?: string\n}\n\n/**\n * Build a `MakeWorkerAgent` that starts one provider-owned native TUI per worker. A Scope supplies\n * the durable admission hook and node attempt; the worker exposes `interactiveReady`, so the exact\n * provider reference is written before another process can attach, and `attachWorker` reconnects\n * it through the provider's public `get`/interactive contract.\n */\nexport function workerFromInteractiveProvider(\n provider: AgentEnvironmentProvider,\n options: InteractiveWorkerOptions = {},\n): MakeWorkerAgent {\n if (!provider.name.trim())\n throw new Error('workerFromInteractiveProvider: provider.name required')\n if (!provider.get) {\n throw new Error(\n `workerFromInteractiveProvider(${provider.name}): provider.get is required for reconnect`,\n )\n }\n const capturedEnvironment = options.environment\n ? (structuredClone(options.environment) as InteractiveWorkerEnvironment)\n : undefined\n const unscopedNamespace = randomUUID()\n let unscopedOrdinal = 0\n const runtime = options.runtime ?? (provider.name as Runtime)\n\n return (rawProfile, spawnContext) => {\n const profile = executableAgentProfileSnapshot(\n rawProfile,\n `workerFromInteractiveProvider(${provider.name})`,\n )\n const input: InteractiveWorkerKeyInput = {\n provider: provider.name,\n profile,\n ...(spawnContext === undefined ? {} : { context: spawnContext }),\n }\n const assignmentId =\n spawnContext?.assignmentId ?? `unscoped:${unscopedNamespace}:${unscopedOrdinal++}`\n const baseInput = { ...input, nodeId: spawnContext?.parentNodeId }\n const environmentKey = stableKey(\n options.environmentIdempotencyKey?.({ ...baseInput }) ??\n derivedKey('supervised-interactive-environment', {\n provider: provider.name,\n assignmentId,\n parentNodeId: spawnContext?.parentNodeId,\n profile,\n }),\n 'environment idempotency key',\n )\n const name = profile.name ?? 'interactive-worker'\n\n const executorFactory = (\n spec: AgentSpec,\n ctx: ExecutorContext,\n ): Executor<InteractiveWorkerResult> =>\n interactiveExecutor({\n provider,\n profile: spec.profile,\n context: spawnContext,\n environment: capturedEnvironment,\n environmentKey,\n interactiveKey: (task: unknown) =>\n stableKey(\n options.interactiveIdempotencyKey?.({\n ...baseInput,\n task,\n }) ??\n derivedKey('supervised-interactive-session', {\n provider: provider.name,\n assignmentId,\n parentNodeId: spawnContext?.parentNodeId,\n profile: spec.profile,\n task,\n }),\n 'interactive idempotency key',\n ),\n holderId: (task: unknown) => {\n const selected =\n typeof options.holderId === 'function'\n ? options.holderId({ ...baseInput, task })\n : options.holderId\n return stableKey(\n selected ??\n `runtime-interactive-worker:${canonicalCandidateDigest({\n provider: provider.name,\n assignmentId,\n })}`,\n 'interactive holder id',\n )\n },\n initialPrompt: options.initialPrompt,\n cwd: options.cwd,\n cols: options.cols,\n rows: options.rows,\n runtime,\n pollIntervalMs: options.pollIntervalMs,\n destroyEnvironmentOnTeardown: options.destroyEnvironmentOnTeardown,\n executionAttemptId: ctx.node?.attemptId,\n nodeId: ctx.node?.nodeId,\n admission: admissionWriter(ctx, provider.name, ctx.node?.nodeId),\n })\n\n const spec: AgentSpec = {\n profile,\n harness: null,\n executorFactory,\n ...(spawnContext?.execution ? { execution: spawnContext.execution } : {}),\n }\n return {\n name,\n act: async () => {\n throw new Error(\n 'workerFromInteractiveProvider: interactive workers execute through executorSpec',\n )\n },\n executorSpec: spec,\n } as Agent<unknown, InteractiveWorkerResult> & { executorSpec: AgentSpec }\n }\n}\n\nfunction admissionWriter(\n ctx: ExecutorContext,\n provider: string,\n workerId: string | undefined,\n): InteractiveAdmissionWriter {\n const candidate = ctx.seams[interactiveAdmissionSeamKey]\n if (typeof candidate === 'function') {\n return async (admission) => {\n await (candidate as (value: RetainedInteractiveAdmission) => Promise<void>)(admission)\n }\n }\n // In-memory runs still need a real hook because retained-start refuses an omitted hook. The\n // durable Scope path always supplies the Runtime-owned writer above; this fallback is explicit\n // and process-local, never mistaken for restart evidence.\n const records = new Map<string, RetainedInteractiveAdmission>()\n return async (admission) => {\n const prior = records.get(admission.phase)\n if (prior && canonicalCandidateDigest(prior) !== canonicalCandidateDigest(admission)) {\n throw new Error(\n `worker ${workerId ?? '(unscoped)'} provider ${provider} admission changed in memory`,\n )\n }\n records.set(admission.phase, detachedSnapshot(admission, 'interactive admission'))\n }\n}\n\nfunction derivedKey(kind: string, value: unknown): string {\n return `${kind}-${canonicalCandidateDigest(value).slice('sha256:'.length)}`\n}\n\nfunction stableKey(value: string, label: string): string {\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new Error(`${label} must be a non-empty string`)\n }\n const key = value.trim()\n if (key.length > 256) throw new Error(`${label} must not exceed 256 bytes`)\n return key\n}\n","/**\n * Public one-call composition for a durable Runtime supervisor proof run.\n *\n * This is intentionally a thin owner of existing Runtime primitives. The supervisor owns the\n * root abort channel and join barrier, Scope owns worker admission and lifecycle, and the provider\n * owns the environment and interactive process. External clients receive identifiers and opaque\n * handles; they do not receive a second supervisor protocol or a copy of provider state.\n *\n * @experimental\n */\n\nimport { randomUUID } from 'node:crypto'\nimport { mkdirSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { dirname, join, resolve } from 'node:path'\nimport {\n type AgentProfile,\n agentProfileSchema,\n canonicalAgentProfileDigest,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport type {\n AgentEnvironmentCapabilities,\n AgentEnvironmentProvider,\n} from '@tangle-network/agent-interface/environment-provider'\nimport type { McpToolDescriptor } from '../../mcp/server'\nimport { createCoordinationTools } from '../../mcp/tools/coordination-manager'\nimport { sleep } from '../util'\nimport { armDeadlineTimer } from './deadline'\nimport { createCancelAcknowledger, createSteerAcknowledger } from './driver-control-acknowledgers'\nimport { writeAtomicDurableFile } from './durable-file'\nimport {\n type InteractiveWorkerEnvironment,\n workerFromInteractiveProvider,\n} from './interactive-worker'\nimport { createFileRunContext } from './run-context'\nimport { supervisorRunDir } from './run-layout'\nimport { createRootHandle, createSupervisor } from './supervisor'\nimport type { Agent, Budget, Scope, SpawnEvent, SupervisedResult } from './types'\nimport { readWorkerInteractiveBinding } from './worker-interactive'\n\nconst DEFAULT_POLL_MS = 25\nconst ROOT_MAX_ITERATIONS = 100\nconst ROOT_MAX_TOKENS = 100_000\nconst WORKER_MAX_ITERATIONS = 25\nconst WORKER_MAX_TOKENS = 25_000\n\n/** Caller-supplied environment provider for one supervisor run. */\nexport interface ProvisionSupervisorConnection {\n /** A constructed provider that owns exact-profile admission and environment reconnection. */\n readonly provider: AgentEnvironmentProvider\n}\n\n/** Input to the public Runtime supervisor provisioner. */\nexport interface ProvisionSupervisorRequest {\n readonly invocationId: string\n /** Caller-owned task assigned to the first interactive worker. */\n readonly task: string\n /** Canonical profile assigned to the first interactive worker. */\n readonly profile: AgentProfile\n /** Generic provider create fields forwarded to the interactive worker. */\n readonly workerEnvironment?: InteractiveWorkerEnvironment\n /** Root directory for Runtime-owned `.agent/supervisor` state. */\n readonly workspaceDir?: string\n /** Maximum wall-clock time for the complete supervisor lifecycle, including cleanup. Omit for no lifecycle deadline. */\n readonly timeoutMs?: number\n /** Poll cadence for lifecycle/control readiness. */\n readonly pollMs?: number\n /** Constructed provider for one execution connection. */\n readonly connection: ProvisionSupervisorConnection\n}\n\n/** Exact owner-scoped cleanup receipt returned after Runtime releases the run resources. */\nexport interface SupervisorCleanupReceipt {\n readonly status: 'completed'\n readonly rootDir: string\n readonly supervisorId: string\n readonly workerId: string\n readonly supervisorStatus: string\n readonly workerStatus: 'running' | 'done' | 'down' | 'cancelled'\n readonly resourcesReleased: true\n readonly remainingResources: readonly []\n}\n\n/** Handles for one Runtime-owned supervisor and its first interactive worker. */\nexport interface ProvisionedSupervisor {\n readonly rootDir: string\n readonly supervisorId: string\n readonly workerId: string\n /** Provider source for `attachWorker`; omitted only when resolution did not produce one. */\n readonly providers?: AgentEnvironmentProvider\n /** Capability-derived terminal takeover requirement. */\n readonly terminalTakeover: 'required' | 'unsupported' | 'unspecified'\n cleanup(): Promise<SupervisorCleanupReceipt>\n}\n\nclass SupervisorProvisionUnavailableError extends Error {\n readonly unavailable = true as const\n\n constructor(message: string, cause?: unknown) {\n super(message, cause === undefined ? undefined : { cause })\n this.name = 'SupervisorProvisionUnavailableError'\n }\n}\n\ninterface MutableState {\n readonly id: string\n status: string\n readonly task: string\n readonly workspaceDir: string\n readonly budget: number\n readonly workerModel?: string\n readonly startedAt: string\n completedAt?: string\n}\n\ninterface Deferred<T> {\n readonly promise: Promise<T>\n resolve(value: T): void\n reject(error: unknown): void\n readonly settled: () => boolean\n}\n\n/**\n * Provision one real provider-backed worker and keep its owning manager alive for controls.\n *\n * The root manager does not use a model. It runs the same coordination tools used by a driver in a\n * small deterministic loop, so durable steer and cancel requests are acknowledged by the owning\n * Runtime turn loop and never by a test-only shortcut. The caller owns profile, task, and provider\n * connection selection; Runtime does not infer them from process environment variables.\n */\nexport async function provisionSupervisor(\n request: ProvisionSupervisorRequest,\n): Promise<ProvisionedSupervisor> {\n const input = normalizeRequest(request)\n const provider = resolveProvider(input)\n const capabilities = await readCapabilities(provider)\n const terminalTakeover = terminalCapability(capabilities)\n const profile = input.profile\n const rootDir = resolve(input.workspaceDir ?? makeWorkspaceDir())\n mkdirSync(rootDir, { recursive: true })\n const supervisorId = supervisorIdFor(input.invocationId)\n const eventDir = supervisorRunDir(rootDir, supervisorId)\n const statePath = join(eventDir, 'state.json')\n mkdirSync(dirname(eventDir), { recursive: true })\n try {\n // The run directory is the cross-process invocation lock. A non-recursive mkdir closes the\n // duplicate-start race before any journal or provider resource is created.\n mkdirSync(eventDir)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'EEXIST') {\n throw unavailable(\n `Runtime supervisor '${supervisorId}' already exists at '${eventDir}'; use a new invocationId`,\n )\n }\n throw error\n }\n\n const context = createFileRunContext(eventDir)\n const startedAtMs = Date.now()\n const state: MutableState = {\n id: supervisorId,\n status: 'running',\n task: input.task,\n workspaceDir: rootDir,\n budget: ROOT_MAX_TOKENS,\n ...(profile.model?.default === undefined ? {} : { workerModel: profile.model.default }),\n startedAt: new Date(startedAtMs).toISOString(),\n }\n writeState(statePath, state)\n\n const rootHandle = createRootHandle<unknown>()\n const supervisor = createSupervisor<unknown, unknown>()\n supervisor.attach(rootHandle)\n const workerSpawned = deferred<string>()\n const workerRunning = deferred<void>()\n const workerProfile = profile\n const workerEnvironment = {\n ...(input.workerEnvironment ?? {}),\n metadata: {\n ...(input.workerEnvironment?.metadata ?? {}),\n runtime: 'agent-runtime',\n invocationId: input.invocationId,\n },\n name: input.workerEnvironment?.name ?? `runtime-${supervisorId}`,\n }\n const makeWorkerAgent = workerFromInteractiveProvider(provider, {\n environment: workerEnvironment,\n pollIntervalMs: input.pollMs,\n destroyEnvironmentOnTeardown: true,\n })\n\n const rootAgent: Agent<unknown, unknown> = {\n name: 'runtime-supervisor-root',\n async act(_task: unknown, scope: Scope<unknown>): Promise<unknown> {\n const coord = createCoordinationTools({\n scope,\n blobs: context.blobs,\n makeWorkerAgent,\n perWorker: workerBudget(),\n })\n await coord.ready()\n const spawn = findTool(coord.tools, 'spawn_worker')\n const result = await spawn.handler({\n profile: workerProfile,\n task: input.task,\n label: 'interactive-worker',\n })\n const childId = workerIdFromSpawn(result)\n workerSpawned.resolve(childId)\n\n for (;;) {\n const child = scope.view.nodes.find((node) => node.id === childId)\n if (child?.status === 'running') break\n if (\n child === undefined ||\n child.status === 'done' ||\n child.status === 'failed' ||\n child.status === 'cancelled'\n ) {\n throw new Error(`Runtime supervisor worker '${childId}' ended before becoming live`)\n }\n await delay(input.pollMs)\n }\n workerRunning.resolve()\n\n const steerAcknowledger = createSteerAcknowledger({\n dir: eventDir,\n coord,\n now: Date.now,\n ownerId: scope.view.root,\n })\n const cancelAcknowledger = createCancelAcknowledger({\n dir: eventDir,\n coord,\n scope,\n now: Date.now,\n ownerId: scope.view.root,\n controlScope: 'run',\n })\n try {\n while (true) {\n await steerAcknowledger.pass('turn')\n cancelAcknowledger.pass('turn')\n // The wake owns the single scope cursor drain. Calling `scope.next()` directly here\n // would bypass the coordination ledger and make a real cancellation look unknown. Its\n // heartbeat bounds each pass so control requests are observed while the worker runs.\n const wake = await coord.awaitWake({\n attempt: 1,\n signal: scope.signal,\n heartbeatMs: input.pollMs,\n debounceMs: 0,\n })\n if (wake?.events.some((event) => event.type === 'settled')) {\n await steerAcknowledger.pass('final')\n cancelAcknowledger.pass('final')\n return undefined\n }\n if (wake === undefined) {\n throw new Error(`Runtime supervisor worker '${childId}' ended without a settlement`)\n }\n }\n } finally {\n // The final pass closes requests that landed after the last turn. It is idempotent with the\n // normal path and prevents an admitted operation from remaining open after root teardown.\n await steerAcknowledger.pass('final')\n cancelAcknowledger.pass('final')\n cancelAcknowledger.finish()\n }\n },\n }\n const runBudget = rootBudget(input.timeoutMs)\n let runResult: SupervisedResult<unknown> | undefined\n let runError: unknown\n let runSettled = false\n const runPromise = supervisor\n .run(rootAgent, input.task, {\n budget: runBudget,\n rootIdentity: {\n profileDigest: canonicalAgentProfileDigest(profile),\n taskDigest: canonicalCandidateDigest(input.task),\n },\n runId: supervisorId,\n ...context,\n interactiveBindingDir: eventDir,\n maxDepth: 1,\n workerSlots: 1,\n })\n .then(\n (result) => {\n runResult = result\n runSettled = true\n updateStateFromResult(state, result)\n writeState(statePath, state)\n return result\n },\n (error) => {\n runError = error\n runSettled = true\n state.status = 'down'\n state.completedAt = new Date().toISOString()\n writeState(statePath, state)\n throw error\n },\n )\n void runPromise.catch(() => undefined)\n\n let workerId: string\n try {\n workerId = await waitForWorkerSpawn(workerSpawned.promise, runPromise, input.timeoutMs)\n await waitForWorkerRunning(workerRunning.promise, runPromise, input.timeoutMs)\n if (terminalTakeover === 'required') {\n await waitForInteractiveBinding(eventDir, workerId, runPromise, input.timeoutMs, input.pollMs)\n }\n } catch (error) {\n if (!runSettled) {\n try {\n rootHandle.abort('supervisor provisioning failed')\n } catch {\n // The supervisor may have released the handle between the state read and this abort.\n }\n }\n await runPromise.catch(() => undefined)\n throw error\n }\n\n let cleanupPromise: Promise<SupervisorCleanupReceipt> | undefined\n const cleanup = async (): Promise<SupervisorCleanupReceipt> => {\n cleanupPromise ??= (async () => {\n if (!runSettled) {\n try {\n rootHandle.abort('supervisor cleanup')\n } catch {\n // A concurrent run completion already released the handle.\n }\n }\n const result = await runPromise.catch((error) => {\n runError = error\n return undefined\n })\n if (result !== undefined) runResult = result\n if (runError !== undefined) throw runError\n const finalEvents = await waitForWorkerTerminal(\n context.journal,\n supervisorId,\n workerId,\n input.timeoutMs,\n input.pollMs,\n )\n const workerStatus = workerStatusFromEvents(finalEvents, workerId)\n if (workerStatus === 'running') {\n throw new Error(`Runtime supervisor worker '${workerId}' did not reach a terminal state`)\n }\n if (runResult?.teardownUnconfirmed?.length) {\n const environments = runResult.teardownUnconfirmed.flatMap((node) =>\n (node.environments ?? []).map(\n (environment) => `${environment.provider}:${environment.environmentId}`,\n ),\n )\n throw new Error(\n `Runtime supervisor cleanup could not confirm ${runResult.teardownUnconfirmed.length} resource(s) released${\n environments.length > 0 ? `; environments still held: ${environments.join(', ')}` : ''\n }`,\n )\n }\n const supervisorStatus = state.status\n state.completedAt ??= new Date().toISOString()\n writeState(statePath, state)\n return Object.freeze({\n status: 'completed' as const,\n rootDir,\n supervisorId,\n workerId,\n supervisorStatus,\n workerStatus,\n resourcesReleased: true as const,\n remainingResources: Object.freeze([]) as readonly [],\n })\n })()\n return cleanupPromise\n }\n\n return Object.freeze({\n rootDir,\n supervisorId,\n workerId,\n providers: provider,\n terminalTakeover,\n cleanup,\n })\n}\n\nfunction normalizeRequest(request: ProvisionSupervisorRequest): ProvisionSupervisorRequest & {\n readonly invocationId: string\n readonly task: string\n readonly timeoutMs: number | undefined\n readonly pollMs: number\n readonly profile: AgentProfile\n readonly connection: ProvisionSupervisorConnection\n} {\n const invocationId = request.invocationId.trim()\n if (!invocationId) throw new SupervisorProvisionUnavailableError('invocationId is required')\n const task = request.task.trim()\n if (!task) throw new SupervisorProvisionUnavailableError('task is required')\n const profile = resolveProfile(request.profile)\n if (request.connection === undefined) {\n throw new SupervisorProvisionUnavailableError('provider connection is required')\n }\n const timeoutMs =\n request.timeoutMs === undefined ? undefined : positiveNumber(request.timeoutMs, 'timeoutMs')\n const pollMs = positiveNumber(request.pollMs ?? DEFAULT_POLL_MS, 'pollMs')\n return { ...request, invocationId, task, timeoutMs, pollMs, profile }\n}\n\nfunction positiveNumber(value: number, name: string): number {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new SupervisorProvisionUnavailableError(`${name} must be a positive safe integer`)\n }\n return value\n}\n\nfunction makeWorkspaceDir(): string {\n return join(tmpdir(), `agent-runtime-supervisor-${randomUUID()}`)\n}\n\nfunction supervisorIdFor(invocationId: string): string {\n const digest = canonicalCandidateDigest({ kind: 'runtime-supervisor', invocationId })\n return `runtime-supervisor-${digest.slice('sha256:'.length)}`\n}\n\n/** A caller-supplied deadline covers the complete supervisor lifecycle from run start through cleanup. */\nfunction rootBudget(timeoutMs: number | undefined): Budget {\n return {\n maxIterations: ROOT_MAX_ITERATIONS,\n maxTokens: ROOT_MAX_TOKENS,\n ...(timeoutMs === undefined ? {} : { deadlineMs: timeoutMs }),\n }\n}\n\nfunction workerBudget(): Budget {\n return {\n maxIterations: WORKER_MAX_ITERATIONS,\n maxTokens: WORKER_MAX_TOKENS,\n }\n}\n\nfunction resolveProfile(profile: AgentProfile): AgentProfile {\n const parsed = agentProfileSchema.safeParse(profile)\n if (!parsed.success) {\n throw unavailable(\n `Runtime supervisor profile is invalid: ${parsed.error.issues\n .map((issue) => `${issue.path.join('.')}: ${issue.message}`)\n .join('; ')}`,\n )\n }\n return parsed.data\n}\n\nfunction resolveProvider(request: ProvisionSupervisorRequest): AgentEnvironmentProvider {\n const provider = request.connection?.provider\n if (provider === undefined) {\n throw unavailable('Runtime supervisor requires connection.provider')\n }\n return requireReconnectProvider(provider)\n}\n\nfunction requireReconnectProvider(provider: AgentEnvironmentProvider): AgentEnvironmentProvider {\n if (!provider.name.trim()) throw unavailable('Runtime supervisor provider has no name')\n if (typeof provider.get !== 'function') {\n throw unavailable(\n `Runtime supervisor provider '${provider.name}' cannot reconnect environments`,\n )\n }\n return provider\n}\n\nasync function readCapabilities(\n provider: AgentEnvironmentProvider,\n): Promise<AgentEnvironmentCapabilities> {\n try {\n return await provider.capabilities()\n } catch (error) {\n throw unavailable(`Runtime supervisor could not read '${provider.name}' capabilities`, error)\n }\n}\n\nfunction terminalCapability(\n capabilities: AgentEnvironmentCapabilities,\n): 'required' | 'unsupported' | 'unspecified' {\n const interactive = capabilities.interactiveAgent\n if (interactive === undefined) return 'unsupported'\n const complete = [\n interactive.start,\n interactive.control,\n interactive.status,\n interactive.attach,\n interactive.reattach,\n interactive.sendPrompt,\n interactive.input,\n interactive.resize,\n interactive.stop,\n ].every((value) => value === true)\n return complete ? 'required' : 'unsupported'\n}\n\nfunction findTool(tools: readonly McpToolDescriptor[], name: string): McpToolDescriptor {\n const tool = tools.find((candidate) => candidate.name === name)\n if (tool === undefined)\n throw new Error(`Runtime supervisor coordination tool '${name}' is missing`)\n return tool\n}\n\nfunction workerIdFromSpawn(value: unknown): string {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error('Runtime supervisor spawn did not return a worker id')\n }\n const workerId = (value as { workerId?: unknown }).workerId\n if (typeof workerId !== 'string' || !workerId.trim()) {\n throw new Error('Runtime supervisor spawn did not return a worker id')\n }\n return workerId\n}\n\nasync function waitForWorkerSpawn(\n worker: Promise<string>,\n run: Promise<SupervisedResult<unknown>>,\n timeoutMs: number | undefined,\n): Promise<string> {\n return await withTimeout(\n Promise.race([\n worker,\n run.then(() => {\n throw new Error('Runtime supervisor ended before it spawned a worker')\n }),\n ]),\n timeoutMs,\n 'worker spawn',\n )\n}\n\nasync function waitForWorkerRunning(\n running: Promise<void>,\n run: Promise<SupervisedResult<unknown>>,\n timeoutMs: number | undefined,\n): Promise<void> {\n await withTimeout(\n Promise.race([\n running,\n run.then(() => {\n throw new Error('Runtime supervisor ended before the worker became live')\n }),\n ]),\n timeoutMs,\n 'worker readiness',\n )\n}\n\nasync function waitForInteractiveBinding(\n eventDir: string,\n workerId: string,\n run: Promise<SupervisedResult<unknown>>,\n timeoutMs: number | undefined,\n pollMs: number,\n): Promise<void> {\n await withTimeout(\n pollUntil(\n async () => {\n const binding = readWorkerInteractiveBinding(eventDir, workerId)\n if (binding?.status === 'available') return true\n if (binding?.status === 'unavailable') {\n throw unavailable(`Runtime worker '${workerId}' could not publish an interactive binding`)\n }\n return false\n },\n run,\n pollMs,\n ),\n timeoutMs,\n 'interactive terminal binding',\n )\n}\n\nasync function pollUntil(\n read: () => Promise<boolean> | boolean,\n run: Promise<SupervisedResult<unknown>>,\n pollMs: number,\n): Promise<void> {\n for (;;) {\n if (await read()) return\n await Promise.race([\n delay(pollMs),\n run.then(() => {\n throw new Error('Runtime supervisor ended before readiness was observed')\n }),\n ])\n }\n}\n\nasync function withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number | undefined,\n label: string,\n): Promise<T> {\n if (timeoutMs === undefined) return await promise\n let clearTimer: (() => void) | undefined\n const timeout = new Promise<never>((_resolve, reject) => {\n clearTimer = armDeadlineTimer(timeoutMs, () =>\n reject(unavailable(`Runtime supervisor timed out waiting for ${label}`)),\n )\n })\n try {\n return await Promise.race([promise, timeout])\n } finally {\n clearTimer?.()\n }\n}\n\nfunction delay(ms: number, keepAlive = false): Promise<void> {\n return sleep(ms, undefined, keepAlive)\n}\n\nfunction updateStateFromResult(state: MutableState, result: SupervisedResult<unknown>): void {\n state.status =\n result.kind === 'winner' ? 'done' : result.reason === 'cancelled' ? 'cancelled' : 'down'\n state.completedAt = new Date().toISOString()\n}\n\nfunction workerStatusFromEvents(\n events: readonly SpawnEvent[],\n workerId: string,\n): SupervisorCleanupReceipt['workerStatus'] {\n let status: SupervisorCleanupReceipt['workerStatus'] = 'running'\n let terminal = false\n for (const event of events) {\n if (event.id !== workerId) continue\n if (terminal) continue\n if (event.kind === 'spawned' || event.kind === 'progress') status = 'running'\n else if (event.kind === 'settled') {\n status = event.status === 'done' ? 'done' : 'down'\n terminal = true\n } else if (event.kind === 'cancelled') {\n status = 'cancelled'\n terminal = true\n }\n }\n return status\n}\n\nasync function waitForWorkerTerminal(\n journal: import('./types').SpawnJournal,\n root: string,\n workerId: string,\n timeoutMs: number | undefined,\n pollMs: number,\n): Promise<SpawnEvent[]> {\n const deadline = timeoutMs === undefined ? undefined : Date.now() + timeoutMs\n for (;;) {\n const events = await journal.loadTree(root)\n if (events !== undefined && workerStatusFromEvents(events, workerId) !== 'running') {\n return events\n }\n if (deadline !== undefined && Date.now() >= deadline) {\n throw unavailable(`Runtime supervisor timed out waiting for worker '${workerId}' to settle`)\n }\n // Cleanup is an explicit lifecycle operation. Keep this bounded poll referenced so a caller\n // awaiting cleanup cannot have Node exit while the provider is still committing the terminal\n // worker event.\n await delay(pollMs, true)\n }\n}\n\nfunction deferred<T>(): Deferred<T> {\n let done = false\n let resolveValue!: (value: T) => void\n let rejectValue!: (error: unknown) => void\n const promise = new Promise<T>((resolvePromise, rejectPromise) => {\n resolveValue = (value) => {\n if (done) return\n done = true\n resolvePromise(value)\n }\n rejectValue = (error) => {\n if (done) return\n done = true\n rejectPromise(error)\n }\n })\n return {\n promise,\n resolve: resolveValue,\n reject: rejectValue,\n settled: () => done,\n }\n}\n\nfunction unavailable(message: string, cause?: unknown): SupervisorProvisionUnavailableError {\n return new SupervisorProvisionUnavailableError(message, cause)\n}\n\nfunction writeState(path: string, state: MutableState): void {\n mkdirSync(dirname(path), { recursive: true })\n writeAtomicDurableFile(path, `${JSON.stringify(state)}\\n`, { mode: 0o600 })\n}\n"],"mappings":";;;;;;;;;;;;;;AAaA,MAAM,2BAA2B;;;;;;;;;;AAuBjC,eAAsB,gCACpB,SAC8C;CAC9C,IAAI,QAAQ,QAAQ,SAAS,MAAM,WAAW,QAAQ,OAAO,MAAM;CACnE,MAAM,WAAW,QAAQ,sBAAsB;CAC/C,IAAI,CAAC,OAAO,cAAc,QAAQ,KAAK,WAAW,GAChD,MAAM,IAAI,MAAM,uEAAuE;CAEzF,IAAI,QAAQ,eAAe,SAAS,MAAM,6BAA6B,QAAQ,MAAM;CACrF,IAAI,QAAQ,eAAe,UAAU;EACnC,MAAM,YAAY,MAAM,2BAA2B,QAAQ,MAAM;EACjE,IAAI,QAAQ,QAAQ,SAAS,MAAM,WAAW,QAAQ,OAAO,MAAM;EACnE,IAAI,WAAW,OAAO;CACxB;CACA,IAAI,aAAa;CACjB,KAAK,IAAI,WAAW,GAAG,YAAY,0BAA0B,YAAY,GAAG;EAC1E,IAAI,QAAQ,QAAQ,SAAS,MAAM,WAAW,QAAQ,OAAO,MAAM;EACnE,MAAM,WAAW;GACf,aAAa,wBAAwB,QAAQ,QAAQ,QAAQ,UAAU,UAAU;GACjF,KAAK,QAAQ,OAAO;GACpB,UAAU,QAAQ;GAClB,oBAAoB;EACtB;EACA,MAAM,kBAAkB,MAAM,QAAQ,OAAO,aAC3C;GACE,GAAG;GACH,eAAe,iDAAiD,QAAQ;EAC1E,GACA,QAAQ,WAAW,KAAA,IAAY,KAAA,IAAY,EAAE,Q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M;IACV,OAAO;IACP,cAAc,KAAK;GACrB;EACF,CAEQ;EACN,SAAS;EACT,QAAQ;EACR,eAAe;CACjB;AACF;AAEA,SAAS,YAAY,SAAiB,OAAsD;CAC1F,OAAO,IAAI,oCAAoC,SAAS,KAAK;AAC/D;AAEA,SAAS,WAAW,MAAc,OAA2B;CAC3D,UAAU,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;CAC5C,uBAAuB,MAAM,GAAG,KAAK,UAAU,KAAK,EAAE,KAAK,EAAE,MAAM,IAAM,CAAC;AAC5E"}
|
|
1
|
+
{"version":3,"file":"provision-supervisor-jR8FxV0u.js","names":[],"sources":["../src/runtime/retained-interactive-control.ts","../src/runtime/supervise/interactive-executor.ts","../src/runtime/supervise/interactive-worker.ts","../src/runtime/supervise/provision-supervisor.ts"],"sourcesContent":["import type { AgentInteractiveSessionControlClaim } from '@tangle-network/agent-interface'\nimport {\n agentInteractiveSessionControlClaimRequestDigest,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport {\n acceptedInteractiveControl,\n offerInteractiveControl,\n prepareInteractiveDelegation,\n} from './retained-interactive-delegation'\nimport type { RetainedInteractiveRunHandle } from './retained-interactive-types'\nimport { abortError } from './util'\n\nconst MAX_GENERATION_CONFLICTS = 8\n\n/** Input for acquiring write authority over one exact interactive process. @stable */\nexport interface ClaimRetainedInteractiveControlOptions {\n readonly handle: RetainedInteractiveRunHandle\n readonly holderId: string\n /** Last known provider generation. Zero discovers the current generation safely. */\n readonly expectedGeneration?: number\n readonly signal?: AbortSignal\n /** Explicit full-control delegation within private local Runtime state. The accepted claim\n * retains the real holder identity and grants attach/input/resize, prompt and stop authority. */\n readonly delegation?: 'offer' | 'accept'\n}\n\n/**\n * Acquire provider-issued write authority without reading authority from status.\n *\n * A new coordinator starts at generation zero. If another claim already exists,\n * the provider returns its public generation and this helper retries one new\n * compare-and-swap operation. Every generation has a deterministic operation\n * identifier, so retrying after an ambiguous response cannot create two claims.\n * @stable\n */\nexport async function claimRetainedInteractiveControl(\n options: ClaimRetainedInteractiveControlOptions,\n): Promise<AgentInteractiveSessionControlClaim> {\n if (options.signal?.aborted) throw abortError(options.signal.reason)\n const expected = options.expectedGeneration ?? 0\n if (!Number.isSafeInteger(expected) || expected < 0) {\n throw new Error('interactive control expectedGeneration must be a non-negative integer')\n }\n if (options.delegation === 'offer') await prepareInteractiveDelegation(options.handle)\n if (options.delegation === 'accept') {\n const delegated = await acceptedInteractiveControl(options.handle)\n if (options.signal?.aborted) throw abortError(options.signal.reason)\n if (delegated) return delegated\n }\n let generation = expected\n for (let conflict = 0; conflict <= MAX_GENERATION_CONFLICTS; conflict += 1) {\n if (options.signal?.aborted) throw abortError(options.signal.reason)\n const material = {\n operationId: controlClaimOperationId(options.handle, options.holderId, generation),\n ref: options.handle.ref,\n holderId: options.holderId,\n expectedGeneration: generation,\n }\n const acknowledgement = await options.handle.claimControl(\n {\n ...material,\n requestDigest: agentInteractiveSessionControlClaimRequestDigest(material),\n },\n options.signal === undefined ? undefined : { signal: options.signal },\n )\n if (acknowledgement.status === 'accepted' || acknowledgement.status === 'replayed') {\n const control = acknowledgement.control\n if (control === undefined) {\n throw new Error('provider accepted interactive control without returning its claim')\n }\n if (Date.parse(control.expiresAt) <= Date.now()) {\n throw new Error('provider returned an expired interactive control claim')\n }\n if (options.delegation === 'offer') await offerInteractiveControl(options.handle, control)\n return control\n }\n if (\n acknowledgement.status !== 'conflict' ||\n acknowledgement.conflictReason !== 'generation_mismatch'\n ) {\n throw new Error(\n acknowledgement.status === 'unknown'\n ? 'interactive control claim outcome is unknown; retry the same acquisition'\n : 'interactive control claim operation conflicts with different request material',\n )\n }\n const current = acknowledgement.currentGeneration\n if (current === undefined || current <= generation) {\n throw new Error('provider returned a non-advancing interactive control generation')\n }\n generation = current\n }\n throw new Error('interactive control changed too often to acquire safely')\n}\n\nfunction controlClaimOperationId(\n handle: RetainedInteractiveRunHandle,\n holderId: string,\n expectedGeneration: number,\n): string {\n const digest = canonicalCandidateDigest({\n kind: 'retained-interactive-control-claim.v1',\n ref: handle.ref,\n holderId,\n expectedGeneration,\n })\n return `interactive-claim-${digest.slice('sha256:'.length, 'sha256:'.length + 40)}`\n}\n","/**\n * The executor behind one interactive worker: starts the provider's retained interactive process,\n * polls it to exit, relays steers as prompts, and stops and releases it exactly once.\n */\n\nimport {\n type AgentInteractiveSessionPromptCommand,\n type AgentInteractiveSessionStatus,\n type AgentInteractiveSessionStopAcknowledgement,\n type AgentInteractiveSessionStopCommand,\n type AgentProfile,\n agentInteractiveSessionPromptRequestDigest,\n agentInteractiveSessionStopRequestDigest,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport type {\n AgentEnvironment,\n AgentEnvironmentProvider,\n} from '@tangle-network/agent-interface/environment-provider'\nimport { contentAddress } from '../../durable/content-address'\nimport type { WorkerSpawnContext } from '../../mcp/tools/coordination-contracts'\nimport { startRetainedInteractiveRun } from '../retained-interactive'\nimport { claimRetainedInteractiveControl } from '../retained-interactive-control'\nimport { destroyInteractiveEnvironment, environmentGone } from '../retained-interactive-lifecycle'\nimport type { RetainedInteractiveRunHandle } from '../retained-interactive-types'\nimport { retainedCreateMaterial } from '../retained-run-intent'\nimport type { RetainedInteractiveAdmission } from '../retained-run-types'\nimport { sleep } from '../util'\nimport { linkAbort, signalAbortError } from './abortable'\nimport { createInbox, failPendingAfter } from './inbox'\nimport type { InteractiveAdmissionWriter } from './interactive-admission'\nimport type {\n InteractiveWorkerEnvironment,\n InteractiveWorkerOptions,\n InteractiveWorkerResult,\n} from './interactive-worker'\nimport {\n attestRuntimeOwnedPendingExecutor,\n finalizeRuntimeOwnedPendingExecutor,\n newExecutionAttemptId,\n} from './materialization'\nimport { concreteProfileModel } from './model-policy'\nimport { detachedSnapshot } from './snapshot'\nimport { taskToPrompt } from './task-prompt'\nimport type {\n Executor,\n ExecutorCancellation,\n ExecutorResult,\n HeldEnvironment,\n Runtime,\n Spend,\n UsageEvent,\n WorkerInteractiveSession,\n} from './types'\n\nconst INTERACTIVE_TEARDOWN_TIMEOUT_MS = 30_000\n\nexport interface InteractiveExecutorInput {\n readonly provider: AgentEnvironmentProvider\n readonly profile: AgentProfile\n readonly context?: WorkerSpawnContext\n readonly environment?: InteractiveWorkerEnvironment\n readonly environmentKey: string\n readonly interactiveKey: (task: unknown) => string\n readonly holderId: (task: unknown) => string\n readonly initialPrompt?: InteractiveWorkerOptions['initialPrompt']\n readonly cwd?: string\n readonly cols?: number\n readonly rows?: number\n readonly runtime: Runtime\n readonly pollIntervalMs?: number\n readonly destroyEnvironmentOnTeardown?: boolean\n readonly executionAttemptId?: string\n readonly nodeId?: string\n readonly admission: InteractiveAdmissionWriter\n}\n\n/** The one record an interactive executor reads and writes across start, poll, steer, stop and teardown. */\ninterface InteractiveRun {\n readonly input: InteractiveExecutorInput\n readonly attemptId: string\n readonly localController: AbortController\n readonly inbox: ReturnType<typeof createInbox>\n readonly planned: PlannedDeclaration\n readonly stopOperations: Map<string, Promise<ExecutorCancellation>>\n readonly memoryAdmissions: Map<string, RetainedInteractiveAdmission>\n readonly ready: Promise<WorkerInteractiveSession>\n readonly resolveReady: (session: WorkerInteractiveSession) => void\n executor: Executor<InteractiveWorkerResult>\n handle: RetainedInteractiveRunHandle | undefined\n createdEnvironment: AgentEnvironment | undefined\n environmentId: string | undefined\n artifact: ExecutorResult<InteractiveWorkerResult> | undefined\n activeLink: ReturnType<typeof linkAbort> | undefined\n startPromise: Promise<RetainedInteractiveRunHandle> | undefined\n executeStarted: boolean\n teardownComplete: boolean\n teardownPromise: Promise<{ destroyed: boolean }> | undefined\n flushChain: Promise<void>\n controlError: unknown\n}\n\ntype PlannedDeclaration = ReturnType<typeof plannedDeclarationOf>\n\nconst descriptorOf = (input: InteractiveExecutorInput) =>\n ({\n kind: 'interactive-session',\n provider: input.provider.name,\n transport: 'agent-environment',\n }) as const\n\nfunction plannedDeclarationOf(input: InteractiveExecutorInput) {\n const declaredEnvironment = input.environment\n ? retainedCreateMaterial({\n ...input.environment,\n profile: input.profile,\n idempotencyKey: input.environmentKey,\n })\n : null\n const profileModel = concreteProfileModel(input.profile)\n return {\n effectiveProfile: input.profile,\n backend: input.provider.name,\n model: profileModel\n ? { status: 'known' as const, id: profileModel }\n : { status: 'unknown' as const, reason: 'provider selected the model' },\n execution: { kind: 'interactive-session', id: input.nodeId ?? input.environmentKey },\n materializer: 'retained-interactive-provider',\n plan: {\n kind: 'retained-interactive-provider',\n provider: input.provider.name,\n environment: declaredEnvironment,\n environmentIdempotencyKey: input.environmentKey,\n destroyEnvironmentOnTeardown: input.destroyEnvironmentOnTeardown !== false,\n },\n }\n}\n\nexport function interactiveExecutor(\n input: InteractiveExecutorInput,\n): Executor<InteractiveWorkerResult> {\n const attemptId =\n input.executionAttemptId ?? newExecutionAttemptId(input.nodeId ?? input.environmentKey)\n let resolveReady!: (session: WorkerInteractiveSession) => void\n const ready = new Promise<WorkerInteractiveSession>((resolve) => {\n resolveReady = resolve\n })\n const run: InteractiveRun = {\n input,\n attemptId,\n localController: new AbortController(),\n inbox: createInbox(),\n planned: plannedDeclarationOf(input),\n stopOperations: new Map(),\n memoryAdmissions: new Map(),\n ready,\n resolveReady,\n executor: undefined as unknown as Executor<InteractiveWorkerResult>,\n handle: undefined,\n createdEnvironment: undefined,\n environmentId: undefined,\n artifact: undefined,\n activeLink: undefined,\n startPromise: undefined,\n executeStarted: false,\n teardownComplete: false,\n teardownPromise: undefined,\n flushChain: Promise.resolve(),\n controlError: undefined,\n }\n run.executor = interactiveSurface(run)\n attestRuntimeOwnedPendingExecutor(run.executor, input.runtime, run.planned, {\n attemptId,\n binding: {\n provider: input.provider.name,\n environmentIdempotencyKey: input.environmentKey,\n nodeId: input.nodeId ?? null,\n },\n descriptor: descriptorOf(input),\n })\n return run.executor\n}\n\nfunction interactiveSurface(run: InteractiveRun): Executor<InteractiveWorkerResult> {\n const { input } = run\n return {\n runtime: input.runtime,\n teardownTimeoutMs: INTERACTIVE_TEARDOWN_TIMEOUT_MS,\n execute(task, signal): AsyncIterable<UsageEvent> {\n if (run.executeStarted || run.teardownComplete || run.teardownPromise !== undefined) {\n throw new Error('workerFromInteractiveProvider: execute() may only be called once')\n }\n run.executeStarted = true\n run.startPromise = startInteractive(run, task, signal)\n return failPendingAfter(run.inbox, runInteractive(run, signal))\n },\n deliver(message: unknown): boolean {\n if (run.teardownComplete || run.teardownPromise !== undefined) return false\n const accepted = run.inbox.deliver(message)\n if (accepted) void flushInbox(run)\n return accepted\n },\n interactive(): WorkerInteractiveSession {\n return run.handle\n ? { status: 'available', handle: run.handle }\n : { status: 'unavailable', reason: 'interactive-session-not-started' }\n },\n interactiveReady(): Promise<WorkerInteractiveSession> {\n return run.ready\n },\n async cancel(request): Promise<ExecutorCancellation> {\n const existing = run.stopOperations.get(request.operationId)\n if (existing) return existing\n const operation = stopInteractive(run, request.operationId, request.reason, request.signal)\n const tracked = operation.then((result) => {\n if (\n result.status === 'unknown' &&\n run.stopOperations.get(request.operationId) === tracked\n ) {\n run.stopOperations.delete(request.operationId)\n }\n return result\n })\n run.stopOperations.set(request.operationId, tracked)\n return tracked\n },\n teardown(grace): Promise<{ destroyed: boolean }> {\n void grace\n if (run.teardownComplete) return Promise.resolve({ destroyed: true })\n if (run.teardownPromise !== undefined) return run.teardownPromise\n const pending = teardownInteractive(run)\n run.teardownPromise = pending.then(\n (result) => {\n run.teardownComplete = true\n return result\n },\n (error) => {\n run.teardownPromise = undefined\n throw error\n },\n )\n return run.teardownPromise\n },\n heldEnvironments(): ReadonlyArray<HeldEnvironment> {\n if (run.teardownComplete || input.destroyEnvironmentOnTeardown === false) return []\n const held =\n run.createdEnvironment?.id ?? run.environmentId ?? run.handle?.ref.run.environmentId\n return held === undefined ? [] : [{ provider: input.provider.name, environmentId: held }]\n },\n resultArtifact(): ExecutorResult<InteractiveWorkerResult> {\n if (!run.artifact) {\n throw new Error(\n 'workerFromInteractiveProvider: resultArtifact() read before execution settled',\n )\n }\n return run.artifact\n },\n }\n}\n\nfunction initialPromptFor(input: InteractiveExecutorInput, task: unknown): string {\n const initialPrompt =\n typeof input.initialPrompt === 'function'\n ? input.initialPrompt(task, {\n provider: input.provider.name,\n profile: input.profile,\n ...(input.context === undefined ? {} : { context: input.context }),\n task,\n ...(input.nodeId === undefined ? {} : { nodeId: input.nodeId }),\n })\n : (input.initialPrompt ?? taskToPrompt(task))\n if (typeof initialPrompt !== 'string') {\n throw new Error('workerFromInteractiveProvider: initialPrompt must return a string')\n }\n return initialPrompt\n}\n\n/** Keep each admission phase's first snapshot in memory and refuse a retry that changes it. */\nasync function recordAdmission(\n run: InteractiveRun,\n admission: RetainedInteractiveAdmission,\n): Promise<void> {\n run.environmentId =\n admission.phase === 'interactive_environment' ? admission.environmentId : run.environmentId\n const existing = run.memoryAdmissions.get(admission.phase)\n if (existing !== undefined) {\n if (canonicalCandidateDigest(existing) !== canonicalCandidateDigest(admission)) {\n throw new Error(`interactive admission phase '${admission.phase}' changed across retry`)\n }\n } else {\n run.memoryAdmissions.set(admission.phase, detachedSnapshot(admission, 'interactive admission'))\n }\n await run.input.admission(admission)\n}\n\nasync function startInteractive(\n run: InteractiveRun,\n task: unknown,\n signal: AbortSignal,\n): Promise<RetainedInteractiveRunHandle> {\n const { input } = run\n try {\n run.activeLink = linkAbort(signal, run.localController.signal)\n const initialPrompt = initialPromptFor(input, task)\n const interactiveIdempotencyKey = input.interactiveKey(task)\n const started = await startRetainedInteractiveRun({\n provider: {\n ...input.provider,\n async create(environmentInput): Promise<AgentEnvironment> {\n const environment = await input.provider.create!(environmentInput)\n run.createdEnvironment = environment\n return environment\n },\n },\n environment: {\n ...(input.environment ?? {}),\n profile: input.profile,\n idempotencyKey: input.environmentKey,\n },\n interactiveIdempotencyKey,\n ...(initialPrompt.length === 0 ? {} : { initialPrompt }),\n ...(input.cwd === undefined ? {} : { cwd: input.cwd }),\n ...(input.cols === undefined ? {} : { cols: input.cols }),\n ...(input.rows === undefined ? {} : { rows: input.rows }),\n onAdmission: (admission) => recordAdmission(run, admission),\n signal: run.activeLink.signal,\n })\n finalizeRuntimeOwnedPendingExecutor(\n run.executor,\n {\n ...run.planned,\n execution: { kind: 'interactive-session', id: started.ref.run.executionId },\n plan: {\n ...run.planned.plan,\n environmentId: started.ref.run.environmentId,\n interactiveIdempotencyKey,\n },\n },\n {\n attemptId: run.attemptId,\n binding: {\n provider: input.provider.name,\n ref: started.ref,\n environmentId: started.ref.run.environmentId,\n },\n descriptor: descriptorOf(input),\n },\n )\n run.handle = started\n run.resolveReady({ status: 'available', handle: started })\n void flushInbox(run)\n return started\n } catch (error) {\n run.resolveReady({ status: 'unavailable', reason: unavailableReason(error) })\n run.activeLink?.release()\n throw error\n }\n}\n\nasync function* runInteractive(\n run: InteractiveRun,\n signal: AbortSignal,\n): AsyncIterable<UsageEvent> {\n const { input, localController } = run\n const startedAt = Date.now()\n try {\n const current = await run.startPromise\n if (current === undefined) {\n throw new Error('workerFromInteractiveProvider: interactive start did not begin')\n }\n yield { kind: 'iteration' }\n // Native TUI sessions do not expose a complete turn receipt. These zero counters are an\n // observed floor and the explicit false markers keep the run's accounting honest.\n yield { kind: 'tokens', input: 0, output: 0, tokensKnown: false }\n yield { kind: 'cost', usd: 0, usdKnown: false, provenance: 'uncaptured' }\n let status: AgentInteractiveSessionStatus | undefined\n for (;;) {\n if (signal.aborted || localController.signal.aborted) {\n throw signalAbortError(\n signal.aborted ? signal : localController.signal,\n 'interactive execution aborted',\n )\n }\n status = await current.status({ signal: run.activeLink?.signal })\n await run.flushChain\n if (run.controlError !== undefined) throw controlErrorValue(run.controlError)\n if (status.state !== 'running') break\n await sleep(input.pollIntervalMs ?? 100, run.activeLink?.signal)\n }\n const finished = status\n const output: InteractiveWorkerResult = {\n provider: input.provider.name,\n environmentId: current.ref.run.environmentId,\n sessionId: current.ref.run.sessionId,\n executionId: current.ref.run.executionId,\n state: finished?.state === 'exited' ? 'exited' : 'unknown',\n ref: current.ref,\n ...(finished?.state === 'exited' && finished.reason ? { reason: finished.reason } : {}),\n ...(finished?.state === 'exited' && finished.exitCode !== undefined\n ? { exitCode: finished.exitCode }\n : {}),\n ...(finished?.state === 'exited' && finished.exitSignal !== undefined\n ? { exitSignal: finished.exitSignal }\n : {}),\n }\n const spent: Spend = {\n iterations: 1,\n tokens: { input: 0, output: 0 },\n tokensKnown: false,\n usd: 0,\n usdKnown: false,\n ms: Date.now() - startedAt,\n }\n run.artifact = {\n outRef: contentAddress(output),\n out: output,\n spent,\n }\n } finally {\n run.activeLink?.release()\n }\n}\n\nasync function flushInbox(run: InteractiveRun): Promise<void> {\n run.flushChain = run.flushChain.then(async () => {\n const handle = run.handle\n if (!handle) return\n const lease = run.inbox.take()\n try {\n const messages = lease.messages\n if (messages.length === 0) return\n const prompt = run.inbox.fold(messages)\n const operationId = `interactive-prompt-${canonicalCandidateDigest({\n ref: handle.ref,\n prompt,\n }).slice('sha256:'.length)}`\n const control = await claimRetainedInteractiveControl({\n handle,\n holderId: run.input.holderId(undefined),\n })\n const material = {\n operationId,\n ref: handle.ref,\n control,\n prompt,\n }\n const command: AgentInteractiveSessionPromptCommand = {\n ...material,\n requestDigest: agentInteractiveSessionPromptRequestDigest(material),\n }\n await handle.sendPrompt(command)\n for (const message of messages) lease.commit(operationId, message.id)\n } catch (error) {\n lease.release()\n run.controlError ??= error\n }\n })\n await run.flushChain\n}\n\nasync function stopInteractive(\n run: InteractiveRun,\n operationId: string,\n reason?: string,\n signal?: AbortSignal,\n): Promise<ExecutorCancellation> {\n const observedAt = new Date().toISOString()\n const handle = run.handle\n if (!handle) {\n run.localController.abort(reason ?? 'interactive cancellation requested')\n return {\n status: 'unknown',\n effect: 'cancel_requested',\n observedAt,\n detail: 'interactive process has not published a provider reference',\n }\n }\n try {\n const control = await claimRetainedInteractiveControl({\n handle,\n holderId: run.input.holderId(undefined),\n signal,\n })\n const material = { operationId, ref: handle.ref, control }\n const command: AgentInteractiveSessionStopCommand = {\n ...material,\n requestDigest: agentInteractiveSessionStopRequestDigest(material),\n }\n const acknowledgement = await handle.stop(\n command,\n signal === undefined ? undefined : { signal },\n )\n run.localController.abort(reason ?? 'interactive cancellation requested')\n return cancellationFromAcknowledgement(acknowledgement, observedAt)\n } catch (error) {\n run.localController.abort(reason ?? 'interactive cancellation requested')\n return {\n status: 'unknown',\n effect: 'cancel_requested',\n observedAt,\n detail: error instanceof Error ? error.message : String(error),\n evidence: { operationId },\n }\n }\n}\n\nasync function teardownInteractive(run: InteractiveRun): Promise<{ destroyed: boolean }> {\n run.localController.abort('interactive worker teardown')\n run.activeLink?.release()\n await run.startPromise?.catch(() => undefined)\n if (run.handle) {\n const status = await safeStatus(run.handle)\n if (status?.state === 'running') {\n const operationId = `interactive-teardown-${canonicalCandidateDigest(run.handle.ref).slice(\n 'sha256:'.length,\n )}`\n const cancellation = await stopInteractive(run, operationId, 'interactive worker teardown')\n if (cancellation.status === 'rejected' || cancellation.status === 'unknown') {\n throw new Error(cancellation.detail ?? 'interactive teardown was not acknowledged')\n }\n }\n }\n await destroyEnvironment(run)\n return { destroyed: true }\n}\n\nasync function destroyEnvironment(run: InteractiveRun): Promise<void> {\n const { input } = run\n if (input.destroyEnvironmentOnTeardown === false) return\n if (run.createdEnvironment !== undefined) {\n await destroyConfirmed(input.provider, run.createdEnvironment)\n return\n }\n if (!input.provider.get) return\n // The exact provider reference is durable and remains available even when the admission\n // callback was interrupted after the environment was created. Use it as the cleanup identity\n // so an aborted provider signal cannot turn a real environment into an unconfirmed leak.\n const cleanupEnvironmentId = run.environmentId ?? run.handle?.ref.run.environmentId\n if (!cleanupEnvironmentId) return\n const environment = await input.provider.get(cleanupEnvironmentId)\n if (environment !== undefined && environment !== null) {\n await destroyConfirmed(input.provider, environment)\n }\n}\n\nasync function destroyConfirmed(\n provider: AgentEnvironmentProvider,\n environment: AgentEnvironment,\n): Promise<void> {\n try {\n await destroyInteractiveEnvironment(environment)\n } catch (error) {\n // A delete whose answer was lost fails not-found on every later attempt; the provider's\n // lookup confirming the environment gone is the destroy's confirmation.\n if (!(await environmentGone(provider, environment.id))) throw error\n }\n}\n\nfunction unavailableReason(\n error: unknown,\n): 'provider-has-no-interactive-contract' | 'interactive-binding-stale' {\n const message = error instanceof Error ? error.message : String(error)\n return message.includes('interactive') || message.includes('Interactive')\n ? 'provider-has-no-interactive-contract'\n : 'interactive-binding-stale'\n}\n\nfunction cancellationFromAcknowledgement(\n acknowledgement: AgentInteractiveSessionStopAcknowledgement,\n observedAt: string,\n): ExecutorCancellation {\n const status =\n acknowledgement.status === 'accepted' || acknowledgement.status === 'replayed'\n ? 'accepted'\n : acknowledgement.status === 'conflict'\n ? 'rejected'\n : 'unknown'\n const effect =\n acknowledgement.effect === 'stopped'\n ? 'cancelled'\n : acknowledgement.effect === 'not_live'\n ? 'not_live'\n : acknowledgement.effect === 'stop_requested'\n ? 'cancel_requested'\n : 'unknown'\n return {\n status,\n effect,\n observedAt,\n ...(acknowledgement.message === undefined ? {} : { detail: acknowledgement.message }),\n evidence: {\n operationId: acknowledgement.operationId,\n requestDigest: acknowledgement.requestDigest,\n providerStatus: acknowledgement.status,\n providerEffect: acknowledgement.effect,\n },\n }\n}\n\nfunction controlErrorValue(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error))\n}\n\nasync function safeStatus(\n handle: RetainedInteractiveRunHandle,\n): Promise<AgentInteractiveSessionStatus | undefined> {\n let timer: ReturnType<typeof setTimeout> | undefined\n const timeout = new Promise<undefined>((resolve) => {\n timer = setTimeout(() => resolve(undefined), 100)\n timer.unref?.()\n })\n try {\n // A provider environment created with the worker's abort signal may reject or hang all\n // subsequent calls after the scope begins teardown. Keep status best-effort and let the fresh\n // environment lookup below prove release without spending the teardown acknowledgement window\n // on a stale connection.\n return await Promise.race([handle.status(), timeout])\n } catch {\n return undefined\n } finally {\n if (timer !== undefined) clearTimeout(timer)\n }\n}\n","/**\n * Runtime-owned worker seam for a provider's native interactive coding-agent process. It composes\n * the retained-interactive lifecycle, adding no second stream, replay buffer, session id or\n * cancellation protocol: the provider owns process state; Scope owns the worker, journal, budget\n * and local control inbox.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport {\n type AgentInteractiveSessionRef,\n type AgentProfile,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport type {\n AgentEnvironmentProvider,\n CreateAgentEnvironmentInput,\n} from '@tangle-network/agent-interface/environment-provider'\nimport type { MakeWorkerAgent, WorkerSpawnContext } from '../../mcp/tools/coordination-contracts'\nimport type { RetainedInteractiveAdmission } from '../retained-run-types'\nimport { executableAgentProfileSnapshot } from './executable-spec'\nimport {\n type InteractiveAdmissionWriter,\n interactiveAdmissionSeamKey,\n} from './interactive-admission'\nimport { interactiveExecutor } from './interactive-executor'\nimport { detachedSnapshot } from './snapshot'\nimport type { Agent, AgentSpec, Executor, ExecutorContext, Runtime } from './types'\n\n/** Environment fields supplied to every interactive worker after Runtime adds the exact profile. */\nexport type InteractiveWorkerEnvironment = Omit<\n CreateAgentEnvironmentInput,\n 'profile' | 'idempotencyKey' | 'signal'\n>\n\n/** Native interactive worker output. Provider usage is intentionally not fabricated. */\nexport interface InteractiveWorkerResult {\n readonly provider: string\n readonly environmentId: string\n readonly sessionId: string\n readonly executionId: string\n readonly state: 'exited' | 'unknown'\n readonly ref: AgentInteractiveSessionRef\n readonly reason?: string\n readonly exitCode?: number\n readonly exitSignal?: string\n}\n\n/** Configuration shared by every worker produced by `workerFromInteractiveProvider`. */\nexport interface InteractiveWorkerOptions {\n /** Provider create fields. Runtime supplies `profile`, the two idempotency keys, and `signal`. */\n readonly environment?: InteractiveWorkerEnvironment\n /** Stable environment identity override. Defaults to a digest of the exact worker assignment. */\n readonly environmentIdempotencyKey?: (input: InteractiveWorkerKeyInput) => string\n /** Stable interactive-session identity override. Defaults to a digest of assignment and task. */\n readonly interactiveIdempotencyKey?: (input: InteractiveWorkerKeyInput) => string\n /** Provider holder id used only while the worker sends a steer or stop command. */\n readonly holderId?: string | ((input: InteractiveWorkerKeyInput) => string)\n /** Initial prompt override. The exact worker task is the default prompt. */\n readonly initialPrompt?: string | ((task: unknown, input: InteractiveWorkerKeyInput) => string)\n readonly cwd?: string\n readonly cols?: number\n readonly rows?: number\n /** Runtime tag written into tree snapshots. Defaults to the provider name. */\n readonly runtime?: Runtime\n /** Poll delay used while waiting for the provider's native process to exit. */\n readonly pollIntervalMs?: number\n /** Destroy the provider environment after the process is terminal. Defaults to true. */\n readonly destroyEnvironmentOnTeardown?: boolean\n}\n\n/** Stable input available to key and holder functions. */\nexport interface InteractiveWorkerKeyInput {\n readonly provider: string\n readonly profile: AgentProfile\n readonly context?: WorkerSpawnContext\n readonly task?: unknown\n readonly nodeId?: string\n}\n\n/**\n * Build a `MakeWorkerAgent` that starts one provider-owned native TUI per worker. A Scope supplies\n * the durable admission hook and node attempt; the worker exposes `interactiveReady`, so the exact\n * provider reference is written before another process can attach, and `attachWorker` reconnects\n * it through the provider's public `get`/interactive contract.\n */\nexport function workerFromInteractiveProvider(\n provider: AgentEnvironmentProvider,\n options: InteractiveWorkerOptions = {},\n): MakeWorkerAgent {\n if (!provider.name.trim())\n throw new Error('workerFromInteractiveProvider: provider.name required')\n if (!provider.get) {\n throw new Error(\n `workerFromInteractiveProvider(${provider.name}): provider.get is required for reconnect`,\n )\n }\n const capturedEnvironment = options.environment\n ? (structuredClone(options.environment) as InteractiveWorkerEnvironment)\n : undefined\n const unscopedNamespace = randomUUID()\n let unscopedOrdinal = 0\n const runtime = options.runtime ?? (provider.name as Runtime)\n\n return (rawProfile, spawnContext) => {\n const profile = executableAgentProfileSnapshot(\n rawProfile,\n `workerFromInteractiveProvider(${provider.name})`,\n )\n const input: InteractiveWorkerKeyInput = {\n provider: provider.name,\n profile,\n ...(spawnContext === undefined ? {} : { context: spawnContext }),\n }\n const assignmentId =\n spawnContext?.assignmentId ?? `unscoped:${unscopedNamespace}:${unscopedOrdinal++}`\n const baseInput = { ...input, nodeId: spawnContext?.parentNodeId }\n const environmentKey = stableKey(\n options.environmentIdempotencyKey?.({ ...baseInput }) ??\n derivedKey('supervised-interactive-environment', {\n provider: provider.name,\n assignmentId,\n parentNodeId: spawnContext?.parentNodeId,\n profile,\n }),\n 'environment idempotency key',\n )\n const name = profile.name ?? 'interactive-worker'\n\n const executorFactory = (\n spec: AgentSpec,\n ctx: ExecutorContext,\n ): Executor<InteractiveWorkerResult> =>\n interactiveExecutor({\n provider,\n profile: spec.profile,\n context: spawnContext,\n environment: capturedEnvironment,\n environmentKey,\n interactiveKey: (task: unknown) =>\n stableKey(\n options.interactiveIdempotencyKey?.({\n ...baseInput,\n task,\n }) ??\n derivedKey('supervised-interactive-session', {\n provider: provider.name,\n assignmentId,\n parentNodeId: spawnContext?.parentNodeId,\n profile: spec.profile,\n task,\n }),\n 'interactive idempotency key',\n ),\n holderId: (task: unknown) => {\n const selected =\n typeof options.holderId === 'function'\n ? options.holderId({ ...baseInput, task })\n : options.holderId\n return stableKey(\n selected ??\n `runtime-interactive-worker:${canonicalCandidateDigest({\n provider: provider.name,\n assignmentId,\n })}`,\n 'interactive holder id',\n )\n },\n initialPrompt: options.initialPrompt,\n cwd: options.cwd,\n cols: options.cols,\n rows: options.rows,\n runtime,\n pollIntervalMs: options.pollIntervalMs,\n destroyEnvironmentOnTeardown: options.destroyEnvironmentOnTeardown,\n executionAttemptId: ctx.node?.attemptId,\n nodeId: ctx.node?.nodeId,\n admission: admissionWriter(ctx, provider.name, ctx.node?.nodeId),\n })\n\n const spec: AgentSpec = {\n profile,\n harness: null,\n executorFactory,\n ...(spawnContext?.execution ? { execution: spawnContext.execution } : {}),\n }\n return {\n name,\n act: async () => {\n throw new Error(\n 'workerFromInteractiveProvider: interactive workers execute through executorSpec',\n )\n },\n executorSpec: spec,\n } as Agent<unknown, InteractiveWorkerResult> & { executorSpec: AgentSpec }\n }\n}\n\nfunction admissionWriter(\n ctx: ExecutorContext,\n provider: string,\n workerId: string | undefined,\n): InteractiveAdmissionWriter {\n const candidate = ctx.seams[interactiveAdmissionSeamKey]\n if (typeof candidate === 'function') {\n return async (admission) => {\n await (candidate as (value: RetainedInteractiveAdmission) => Promise<void>)(admission)\n }\n }\n // In-memory runs still need a real hook because retained-start refuses an omitted hook. The\n // durable Scope path always supplies the Runtime-owned writer above; this fallback is explicit\n // and process-local, never mistaken for restart evidence.\n const records = new Map<string, RetainedInteractiveAdmission>()\n return async (admission) => {\n const prior = records.get(admission.phase)\n if (prior && canonicalCandidateDigest(prior) !== canonicalCandidateDigest(admission)) {\n throw new Error(\n `worker ${workerId ?? '(unscoped)'} provider ${provider} admission changed in memory`,\n )\n }\n records.set(admission.phase, detachedSnapshot(admission, 'interactive admission'))\n }\n}\n\nfunction derivedKey(kind: string, value: unknown): string {\n return `${kind}-${canonicalCandidateDigest(value).slice('sha256:'.length)}`\n}\n\nfunction stableKey(value: string, label: string): string {\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new Error(`${label} must be a non-empty string`)\n }\n const key = value.trim()\n if (key.length > 256) throw new Error(`${label} must not exceed 256 bytes`)\n return key\n}\n","/**\n * Public one-call composition for a durable Runtime supervisor proof run.\n *\n * This is intentionally a thin owner of existing Runtime primitives. The supervisor owns the\n * root abort channel and join barrier, Scope owns worker admission and lifecycle, and the provider\n * owns the environment and interactive process. External clients receive identifiers and opaque\n * handles; they do not receive a second supervisor protocol or a copy of provider state.\n *\n * @experimental\n */\n\nimport { randomUUID } from 'node:crypto'\nimport { mkdirSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { dirname, join, resolve } from 'node:path'\nimport {\n type AgentProfile,\n agentProfileSchema,\n canonicalAgentProfileDigest,\n canonicalCandidateDigest,\n} from '@tangle-network/agent-interface'\nimport type {\n AgentEnvironmentCapabilities,\n AgentEnvironmentProvider,\n} from '@tangle-network/agent-interface/environment-provider'\nimport type { McpToolDescriptor } from '../../mcp/server'\nimport { createCoordinationTools } from '../../mcp/tools/coordination-manager'\nimport { sleep } from '../util'\nimport { armDeadlineTimer } from './deadline'\nimport { createCancelAcknowledger, createSteerAcknowledger } from './driver-control-acknowledgers'\nimport { writeAtomicDurableFile } from './durable-file'\nimport {\n type InteractiveWorkerEnvironment,\n workerFromInteractiveProvider,\n} from './interactive-worker'\nimport { createFileRunContext } from './run-context'\nimport { supervisorRunDir } from './run-layout'\nimport { createRootHandle, createSupervisor } from './supervisor'\nimport type { Agent, Budget, Scope, SpawnEvent, SupervisedResult } from './types'\nimport { readWorkerInteractiveBinding } from './worker-interactive'\n\nconst DEFAULT_POLL_MS = 25\nconst ROOT_MAX_ITERATIONS = 100\nconst ROOT_MAX_TOKENS = 100_000\nconst WORKER_MAX_ITERATIONS = 25\nconst WORKER_MAX_TOKENS = 25_000\n\n/** Caller-supplied environment provider for one supervisor run. */\nexport interface ProvisionSupervisorConnection {\n /** A constructed provider that owns exact-profile admission and environment reconnection. */\n readonly provider: AgentEnvironmentProvider\n}\n\n/** Input to the public Runtime supervisor provisioner. */\nexport interface ProvisionSupervisorRequest {\n readonly invocationId: string\n /** Caller-owned task assigned to the first interactive worker. */\n readonly task: string\n /** Canonical profile assigned to the first interactive worker. */\n readonly profile: AgentProfile\n /** Generic provider create fields forwarded to the interactive worker. */\n readonly workerEnvironment?: InteractiveWorkerEnvironment\n /** Root directory for Runtime-owned `.agent/supervisor` state. */\n readonly workspaceDir?: string\n /** Maximum wall-clock time for the complete supervisor lifecycle, including cleanup. Omit for no lifecycle deadline. */\n readonly timeoutMs?: number\n /** Poll cadence for lifecycle/control readiness. */\n readonly pollMs?: number\n /** Constructed provider for one execution connection. */\n readonly connection: ProvisionSupervisorConnection\n}\n\n/** Exact owner-scoped cleanup receipt returned after Runtime releases the run resources. */\nexport interface SupervisorCleanupReceipt {\n readonly status: 'completed'\n readonly rootDir: string\n readonly supervisorId: string\n readonly workerId: string\n readonly supervisorStatus: string\n readonly workerStatus: 'running' | 'done' | 'down' | 'cancelled'\n readonly resourcesReleased: true\n readonly remainingResources: readonly []\n}\n\n/** Handles for one Runtime-owned supervisor and its first interactive worker. */\nexport interface ProvisionedSupervisor {\n readonly rootDir: string\n readonly supervisorId: string\n readonly workerId: string\n /** Provider source for `attachWorker`; omitted only when resolution did not produce one. */\n readonly providers?: AgentEnvironmentProvider\n /** Capability-derived terminal takeover requirement. */\n readonly terminalTakeover: 'required' | 'unsupported' | 'unspecified'\n cleanup(): Promise<SupervisorCleanupReceipt>\n}\n\nclass SupervisorProvisionUnavailableError extends Error {\n readonly unavailable = true as const\n\n constructor(message: string, cause?: unknown) {\n super(message, cause === undefined ? undefined : { cause })\n this.name = 'SupervisorProvisionUnavailableError'\n }\n}\n\ninterface MutableState {\n readonly id: string\n status: string\n readonly task: string\n readonly workspaceDir: string\n readonly budget: number\n readonly workerModel?: string\n readonly startedAt: string\n completedAt?: string\n}\n\ninterface Deferred<T> {\n readonly promise: Promise<T>\n resolve(value: T): void\n reject(error: unknown): void\n readonly settled: () => boolean\n}\n\n/**\n * Provision one real provider-backed worker and keep its owning manager alive for controls.\n *\n * The root manager does not use a model. It runs the same coordination tools used by a driver in a\n * small deterministic loop, so durable steer and cancel requests are acknowledged by the owning\n * Runtime turn loop and never by a test-only shortcut. The caller owns profile, task, and provider\n * connection selection; Runtime does not infer them from process environment variables.\n */\nexport async function provisionSupervisor(\n request: ProvisionSupervisorRequest,\n): Promise<ProvisionedSupervisor> {\n const input = normalizeRequest(request)\n const provider = resolveProvider(input)\n const capabilities = await readCapabilities(provider)\n const terminalTakeover = terminalCapability(capabilities)\n const profile = input.profile\n const rootDir = resolve(input.workspaceDir ?? makeWorkspaceDir())\n mkdirSync(rootDir, { recursive: true })\n const supervisorId = supervisorIdFor(input.invocationId)\n const eventDir = supervisorRunDir(rootDir, supervisorId)\n const statePath = join(eventDir, 'state.json')\n mkdirSync(dirname(eventDir), { recursive: true })\n try {\n // The run directory is the cross-process invocation lock. A non-recursive mkdir closes the\n // duplicate-start race before any journal or provider resource is created.\n mkdirSync(eventDir)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'EEXIST') {\n throw unavailable(\n `Runtime supervisor '${supervisorId}' already exists at '${eventDir}'; use a new invocationId`,\n )\n }\n throw error\n }\n\n const context = createFileRunContext(eventDir)\n const startedAtMs = Date.now()\n const state: MutableState = {\n id: supervisorId,\n status: 'running',\n task: input.task,\n workspaceDir: rootDir,\n budget: ROOT_MAX_TOKENS,\n ...(profile.model?.default === undefined ? {} : { workerModel: profile.model.default }),\n startedAt: new Date(startedAtMs).toISOString(),\n }\n writeState(statePath, state)\n\n const rootHandle = createRootHandle<unknown>()\n const supervisor = createSupervisor<unknown, unknown>()\n supervisor.attach(rootHandle)\n const workerSpawned = deferred<string>()\n const workerRunning = deferred<void>()\n const workerProfile = profile\n const workerEnvironment = {\n ...(input.workerEnvironment ?? {}),\n metadata: {\n ...(input.workerEnvironment?.metadata ?? {}),\n runtime: 'agent-runtime',\n invocationId: input.invocationId,\n },\n name: input.workerEnvironment?.name ?? `runtime-${supervisorId}`,\n }\n const makeWorkerAgent = workerFromInteractiveProvider(provider, {\n environment: workerEnvironment,\n pollIntervalMs: input.pollMs,\n destroyEnvironmentOnTeardown: true,\n })\n\n const rootAgent: Agent<unknown, unknown> = {\n name: 'runtime-supervisor-root',\n async act(_task: unknown, scope: Scope<unknown>): Promise<unknown> {\n const coord = createCoordinationTools({\n scope,\n blobs: context.blobs,\n makeWorkerAgent,\n perWorker: workerBudget(),\n })\n await coord.ready()\n const spawn = findTool(coord.tools, 'spawn_worker')\n const result = await spawn.handler({\n profile: workerProfile,\n task: input.task,\n label: 'interactive-worker',\n })\n const childId = workerIdFromSpawn(result)\n workerSpawned.resolve(childId)\n\n for (;;) {\n const child = scope.view.nodes.find((node) => node.id === childId)\n if (child?.status === 'running') break\n if (\n child === undefined ||\n child.status === 'done' ||\n child.status === 'failed' ||\n child.status === 'cancelled'\n ) {\n throw new Error(`Runtime supervisor worker '${childId}' ended before becoming live`)\n }\n await delay(input.pollMs)\n }\n workerRunning.resolve()\n\n const steerAcknowledger = createSteerAcknowledger({\n dir: eventDir,\n coord,\n now: Date.now,\n ownerId: scope.view.root,\n })\n const cancelAcknowledger = createCancelAcknowledger({\n dir: eventDir,\n coord,\n scope,\n now: Date.now,\n ownerId: scope.view.root,\n controlScope: 'run',\n })\n try {\n while (true) {\n await steerAcknowledger.pass('turn')\n cancelAcknowledger.pass('turn')\n // The wake owns the single scope cursor drain. Calling `scope.next()` directly here\n // would bypass the coordination ledger and make a real cancellation look unknown. Its\n // heartbeat bounds each pass so control requests are observed while the worker runs.\n const wake = await coord.awaitWake({\n attempt: 1,\n signal: scope.signal,\n heartbeatMs: input.pollMs,\n debounceMs: 0,\n })\n if (wake?.events.some((event) => event.type === 'settled')) {\n await steerAcknowledger.pass('final')\n cancelAcknowledger.pass('final')\n return undefined\n }\n if (wake === undefined) {\n throw new Error(`Runtime supervisor worker '${childId}' ended without a settlement`)\n }\n }\n } finally {\n // The final pass closes requests that landed after the last turn. It is idempotent with the\n // normal path and prevents an admitted operation from remaining open after root teardown.\n await steerAcknowledger.pass('final')\n cancelAcknowledger.pass('final')\n cancelAcknowledger.finish()\n }\n },\n }\n const runBudget = rootBudget(input.timeoutMs)\n let runResult: SupervisedResult<unknown> | undefined\n let runError: unknown\n let runSettled = false\n const runPromise = supervisor\n .run(rootAgent, input.task, {\n budget: runBudget,\n rootIdentity: {\n profileDigest: canonicalAgentProfileDigest(profile),\n taskDigest: canonicalCandidateDigest(input.task),\n },\n runId: supervisorId,\n ...context,\n interactiveBindingDir: eventDir,\n maxDepth: 1,\n workerSlots: 1,\n })\n .then(\n (result) => {\n runResult = result\n runSettled = true\n updateStateFromResult(state, result)\n writeState(statePath, state)\n return result\n },\n (error) => {\n runError = error\n runSettled = true\n state.status = 'down'\n state.completedAt = new Date().toISOString()\n writeState(statePath, state)\n throw error\n },\n )\n void runPromise.catch(() => undefined)\n\n let workerId: string\n try {\n workerId = await waitForWorkerSpawn(workerSpawned.promise, runPromise, input.timeoutMs)\n await waitForWorkerRunning(workerRunning.promise, runPromise, input.timeoutMs)\n if (terminalTakeover === 'required') {\n await waitForInteractiveBinding(eventDir, workerId, runPromise, input.timeoutMs, input.pollMs)\n }\n } catch (error) {\n if (!runSettled) {\n try {\n rootHandle.abort('supervisor provisioning failed')\n } catch {\n // The supervisor may have released the handle between the state read and this abort.\n }\n }\n await runPromise.catch(() => undefined)\n throw error\n }\n\n let cleanupPromise: Promise<SupervisorCleanupReceipt> | undefined\n const cleanup = async (): Promise<SupervisorCleanupReceipt> => {\n cleanupPromise ??= (async () => {\n if (!runSettled) {\n try {\n rootHandle.abort('supervisor cleanup')\n } catch {\n // A concurrent run completion already released the handle.\n }\n }\n const result = await runPromise.catch((error) => {\n runError = error\n return undefined\n })\n if (result !== undefined) runResult = result\n if (runError !== undefined) throw runError\n const finalEvents = await waitForWorkerTerminal(\n context.journal,\n supervisorId,\n workerId,\n input.timeoutMs,\n input.pollMs,\n )\n const workerStatus = workerStatusFromEvents(finalEvents, workerId)\n if (workerStatus === 'running') {\n throw new Error(`Runtime supervisor worker '${workerId}' did not reach a terminal state`)\n }\n if (runResult?.teardownUnconfirmed?.length) {\n const environments = runResult.teardownUnconfirmed.flatMap((node) =>\n (node.environments ?? []).map(\n (environment) => `${environment.provider}:${environment.environmentId}`,\n ),\n )\n throw new Error(\n `Runtime supervisor cleanup could not confirm ${runResult.teardownUnconfirmed.length} resource(s) released${\n environments.length > 0 ? `; environments still held: ${environments.join(', ')}` : ''\n }`,\n )\n }\n const supervisorStatus = state.status\n state.completedAt ??= new Date().toISOString()\n writeState(statePath, state)\n return Object.freeze({\n status: 'completed' as const,\n rootDir,\n supervisorId,\n workerId,\n supervisorStatus,\n workerStatus,\n resourcesReleased: true as const,\n remainingResources: Object.freeze([]) as readonly [],\n })\n })()\n return cleanupPromise\n }\n\n return Object.freeze({\n rootDir,\n supervisorId,\n workerId,\n providers: provider,\n terminalTakeover,\n cleanup,\n })\n}\n\nfunction normalizeRequest(request: ProvisionSupervisorRequest): ProvisionSupervisorRequest & {\n readonly invocationId: string\n readonly task: string\n readonly timeoutMs: number | undefined\n readonly pollMs: number\n readonly profile: AgentProfile\n readonly connection: ProvisionSupervisorConnection\n} {\n const invocationId = request.invocationId.trim()\n if (!invocationId) throw new SupervisorProvisionUnavailableError('invocationId is required')\n const task = request.task.trim()\n if (!task) throw new SupervisorProvisionUnavailableError('task is required')\n const profile = resolveProfile(request.profile)\n if (request.connection === undefined) {\n throw new SupervisorProvisionUnavailableError('provider connection is required')\n }\n const timeoutMs =\n request.timeoutMs === undefined ? undefined : positiveNumber(request.timeoutMs, 'timeoutMs')\n const pollMs = positiveNumber(request.pollMs ?? DEFAULT_POLL_MS, 'pollMs')\n return { ...request, invocationId, task, timeoutMs, pollMs, profile }\n}\n\nfunction positiveNumber(value: number, name: string): number {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new SupervisorProvisionUnavailableError(`${name} must be a positive safe integer`)\n }\n return value\n}\n\nfunction makeWorkspaceDir(): string {\n return join(tmpdir(), `agent-runtime-supervisor-${randomUUID()}`)\n}\n\nfunction supervisorIdFor(invocationId: string): string {\n const digest = canonicalCandidateDigest({ kind: 'runtime-supervisor', invocationId })\n return `runtime-supervisor-${digest.slice('sha256:'.length)}`\n}\n\n/** A caller-supplied deadline covers the complete supervisor lifecycle from run start through cleanup. */\nfunction rootBudget(timeoutMs: number | undefined): Budget {\n return {\n maxIterations: ROOT_MAX_ITERATIONS,\n maxTokens: ROOT_MAX_TOKENS,\n ...(timeoutMs === undefined ? {} : { deadlineMs: timeoutMs }),\n }\n}\n\nfunction workerBudget(): Budget {\n return {\n maxIterations: WORKER_MAX_ITERATIONS,\n maxTokens: WORKER_MAX_TOKENS,\n }\n}\n\nfunction resolveProfile(profile: AgentProfile): AgentProfile {\n const parsed = agentProfileSchema.safeParse(profile)\n if (!parsed.success) {\n throw unavailable(\n `Runtime supervisor profile is invalid: ${parsed.error.issues\n .map((issue) => `${issue.path.join('.')}: ${issue.message}`)\n .join('; ')}`,\n )\n }\n return parsed.data\n}\n\nfunction resolveProvider(request: ProvisionSupervisorRequest): AgentEnvironmentProvider {\n const provider = request.connection?.provider\n if (provider === undefined) {\n throw unavailable('Runtime supervisor requires connection.provider')\n }\n return requireReconnectProvider(provider)\n}\n\nfunction requireReconnectProvider(provider: AgentEnvironmentProvider): AgentEnvironmentProvider {\n if (!provider.name.trim()) throw unavailable('Runtime supervisor provider has no name')\n if (typeof provider.get !== 'function') {\n throw unavailable(\n `Runtime supervisor provider '${provider.name}' cannot reconnect environments`,\n )\n }\n return provider\n}\n\nasync function readCapabilities(\n provider: AgentEnvironmentProvider,\n): Promise<AgentEnvironmentCapabilities> {\n try {\n return await provider.capabilities()\n } catch (error) {\n throw unavailable(`Runtime supervisor could not read '${provider.name}' capabilities`, error)\n }\n}\n\nfunction terminalCapability(\n capabilities: AgentEnvironmentCapabilities,\n): 'required' | 'unsupported' | 'unspecified' {\n const interactive = capabilities.interactiveAgent\n if (interactive === undefined) return 'unsupported'\n const complete = [\n interactive.start,\n interactive.control,\n interactive.status,\n interactive.attach,\n interactive.reattach,\n interactive.sendPrompt,\n interactive.input,\n interactive.resize,\n interactive.stop,\n ].every((value) => value === true)\n return complete ? 'required' : 'unsupported'\n}\n\nfunction findTool(tools: readonly McpToolDescriptor[], name: string): McpToolDescriptor {\n const tool = tools.find((candidate) => candidate.name === name)\n if (tool === undefined)\n throw new Error(`Runtime supervisor coordination tool '${name}' is missing`)\n return tool\n}\n\nfunction workerIdFromSpawn(value: unknown): string {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error('Runtime supervisor spawn did not return a worker id')\n }\n const workerId = (value as { workerId?: unknown }).workerId\n if (typeof workerId !== 'string' || !workerId.trim()) {\n throw new Error('Runtime supervisor spawn did not return a worker id')\n }\n return workerId\n}\n\nasync function waitForWorkerSpawn(\n worker: Promise<string>,\n run: Promise<SupervisedResult<unknown>>,\n timeoutMs: number | undefined,\n): Promise<string> {\n return await withTimeout(\n Promise.race([\n worker,\n run.then(() => {\n throw new Error('Runtime supervisor ended before it spawned a worker')\n }),\n ]),\n timeoutMs,\n 'worker spawn',\n )\n}\n\nasync function waitForWorkerRunning(\n running: Promise<void>,\n run: Promise<SupervisedResult<unknown>>,\n timeoutMs: number | undefined,\n): Promise<void> {\n await withTimeout(\n Promise.race([\n running,\n run.then(() => {\n throw new Error('Runtime supervisor ended before the worker became live')\n }),\n ]),\n timeoutMs,\n 'worker readiness',\n )\n}\n\nasync function waitForInteractiveBinding(\n eventDir: string,\n workerId: string,\n run: Promise<SupervisedResult<unknown>>,\n timeoutMs: number | undefined,\n pollMs: number,\n): Promise<void> {\n await withTimeout(\n pollUntil(\n async () => {\n const binding = readWorkerInteractiveBinding(eventDir, workerId)\n if (binding?.status === 'available') return true\n if (binding?.status === 'unavailable') {\n throw unavailable(`Runtime worker '${workerId}' could not publish an interactive binding`)\n }\n return false\n },\n run,\n pollMs,\n ),\n timeoutMs,\n 'interactive terminal binding',\n )\n}\n\nasync function pollUntil(\n read: () => Promise<boolean> | boolean,\n run: Promise<SupervisedResult<unknown>>,\n pollMs: number,\n): Promise<void> {\n for (;;) {\n if (await read()) return\n await Promise.race([\n delay(pollMs),\n run.then(() => {\n throw new Error('Runtime supervisor ended before readiness was observed')\n }),\n ])\n }\n}\n\nasync function withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number | undefined,\n label: string,\n): Promise<T> {\n if (timeoutMs === undefined) return await promise\n let clearTimer: (() => void) | undefined\n const timeout = new Promise<never>((_resolve, reject) => {\n clearTimer = armDeadlineTimer(timeoutMs, () =>\n reject(unavailable(`Runtime supervisor timed out waiting for ${label}`)),\n )\n })\n try {\n return await Promise.race([promise, timeout])\n } finally {\n clearTimer?.()\n }\n}\n\nfunction delay(ms: number, keepAlive = false): Promise<void> {\n return sleep(ms, undefined, keepAlive)\n}\n\nfunction updateStateFromResult(state: MutableState, result: SupervisedResult<unknown>): void {\n state.status =\n result.kind === 'winner' ? 'done' : result.reason === 'cancelled' ? 'cancelled' : 'down'\n state.completedAt = new Date().toISOString()\n}\n\nfunction workerStatusFromEvents(\n events: readonly SpawnEvent[],\n workerId: string,\n): SupervisorCleanupReceipt['workerStatus'] {\n let status: SupervisorCleanupReceipt['workerStatus'] = 'running'\n let terminal = false\n for (const event of events) {\n if (event.id !== workerId) continue\n if (terminal) continue\n if (event.kind === 'spawned' || event.kind === 'progress') status = 'running'\n else if (event.kind === 'settled') {\n status = event.status === 'done' ? 'done' : 'down'\n terminal = true\n } else if (event.kind === 'cancelled') {\n status = 'cancelled'\n terminal = true\n }\n }\n return status\n}\n\nasync function waitForWorkerTerminal(\n journal: import('./types').SpawnJournal,\n root: string,\n workerId: string,\n timeoutMs: number | undefined,\n pollMs: number,\n): Promise<SpawnEvent[]> {\n const deadline = timeoutMs === undefined ? undefined : Date.now() + timeoutMs\n for (;;) {\n const events = await journal.loadTree(root)\n if (events !== undefined && workerStatusFromEvents(events, workerId) !== 'running') {\n return events\n }\n if (deadline !== undefined && Date.now() >= deadline) {\n throw unavailable(`Runtime supervisor timed out waiting for worker '${workerId}' to settle`)\n }\n // Cleanup is an explicit lifecycle operation. Keep this bounded poll referenced so a caller\n // awaiting cleanup cannot have Node exit while the provider is still committing the terminal\n // worker event.\n await delay(pollMs, true)\n }\n}\n\nfunction deferred<T>(): Deferred<T> {\n let done = false\n let resolveValue!: (value: T) => void\n let rejectValue!: (error: unknown) => void\n const promise = new Promise<T>((resolvePromise, rejectPromise) => {\n resolveValue = (value) => {\n if (done) return\n done = true\n resolvePromise(value)\n }\n rejectValue = (error) => {\n if (done) return\n done = true\n rejectPromise(error)\n }\n })\n return {\n promise,\n resolve: resolveValue,\n reject: rejectValue,\n settled: () => done,\n }\n}\n\nfunction unavailable(message: string, cause?: unknown): SupervisorProvisionUnavailableError {\n return new SupervisorProvisionUnavailableError(message, cause)\n}\n\nfunction writeState(path: string, state: MutableState): void {\n mkdirSync(dirname(path), { recursive: true })\n writeAtomicDurableFile(path, `${JSON.stringify(state)}\\n`, { mode: 0o600 })\n}\n"],"mappings":";;;;;;;;;;;;;;AAaA,MAAM,2BAA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1,5 +1,5 @@
|
|
|
1
1
|
import { H as spawnJournalRecordEvents } from "./scope-DSm2RW5I.js";
|
|
2
|
-
import { s as readRunParking } from "./supervisor-
|
|
2
|
+
import { s as readRunParking } from "./supervisor-Buv6rd8h.js";
|
|
3
3
|
import { a as readCommittedJsonLines, t as isNoEntError } from "./jsonl-file-BeUa5EDx.js";
|
|
4
4
|
import { a as writeAtomicDurableFile, c as mutateRunClaim, l as runGenerationPath, r as publishExclusiveDurableFile, u as runWithWriteClaim } from "./durable-file-DstVeHcj.js";
|
|
5
5
|
import { r as readRunCancelRequest } from "./run-cancellation-ZmRSYLu5.js";
|
|
@@ -348,4 +348,4 @@ async function readRunState(runDir) {
|
|
|
348
348
|
}
|
|
349
349
|
export { readRunDirectoryLock as a, acquireRunDirectoryLock as i, readSpawnJournal as n, runDirectoryHolderIsLive as o, RunDirectoryLockedError as r, readRunState as t };
|
|
350
350
|
|
|
351
|
-
//# sourceMappingURL=run-state-
|
|
351
|
+
//# sourceMappingURL=run-state-D4R8gEFv.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-state-Dt-v0Fr8.js","names":["delay"],"sources":["../src/durable/run-lock.ts","../src/durable/spawn-journal/read.ts","../src/durable/run-state.ts"],"sourcesContent":["import {\n closeSync,\n existsSync,\n fstatSync,\n mkdirSync,\n openSync,\n readFileSync,\n unlinkSync,\n} from 'node:fs'\nimport { resolve } from 'node:path'\nimport { setTimeout as delay } from 'node:timers/promises'\nimport {\n type LockHolderRecord,\n type LockIdentity,\n lockHolderVerdict,\n lockIdentity,\n parseLockHolderRecord,\n readLockHolderIdentity,\n} from '@tangle-network/agent-eval/lock-holder'\nimport {\n publishExclusiveDurableFile,\n writeAtomicDurableFile,\n} from '../runtime/supervise/durable-file'\nimport { isNoEntError } from './jsonl-file'\nimport { mutateRunClaim, runGenerationPath, runWithWriteClaim } from './run-fence'\n\n/*\n * Exclusive ownership of one durable run directory for the life of one `supervisePursuit` call.\n *\n * Measured motive (discovery-lab recursive smoke r1): the recovery protocol is\n * `SIGKILL` the runner while a child is live, then resume on the same directory. PID 1527 was\n * killed at 06:20:27Z and PID 2058 resumed at 06:24:59Z. Nothing refused a second process while\n * the first was still alive; two processes on one directory both append to `spawn-journal.jsonl`\n * and `observer.jsonl`, and the recorded assignment keys and settlements stop being one sequence.\n * The operator relied on timing. This lock makes the second process refuse and name the holder.\n *\n * The holder is identified by its pid and the OS's start token for that pid. r1 ran in a\n * container whose pids are small (1527, 2058) and restart from 1, so a pid alone names the wrong\n * process after enough spawns: a lock left by a killed run would then match an unrelated live\n * process and hold the directory until an operator removed the file. Whether a holder is dead is\n * agent-eval's one dead-owner rule (`@tangle-network/agent-eval/lock-holder`): the record carries\n * the start token, host, boot id, pid namespace and the lock file's own inode identity, and a\n * holder is reclaimed only when those prove it gone or its pid reused. A record that cannot prove\n * that, such as one written before these fields existed, is refused and is removed by hand.\n *\n * The lock is operational state, not evidence: replay, projection, and the settle record ignore\n * it. A holder whose process is gone is reclaimed through Eval's crash-recoverable mutation lock.\n */\n\n/** The lock file `supervisePursuit` holds inside a run directory for the life of one call. */\nexport const RUN_DIRECTORY_LOCK_FILE = 'supervise.lock'\n\n/** What the lock file records about its holder. */\nexport interface RunDirectoryLockHolder {\n readonly pid: number\n /** Monotonic acquisition generation; absent on legacy lock records. */\n readonly generation?: number\n /** ISO instant the holder took the lock. */\n readonly startedAt: string\n readonly runId: string\n /** The OS's start token for `pid` when the host reports one. A holder without one is never proved dead. */\n readonly processStart?: string\n /** Hostname of the holder. Records written before it existed are never proved dead. */\n readonly host?: string\n readonly bootId?: string\n readonly pidNamespace?: string\n /** Inode identity of the lock file this record was written into. */\n readonly lock?: LockIdentity\n}\n\n/** A held lock. `release()` removes the file; it is safe to call more than once. */\nexport interface RunDirectoryLock extends RunDirectoryLockHolder {\n readonly generation: number\n readonly path: string\n /** Bind durable writes to this acquisition, including work queued before release. */\n run<T>(operation: () => T): T\n release(): Promise<void>\n}\n\n/** The directory is held by a live process. `holder` is what that process recorded. */\nexport class RunDirectoryLockedError extends Error {\n readonly path: string\n readonly holder: RunDirectoryLockHolder\n\n constructor(path: string, holder: RunDirectoryLockHolder) {\n super(\n `supervisePursuit: ${path} is held by pid ${holder.pid} (run '${holder.runId}', since ${holder.startedAt}); one process drives a run directory at a time`,\n )\n this.name = 'RunDirectoryLockedError'\n this.path = path\n this.holder = holder\n }\n}\n\n/**\n * Take `runDir/supervise.lock`, or refuse.\n *\n * The file is published with its full content or not at all, so a contender never reads a\n * half-written holder. A lock whose holder is proved dead (its pid no longer exists, the pid now\n * belongs to a process with a different start token, or the host rebooted) is stale and is removed\n * under the mutation guard; a holder that is alive or cannot be proved dead refuses. An empty file\n * names no holder and is reclaimed. A file with unreadable content is left in place and refused:\n * reclaiming it could evict a live holder written by something other than this module.\n */\nexport async function acquireRunDirectoryLock(\n runDir: string,\n runId: string,\n now: () => number = Date.now,\n): Promise<RunDirectoryLock> {\n const dir = resolve(runDir)\n const path = resolve(dir, RUN_DIRECTORY_LOCK_FILE)\n mkdirSync(dir, { recursive: true })\n const { pid, ...identity } = readLockHolderIdentity(process.pid)\n const owner = { pid, startedAt: new Date(now()).toISOString(), runId, ...identity }\n return mutateRunClaim(path, () => {\n const existing = readLockFile(path)\n if (existing.state === 'holder' && !holderIsDead(existing)) {\n throw new RunDirectoryLockedError(path, existing.holder)\n }\n let previousGeneration = 0\n try {\n previousGeneration = Number(readFileSync(runGenerationPath(dir), 'utf8'))\n if (!Number.isSafeInteger(previousGeneration) || previousGeneration < 1) {\n throw new Error('invalid run directory generation counter')\n }\n } catch (error) {\n if (!isNoEntError(error)) throw error\n }\n const generation =\n Math.max(\n previousGeneration,\n existing.state === 'holder' ? (existing.holder.generation ?? 0) : 0,\n ) + 1\n if (!Number.isSafeInteger(generation)) throw new Error('run directory generation exhausted')\n writeAtomicDurableFile(runGenerationPath(dir), `${generation}\\n`)\n if (existing.state !== 'missing') removeIfPresent(path)\n const written: { holder?: RunDirectoryLockHolder } = {}\n // The lock file is a hard link of the temporary file, so the temporary file's inode identity\n // is the lock's, and a later verdict can prove this record was written for this very lock.\n const published = publishExclusiveDurableFile(path, (file) => {\n written.holder = Object.freeze({ ...owner, generation, lock: lockIdentity(file) })\n return `${JSON.stringify(written.holder)}\\n`\n })\n const holder = written.holder\n if (!published || holder === undefined) {\n throw new Error(`supervisePursuit: could not take ${path}`)\n }\n let released = false\n return Object.freeze({\n ...holder,\n generation,\n path,\n run: <T>(operation: () => T): T => {\n if (holder.lock === undefined) throw new Error('run lock has no inode identity')\n return runWithWriteClaim({ path, generation, lock: holder.lock }, operation)\n },\n release: async () => {\n if (released) return\n await releaseHolder(path, holder)\n released = true\n },\n })\n })\n}\n\n/** Read the holder a lock file names, or `undefined` when no lock file names one. */\nexport async function readRunDirectoryLock(\n runDir: string,\n): Promise<RunDirectoryLockHolder | undefined> {\n const existing = await readLockFile(resolve(runDir, RUN_DIRECTORY_LOCK_FILE))\n return existing.state === 'holder' ? existing.holder : undefined\n}\n\n/** What {@link runDirectoryHolderIsLive} proved about a run directory's recorded holder. */\nexport interface RunDirectoryHolderLiveness {\n /** False only when the holder that took the lock is proved dead; a holder that cannot be proved dead reads as live. */\n readonly live: boolean\n /** The holder could not be verified on this host. `live` stays conservative for exclusion. */\n readonly unknown?: true\n /** The holder the lock file names. Absent when no lock file names one, which reads as not live. */\n readonly holder?: RunDirectoryLockHolder\n}\n\n/**\n * Whether a run directory is still held by the live process that took its lock.\n *\n * The same rule `acquireRunDirectoryLock` applies to decide whether a lock is stale, exposed so a\n * caller — a supervisor picking up an abandoned directory, an operator tool listing runs — asks\n * the question instead of hand-rolling `process.kill(pid, 0)`. A bare signal probe cannot tell a\n * live holder from an unrelated process that later took the same pid, which is the failure this\n * lock's start token exists to prevent.\n *\n * The answer is ADVISORY: it is read outside the mutation guard `acquireRunDirectoryLock` holds,\n * so a `false` can be stale by the time the caller acts on it and a concurrent acquire can take\n * the directory in between. Reporting and listing are what this is for. A caller that intends to\n * TAKE the directory calls `acquireRunDirectoryLock`, which evaluates the same rule under the\n * guard and refuses atomically.\n */\nexport async function runDirectoryHolderIsLive(\n runDir: string,\n): Promise<RunDirectoryHolderLiveness> {\n const existing = await readLockFile(resolve(runDir, RUN_DIRECTORY_LOCK_FILE))\n if (existing.state !== 'holder') return { live: false }\n const verdict = lockHolderVerdict(existing.record, existing.current)\n return {\n live: verdict.liveness !== 'dead',\n holder: existing.holder,\n ...(verdict.liveness === 'unknown' ? { unknown: true as const } : {}),\n }\n}\n\ntype LockFileState =\n | { readonly state: 'missing' }\n | { readonly state: 'empty' }\n | {\n readonly state: 'holder'\n readonly holder: RunDirectoryLockHolder\n /** The holder as agent-eval's rule reads it; absent when the record names no host. */\n readonly record: LockHolderRecord | undefined\n /** Inode identity of the file the holder was read from. */\n readonly current: LockIdentity\n }\n\nfunction readLockFile(path: string): LockFileState {\n let text: string\n let current: LockIdentity\n try {\n const file = openSync(path, 'r')\n try {\n current = lockIdentity(fstatSync(file, { bigint: true }))\n text = readFileSync(file, 'utf8')\n } finally {\n closeSync(file)\n }\n } catch (error) {\n if (isNoEntError(error)) return { state: 'missing' }\n throw error\n }\n // This module publishes the file with its full content or not at all, so an empty file was\n // not left by a live holder.\n if (text.trim().length === 0) return { state: 'empty' }\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch (cause) {\n throw new Error(`supervisePursuit: ${path} is not a readable lock file; remove it by hand`, {\n cause,\n })\n }\n const record = parsed as Partial<RunDirectoryLockHolder> | null\n if (\n typeof record !== 'object' ||\n record === null ||\n typeof record.pid !== 'number' ||\n !Number.isInteger(record.pid) ||\n record.pid <= 0 ||\n typeof record.startedAt !== 'string' ||\n typeof record.runId !== 'string' ||\n (record.processStart !== undefined && typeof record.processStart !== 'string') ||\n (record.generation !== undefined &&\n (!Number.isSafeInteger(record.generation) || record.generation < 1))\n ) {\n throw new Error(`supervisePursuit: ${path} is not a readable lock file; remove it by hand`)\n }\n const { pid, startedAt, runId, processStart } = record\n // A missing or malformed identity field is dropped, which leaves the holder never provably dead.\n const verdictRecord = parseLockHolderRecord(parsed)\n const { pid: _pid, ...identity } = verdictRecord ?? { pid }\n return {\n state: 'holder',\n holder: Object.freeze({\n pid,\n startedAt,\n runId,\n ...(record.generation === undefined ? {} : { generation: record.generation }),\n ...(processStart === undefined ? {} : { processStart }),\n ...identity,\n }),\n record: verdictRecord,\n current,\n }\n}\n\n/** agent-eval's dead-owner rule: only a holder proved dead is stale; alive or unknown stays held. */\nfunction holderIsDead(existing: Extract<LockFileState, { state: 'holder' }>): boolean {\n return lockHolderVerdict(existing.record, existing.current).liveness === 'dead'\n}\n\n/** Remove the lock only while it still names this holder; a reclaimed lock belongs to its new owner. */\nasync function releaseHolder(path: string, holder: RunDirectoryLockHolder): Promise<void> {\n const deadline = performance.now() + 1_000\n while (existsSync(`${path}.guard`) && performance.now() < deadline) await delay(10)\n mutateRunClaim(path, () => {\n const existing = readLockFile(path)\n if (existing.state !== 'holder') return\n if (\n existing.holder.pid !== holder.pid ||\n existing.holder.startedAt !== holder.startedAt ||\n existing.holder.runId !== holder.runId ||\n existing.holder.processStart !== holder.processStart ||\n existing.holder.generation !== holder.generation ||\n existing.holder.lock?.dev !== holder.lock?.dev ||\n existing.holder.lock?.ino !== holder.lock?.ino ||\n existing.holder.lock?.birthtimeNs !== holder.lock?.birthtimeNs\n )\n return\n removeIfPresent(path)\n })\n}\n\nfunction removeIfPresent(path: string): void {\n try {\n unlinkSync(path)\n } catch (error) {\n if (!isNoEntError(error)) throw error\n }\n}\n","import { createHash } from 'node:crypto'\nimport type { BigIntStats } from 'node:fs'\nimport { type FileHandle, open, stat } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { isRecord } from '@tangle-network/agent-core'\nimport type { NodeId, SpawnEvent } from '../../runtime/supervise/types'\nimport { isNoEntError, readCommittedJsonLines } from '../jsonl-file'\nimport { spawnJournalRecordEvents } from './record-events'\n\n/** Serializable checkpoint of a committed byte boundary, bound to one file and its bytes. */\nexport interface SpawnJournalCursor {\n readonly file: string\n readonly offset: number\n readonly boundary: string\n}\n\n/** Physical groups expand to event records; the owning tree is preserved for every event. */\nexport type SpawnJournalReadRecord =\n | { readonly kind: 'begin'; readonly root: NodeId; readonly at: string }\n | { readonly kind: 'event'; readonly root: NodeId; readonly event: SpawnEvent }\n\nexport interface SpawnJournalReadOptions {\n readonly after?: SpawnJournalCursor\n /** Initial opening-and-tail window, or an incremental page's byte budget. A crossing record\n * is read whole, so one large record can exceed this budget. Omit for complete history. */\n readonly tailBytes?: number\n}\n\nexport interface SpawnJournalReadResult {\n readonly records: ReadonlyArray<SpawnJournalReadRecord>\n /** Absent only when the journal does not exist. Treat as opaque and persist unchanged. */\n readonly cursor?: SpawnJournalCursor\n /** The supplied cursor no longer matches; this page starts over. */\n readonly reset: boolean\n /** An initial opening-and-tail window omitted records between its two windows. */\n readonly truncated: boolean\n /** Bytes after the committed cursor in this snapshot, including an incomplete final write. */\n readonly remainingBytes: number\n}\n\n/** Read a fixed journal prefix, with historical envelopes and framing owned by Runtime.\n * Missing journals return an empty page. Malformed committed records fail; incomplete final\n * writes remain unread for the next call. Cursors detect replacement, truncation and edits at\n * their sampled opening/boundary; they are not integrity proofs against arbitrary file edits.\n */\nexport async function readSpawnJournal(\n runDir: string,\n options: SpawnJournalReadOptions = {},\n): Promise<SpawnJournalReadResult> {\n const { after, tailBytes } = options\n if (tailBytes !== undefined && (!Number.isSafeInteger(tailBytes) || tailBytes < 1)) {\n throw new RangeError('readSpawnJournal: tailBytes must be a positive safe integer')\n }\n const path = join(runDir, 'spawn-journal.jsonl')\n let handle: FileHandle\n try {\n handle = await open(path, 'r')\n } catch (error) {\n if (isNoEntError(error)) {\n return { records: [], reset: after !== undefined, truncated: false, remainingBytes: 0 }\n }\n throw error\n }\n try {\n const snapshot = await handle.stat({ bigint: true })\n if (!snapshot.isFile()) throw new Error(`${path}: expected a regular file`)\n const size = Number(snapshot.size)\n const file = identity(snapshot)\n const resumed =\n after !== undefined &&\n after.file === file &&\n Number.isSafeInteger(after.offset) &&\n after.offset >= 0 &&\n after.offset <= size &&\n after.boundary === (await boundary(handle, after.offset))\n let offset = resumed ? after.offset : 0\n const records: SpawnJournalReadRecord[] = []\n const read = async (start: number, end: number, firstOnly = false): Promise<void> => {\n offset = start\n for await (const record of readCommittedJsonLines<unknown>(path, {\n handle,\n start,\n end,\n strictUtf8: true,\n onCommit: (committed) => {\n offset = committed\n },\n })) {\n if (!isRecord(record) || typeof record.root !== 'string') {\n throw new Error(`${path}: spawn journal record has no root`)\n }\n if (record.kind === 'begin') {\n if (typeof record.at !== 'string') throw new Error(`${path}: begin record has no at`)\n records.push({ kind: 'begin', root: record.root, at: record.at })\n } else {\n for (const event of spawnJournalRecordEvents(record)) {\n if (\n !isRecord(event) ||\n typeof event.kind !== 'string' ||\n typeof event.id !== 'string'\n ) {\n throw new Error(`${path}: spawn journal record has no event identity`)\n }\n records.push({ kind: 'event', root: record.root, event })\n }\n }\n if (firstOnly) break\n }\n }\n let truncated = false\n if (!resumed && tailBytes !== undefined && size > tailBytes) {\n await read(0, size, true)\n const openingEnd = offset\n const tailStart = await lineBoundary(handle, size - tailBytes, size, -1)\n truncated = tailStart > openingEnd\n await read(Math.max(openingEnd, tailStart), size)\n // A long torn tail must not hide the latest committed activity before it.\n if (offset === tailStart && tailStart > openingEnd) {\n const previous = await lineBoundary(handle, tailStart - 1, size, -1)\n truncated = previous > openingEnd\n await read(Math.max(openingEnd, previous), tailStart)\n }\n } else {\n const end =\n resumed && tailBytes !== undefined && size - offset > tailBytes\n ? await lineBoundary(handle, offset + tailBytes, size, 1)\n : size\n await read(offset, end)\n }\n if (identity(await stat(path, { bigint: true })) !== file || (await handle.stat()).size < size)\n throw new Error(`${path}: journal changed while reading its committed prefix`)\n return {\n records,\n cursor: { file, offset, boundary: await boundary(handle, offset) },\n reset: after !== undefined && !resumed,\n truncated,\n remainingBytes: size - offset,\n }\n } finally {\n await handle.close()\n }\n}\n\nfunction identity(info: BigIntStats): string {\n return `${info.dev}:${info.ino}:${info.birthtimeNs}`\n}\n\nasync function bytes(handle: FileHandle, start: number, length: number): Promise<Buffer> {\n const buffer = Buffer.alloc(length)\n const { bytesRead } = await handle.read(buffer, 0, length, start)\n if (bytesRead !== length) throw new Error('spawn journal changed while reading its boundary')\n return buffer\n}\n\nasync function boundary(handle: FileHandle, offset: number): Promise<string> {\n const length = Math.min(offset, 128)\n return createHash('sha256')\n .update(await bytes(handle, 0, length))\n .update(await bytes(handle, offset - length, length))\n .digest('hex')\n}\n\n/** Include the record crossing a tail window or incremental page boundary. */\nasync function lineBoundary(\n handle: FileHandle,\n position: number,\n size: number,\n direction: -1 | 1,\n): Promise<number> {\n while (position > 0 && position < size) {\n const start = direction === -1 ? Math.max(0, position - 65_536) : position\n const end = direction === -1 ? position : Math.min(size, position + 65_536)\n const part = await bytes(handle, start, end - start)\n const newline = direction === -1 ? part.lastIndexOf(10) : part.indexOf(10)\n if (newline !== -1) return start + newline + 1\n position = direction === -1 ? start : end\n }\n return position\n}\n","import type { RuntimeFailureCause } from '../runtime/failure-cause'\nimport { type RunCancelRequest, readRunCancelRequest } from '../runtime/supervise/run-cancellation'\nimport { readRunParking } from '../runtime/supervise/run-parking'\nimport type { SupervisedResult } from '../runtime/supervise/types'\nimport { runDirectoryHolderIsLive } from './run-lock'\nimport { readFailureRecord, readSettleRecord } from './settle-record'\nimport { readSpawnJournal } from './spawn-journal/read'\n\n/** Runtime evidence only. Product-specific launch, checks and trace completeness belong to callers. */\nexport interface RunState {\n /** Absent when a recorded holder cannot be verified on this host. */\n readonly phase?: 'running' | 'parked' | 'cancelling' | 'settled' | 'down'\n /** A persisted typed root failure; legacy failure messages do not establish a code. */\n readonly failureCode?: RuntimeFailureCause['code']\n readonly settle?: SupervisedResult<unknown>\n readonly cancelRequest?: RunCancelRequest\n /** Absent when holder liveness is unknown. This is advisory, never ownership authorization. */\n readonly holderLive?: boolean\n /** Latest explicit Runtime timestamp observed, as ISO UTC; never a filesystem mtime. */\n readonly lastActivityAt?: string\n}\n\n/** Compose maintained record readers. Terminal settlement outranks cancellation and parking;\n * a request remains cancelling until settlement. An unheld run with evidence is down.\n * No Runtime evidence (including a missing or empty directory) returns undefined. Reads are\n * advisory snapshots across independently published files, not a transaction or a resume gate.\n */\nexport async function readRunState(runDir: string): Promise<RunState | undefined> {\n const [settle, failure, parking, holder, journal] = await Promise.all([\n readSettleRecord(runDir),\n readFailureRecord(runDir),\n readRunParking(runDir),\n runDirectoryHolderIsLive(runDir),\n readSpawnJournal(runDir, { tailBytes: 65_536 }),\n ])\n const cancelRequest = readRunCancelRequest(runDir)\n if (\n !settle &&\n !failure &&\n !parking &&\n !holder.holder &&\n !cancelRequest &&\n journal.records.length === 0\n ) {\n return undefined\n }\n const holderLive = holder.unknown ? undefined : holder.live\n const phase = settle\n ? 'settled'\n : cancelRequest\n ? 'cancelling'\n : parking\n ? 'parked'\n : holderLive === true\n ? 'running'\n : holderLive === false\n ? 'down'\n : undefined\n const root = settle?.tree.nodes?.find((node) => node.id === settle.tree.root)\n const failureCode =\n (settle?.kind === 'no-winner' && settle.reason === 'driver-failed'\n ? settle.error?.failure?.code\n : undefined) ?? root?.failure?.code\n let latest: number | undefined\n const observe = (at: string | number | undefined): void => {\n const timestamp = at === undefined ? undefined : new Date(at).getTime()\n if (timestamp !== undefined && Number.isFinite(timestamp)) {\n latest = latest === undefined ? timestamp : Math.max(latest, timestamp)\n }\n }\n observe(failure?.at)\n observe(parking?.since)\n observe(cancelRequest?.at)\n observe(holder.holder?.startedAt)\n for (const record of journal.records)\n observe(record.kind === 'begin' ? record.at : record.event.at)\n for (const node of settle?.tree.nodes ?? []) {\n observe(node.spawnedAt)\n observe(node.settledAt)\n }\n const lastActivityAt = latest === undefined ? undefined : new Date(latest).toISOString()\n return {\n ...(phase === undefined ? {} : { phase }),\n ...(failureCode === undefined ? {} : { failureCode }),\n ...(settle === undefined ? {} : { settle }),\n ...(cancelRequest === undefined ? {} : { cancelRequest }),\n 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able/spawn-journal/read.ts","../src/durable/run-state.ts"],"sourcesContent":["import {\n closeSync,\n existsSync,\n fstatSync,\n mkdirSync,\n openSync,\n readFileSync,\n unlinkSync,\n} from 'node:fs'\nimport { resolve } from 'node:path'\nimport { setTimeout as delay } from 'node:timers/promises'\nimport {\n type LockHolderRecord,\n type LockIdentity,\n lockHolderVerdict,\n lockIdentity,\n parseLockHolderRecord,\n readLockHolderIdentity,\n} from '@tangle-network/agent-eval/lock-holder'\nimport {\n publishExclusiveDurableFile,\n writeAtomicDurableFile,\n} from '../runtime/supervise/durable-file'\nimport { isNoEntError } from './jsonl-file'\nimport { mutateRunClaim, runGenerationPath, runWithWriteClaim } from './run-fence'\n\n/*\n * Exclusive ownership of one durable run directory for the life of one `supervisePursuit` call.\n *\n * Measured motive (discovery-lab recursive smoke r1): the recovery protocol is\n * `SIGKILL` the runner while a child is live, then resume on the same directory. PID 1527 was\n * killed at 06:20:27Z and PID 2058 resumed at 06:24:59Z. Nothing refused a second process while\n * the first was still alive; two processes on one directory both append to `spawn-journal.jsonl`\n * and `observer.jsonl`, and the recorded assignment keys and settlements stop being one sequence.\n * The operator relied on timing. This lock makes the second process refuse and name the holder.\n *\n * The holder is identified by its pid and the OS's start token for that pid. r1 ran in a\n * container whose pids are small (1527, 2058) and restart from 1, so a pid alone names the wrong\n * process after enough spawns: a lock left by a killed run would then match an unrelated live\n * process and hold the directory until an operator removed the file. Whether a holder is dead is\n * agent-eval's one dead-owner rule (`@tangle-network/agent-eval/lock-holder`): the record carries\n * the start token, host, boot id, pid namespace and the lock file's own inode identity, and a\n * holder is reclaimed only when those prove it gone or its pid reused. A record that cannot prove\n * that, such as one written before these fields existed, is refused and is removed by hand.\n *\n * The lock is operational state, not evidence: replay, projection, and the settle record ignore\n * it. A holder whose process is gone is reclaimed through Eval's crash-recoverable mutation lock.\n */\n\n/** The lock file `supervisePursuit` holds inside a run directory for the life of one call. */\nexport const RUN_DIRECTORY_LOCK_FILE = 'supervise.lock'\n\n/** What the lock file records about its holder. */\nexport interface RunDirectoryLockHolder {\n readonly pid: number\n /** Monotonic acquisition generation; absent on legacy lock records. */\n readonly generation?: number\n /** ISO instant the holder took the lock. */\n readonly startedAt: string\n readonly runId: string\n /** The OS's start token for `pid` when the host reports one. A holder without one is never proved dead. */\n readonly processStart?: string\n /** Hostname of the holder. Records written before it existed are never proved dead. */\n readonly host?: string\n readonly bootId?: string\n readonly pidNamespace?: string\n /** Inode identity of the lock file this record was written into. */\n readonly lock?: LockIdentity\n}\n\n/** A held lock. `release()` removes the file; it is safe to call more than once. */\nexport interface RunDirectoryLock extends RunDirectoryLockHolder {\n readonly generation: number\n readonly path: string\n /** Bind durable writes to this acquisition, including work queued before release. */\n run<T>(operation: () => T): T\n release(): Promise<void>\n}\n\n/** The directory is held by a live process. `holder` is what that process recorded. */\nexport class RunDirectoryLockedError extends Error {\n readonly path: string\n readonly holder: RunDirectoryLockHolder\n\n constructor(path: string, holder: RunDirectoryLockHolder) {\n super(\n `supervisePursuit: ${path} is held by pid ${holder.pid} (run '${holder.runId}', since ${holder.startedAt}); one process drives a run directory at a time`,\n )\n this.name = 'RunDirectoryLockedError'\n this.path = path\n this.holder = holder\n }\n}\n\n/**\n * Take `runDir/supervise.lock`, or refuse.\n *\n * The file is published with its full content or not at all, so a contender never reads a\n * half-written holder. A lock whose holder is proved dead (its pid no longer exists, the pid now\n * belongs to a process with a different start token, or the host rebooted) is stale and is removed\n * under the mutation guard; a holder that is alive or cannot be proved dead refuses. An empty file\n * names no holder and is reclaimed. A file with unreadable content is left in place and refused:\n * reclaiming it could evict a live holder written by something other than this module.\n */\nexport async function acquireRunDirectoryLock(\n runDir: string,\n runId: string,\n now: () => number = Date.now,\n): Promise<RunDirectoryLock> {\n const dir = resolve(runDir)\n const path = resolve(dir, RUN_DIRECTORY_LOCK_FILE)\n mkdirSync(dir, { recursive: true })\n const { pid, ...identity } = readLockHolderIdentity(process.pid)\n const owner = { pid, startedAt: new Date(now()).toISOString(), runId, ...identity }\n return mutateRunClaim(path, () => {\n const existing = readLockFile(path)\n if (existing.state === 'holder' && !holderIsDead(existing)) {\n throw new RunDirectoryLockedError(path, existing.holder)\n }\n let previousGeneration = 0\n try {\n previousGeneration = Number(readFileSync(runGenerationPath(dir), 'utf8'))\n if (!Number.isSafeInteger(previousGeneration) || previousGeneration < 1) {\n throw new Error('invalid run directory generation counter')\n }\n } catch (error) {\n if (!isNoEntError(error)) throw error\n }\n const generation =\n Math.max(\n previousGeneration,\n existing.state === 'holder' ? (existing.holder.generation ?? 0) : 0,\n ) + 1\n if (!Number.isSafeInteger(generation)) throw new Error('run directory generation exhausted')\n writeAtomicDurableFile(runGenerationPath(dir), `${generation}\\n`)\n if (existing.state !== 'missing') removeIfPresent(path)\n const written: { holder?: RunDirectoryLockHolder } = {}\n // The lock file is a hard link of the temporary file, so the temporary file's inode identity\n // is the lock's, and a later verdict can prove this record was written for this very lock.\n const published = publishExclusiveDurableFile(path, (file) => {\n written.holder = Object.freeze({ ...owner, generation, lock: lockIdentity(file) })\n return `${JSON.stringify(written.holder)}\\n`\n })\n const holder = written.holder\n if (!published || holder === undefined) {\n throw new Error(`supervisePursuit: could not take ${path}`)\n }\n let released = false\n return Object.freeze({\n ...holder,\n generation,\n path,\n run: <T>(operation: () => T): T => {\n if (holder.lock === undefined) throw new Error('run lock has no inode identity')\n return runWithWriteClaim({ path, generation, lock: holder.lock }, operation)\n },\n release: async () => {\n if (released) return\n await releaseHolder(path, holder)\n released = true\n },\n })\n })\n}\n\n/** Read the holder a lock file names, or `undefined` when no lock file names one. */\nexport async function readRunDirectoryLock(\n runDir: string,\n): Promise<RunDirectoryLockHolder | undefined> {\n const existing = await readLockFile(resolve(runDir, RUN_DIRECTORY_LOCK_FILE))\n return existing.state === 'holder' ? existing.holder : undefined\n}\n\n/** What {@link runDirectoryHolderIsLive} proved about a run directory's recorded holder. */\nexport interface RunDirectoryHolderLiveness {\n /** False only when the holder that took the lock is proved dead; a holder that cannot be proved dead reads as live. */\n readonly live: boolean\n /** The holder could not be verified on this host. `live` stays conservative for exclusion. */\n readonly unknown?: true\n /** The holder the lock file names. Absent when no lock file names one, which reads as not live. */\n readonly holder?: RunDirectoryLockHolder\n}\n\n/**\n * Whether a run directory is still held by the live process that took its lock.\n *\n * The same rule `acquireRunDirectoryLock` applies to decide whether a lock is stale, exposed so a\n * caller — a supervisor picking up an abandoned directory, an operator tool listing runs — asks\n * the question instead of hand-rolling `process.kill(pid, 0)`. A bare signal probe cannot tell a\n * live holder from an unrelated process that later took the same pid, which is the failure this\n * lock's start token exists to prevent.\n *\n * The answer is ADVISORY: it is read outside the mutation guard `acquireRunDirectoryLock` holds,\n * so a `false` can be stale by the time the caller acts on it and a concurrent acquire can take\n * the directory in between. Reporting and listing are what this is for. A caller that intends to\n * TAKE the directory calls `acquireRunDirectoryLock`, which evaluates the same rule under the\n * guard and refuses atomically.\n */\nexport async function runDirectoryHolderIsLive(\n runDir: string,\n): Promise<RunDirectoryHolderLiveness> {\n const existing = await readLockFile(resolve(runDir, RUN_DIRECTORY_LOCK_FILE))\n if (existing.state !== 'holder') return { live: false }\n const verdict = lockHolderVerdict(existing.record, existing.current)\n return {\n live: verdict.liveness !== 'dead',\n holder: existing.holder,\n ...(verdict.liveness === 'unknown' ? { unknown: true as const } : {}),\n }\n}\n\ntype LockFileState =\n | { readonly state: 'missing' }\n | { readonly state: 'empty' }\n | {\n readonly state: 'holder'\n readonly holder: RunDirectoryLockHolder\n /** The holder as agent-eval's rule reads it; absent when the record names no host. */\n readonly record: LockHolderRecord | undefined\n /** Inode identity of the file the holder was read from. */\n readonly current: LockIdentity\n }\n\nfunction readLockFile(path: string): LockFileState {\n let text: string\n let current: LockIdentity\n try {\n const file = openSync(path, 'r')\n try {\n current = lockIdentity(fstatSync(file, { bigint: true }))\n text = readFileSync(file, 'utf8')\n } finally {\n closeSync(file)\n }\n } catch (error) {\n if (isNoEntError(error)) return { state: 'missing' }\n throw error\n }\n // This module publishes the file with its full content or not at all, so an empty file was\n // not left by a live holder.\n if (text.trim().length === 0) return { state: 'empty' }\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch (cause) {\n throw new Error(`supervisePursuit: ${path} is not a readable lock file; remove it by hand`, {\n cause,\n })\n }\n const record = parsed as Partial<RunDirectoryLockHolder> | null\n if (\n typeof record !== 'object' ||\n record === null ||\n typeof record.pid !== 'number' ||\n !Number.isInteger(record.pid) ||\n record.pid <= 0 ||\n typeof record.startedAt !== 'string' ||\n typeof record.runId !== 'string' ||\n (record.processStart !== undefined && typeof record.processStart !== 'string') ||\n (record.generation !== undefined &&\n (!Number.isSafeInteger(record.generation) || record.generation < 1))\n ) {\n throw new Error(`supervisePursuit: ${path} is not a readable lock file; remove it by hand`)\n }\n const { pid, startedAt, runId, processStart } = record\n // A missing or malformed identity field is dropped, which leaves the holder never provably dead.\n const verdictRecord = parseLockHolderRecord(parsed)\n const { pid: _pid, ...identity } = verdictRecord ?? { pid }\n return {\n state: 'holder',\n holder: Object.freeze({\n pid,\n startedAt,\n runId,\n ...(record.generation === undefined ? {} : { generation: record.generation }),\n ...(processStart === undefined ? {} : { processStart }),\n ...identity,\n }),\n record: verdictRecord,\n current,\n }\n}\n\n/** agent-eval's dead-owner rule: only a holder proved dead is stale; alive or unknown stays held. */\nfunction holderIsDead(existing: Extract<LockFileState, { state: 'holder' }>): boolean {\n return lockHolderVerdict(existing.record, existing.current).liveness === 'dead'\n}\n\n/** Remove the lock only while it still names this holder; a reclaimed lock belongs to its new owner. */\nasync function releaseHolder(path: string, holder: RunDirectoryLockHolder): Promise<void> {\n const deadline = performance.now() + 1_000\n while (existsSync(`${path}.guard`) && performance.now() < deadline) await delay(10)\n mutateRunClaim(path, () => {\n const existing = readLockFile(path)\n if (existing.state !== 'holder') return\n if (\n existing.holder.pid !== holder.pid ||\n existing.holder.startedAt !== holder.startedAt ||\n existing.holder.runId !== holder.runId ||\n existing.holder.processStart !== holder.processStart ||\n existing.holder.generation !== holder.generation ||\n existing.holder.lock?.dev !== holder.lock?.dev ||\n existing.holder.lock?.ino !== holder.lock?.ino ||\n existing.holder.lock?.birthtimeNs !== holder.lock?.birthtimeNs\n )\n return\n removeIfPresent(path)\n })\n}\n\nfunction removeIfPresent(path: string): void {\n try {\n unlinkSync(path)\n } catch (error) {\n if (!isNoEntError(error)) throw error\n }\n}\n","import { createHash } from 'node:crypto'\nimport type { BigIntStats } from 'node:fs'\nimport { type FileHandle, open, stat } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { isRecord } from '@tangle-network/agent-core'\nimport type { NodeId, SpawnEvent } from '../../runtime/supervise/types'\nimport { isNoEntError, readCommittedJsonLines } from '../jsonl-file'\nimport { spawnJournalRecordEvents } from './record-events'\n\n/** Serializable checkpoint of a committed byte boundary, bound to one file and its bytes. */\nexport interface SpawnJournalCursor {\n readonly file: string\n readonly offset: number\n readonly boundary: string\n}\n\n/** Physical groups expand to event records; the owning tree is preserved for every event. */\nexport type SpawnJournalReadRecord =\n | { readonly kind: 'begin'; readonly root: NodeId; readonly at: string }\n | { readonly kind: 'event'; readonly root: NodeId; readonly event: SpawnEvent }\n\nexport interface SpawnJournalReadOptions {\n readonly after?: SpawnJournalCursor\n /** Initial opening-and-tail window, or an incremental page's byte budget. A crossing record\n * is read whole, so one large record can exceed this budget. Omit for complete history. */\n readonly tailBytes?: number\n}\n\nexport interface SpawnJournalReadResult {\n readonly records: ReadonlyArray<SpawnJournalReadRecord>\n /** Absent only when the journal does not exist. Treat as opaque and persist unchanged. */\n readonly cursor?: SpawnJournalCursor\n /** The supplied cursor no longer matches; this page starts over. */\n readonly reset: boolean\n /** An initial opening-and-tail window omitted records between its two windows. */\n readonly truncated: boolean\n /** Bytes after the committed cursor in this snapshot, including an incomplete final write. */\n readonly remainingBytes: number\n}\n\n/** Read a fixed journal prefix, with historical envelopes and framing owned by Runtime.\n * Missing journals return an empty page. Malformed committed records fail; incomplete final\n * writes remain unread for the next call. Cursors detect replacement, truncation and edits at\n * their sampled opening/boundary; they are not integrity proofs against arbitrary file edits.\n */\nexport async function readSpawnJournal(\n runDir: string,\n options: SpawnJournalReadOptions = {},\n): Promise<SpawnJournalReadResult> {\n const { after, tailBytes } = options\n if (tailBytes !== undefined && (!Number.isSafeInteger(tailBytes) || tailBytes < 1)) {\n throw new RangeError('readSpawnJournal: tailBytes must be a positive safe integer')\n }\n const path = join(runDir, 'spawn-journal.jsonl')\n let handle: FileHandle\n try {\n handle = await open(path, 'r')\n } catch (error) {\n if (isNoEntError(error)) {\n return { records: [], reset: after !== undefined, truncated: false, remainingBytes: 0 }\n }\n throw error\n }\n try {\n const snapshot = await handle.stat({ bigint: true })\n if (!snapshot.isFile()) throw new Error(`${path}: expected a regular file`)\n const size = Number(snapshot.size)\n const file = identity(snapshot)\n const resumed =\n after !== undefined &&\n after.file === file &&\n Number.isSafeInteger(after.offset) &&\n after.offset >= 0 &&\n after.offset <= size &&\n after.boundary === (await boundary(handle, after.offset))\n let offset = resumed ? after.offset : 0\n const records: SpawnJournalReadRecord[] = []\n const read = async (start: number, end: number, firstOnly = false): Promise<void> => {\n offset = start\n for await (const record of readCommittedJsonLines<unknown>(path, {\n handle,\n start,\n end,\n strictUtf8: true,\n onCommit: (committed) => {\n offset = committed\n },\n })) {\n if (!isRecord(record) || typeof record.root !== 'string') {\n throw new Error(`${path}: spawn journal record has no root`)\n }\n if (record.kind === 'begin') {\n if (typeof record.at !== 'string') throw new Error(`${path}: begin record has no at`)\n records.push({ kind: 'begin', root: record.root, at: record.at })\n } else {\n for (const event of spawnJournalRecordEvents(record)) {\n if (\n !isRecord(event) ||\n typeof event.kind !== 'string' ||\n typeof event.id !== 'string'\n ) {\n throw new Error(`${path}: spawn journal record has no event identity`)\n }\n records.push({ kind: 'event', root: record.root, event })\n }\n }\n if (firstOnly) break\n }\n }\n let truncated = false\n if (!resumed && tailBytes !== undefined && size > tailBytes) {\n await read(0, size, true)\n const openingEnd = offset\n const tailStart = await lineBoundary(handle, size - tailBytes, size, -1)\n truncated = tailStart > openingEnd\n await read(Math.max(openingEnd, tailStart), size)\n // A long torn tail must not hide the latest committed activity before it.\n if (offset === tailStart && tailStart > openingEnd) {\n const previous = await lineBoundary(handle, tailStart - 1, size, -1)\n truncated = previous > openingEnd\n await read(Math.max(openingEnd, previous), tailStart)\n }\n } else {\n const end =\n resumed && tailBytes !== undefined && size - offset > tailBytes\n ? await lineBoundary(handle, offset + tailBytes, size, 1)\n : size\n await read(offset, end)\n }\n if (identity(await stat(path, { bigint: true })) !== file || (await handle.stat()).size < size)\n throw new Error(`${path}: journal changed while reading its committed prefix`)\n return {\n records,\n cursor: { file, offset, boundary: await boundary(handle, offset) },\n reset: after !== undefined && !resumed,\n truncated,\n remainingBytes: size - offset,\n }\n } finally {\n await handle.close()\n }\n}\n\nfunction identity(info: BigIntStats): string {\n return `${info.dev}:${info.ino}:${info.birthtimeNs}`\n}\n\nasync function bytes(handle: FileHandle, start: number, length: number): Promise<Buffer> {\n const buffer = Buffer.alloc(length)\n const { bytesRead } = await handle.read(buffer, 0, length, start)\n if (bytesRead !== length) throw new Error('spawn journal changed while reading its boundary')\n return buffer\n}\n\nasync function boundary(handle: FileHandle, offset: number): Promise<string> {\n const length = Math.min(offset, 128)\n return createHash('sha256')\n .update(await bytes(handle, 0, length))\n .update(await bytes(handle, offset - length, length))\n .digest('hex')\n}\n\n/** Include the record crossing a tail window or incremental page boundary. */\nasync function lineBoundary(\n handle: FileHandle,\n position: number,\n size: number,\n direction: -1 | 1,\n): Promise<number> {\n while (position > 0 && position < size) {\n const start = direction === -1 ? Math.max(0, position - 65_536) : position\n const end = direction === -1 ? position : Math.min(size, position + 65_536)\n const part = await bytes(handle, start, end - start)\n const newline = direction === -1 ? part.lastIndexOf(10) : part.indexOf(10)\n if (newline !== -1) return start + newline + 1\n position = direction === -1 ? start : end\n }\n return position\n}\n","import type { RuntimeFailureCause } from '../runtime/failure-cause'\nimport { type RunCancelRequest, readRunCancelRequest } from '../runtime/supervise/run-cancellation'\nimport { readRunParking } from '../runtime/supervise/run-parking'\nimport type { SupervisedResult } from '../runtime/supervise/types'\nimport { runDirectoryHolderIsLive } from './run-lock'\nimport { readFailureRecord, readSettleRecord } from './settle-record'\nimport { readSpawnJournal } from './spawn-journal/read'\n\n/** Runtime evidence only. Product-specific launch, checks and trace completeness belong to callers. */\nexport interface RunState {\n /** Absent when a recorded holder cannot be verified on this host. */\n readonly phase?: 'running' | 'parked' | 'cancelling' | 'settled' | 'down'\n /** A persisted typed root failure; legacy failure messages do not establish a code. */\n readonly failureCode?: RuntimeFailureCause['code']\n readonly settle?: SupervisedResult<unknown>\n readonly cancelRequest?: RunCancelRequest\n /** Absent when holder liveness is unknown. This is advisory, never ownership authorization. */\n readonly holderLive?: boolean\n /** Latest explicit Runtime timestamp observed, as ISO UTC; never a filesystem mtime. */\n readonly lastActivityAt?: string\n}\n\n/** Compose maintained record readers. Terminal settlement outranks cancellation and parking;\n * a request remains cancelling until settlement. An unheld run with evidence is down.\n * No Runtime evidence (including a missing or empty directory) returns undefined. Reads are\n * advisory snapshots across independently published files, not a transaction or a resume gate.\n */\nexport async function readRunState(runDir: string): Promise<RunState | undefined> {\n const [settle, failure, parking, holder, journal] = await Promise.all([\n readSettleRecord(runDir),\n readFailureRecord(runDir),\n readRunParking(runDir),\n runDirectoryHolderIsLive(runDir),\n readSpawnJournal(runDir, { tailBytes: 65_536 }),\n ])\n const cancelRequest = readRunCancelRequest(runDir)\n if (\n !settle &&\n !failure &&\n !parking &&\n !holder.holder &&\n !cancelRequest &&\n journal.records.length === 0\n ) {\n return undefined\n }\n const holderLive = holder.unknown ? undefined : holder.live\n const phase = settle\n ? 'settled'\n : cancelRequest\n ? 'cancelling'\n : parking\n ? 'parked'\n : holderLive === true\n ? 'running'\n : holderLive === false\n ? 'down'\n : undefined\n const root = settle?.tree.nodes?.find((node) => node.id === settle.tree.root)\n const failureCode =\n (settle?.kind === 'no-winner' && settle.reason === 'driver-failed'\n ? settle.error?.failure?.code\n : undefined) ?? root?.failure?.code\n let latest: number | undefined\n const observe = (at: string | number | undefined): void => {\n const timestamp = at === undefined ? undefined : new Date(at).getTime()\n if (timestamp !== undefined && Number.isFinite(timestamp)) {\n latest = latest === undefined ? timestamp : Math.max(latest, timestamp)\n }\n }\n observe(failure?.at)\n observe(parking?.since)\n observe(cancelRequest?.at)\n observe(holder.holder?.startedAt)\n for (const record of journal.records)\n observe(record.kind === 'begin' ? record.at : record.event.at)\n for (const node of settle?.tree.nodes ?? []) {\n observe(node.spawnedAt)\n observe(node.settledAt)\n }\n const lastActivityAt = latest === undefined ? undefined : new Date(latest).toISOString()\n return {\n ...(phase === undefined ? {} : { phase }),\n ...(failureCode === undefined ? {} : { failureCode }),\n ...(settle === undefined ? {} : { settle }),\n ...(cancelRequest === undefined ? {} : { cancelRequest }),\n ...(holderLive === undefined ? {} : { holderLive }),\n ...(lastActivityAt === undefined ? {} : { lastActivityAt }),\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAkDA,MAAa,0BAA0B;;AA8BvC,IAAa,0BAAb,cAA6C,MAAM;CACjD;CACA;CAEA,YAAY,MAAc,QAAgC;EACxD,MACE,qBAAqB,KAAK,kBAAkB,OAAO,IAAI,SAAS,OAAO,MAAM,WAAW,OAAO,UAAU,gDAC3G;EACA,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,SAAS;CAChB;AACF;;;;;;;;;;;AAYA,eAAsB,wBACpB,QACA,OACA,MAAoB,KAAK,KACE;CAC3B,MAAM,MAAM,QAAQ,MAAM;CAC1B,MAAM,OAAO,QAAQ,KAAK,uBAAuB;CACjD,UAAU,KAAK,EAAE,WAAW,KAAK,CAAC;CAClC,MAAM,EAAE,KAAK,GAAG,aAAa,uBAAuB,QAAQ,GAAG;CAC/D,MAAM,QAAQ;EAAE;EAAK,WAAW,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,YAAY;EAAG;EAAO,GAAG;CAAS;CAClF,OAAO,eAAe,YAAY;EAChC,MAAM,WAAW,aAAa,IAAI;EAClC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