@tangle-network/agent-runtime 0.240.0 → 0.247.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/dist/{activation-q224yRQK.js → activation-DYqnl8zq.js} +3 -3
  2. package/dist/{activation-q224yRQK.js.map → activation-DYqnl8zq.js.map} +1 -1
  3. package/dist/{activation-CtkpoWet.d.ts → activation-DizpINK3.d.ts} +115 -5
  4. package/dist/agent.d.ts +2 -2
  5. package/dist/agent.js +2 -2
  6. package/dist/candidate-execution/index.js +7 -7
  7. package/dist/candidate-execution/index.js.map +1 -1
  8. package/dist/{coordination-driver-CMprWr0k.js → coordination-driver-BV4AAUns.js} +35 -14
  9. package/dist/coordination-driver-BV4AAUns.js.map +1 -0
  10. package/dist/{delegate-kwBecu_w.js → delegate-DQAzB5Xv.js} +2 -2
  11. package/dist/{delegate-kwBecu_w.js.map → delegate-DQAzB5Xv.js.map} +1 -1
  12. package/dist/{durable-file-D24y9zg7.js → durable-file-DWQA4ooo.js} +2 -2
  13. package/dist/{durable-file-D24y9zg7.js.map → durable-file-DWQA4ooo.js.map} +1 -1
  14. package/dist/durable.d.ts +2 -2
  15. package/dist/durable.js +3 -3
  16. package/dist/{graph-Bke7I2gs.js → graph-DcBmMLIp.js} +3 -3
  17. package/dist/{graph-Bke7I2gs.js.map → graph-DcBmMLIp.js.map} +1 -1
  18. package/dist/{improvement-cycle-BpSVwIJw.js → improvement-cycle-B049YmQ8.js} +458 -60
  19. package/dist/improvement-cycle-B049YmQ8.js.map +1 -0
  20. package/dist/{index-CbZaoYbD.d.ts → index-DLzlXwr6.d.ts} +14 -9
  21. package/dist/index.d.ts +11 -8
  22. package/dist/index.js +27 -17
  23. package/dist/index.js.map +1 -1
  24. package/dist/intelligence.d.ts +7 -5
  25. package/dist/intelligence.js +15 -11
  26. package/dist/intelligence.js.map +1 -1
  27. package/dist/kernel.d.ts +3 -3
  28. package/dist/kernel.js +9 -9
  29. package/dist/{loop-runner-bin-BUkkPt10.d.ts → loop-runner-bin-HbMECmxT.d.ts} +3 -3
  30. package/dist/{loop-runner-bin-DU8XqsGN.js → loop-runner-bin-iqq1azfy.js} +3 -3
  31. package/dist/{loop-runner-bin-DU8XqsGN.js.map → loop-runner-bin-iqq1azfy.js.map} +1 -1
  32. package/dist/loop-runner-bin.d.ts +1 -1
  33. package/dist/loop-runner-bin.js +1 -1
  34. package/dist/mcp/bin.js +3 -3
  35. package/dist/mcp/index.d.ts +5 -5
  36. package/dist/mcp/index.js +4 -4
  37. package/dist/{openai-tools-BI1ofIfL.d.ts → openai-tools-DvLk_Ddg.d.ts} +2 -2
  38. package/dist/{prepare-Dc30WRB0.js → prepare-CibQrhfi.js} +28 -28
  39. package/dist/prepare-CibQrhfi.js.map +1 -0
  40. package/dist/profiles.d.ts +2 -2
  41. package/dist/{protected-model-port-D5gDcnrH.js → protected-model-port-Dhdi5mDl.js} +3 -3
  42. package/dist/{protected-model-port-D5gDcnrH.js.map → protected-model-port-Dhdi5mDl.js.map} +1 -1
  43. package/dist/{protected-redaction-wGo44k2K.js → protected-redaction-Fn1ETfJ-.js} +6 -6
  44. package/dist/protected-redaction-Fn1ETfJ-.js.map +1 -0
  45. package/dist/{provision-supervisor-DoSrqsM7.js → provision-supervisor-BgQx2Avp.js} +5 -5
  46. package/dist/{provision-supervisor-DoSrqsM7.js.map → provision-supervisor-BgQx2Avp.js.map} +1 -1
  47. package/dist/{run-layout-hZREkcfu.js → run-layout-hKAJGF4g.js} +7 -2
  48. package/dist/run-layout-hKAJGF4g.js.map +1 -0
  49. package/dist/{runtime-CmuAQsWI.js → runtime-HpTXhB3g.js} +16 -13
  50. package/dist/{runtime-CmuAQsWI.js.map → runtime-HpTXhB3g.js.map} +1 -1
  51. package/dist/{server-shkdLqls.js → server-OOE7mXrN.js} +3 -3
  52. package/dist/{server-shkdLqls.js.map → server-OOE7mXrN.js.map} +1 -1
  53. package/dist/{stream-agent-turn-DayHmtvw.d.ts → stream-agent-turn-CcumM0Bu.d.ts} +2 -2
  54. package/dist/{structural-rollout-CW67upUV.js → structural-rollout-z1A0okaB.js} +2 -2
  55. package/dist/{structural-rollout-CW67upUV.js.map → structural-rollout-z1A0okaB.js.map} +1 -1
  56. package/dist/{substrate-iQOskmQ_.d.ts → substrate-CQ0hfewn.d.ts} +2 -2
  57. package/dist/{supervise-DzoCYAe-.js → supervise-DZEOpzRw.js} +148 -35
  58. package/dist/supervise-DZEOpzRw.js.map +1 -0
  59. package/dist/{supervisor-CFSPj8rx.js → supervisor-BIBWUFUr.js} +325 -150
  60. package/dist/supervisor-BIBWUFUr.js.map +1 -0
  61. package/dist/testing.d.ts +2 -2
  62. package/dist/testing.js +398 -398
  63. package/dist/{top-app-CMMd8DgR.js → top-app-d-bmwO7O.js} +2 -2
  64. package/dist/{top-app-CMMd8DgR.js.map → top-app-d-bmwO7O.js.map} +1 -1
  65. package/dist/tui/bin.js +1 -1
  66. package/dist/tui/index.d.ts +1 -1
  67. package/dist/tui/index.js +2 -2
  68. package/dist/{types-CEma9LKR.d.ts → types-BUhz284C.d.ts} +25 -11
  69. package/dist/{workspace-archive-CBX0hwL_.js → workspace-archive-DSRT4Tro.js} +8 -8
  70. package/dist/workspace-archive-DSRT4Tro.js.map +1 -0
  71. package/package.json +6 -6
  72. package/dist/coordination-driver-CMprWr0k.js.map +0 -1
  73. package/dist/improvement-cycle-BpSVwIJw.js.map +0 -1
  74. package/dist/prepare-Dc30WRB0.js.map +0 -1
  75. package/dist/protected-redaction-wGo44k2K.js.map +0 -1
  76. package/dist/run-layout-hZREkcfu.js.map +0 -1
  77. package/dist/supervise-DzoCYAe-.js.map +0 -1
  78. package/dist/supervisor-CFSPj8rx.js.map +0 -1
  79. package/dist/workspace-archive-CBX0hwL_.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"provision-supervisor-DoSrqsM7.js","names":["abortError"],"sources":["../src/runtime/retained-interactive-control.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 type { RetainedInteractiveRunHandle } from './retained-interactive-types'\nimport { abortError } from './retained-run-binding'\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}\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 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\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 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 * Runtime-owned worker seam for a provider's native interactive coding-agent process.\n *\n * This adapter composes the retained-interactive lifecycle. It does not create a second stream,\n * replay buffer, session id, or cancellation protocol. The provider owns process state; Scope owns\n * the supervised worker, journal, budget, and local control inbox.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport {\n type AgentInteractiveSessionPromptCommand,\n type AgentInteractiveSessionRef,\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 CreateAgentEnvironmentInput,\n} from '@tangle-network/agent-interface/environment-provider'\nimport { contentAddress } from '../../durable/spawn-journal'\nimport type { MakeWorkerAgent, WorkerSpawnContext } from '../../mcp/tools/coordination'\nimport { destroyInteractiveEnvironment } from '../retained-interactive-lifecycle'\nimport type { RetainedInteractiveRunHandle } from '../retained-interactive-types'\nimport { claimRetainedInteractiveControl, startRetainedInteractiveRun } from '../retained-run'\nimport { retainedCreateMaterial } from '../retained-run-intent'\nimport type { RetainedInteractiveAdmission } from '../retained-run-types'\nimport { sleep } from '../util'\nimport { abortError, linkAbort } from './abortable'\nimport { executableAgentProfileSnapshot } from './executable-spec'\nimport { createInbox } from './inbox'\nimport {\n type InteractiveAdmissionWriter,\n interactiveAdmissionSeamKey,\n} from './interactive-admission'\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 Agent,\n AgentSpec,\n Executor,\n ExecutorCancellation,\n ExecutorContext,\n ExecutorResult,\n Runtime,\n Spend,\n UsageEvent,\n WorkerInteractiveSession,\n} 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\nconst INTERACTIVE_TEARDOWN_TIMEOUT_MS = 30_000\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 exact provider-owned native TUI per worker.\n *\n * A Scope supplies the durable admission hook and kernel-minted node attempt. The returned worker\n * exposes `interactiveReady`, so Scope writes the exact provider reference before the worker can be\n * attached by a different process. `attachWorker` then reconnects that same reference through the\n * 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\ninterface 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\nfunction interactiveExecutor(input: InteractiveExecutorInput): Executor<InteractiveWorkerResult> {\n const attemptId =\n input.executionAttemptId ?? newExecutionAttemptId(input.nodeId ?? input.environmentKey)\n const localController = new AbortController()\n const inbox = createInbox()\n let handle: RetainedInteractiveRunHandle | undefined\n let createdEnvironment: AgentEnvironment | undefined\n let environmentId: string | undefined\n let artifact: ExecutorResult<InteractiveWorkerResult> | undefined\n let activeLink: ReturnType<typeof linkAbort> | undefined\n let startPromise: Promise<RetainedInteractiveRunHandle> | undefined\n let executeStarted = false\n let readyResolve!: (session: WorkerInteractiveSession) => void\n const ready = new Promise<WorkerInteractiveSession>((resolve) => {\n readyResolve = resolve\n })\n const stopOperations = new Map<string, Promise<ExecutorCancellation>>()\n const memoryAdmissions = new Map<string, RetainedInteractiveAdmission>()\n let teardownComplete = false\n let teardownPromise: Promise<{ destroyed: boolean }> | undefined\n let flushChain: Promise<void> = Promise.resolve()\n let controlError: unknown\n\n const executor: Executor<InteractiveWorkerResult> = {\n runtime: input.runtime,\n teardownTimeoutMs: INTERACTIVE_TEARDOWN_TIMEOUT_MS,\n execute(task, signal): AsyncIterable<UsageEvent> {\n if (executeStarted || teardownComplete || teardownPromise !== undefined) {\n throw new Error('workerFromInteractiveProvider: execute() may only be called once')\n }\n executeStarted = true\n startPromise = startInteractive(task, signal)\n return runInteractive(signal)\n },\n deliver(message: unknown): boolean {\n if (teardownComplete || teardownPromise !== undefined) return false\n const accepted = inbox.deliver(message)\n if (accepted) void flushInbox()\n return accepted\n },\n interactive(): WorkerInteractiveSession {\n return handle\n ? { status: 'available', handle }\n : { status: 'unavailable', reason: 'interactive-session-not-started' }\n },\n interactiveReady(): Promise<WorkerInteractiveSession> {\n return ready\n },\n async cancel(request): Promise<ExecutorCancellation> {\n const existing = stopOperations.get(request.operationId)\n if (existing) return existing\n const operation = stopInteractive(request.operationId, request.reason, request.signal)\n const tracked = operation.then((result) => {\n if (result.status === 'unknown' && stopOperations.get(request.operationId) === tracked) {\n stopOperations.delete(request.operationId)\n }\n return result\n })\n stopOperations.set(request.operationId, tracked)\n return tracked\n },\n teardown(grace): Promise<{ destroyed: boolean }> {\n void grace\n if (teardownComplete) return Promise.resolve({ destroyed: true })\n if (teardownPromise !== undefined) return teardownPromise\n const pending = teardownInteractive()\n teardownPromise = pending.then(\n (result) => {\n teardownComplete = true\n return result\n },\n (error) => {\n teardownPromise = undefined\n throw error\n },\n )\n return teardownPromise\n },\n resultArtifact(): ExecutorResult<InteractiveWorkerResult> {\n if (!artifact) {\n throw new Error(\n 'workerFromInteractiveProvider: resultArtifact() read before execution settled',\n )\n }\n return artifact\n },\n }\n\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 const plannedDeclaration = {\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 attestRuntimeOwnedPendingExecutor(executor, input.runtime, plannedDeclaration, {\n attemptId,\n binding: {\n provider: input.provider.name,\n environmentIdempotencyKey: input.environmentKey,\n nodeId: input.nodeId ?? null,\n },\n descriptor: {\n kind: 'interactive-session',\n provider: input.provider.name,\n transport: 'agent-environment',\n },\n })\n\n async function startInteractive(\n task: unknown,\n signal: AbortSignal,\n ): Promise<RetainedInteractiveRunHandle> {\n try {\n activeLink = linkAbort(signal, localController.signal)\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 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 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: async (admission) => {\n environmentId =\n admission.phase === 'interactive_environment' ? admission.environmentId : environmentId\n const existing = memoryAdmissions.get(admission.phase)\n if (existing !== undefined) {\n if (canonicalCandidateDigest(existing) !== canonicalCandidateDigest(admission)) {\n throw new Error(\n `interactive admission phase '${admission.phase}' changed across retry`,\n )\n }\n } else {\n memoryAdmissions.set(\n admission.phase,\n detachedSnapshot(admission, 'interactive admission'),\n )\n }\n await input.admission(admission)\n },\n signal: activeLink.signal,\n })\n finalizeRuntimeOwnedPendingExecutor(\n executor,\n {\n ...plannedDeclaration,\n execution: { kind: 'interactive-session', id: started.ref.run.executionId },\n plan: {\n ...plannedDeclaration.plan,\n environmentId: started.ref.run.environmentId,\n interactiveIdempotencyKey,\n },\n },\n {\n attemptId,\n binding: {\n provider: input.provider.name,\n ref: started.ref,\n environmentId: started.ref.run.environmentId,\n },\n descriptor: {\n kind: 'interactive-session',\n provider: input.provider.name,\n transport: 'agent-environment',\n },\n },\n )\n handle = started\n readyResolve({ status: 'available', handle: started })\n void flushInbox()\n return started\n } catch (error) {\n readyResolve({ status: 'unavailable', reason: unavailableReason(error) })\n activeLink?.release()\n throw error\n }\n }\n\n async function* runInteractive(signal: AbortSignal): AsyncIterable<UsageEvent> {\n const startedAt = Date.now()\n try {\n const current = await 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 abortError(\n signal.aborted ? signal : localController.signal,\n 'interactive execution aborted',\n )\n }\n status = await current.status({ signal: activeLink?.signal })\n await flushChain\n if (controlError !== undefined) throw controlErrorValue(controlError)\n if (status.state !== 'running') break\n await sleep(input.pollIntervalMs ?? 100, 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 artifact = {\n outRef: contentAddress(output),\n out: output,\n spent,\n }\n } finally {\n activeLink?.release()\n }\n }\n\n async function flushInbox(): Promise<void> {\n flushChain = flushChain.then(async () => {\n try {\n if (!handle) return\n const messages = inbox.drain()\n if (messages.length === 0) return\n const prompt = 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: 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 } catch (error) {\n controlError ??= error\n }\n })\n await flushChain\n }\n\n async function stopInteractive(\n operationId: string,\n reason?: string,\n signal?: AbortSignal,\n ): Promise<ExecutorCancellation> {\n const observedAt = new Date().toISOString()\n if (!handle) {\n 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: 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 localController.abort(reason ?? 'interactive cancellation requested')\n return cancellationFromAcknowledgement(acknowledgement, observedAt)\n } catch (error) {\n 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\n async function teardownInteractive(): Promise<{ destroyed: boolean }> {\n localController.abort('interactive worker teardown')\n activeLink?.release()\n await startPromise?.catch(() => undefined)\n if (handle) {\n const status = await safeStatus(handle)\n if (status?.state === 'running') {\n const operationId = `interactive-teardown-${canonicalCandidateDigest(handle.ref).slice(\n 'sha256:'.length,\n )}`\n const cancellation = await stopInteractive(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()\n return { destroyed: true }\n }\n\n async function destroyEnvironment(): Promise<void> {\n if (input.destroyEnvironmentOnTeardown === false) return\n if (createdEnvironment !== undefined) {\n await destroyInteractiveEnvironment(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 = environmentId ?? handle?.ref.run.environmentId\n if (!cleanupEnvironmentId) return\n const environment = await input.provider.get(cleanupEnvironmentId)\n if (environment !== undefined && environment !== null) {\n await destroyInteractiveEnvironment(environment)\n }\n }\n\n return executor\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\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 * 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'\nimport { sandboxClientAsProvider } from '../environment-provider'\nimport type { SandboxClient } from '../types'\nimport { sleep } from '../util'\nimport { createCancelAcknowledger, createSteerAcknowledger } from './coordination-driver'\nimport { armDeadlineTimer } from './deadline'\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 provider or Sandbox SDK connection for one supervisor run. */\nexport interface ProvisionSupervisorConnection {\n /** A fully constructed provider. This is the preferred programmatic seam and is testable. */\n readonly provider?: AgentEnvironmentProvider\n /** A Sandbox SDK-compatible client. Runtime adapts it to the public provider contract. */\n readonly client?: SandboxClient\n /** Alias for `client`, accepted so callers can pass their existing connection object. */\n readonly sandboxClient?: SandboxClient\n /** Sandbox API endpoint used only when Runtime constructs the SDK client. */\n readonly endpoint?: string\n /** Transient Sandbox API key used only when Runtime constructs the SDK client. */\n readonly apiKey?: string\n /** Connection kind is descriptive only and does not select a hidden implementation. */\n readonly kind?: string\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 /** Explicit provider, client, or endpoint and API key for one provider 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 = await 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 // Keep each supervisor turn bounded so control requests are observed while the remote\n // worker is running. The coordination tool keeps one settlement drain in flight, so a\n // timeout only ends this turn; it cannot lose the eventual worker event.\n awaitTimeoutMs: input.pollMs,\n })\n await coord.ready()\n const spawn = findTool(coord.tools, 'spawn_worker')\n const awaitEvent = findTool(coord.tools, 'await_event')\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 // `await_event` owns the single scope cursor drain. Calling `scope.next()` directly here\n // would bypass the coordination ledger and make a real cancellation look unknown.\n const event = await awaitEvent.handler({ kinds: ['settled'] })\n if (isSettledEvent(event)) {\n await steerAcknowledger.pass('final')\n cancelAcknowledger.pass('final')\n return undefined\n }\n if (isIdleEvent(event)) {\n throw new Error(`Runtime supervisor worker '${childId}' ended without a settlement`)\n }\n if (!isPendingEvent(event)) {\n throw new Error(`Runtime supervisor returned an invalid settlement response`)\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 maxLiveWorkers: 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 throw new Error(\n `Runtime supervisor cleanup could not confirm ${runResult.teardownUnconfirmed.length} resource(s) released`,\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\nasync function resolveProvider(\n request: ProvisionSupervisorRequest,\n): Promise<AgentEnvironmentProvider> {\n const connection = request.connection\n if (connection === undefined) {\n throw unavailable('Runtime supervisor provider connection is required')\n }\n if (connection?.provider !== undefined) return requireReconnectProvider(connection.provider)\n const client = connection?.client ?? connection?.sandboxClient\n if (client !== undefined) {\n return requireReconnectProvider(sandboxClientAsProvider(client))\n }\n const apiKey = connection.apiKey?.trim()\n const endpoint = connection.endpoint?.trim()\n if (!apiKey || !endpoint) {\n throw unavailable(\n 'Runtime supervisor needs a provider/client or both connection.endpoint and connection.apiKey',\n )\n }\n let module: typeof import('@tangle-network/sandbox')\n try {\n module = await import('@tangle-network/sandbox')\n } catch (error) {\n throw unavailable('Runtime supervisor could not load the Sandbox SDK peer dependency', error)\n }\n const SandboxCtor = (module as { Sandbox?: new (config: unknown) => SandboxClient }).Sandbox\n if (SandboxCtor === undefined) throw unavailable('Sandbox SDK does not export a Sandbox client')\n const provider = sandboxClientAsProvider(new SandboxCtor({ apiKey, baseUrl: endpoint }))\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\nfunction isSettledEvent(value: unknown): boolean {\n return isObject(value) && value.type === 'settled'\n}\n\nfunction isIdleEvent(value: unknown): boolean {\n return isObject(value) && value.idle === true\n}\n\nfunction isPendingEvent(value: unknown): boolean {\n return isObject(value) && value.pending === true\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\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":";;;;;;;;;;;AAQA,MAAM,2BAA2B;;;;;;;;;;AAoBjC,eAAsB,gCACpB,SAC8C;CAC9C,MAAM,WAAW,QAAQ,sBAAsB;CAC/C,IAAI,CAAC,OAAO,cAAc,QAAQ,KAAK,WAAW,GAChD,MAAM,IAAI,MAAM,uEAAuE;CAGzF,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,QAAQ,QAAQ,OAAO,CACtE;EACA,IAAI,gBAAgB,WAAW,cAAc,gBAAgB,WAAW,YAAY;GAClF,MAAM,UAAU,g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S,WAA2B;CAClC,IAAI,OAAO;CACX,IAAI;CACJ,IAAI;CAaJ,OAAO;EACL,SAAA,IAbkB,SAAY,gBAAgB,kBAAkB;GAChE,gBAAgB,UAAU;IACxB,IAAI,MAAM;IACV,OAAO;IACP,eAAe,KAAK;GACtB;GACA,eAAe,UAAU;IACvB,IAAI,MAAM;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-BgQx2Avp.js","names":["abortError"],"sources":["../src/runtime/retained-interactive-control.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 type { RetainedInteractiveRunHandle } from './retained-interactive-types'\nimport { abortError } from './retained-run-binding'\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}\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 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\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 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 * Runtime-owned worker seam for a provider's native interactive coding-agent process.\n *\n * This adapter composes the retained-interactive lifecycle. It does not create a second stream,\n * replay buffer, session id, or cancellation protocol. The provider owns process state; Scope owns\n * the supervised worker, journal, budget, and local control inbox.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport {\n type AgentInteractiveSessionPromptCommand,\n type AgentInteractiveSessionRef,\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 CreateAgentEnvironmentInput,\n} from '@tangle-network/agent-interface/environment-provider'\nimport { contentAddress } from '../../durable/spawn-journal'\nimport type { MakeWorkerAgent, WorkerSpawnContext } from '../../mcp/tools/coordination'\nimport { destroyInteractiveEnvironment } from '../retained-interactive-lifecycle'\nimport type { RetainedInteractiveRunHandle } from '../retained-interactive-types'\nimport { claimRetainedInteractiveControl, startRetainedInteractiveRun } from '../retained-run'\nimport { retainedCreateMaterial } from '../retained-run-intent'\nimport type { RetainedInteractiveAdmission } from '../retained-run-types'\nimport { sleep } from '../util'\nimport { abortError, linkAbort } from './abortable'\nimport { executableAgentProfileSnapshot } from './executable-spec'\nimport { createInbox } from './inbox'\nimport {\n type InteractiveAdmissionWriter,\n interactiveAdmissionSeamKey,\n} from './interactive-admission'\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 Agent,\n AgentSpec,\n Executor,\n ExecutorCancellation,\n ExecutorContext,\n ExecutorResult,\n Runtime,\n Spend,\n UsageEvent,\n WorkerInteractiveSession,\n} 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\nconst INTERACTIVE_TEARDOWN_TIMEOUT_MS = 30_000\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 exact provider-owned native TUI per worker.\n *\n * A Scope supplies the durable admission hook and kernel-minted node attempt. The returned worker\n * exposes `interactiveReady`, so Scope writes the exact provider reference before the worker can be\n * attached by a different process. `attachWorker` then reconnects that same reference through the\n * 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\ninterface 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\nfunction interactiveExecutor(input: InteractiveExecutorInput): Executor<InteractiveWorkerResult> {\n const attemptId =\n input.executionAttemptId ?? newExecutionAttemptId(input.nodeId ?? input.environmentKey)\n const localController = new AbortController()\n const inbox = createInbox()\n let handle: RetainedInteractiveRunHandle | undefined\n let createdEnvironment: AgentEnvironment | undefined\n let environmentId: string | undefined\n let artifact: ExecutorResult<InteractiveWorkerResult> | undefined\n let activeLink: ReturnType<typeof linkAbort> | undefined\n let startPromise: Promise<RetainedInteractiveRunHandle> | undefined\n let executeStarted = false\n let readyResolve!: (session: WorkerInteractiveSession) => void\n const ready = new Promise<WorkerInteractiveSession>((resolve) => {\n readyResolve = resolve\n })\n const stopOperations = new Map<string, Promise<ExecutorCancellation>>()\n const memoryAdmissions = new Map<string, RetainedInteractiveAdmission>()\n let teardownComplete = false\n let teardownPromise: Promise<{ destroyed: boolean }> | undefined\n let flushChain: Promise<void> = Promise.resolve()\n let controlError: unknown\n\n const executor: Executor<InteractiveWorkerResult> = {\n runtime: input.runtime,\n teardownTimeoutMs: INTERACTIVE_TEARDOWN_TIMEOUT_MS,\n execute(task, signal): AsyncIterable<UsageEvent> {\n if (executeStarted || teardownComplete || teardownPromise !== undefined) {\n throw new Error('workerFromInteractiveProvider: execute() may only be called once')\n }\n executeStarted = true\n startPromise = startInteractive(task, signal)\n return runInteractive(signal)\n },\n deliver(message: unknown): boolean {\n if (teardownComplete || teardownPromise !== undefined) return false\n const accepted = inbox.deliver(message)\n if (accepted) void flushInbox()\n return accepted\n },\n interactive(): WorkerInteractiveSession {\n return handle\n ? { status: 'available', handle }\n : { status: 'unavailable', reason: 'interactive-session-not-started' }\n },\n interactiveReady(): Promise<WorkerInteractiveSession> {\n return ready\n },\n async cancel(request): Promise<ExecutorCancellation> {\n const existing = stopOperations.get(request.operationId)\n if (existing) return existing\n const operation = stopInteractive(request.operationId, request.reason, request.signal)\n const tracked = operation.then((result) => {\n if (result.status === 'unknown' && stopOperations.get(request.operationId) === tracked) {\n stopOperations.delete(request.operationId)\n }\n return result\n })\n stopOperations.set(request.operationId, tracked)\n return tracked\n },\n teardown(grace): Promise<{ destroyed: boolean }> {\n void grace\n if (teardownComplete) return Promise.resolve({ destroyed: true })\n if (teardownPromise !== undefined) return teardownPromise\n const pending = teardownInteractive()\n teardownPromise = pending.then(\n (result) => {\n teardownComplete = true\n return result\n },\n (error) => {\n teardownPromise = undefined\n throw error\n },\n )\n return teardownPromise\n },\n resultArtifact(): ExecutorResult<InteractiveWorkerResult> {\n if (!artifact) {\n throw new Error(\n 'workerFromInteractiveProvider: resultArtifact() read before execution settled',\n )\n }\n return artifact\n },\n }\n\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 const plannedDeclaration = {\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 attestRuntimeOwnedPendingExecutor(executor, input.runtime, plannedDeclaration, {\n attemptId,\n binding: {\n provider: input.provider.name,\n environmentIdempotencyKey: input.environmentKey,\n nodeId: input.nodeId ?? null,\n },\n descriptor: {\n kind: 'interactive-session',\n provider: input.provider.name,\n transport: 'agent-environment',\n },\n })\n\n async function startInteractive(\n task: unknown,\n signal: AbortSignal,\n ): Promise<RetainedInteractiveRunHandle> {\n try {\n activeLink = linkAbort(signal, localController.signal)\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 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 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: async (admission) => {\n environmentId =\n admission.phase === 'interactive_environment' ? admission.environmentId : environmentId\n const existing = memoryAdmissions.get(admission.phase)\n if (existing !== undefined) {\n if (canonicalCandidateDigest(existing) !== canonicalCandidateDigest(admission)) {\n throw new Error(\n `interactive admission phase '${admission.phase}' changed across retry`,\n )\n }\n } else {\n memoryAdmissions.set(\n admission.phase,\n detachedSnapshot(admission, 'interactive admission'),\n )\n }\n await input.admission(admission)\n },\n signal: activeLink.signal,\n })\n finalizeRuntimeOwnedPendingExecutor(\n executor,\n {\n ...plannedDeclaration,\n execution: { kind: 'interactive-session', id: started.ref.run.executionId },\n plan: {\n ...plannedDeclaration.plan,\n environmentId: started.ref.run.environmentId,\n interactiveIdempotencyKey,\n },\n },\n {\n attemptId,\n binding: {\n provider: input.provider.name,\n ref: started.ref,\n environmentId: started.ref.run.environmentId,\n },\n descriptor: {\n kind: 'interactive-session',\n provider: input.provider.name,\n transport: 'agent-environment',\n },\n },\n )\n handle = started\n readyResolve({ status: 'available', handle: started })\n void flushInbox()\n return started\n } catch (error) {\n readyResolve({ status: 'unavailable', reason: unavailableReason(error) })\n activeLink?.release()\n throw error\n }\n }\n\n async function* runInteractive(signal: AbortSignal): AsyncIterable<UsageEvent> {\n const startedAt = Date.now()\n try {\n const current = await 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 abortError(\n signal.aborted ? signal : localController.signal,\n 'interactive execution aborted',\n )\n }\n status = await current.status({ signal: activeLink?.signal })\n await flushChain\n if (controlError !== undefined) throw controlErrorValue(controlError)\n if (status.state !== 'running') break\n await sleep(input.pollIntervalMs ?? 100, 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 artifact = {\n outRef: contentAddress(output),\n out: output,\n spent,\n }\n } finally {\n activeLink?.release()\n }\n }\n\n async function flushInbox(): Promise<void> {\n flushChain = flushChain.then(async () => {\n try {\n if (!handle) return\n const messages = inbox.drain()\n if (messages.length === 0) return\n const prompt = 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: 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 } catch (error) {\n controlError ??= error\n }\n })\n await flushChain\n }\n\n async function stopInteractive(\n operationId: string,\n reason?: string,\n signal?: AbortSignal,\n ): Promise<ExecutorCancellation> {\n const observedAt = new Date().toISOString()\n if (!handle) {\n 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: 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 localController.abort(reason ?? 'interactive cancellation requested')\n return cancellationFromAcknowledgement(acknowledgement, observedAt)\n } catch (error) {\n 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\n async function teardownInteractive(): Promise<{ destroyed: boolean }> {\n localController.abort('interactive worker teardown')\n activeLink?.release()\n await startPromise?.catch(() => undefined)\n if (handle) {\n const status = await safeStatus(handle)\n if (status?.state === 'running') {\n const operationId = `interactive-teardown-${canonicalCandidateDigest(handle.ref).slice(\n 'sha256:'.length,\n )}`\n const cancellation = await stopInteractive(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()\n return { destroyed: true }\n }\n\n async function destroyEnvironment(): Promise<void> {\n if (input.destroyEnvironmentOnTeardown === false) return\n if (createdEnvironment !== undefined) {\n await destroyInteractiveEnvironment(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 = environmentId ?? handle?.ref.run.environmentId\n if (!cleanupEnvironmentId) return\n const environment = await input.provider.get(cleanupEnvironmentId)\n if (environment !== undefined && environment !== null) {\n await destroyInteractiveEnvironment(environment)\n }\n }\n\n return executor\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\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 * 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'\nimport { sandboxClientAsProvider } from '../environment-provider'\nimport type { SandboxClient } from '../types'\nimport { sleep } from '../util'\nimport { createCancelAcknowledger, createSteerAcknowledger } from './coordination-driver'\nimport { armDeadlineTimer } from './deadline'\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 provider or Sandbox SDK connection for one supervisor run. */\nexport interface ProvisionSupervisorConnection {\n /** A fully constructed provider. This is the preferred programmatic seam and is testable. */\n readonly provider?: AgentEnvironmentProvider\n /** A Sandbox SDK-compatible client. Runtime adapts it to the public provider contract. */\n readonly client?: SandboxClient\n /** Alias for `client`, accepted so callers can pass their existing connection object. */\n readonly sandboxClient?: SandboxClient\n /** Sandbox API endpoint used only when Runtime constructs the SDK client. */\n readonly endpoint?: string\n /** Transient Sandbox API key used only when Runtime constructs the SDK client. */\n readonly apiKey?: string\n /** Connection kind is descriptive only and does not select a hidden implementation. */\n readonly kind?: string\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 /** Explicit provider, client, or endpoint and API key for one provider 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 = await 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 // Keep each supervisor turn bounded so control requests are observed while the remote\n // worker is running. The coordination tool keeps one settlement drain in flight, so a\n // timeout only ends this turn; it cannot lose the eventual worker event.\n awaitTimeoutMs: input.pollMs,\n })\n await coord.ready()\n const spawn = findTool(coord.tools, 'spawn_worker')\n const awaitEvent = findTool(coord.tools, 'await_event')\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 // `await_event` owns the single scope cursor drain. Calling `scope.next()` directly here\n // would bypass the coordination ledger and make a real cancellation look unknown.\n const event = await awaitEvent.handler({ kinds: ['settled'] })\n if (isSettledEvent(event)) {\n await steerAcknowledger.pass('final')\n cancelAcknowledger.pass('final')\n return undefined\n }\n if (isIdleEvent(event)) {\n throw new Error(`Runtime supervisor worker '${childId}' ended without a settlement`)\n }\n if (!isPendingEvent(event)) {\n throw new Error(`Runtime supervisor returned an invalid settlement response`)\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 maxLiveWorkers: 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 throw new Error(\n `Runtime supervisor cleanup could not confirm ${runResult.teardownUnconfirmed.length} resource(s) released`,\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\nasync function resolveProvider(\n request: ProvisionSupervisorRequest,\n): Promise<AgentEnvironmentProvider> {\n const connection = request.connection\n if (connection === undefined) {\n throw unavailable('Runtime supervisor provider connection is required')\n }\n if (connection?.provider !== undefined) return requireReconnectProvider(connection.provider)\n const client = connection?.client ?? connection?.sandboxClient\n if (client !== undefined) {\n return requireReconnectProvider(sandboxClientAsProvider(client))\n }\n const apiKey = connection.apiKey?.trim()\n const endpoint = connection.endpoint?.trim()\n if (!apiKey || !endpoint) {\n throw unavailable(\n 'Runtime supervisor needs a provider/client or both connection.endpoint and connection.apiKey',\n )\n }\n let module: typeof import('@tangle-network/sandbox')\n try {\n module = await import('@tangle-network/sandbox')\n } catch (error) {\n throw unavailable('Runtime supervisor could not load the Sandbox SDK peer dependency', error)\n }\n const SandboxCtor = (module as { Sandbox?: new (config: unknown) => SandboxClient }).Sandbox\n if (SandboxCtor === undefined) throw unavailable('Sandbox SDK does not export a Sandbox client')\n const provider = sandboxClientAsProvider(new SandboxCtor({ apiKey, baseUrl: endpoint }))\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\nfunction isSettledEvent(value: unknown): boolean {\n return isObject(value) && value.type === 'settled'\n}\n\nfunction isIdleEvent(value: unknown): boolean {\n return isObject(value) && value.idle === true\n}\n\nfunction isPendingEvent(value: unknown): boolean {\n return isObject(value) && value.pending === true\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\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":";;;;;;;;;;;AAQA,MAAM,2BAA2B;;;;;;;;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 +1,4 @@
1
- import { i as writeAtomicDurableFile, n as assertNoSymlinkDescendant, r as publishExclusiveDurableFile, t as appendDurableFile } from "./durable-file-D24y9zg7.js";
1
+ import { a as writeAtomicDurableFile, n as assertNoSymlinkDescendant, r as publishExclusiveDurableFile, t as appendDurableFile } from "./durable-file-DWQA4ooo.js";
2
2
  import { canonicalCandidateDigest } from "@tangle-network/agent-interface";
3
3
  import { createHash } from "node:crypto";
4
4
  import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs";
@@ -122,6 +122,11 @@ function workerSteerAcknowledgementFile(eventDir, operationId) {
122
122
  /**
123
123
  * Admit one steer exactly once under a caller-owned operation id.
124
124
  *
125
+ * Pass `supervisorId` as `worker` to address the root. Router roots consume requests between
126
+ * turns; native roots use their existing accepting inbox during execution, or acknowledge
127
+ * `unsupported` when none is available. Delivery does not prove model consumption.
128
+ * This filesystem API requires trusted write access to the run directory; it adds no MCP grant.
129
+ *
125
130
  * The per-operation request file is linked into place atomically after its bytes reach disk. A
126
131
  * same-body retry returns the winner's request. A changed-body retry fails loud. The NDJSON inbox
127
132
  * and control log are readable projections written only by the admission winner.
@@ -647,4 +652,4 @@ function assertSameSteerRequest(existing, candidate) {
647
652
  //#endregion
648
653
  export { writeWorkerCancellation as A, workerInboxFileFromEventDir as C, workerSteerRequestsDir as D, workerSteerRequestFile as E, writeWorkerSteerAcknowledgement as M, workerSteersDir as O, workerInboxFile as S, workerSteerAcknowledgementsDir as T, supervisorWorkersDir as _, legacySupervisorRunsRoot as a, workerCancellationsDir as b, readWorkerCancelRequests as c, readWorkerSteerRequests as d, runCancelRequestFile as f, supervisorRunsRoot as g, supervisorRunDir as h, legacySupervisorRunDir as i, writeWorkerSteer as j, writeRunCancellation as k, readWorkerCancellation as l, safeWorkerFile as m, cancelWorker as n, readRunCancelRequest as o, runCancellationFile as p, claimWorkerSteerDelivery as r, readRunCancellation as s, cancelRun as t, readWorkerSteerAcknowledgement as u, workerCancelRequestsFile as v, workerSteerAcknowledgementFile as w, workerControlLogFile as x, workerCancellationFile as y };
649
654
 
650
- //# sourceMappingURL=run-layout-hZREkcfu.js.map
655
+ //# sourceMappingURL=run-layout-hKAJGF4g.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-layout-hKAJGF4g.js","names":[],"sources":["../src/runtime/supervise/run-layout.ts"],"sourcesContent":["/**\n * The on-disk supervisor-run layout: `<root>/.agent/supervisor/<id>`.\n *\n * This is the durable, cross-process face of a supervisor run — the counterpart to the in-process\n * `Inbox` seam in `./inbox`. A run persists its state under one directory so that any OTHER process\n * can find it after the fact: `@tangle-network/traces` reads exactly this layout via\n * `traces analyze --supervisor-run-dir`, a restarted host can rehydrate a run it no longer holds\n * handles to, and a human can steer a live worker by appending one NDJSON line. Until now the\n * layout was defined only in the unpublished `loops` repo (`src/supervisor-control.ts`) — a\n * published reader depending on an unpublished writer's convention — so the contract is promoted\n * here, names preserved.\n *\n * `.agent` is the one dot-dir for ALL agent-owned state (skills already write\n * `.agent/hypotheses/`, `.agent/skill-runs.jsonl`); supervisor runs live beside them rather than\n * under a product-branded dir. Runs written by older writers used `.loops/supervisor/<id>` —\n * readers that must see those keep a legacy fallback; this writer never creates `.loops` again.\n *\n * Layout, relative to `supervisorRunDir(root, id)`:\n *\n * steers/requests/<hash>.json one exact, caller-idempotent {@link WorkerSteerRequest}\n * steers/acks/<hash>.json runtime acknowledgement for that steer operation\n * workers/<id>.inbox.ndjson best-effort readable projection of admitted steer requests\n * workers/<label>.ndjson best-effort per-worker control-event log (delivery bookkeeping)\n * cancellations/requests.ndjson worker-scoped cancel requests (durable inbox); each line is a\n * {@link WorkerCancelRequest}\n * cancellations/<opId>.json the acknowledgement for one cancel operation — a\n * {@link WorkerCancellation} written ONLY by the runtime\n * acknowledger in the OWNING manager's turn loop: exact node\n * ids route to the manager that parents them (any depth);\n * label/profile-name references to the root manager alone\n * cancellations/run.request.json the run-scoped cancel request — one {@link RunCancelRequest},\n * the whole RUN rather than one worker\n * cancellations/run.json the acknowledgement for the run-scoped request — a\n * {@link RunCancellation} written ONLY by the runtime (the root\n * manager issues the abort; the `supervise()` settle path records\n * what the run actually did)\n *\n * Reads are tolerant by contract: a partial trailing line (a writer mid-append) or a corrupt line\n * never poisons the rest of the file — later valid lines still matter. Duplicate operation ids\n * collapse to the first admitted request, while a payload conflict fails closed.\n *\n * Promoted from `loops/src/supervisor-control.ts`. Steer admission now requires the exact worker id\n * and a caller-owned operation id. One atomic request file is the durable inbox; the NDJSON file is\n * a readable projection only and never controls idempotency.\n *\n * @experimental\n */\n\nimport { createHash } from 'node:crypto'\nimport { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport { canonicalCandidateDigest, type Sha256Digest } from '@tangle-network/agent-interface'\nimport type { RetainedRunEffect } from '../retained-run-types'\nimport {\n appendDurableFile,\n assertNoSymlinkDescendant,\n publishExclusiveDurableFile,\n writeAtomicDurableFile,\n} from './durable-file'\n\n/** One atomically admitted down-leg request for an exact worker id. @stable */\nexport interface WorkerSteerRequest {\n readonly schemaVersion: 1\n /** Caller-minted stable idempotency key for this operation. */\n readonly operationId: string\n /** Digest of operation id, worker id, message, source, and interrupt mode. */\n readonly requestDigest: Sha256Digest\n /** ISO timestamp of durable admission. */\n readonly at: string\n /** Who asked — 'human', a brain label, a tool name. Provenance, not authorization. */\n readonly source: string\n /** Exact supervised worker node id. */\n readonly worker: string\n readonly message: string\n readonly interrupt: boolean\n}\n\n/** Runtime acknowledgement for one exact steer operation. @stable */\nexport interface WorkerSteerAcknowledgement {\n readonly schemaVersion: 1\n readonly operationId: string\n readonly requestDigest: Sha256Digest\n readonly worker: string\n readonly effect: 'unknown' | 'delivered' | 'not_live' | 'unsupported' | 'refused'\n readonly requestedAt: string\n readonly observedAt: string\n readonly detail: string\n}\n\n/** Caller input for one retry-safe steer operation. @stable */\nexport interface WriteWorkerSteerOptions {\n readonly operationId: string\n readonly message: string\n readonly source?: string\n readonly interrupt?: boolean\n}\n\n/** One durable worker-scoped cancel request appended to the run's cancellation inbox. */\nexport interface WorkerCancelRequest {\n /** Caller-minted stable operation identifier — the idempotency key of the whole operation. */\n readonly operationId: string\n /** ISO timestamp of the append. */\n readonly at: string\n /** Who asked — 'human', a brain label, a tool name. Provenance, not authorization. */\n readonly source: string\n /** The worker the request targets: a workerId (node id — routed to the owning manager at any\n * depth), or a profile name or spawn label (resolved by the root manager against its direct\n * children only). */\n readonly worker: string\n readonly reason?: string\n}\n\n/**\n * The durable acknowledgement state for one worker-scoped cancel operation, keyed by\n * `operationId`. The runtime acknowledger is the ONLY writer; `cancelWorker` only reads it.\n *\n * `effect` reuses the retained-run vocabulary ({@link RetainedRunEffect}) so the runtime has one\n * spelling of the four cancellation states:\n * - `'unknown'` — not yet resolved by the runtime (also what `cancelWorker` returns for\n * a request no acknowledger has answered), or — terminally, with the\n * run-over detail — an abort was issued but the run ended before the\n * termination could be observed. Never a success.\n * - `'cancel_requested'` — the runtime issued the worker's abort; termination not yet proven.\n * - `'cancelled'` — the worker reached a terminal `down` state on the settle path.\n * - `'not_live'` — the worker was not live to cancel (already settled, it settled\n * `done` despite the abort, or the run ended before the request was\n * ever applied). Never a success of THIS operation.\n *\n * Expiry is run end: the owning manager's final pass closes every still-open request it owns\n * (`not_live` never applied, `unknown` issued-but-unproven), so a pending request cannot outlive\n * its run and abort a future spawn that happens to reuse a label.\n */\nexport interface WorkerCancellation {\n readonly operationId: string\n /** The worker reference exactly as requested. */\n readonly worker: string\n readonly effect: RetainedRunEffect\n /** ISO timestamp of the original request. */\n readonly requestedAt: string\n /** ISO timestamp of the runtime's most recent observation of this operation. */\n readonly observedAt: string\n /** The node id the acknowledger resolved `worker` to, once resolved. */\n readonly workerId?: string\n /** The caller's reason, carried verbatim from the request. */\n readonly reason?: string\n /** The runtime's explanation of how it arrived at `effect`. */\n readonly detail?: string\n /**\n * Every node id this operation PROVED terminated: the requested worker plus each descendant of\n * its subtree observed to reach a terminal `down`/`cancelled` journal record at or after the\n * abort was ISSUED — the acknowledger's own `observedAt` on the `cancel_requested` record\n * (runtime clock), never the client's `requestedAt` (a cancelled lead cascades to its subtree\n * by design — the scope signal chain — so the acknowledgement names the set, not one id).\n * Proven at acknowledgement time; post-abort causation is approximate: a descendant that died\n * of its own cause after the abort is indistinguishable from the cascade and may be included,\n * a late teardown journal joins the set on a later pass while the manager still runs, and one\n * still absent at run end is absent from the set. Grows monotonically; empty until termination\n * is proven.\n */\n readonly terminated: ReadonlyArray<string>\n}\n\n/** One durable run-scoped cancel request: cancel the WHOLE run, not one worker. */\nexport interface RunCancelRequest {\n /** Caller-minted stable operation identifier — the idempotency key of the whole operation. */\n readonly operationId: string\n /** ISO timestamp of the write. */\n readonly at: string\n /** Who asked — 'human', a brain label, a tool name. Provenance, not authorization. */\n readonly source: string\n /** Requested observation target, measured by the acknowledgement's deadlineExceeded field.\n * The observer always cascades eagerly. This does not guarantee scheduler latency or cleanup. */\n readonly deadlineMs?: number\n readonly reason?: string\n}\n\n/**\n * The durable acknowledgement state for the run-scoped cancel operation, keyed by `operationId`.\n * The runtime is the ONLY writer; {@link cancelRun} only reads it.\n *\n * `effect` is the same {@link RetainedRunEffect} vocabulary the worker-scoped and retained-run\n * paths use, so the runtime has one spelling of the four cancellation states:\n * - `'unknown'` — no runtime has answered yet. Never a success.\n * - `'cancel_requested'` — the root manager issued the run's cascading abort; the run's terminal\n * state is not yet observed.\n * - `'cancelled'` — the run reached its terminal cancelled state with confirmed teardown.\n * - `'not_live'` — the run was not live to cancel: it settled on its own despite the\n * request, or it ended before the request was applied.\n */\nexport interface RunCancellation {\n /** Runtime path that issued the cascade. */\n readonly path?: 'observer' | 'turn-boundary' | 'fallback'\n /** Runtime clock elapsed between request timestamp and cascade application. */\n readonly appliedAfterMs?: number\n /** Whether application exceeded the requested deadlineMs; absent when no target was requested. */\n readonly deadlineExceeded?: boolean\n readonly operationId: string\n readonly effect: RetainedRunEffect\n /** ISO timestamp of the original request. */\n readonly requestedAt: string\n /** ISO timestamp of the runtime's most recent observation of this operation. */\n readonly observedAt: string\n /** The caller's reason, carried verbatim from the request. */\n readonly reason?: string\n /** The runtime's explanation of how it arrived at `effect`. */\n readonly detail?: string\n}\n\n/** The root every supervisor run of one workspace lives under. */\nexport function supervisorRunsRoot(rootDir: string): string {\n return join(resolve(rootDir), '.agent', 'supervisor')\n}\n\n/** The run directory every artifact of one supervisor run lives under. */\nexport function supervisorRunDir(rootDir: string, id: string): string {\n return join(supervisorRunsRoot(rootDir), id)\n}\n\n/**\n * Where a pre-rename writer put the same run (`<root>/.loops/supervisor/<id>`). Readers that must\n * see historical runs check {@link supervisorRunDir} first and fall back to this; nothing writes\n * here anymore.\n */\nexport function legacySupervisorRunDir(rootDir: string, id: string): string {\n return join(legacySupervisorRunsRoot(rootDir), id)\n}\n\n/**\n * The pre-rename runs root (`<root>/.loops/supervisor`). Only readers that ENUMERATE historical\n * runs need this — the per-id form is {@link legacySupervisorRunDir}. Nothing writes here.\n */\nexport function legacySupervisorRunsRoot(rootDir: string): string {\n return join(resolve(rootDir), '.loops', 'supervisor')\n}\n\n/** A worker label reduced to a safe filename stem. Empty labels get a stable fallback. */\nexport function safeWorkerFile(label: string): string {\n const safe = label.replace(/[^A-Za-z0-9._-]/g, '_')\n return safe.length > 0 ? safe : 'worker'\n}\n\n/** The directory holding every per-worker file of one run (inboxes and control-event logs). */\nexport function supervisorWorkersDir(eventDir: string): string {\n return join(eventDir, 'workers')\n}\n\n/** The durable inbox file for one worker of one run. */\nexport function workerInboxFile(rootDir: string, supervisorId: string, worker: string): string {\n return workerInboxFileFromEventDir(supervisorRunDir(rootDir, supervisorId), worker)\n}\n\n/** Same, addressed from an already-known run directory (the reader's usual entry point). */\nexport function workerInboxFileFromEventDir(eventDir: string, worker: string): string {\n return join(supervisorWorkersDir(eventDir), `${safeWorkerFile(worker)}.inbox.ndjson`)\n}\n\n/**\n * The best-effort control-event log for one worker (`workers/<label>.ndjson`) — delivery\n * bookkeeping for steers, plus whatever lifecycle events a writer chooses to append. Distinct from\n * the inbox: the inbox is the durable down-leg queue, this is the record of what happened to it.\n */\nexport function workerControlLogFile(eventDir: string, worker: string): string {\n return join(supervisorWorkersDir(eventDir), `${safeWorkerFile(worker)}.ndjson`)\n}\n\n/** Directory containing atomically admitted steer requests and runtime acknowledgements. */\nexport function workerSteersDir(eventDir: string): string {\n return join(eventDir, 'steers')\n}\n\n/** Directory containing one canonical request file per steer operation. */\nexport function workerSteerRequestsDir(eventDir: string): string {\n return join(workerSteersDir(eventDir), 'requests')\n}\n\n/** Directory containing one runtime acknowledgement per steer operation. */\nexport function workerSteerAcknowledgementsDir(eventDir: string): string {\n return join(workerSteersDir(eventDir), 'acks')\n}\n\n/** Canonical request file for one caller-owned steer operation id. */\nexport function workerSteerRequestFile(eventDir: string, operationId: string): string {\n return join(workerSteerRequestsDir(eventDir), `${operationFileHash(operationId)}.json`)\n}\n\n/** Runtime acknowledgement file for one caller-owned steer operation id. */\nexport function workerSteerAcknowledgementFile(eventDir: string, operationId: string): string {\n return join(workerSteerAcknowledgementsDir(eventDir), `${operationFileHash(operationId)}.json`)\n}\n\n/**\n * Admit one steer exactly once under a caller-owned operation id.\n *\n * Pass `supervisorId` as `worker` to address the root. Router roots consume requests between\n * turns; native roots use their existing accepting inbox during execution, or acknowledge\n * `unsupported` when none is available. Delivery does not prove model consumption.\n * This filesystem API requires trusted write access to the run directory; it adds no MCP grant.\n *\n * The per-operation request file is linked into place atomically after its bytes reach disk. A\n * same-body retry returns the winner's request. A changed-body retry fails loud. The NDJSON inbox\n * and control log are readable projections written only by the admission winner.\n * @stable\n */\nexport function writeWorkerSteer(\n rootDir: string,\n supervisorId: string,\n worker: string,\n options: WriteWorkerSteerOptions,\n): {\n worker: string\n file: string\n request: WorkerSteerRequest\n acknowledgement?: WorkerSteerAcknowledgement\n replayed: boolean\n} {\n const workerId = worker.trim()\n if (!workerId) throw new Error('writeWorkerSteer: worker id is empty')\n const operationId = options.operationId.trim()\n if (!operationId) throw new Error('writeWorkerSteer: operationId is empty')\n const trimmed = options.message.trim()\n if (!trimmed) throw new Error('steer message is empty')\n const source = options.source?.trim() || 'human'\n const interrupt = options.interrupt === true\n const dir = supervisorRunDir(rootDir, supervisorId)\n const requestDigest = workerSteerRequestDigest({\n operationId,\n worker: workerId,\n message: trimmed,\n source,\n interrupt,\n })\n const request: WorkerSteerRequest = {\n schemaVersion: 1,\n operationId,\n requestDigest,\n at: new Date().toISOString(),\n source,\n worker: workerId,\n message: trimmed,\n interrupt,\n }\n const file = workerSteerRequestFile(dir, operationId)\n assertNoSymlinkDescendant(dir, file, 'steer request')\n mkdirSync(workerSteerRequestsDir(dir), { recursive: true })\n assertNoSymlinkDescendant(dir, file, 'steer request')\n const admitted = admitSteerRequest(file, request)\n if (admitted.replayed) {\n return {\n worker: admitted.request.worker,\n file,\n request: admitted.request,\n ...(readWorkerSteerAcknowledgement(dir, operationId) === undefined\n ? {}\n : { acknowledgement: readWorkerSteerAcknowledgement(dir, operationId) }),\n replayed: true,\n }\n }\n mkdirSync(supervisorWorkersDir(dir), { recursive: true })\n const projection = workerInboxFile(rootDir, supervisorId, workerId)\n try {\n appendFileSync(projection, `${JSON.stringify(request)}\\n`, 'utf8')\n } catch {\n // The atomic operation file is the queue. This projection does not control admission.\n }\n appendWorkerControlEvent(dir, workerId, {\n kind: 'message',\n direction: 'down',\n source,\n operationId,\n requestDigest,\n message: trimmed,\n interrupt,\n queued: true,\n delivered: false,\n })\n return { worker: workerId, file, request, replayed: false }\n}\n\n/** Read every atomically admitted request for one exact worker id, in admission order. @stable */\nexport function readWorkerSteerRequests(eventDir: string, worker?: string): WorkerSteerRequest[] {\n const workerId = worker?.trim()\n if (worker !== undefined && !workerId) return []\n let names: string[]\n assertNoSymlinkDescendant(eventDir, workerSteerRequestsDir(eventDir), 'steer request')\n try {\n names = readdirSync(workerSteerRequestsDir(eventDir))\n } catch {\n return []\n }\n const out: WorkerSteerRequest[] = []\n for (const name of names) {\n if (!name.endsWith('.json')) continue\n try {\n const file = join(workerSteerRequestsDir(eventDir), name)\n assertNoSymlinkDescendant(eventDir, file, 'steer request')\n const parsed = parseWorkerSteerRequest(JSON.parse(readFileSync(file, 'utf8')))\n if (name !== `${operationFileHash(parsed.operationId)}.json`) continue\n if (workerId === undefined || parsed.worker === workerId) out.push(parsed)\n } catch {\n // One corrupt request cannot hide other independently committed operations.\n }\n }\n return out.sort((left, right) =>\n left.at === right.at\n ? left.operationId.localeCompare(right.operationId)\n : left.at.localeCompare(right.at),\n )\n}\n\n/** Read one runtime steer acknowledgement, or `undefined` while no manager has answered. @stable */\nexport function readWorkerSteerAcknowledgement(\n eventDir: string,\n operationId: string,\n): WorkerSteerAcknowledgement | undefined {\n const id = operationId.trim()\n if (!id) throw new Error('readWorkerSteerAcknowledgement: operationId is empty')\n const file = workerSteerAcknowledgementFile(eventDir, id)\n assertNoSymlinkDescendant(eventDir, file, 'steer acknowledgement')\n if (!existsSync(file)) return undefined\n const record = parseWorkerSteerAcknowledgement(JSON.parse(readFileSync(file, 'utf8')))\n if (record.operationId !== id) {\n throw new Error(`steer acknowledgement '${file}' belongs to another operation`)\n }\n return record\n}\n\n/**\n * Claim one steer for delivery with an atomic no-clobber acknowledgement.\n * Returns `true` only to the process that created the pre-delivery record.\n * @internal\n */\nexport function claimWorkerSteerDelivery(\n eventDir: string,\n record: WorkerSteerAcknowledgement,\n): boolean {\n const exact = parseWorkerSteerAcknowledgement(record)\n if (exact.effect !== 'unknown') {\n throw new Error('steer delivery claim must use effect unknown')\n }\n const request = readWorkerSteerRequest(eventDir, exact.operationId)\n if (request === undefined || request.requestDigest !== exact.requestDigest) {\n throw new Error('steer delivery claim does not match an admitted request')\n }\n const dir = workerSteerAcknowledgementsDir(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'steer acknowledgement')\n mkdirSync(dir, { recursive: true })\n assertNoSymlinkDescendant(eventDir, dir, 'steer acknowledgement')\n const file = workerSteerAcknowledgementFile(eventDir, exact.operationId)\n if (publishExclusiveDurableFile(file, `${JSON.stringify(exact, null, 2)}\\n`)) {\n return true\n }\n const winner = readWorkerSteerAcknowledgement(eventDir, exact.operationId)\n if (\n winner === undefined ||\n winner.operationId !== exact.operationId ||\n winner.requestDigest !== exact.requestDigest\n ) {\n throw new Error('steer delivery claim conflicts with another operation')\n }\n return false\n}\n\n/** Atomically replace the runtime acknowledgement for one steer operation. @internal */\nexport function writeWorkerSteerAcknowledgement(\n eventDir: string,\n record: WorkerSteerAcknowledgement,\n): void {\n const exact = parseWorkerSteerAcknowledgement(record)\n const request = readWorkerSteerRequest(eventDir, exact.operationId)\n if (request === undefined || request.requestDigest !== exact.requestDigest) {\n throw new Error('steer acknowledgement does not match an admitted request')\n }\n const dir = workerSteerAcknowledgementsDir(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'steer acknowledgement')\n mkdirSync(dir, { recursive: true })\n assertNoSymlinkDescendant(eventDir, dir, 'steer acknowledgement')\n const file = workerSteerAcknowledgementFile(eventDir, exact.operationId)\n const prior = readWorkerSteerAcknowledgement(eventDir, exact.operationId)\n if (\n prior !== undefined &&\n prior.effect !== 'unknown' &&\n canonicalCandidateDigest(prior) !== canonicalCandidateDigest(exact)\n ) {\n throw new Error(`steer operation '${exact.operationId}' already has a terminal acknowledgement`)\n }\n writeAtomicDurableFile(file, `${JSON.stringify(exact, null, 2)}\\n`)\n}\n\n/** The directory holding every cancellation artifact of one run (request inbox + acknowledgements). */\nexport function workerCancellationsDir(eventDir: string): string {\n return join(eventDir, 'cancellations')\n}\n\n/**\n * The durable cancel-request inbox of one run — one NDJSON line per {@link WorkerCancelRequest}.\n * It stays append-only so independent operations retain admission order and readers can skip a\n * partial trailing line. `appendDurableFile` uses O_APPEND, one write, file fsync, and directory\n * fsync; single-record acknowledgements use atomic replacement instead.\n */\nexport function workerCancelRequestsFile(eventDir: string): string {\n return join(workerCancellationsDir(eventDir), 'requests.ndjson')\n}\n\n/**\n * The acknowledgement file for one cancel operation. The filename is a sanitized stem of the\n * `operationId`; the record inside carries the exact id, and readers verify it so two distinct\n * ids that sanitize to one stem fail loud instead of answering for each other.\n */\nexport function workerCancellationFile(eventDir: string, operationId: string): string {\n return join(workerCancellationsDir(eventDir), `${safeOperationFile(operationId)}.json`)\n}\n\nfunction safeOperationFile(operationId: string): string {\n const safe = operationId.replace(/[^A-Za-z0-9._-]/g, '_')\n if (safe.length === 0) throw new Error('cancel operationId is empty')\n return safe\n}\n\n/** Read every valid cancel request in the run's cancellation inbox. Corrupt lines are skipped. */\nexport function readWorkerCancelRequests(eventDir: string): WorkerCancelRequest[] {\n const dir = workerCancellationsDir(eventDir)\n const file = workerCancelRequestsFile(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'cancel request')\n assertNoSymlinkDescendant(eventDir, file, 'cancel request')\n if (!existsSync(file)) return []\n const out: WorkerCancelRequest[] = []\n const byOperationId = new Map<string, WorkerCancelRequest>()\n let raw = ''\n try {\n raw = readFileSync(file, 'utf8')\n } catch {\n return out\n }\n for (const line of raw.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed) continue\n let parsed: Partial<WorkerCancelRequest>\n try {\n parsed = JSON.parse(trimmed) as Partial<WorkerCancelRequest>\n } catch {\n // Ignore partial or corrupt input lines; later valid lines still matter.\n continue\n }\n if (!isWorkerCancelRequest(parsed)) continue\n const prior = byOperationId.get(parsed.operationId)\n if (prior !== undefined) {\n assertSameWorkerCancelRequest(prior, parsed)\n } else {\n byOperationId.set(parsed.operationId, parsed)\n out.push(parsed)\n }\n }\n return out\n}\n\n/**\n * Read the acknowledgement for one cancel operation. `undefined` when the runtime has not\n * answered. A record whose stored `operationId` differs from the requested one is a filename\n * collision between two sanitized ids — fail loud rather than return another operation's answer.\n */\nexport function readWorkerCancellation(\n eventDir: string,\n operationId: string,\n): WorkerCancellation | undefined {\n const dir = workerCancellationsDir(eventDir)\n const file = workerCancellationFile(eventDir, operationId)\n assertNoSymlinkDescendant(eventDir, dir, 'cancel acknowledgement')\n assertNoSymlinkDescendant(eventDir, file, 'cancel acknowledgement')\n if (!existsSync(file)) return undefined\n const parsed = JSON.parse(readFileSync(file, 'utf8')) as WorkerCancellation\n if (parsed.operationId !== operationId) {\n throw new Error(\n `cancel acknowledgement collision: '${file}' holds operation '${parsed.operationId}', ` +\n `not '${operationId}' — use operation ids that stay distinct after filename sanitization`,\n )\n }\n return parsed\n}\n\n/**\n * Durably write one acknowledgement record. The shared writer fsyncs the file and containing\n * directory, so a concurrent reader sees the prior complete record or the new complete record.\n *\n * @internal The runtime acknowledger is the only intended writer; clients read via\n * {@link readWorkerCancellation} or {@link cancelWorker}.\n */\nexport function writeWorkerCancellation(eventDir: string, record: WorkerCancellation): void {\n const dir = workerCancellationsDir(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'cancel acknowledgement')\n mkdirSync(dir, { recursive: true })\n assertNoSymlinkDescendant(eventDir, dir, 'cancel acknowledgement')\n const file = workerCancellationFile(eventDir, record.operationId)\n assertNoSymlinkDescendant(eventDir, file, 'cancel acknowledgement')\n writeAtomicDurableFile(file, `${JSON.stringify(record, null, 2)}\\n`, { mode: 0o600 })\n}\n\n/**\n * Request the cancellation of ONE worker, idempotently, and return the operation's current\n * durable state.\n *\n * The write half of the acknowledged-cancellation contract (`writeWorkerSteer` is the steer\n * analog): append the request to the run's cancellation inbox, where the OWNING manager's\n * acknowledger (its turn loop — the root for label/profile references, the parent manager for an\n * exact node id at any depth) applies it — aborting exactly that worker's subtree and recording\n * what it proved. This function never applies the cancellation itself; writing a\n * request file is not an acknowledgement.\n *\n * Idempotency is a lookup: when an acknowledgement for `operationId` already exists, it is\n * returned AS-IS and nothing is appended — repeating one operation can never apply twice. A\n * retry that changes the worker, source, or reason fails closed. A request the runtime has not\n * answered yet returns `effect: 'unknown'` (never a success); call again with the same\n * `operationId` — or `readWorkerCancellation` — to read the acknowledged result after a\n * reconnect.\n */\nexport function cancelWorker(\n eventDir: string,\n worker: string,\n operationId: string,\n options: { readonly reason?: string; readonly source?: string } = {},\n): WorkerCancellation {\n const ref = worker.trim()\n if (!ref) throw new Error('cancelWorker: worker reference is empty')\n const opId = operationId.trim()\n if (!opId) throw new Error('cancelWorker: operationId is empty')\n const pending = readWorkerCancelRequests(eventDir).find((r) => r.operationId === opId)\n const candidate = {\n operationId: opId,\n worker: ref,\n source: options.source ?? 'human',\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n }\n if (pending !== undefined) assertSameWorkerCancelRequest(pending, candidate)\n const acknowledged = readWorkerCancellation(eventDir, opId)\n if (acknowledged !== undefined) {\n if (pending === undefined && options.source !== undefined) {\n throw new Error(\n `cancelWorker: operation '${opId}' cannot verify source without its admitted request`,\n )\n }\n assertWorkerCancellationMatchesCandidate(acknowledged, candidate)\n return acknowledged\n }\n const source = options.source ?? 'human'\n const request: WorkerCancelRequest = pending ?? {\n operationId: opId,\n at: new Date().toISOString(),\n source,\n worker: ref,\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n }\n if (!pending) {\n const dir = workerCancellationsDir(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'cancel request')\n mkdirSync(dir, { recursive: true })\n assertNoSymlinkDescendant(eventDir, dir, 'cancel request')\n const file = workerCancelRequestsFile(eventDir)\n assertNoSymlinkDescendant(eventDir, file, 'cancel request')\n appendDurableFile(file, `${JSON.stringify(request)}\\n`, { mode: 0o600 })\n appendWorkerControlEvent(eventDir, ref, {\n kind: 'cancel-request',\n operationId: opId,\n source,\n queued: true,\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n })\n }\n return {\n operationId: opId,\n worker: request.worker,\n effect: 'unknown',\n requestedAt: request.at,\n observedAt: request.at,\n ...(request.reason === undefined ? {} : { reason: request.reason }),\n detail: 'request queued; no runtime acknowledger has answered yet',\n terminated: [],\n }\n}\n\n/** The run-scoped cancel request file of one run — one {@link RunCancelRequest}. */\nexport function runCancelRequestFile(eventDir: string): string {\n return join(workerCancellationsDir(eventDir), 'run.request.json')\n}\n\n/** The run-scoped acknowledgement file of one run — one {@link RunCancellation}. */\nexport function runCancellationFile(eventDir: string): string {\n return join(workerCancellationsDir(eventDir), 'run.json')\n}\n\n/** Read the run-scoped cancel request, or `undefined` when none was written. */\nexport function readRunCancelRequest(eventDir: string): RunCancelRequest | undefined {\n const dir = workerCancellationsDir(eventDir)\n const file = runCancelRequestFile(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel request')\n assertNoSymlinkDescendant(eventDir, file, 'run cancel request')\n if (!existsSync(file)) return undefined\n const parsed = JSON.parse(readFileSync(file, 'utf8')) as Partial<RunCancelRequest>\n if (!isRunCancelRequest(parsed)) {\n throw new Error(`run cancel request '${file}' is not a complete RunCancelRequest`)\n }\n return parsed\n}\n\n/**\n * Read the acknowledgement for the run-scoped cancel operation. `undefined` when the runtime has\n * not answered. A record holding a DIFFERENT `operationId` belongs to another operation on the\n * same run — fail loud rather than answer for it.\n */\nexport function readRunCancellation(\n eventDir: string,\n operationId: string,\n): RunCancellation | undefined {\n const dir = workerCancellationsDir(eventDir)\n const file = runCancellationFile(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel acknowledgement')\n assertNoSymlinkDescendant(eventDir, file, 'run cancel acknowledgement')\n if (!existsSync(file)) return undefined\n const parsed = JSON.parse(readFileSync(file, 'utf8')) as RunCancellation\n if (parsed.operationId !== operationId) {\n throw new Error(\n `run cancel acknowledgement '${file}' holds operation '${parsed.operationId}', not ` +\n `'${operationId}' — one run carries one run-scoped cancel operation`,\n )\n }\n return parsed\n}\n\n/**\n * Durably write the run-scoped acknowledgement. The shared writer fsyncs the file and containing\n * directory, so a concurrent reader sees the prior complete record or the new complete record.\n *\n * @internal The runtime is the only intended writer; clients read via {@link readRunCancellation}\n * or {@link cancelRun}.\n */\nexport function writeRunCancellation(eventDir: string, record: RunCancellation): void {\n const dir = workerCancellationsDir(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel acknowledgement')\n mkdirSync(dir, { recursive: true })\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel acknowledgement')\n const file = runCancellationFile(eventDir)\n assertNoSymlinkDescendant(eventDir, file, 'run cancel acknowledgement')\n writeAtomicDurableFile(file, `${JSON.stringify(record, null, 2)}\\n`, { mode: 0o600 })\n}\n\n/**\n * Request the cancellation of the WHOLE run, idempotently, and return the operation's current\n * durable state.\n *\n * The run-scoped twin of {@link cancelWorker}: write the request into the run's cancellation\n * directory, where the run's own root manager applies it — aborting the root through the one\n * cascade controller the run already has, so every live worker comes down with it. This function\n * never applies the cancellation itself; writing a request file is not an acknowledgement.\n *\n * Idempotency is a lookup: when an acknowledgement for `operationId` already exists it is returned\n * AS-IS and nothing is written. A retry that changes the source or reason fails closed. A request\n * the runtime has not answered yet returns `effect: 'unknown'` (never a success); call again with\n * the same `operationId` — or {@link readRunCancellation} — to read the acknowledged result\n * after a reconnect.\n *\n * A run carries ONE run-scoped operation: a second request under a different `operationId` throws\n * rather than silently replacing the pending one, because both would claim the same single abort.\n */\nexport function cancelRun(\n eventDir: string,\n operationId: string,\n options: {\n readonly reason?: string\n readonly source?: string\n readonly deadlineMs?: number\n } = {},\n): RunCancellation {\n if (\n options.deadlineMs !== undefined &&\n (!Number.isFinite(options.deadlineMs) || options.deadlineMs < 0)\n ) {\n throw new Error('cancelRun: deadlineMs must be a finite nonnegative number')\n }\n const opId = operationId.trim()\n if (!opId) throw new Error('cancelRun: operationId is empty')\n const pending = readRunCancelRequest(eventDir)\n if (pending !== undefined && pending.operationId !== opId) {\n throw new Error(\n `cancelRun: run cancel '${pending.operationId}' is already pending for this run; ` +\n `read it with readRunCancellation instead of issuing '${opId}'`,\n )\n }\n const candidate = {\n operationId: opId,\n source: options.source ?? 'human',\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n ...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),\n }\n if (pending !== undefined) assertSameRunCancelRequest(pending, candidate)\n const acknowledged = readRunCancellation(eventDir, opId)\n if (acknowledged !== undefined) {\n if (pending === undefined && options.source !== undefined) {\n throw new Error(\n `cancelRun: operation '${opId}' cannot verify source without its admitted request`,\n )\n }\n assertRunCancellationMatchesCandidate(acknowledged, candidate)\n return acknowledged\n }\n const source = options.source ?? 'human'\n const request: RunCancelRequest = pending ?? {\n operationId: opId,\n at: new Date().toISOString(),\n source,\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n ...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),\n }\n if (pending === undefined) {\n const dir = workerCancellationsDir(eventDir)\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel request')\n mkdirSync(dir, { recursive: true })\n assertNoSymlinkDescendant(eventDir, dir, 'run cancel request')\n const file = runCancelRequestFile(eventDir)\n assertNoSymlinkDescendant(eventDir, file, 'run cancel request')\n writeAtomicDurableFile(file, `${JSON.stringify(request, null, 2)}\\n`, { mode: 0o600 })\n appendWorkerControlEvent(eventDir, 'run', {\n kind: 'run-cancel-request',\n operationId: opId,\n source,\n queued: true,\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n ...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),\n })\n }\n return {\n operationId: opId,\n effect: 'unknown',\n requestedAt: request.at,\n observedAt: request.at,\n ...(request.reason === undefined ? {} : { reason: request.reason }),\n detail: 'request queued; no runtime acknowledger has answered yet',\n }\n}\n\ntype WorkerCancelRequestCandidate = {\n readonly operationId: string\n readonly worker: string\n readonly source: string\n readonly reason?: string\n}\n\ntype RunCancelRequestCandidate = {\n readonly deadlineMs?: number\n readonly operationId: string\n readonly source: string\n readonly reason?: string\n}\n\nfunction assertSameWorkerCancelRequest(\n existing: WorkerCancelRequest,\n candidate: WorkerCancelRequestCandidate,\n): void {\n if (existing.operationId !== candidate.operationId) {\n throw new Error(`cancelWorker: operation '${candidate.operationId}' has an id collision`)\n }\n if (existing.worker !== candidate.worker) {\n throw new Error(\n `cancelWorker: operation '${candidate.operationId}' conflicts with its admitted request ` +\n `(worker '${existing.worker}' != '${candidate.worker}')`,\n )\n }\n if (existing.source !== candidate.source) {\n throw new Error(\n `cancelWorker: operation '${candidate.operationId}' conflicts with its admitted request ` +\n `(source '${existing.source}' != '${candidate.source}')`,\n )\n }\n if (existing.reason !== candidate.reason) {\n throw new Error(\n `cancelWorker: operation '${candidate.operationId}' conflicts with its admitted request ` +\n `(reason differs)`,\n )\n }\n}\n\nfunction assertWorkerCancellationMatchesCandidate(\n existing: WorkerCancellation,\n candidate: WorkerCancelRequestCandidate,\n): void {\n if (existing.worker !== candidate.worker) {\n throw new Error(\n `cancelWorker: operation '${candidate.operationId}' conflicts with its acknowledgement ` +\n `(worker '${existing.worker}' != '${candidate.worker}')`,\n )\n }\n if (existing.reason !== candidate.reason) {\n throw new Error(\n `cancelWorker: operation '${candidate.operationId}' conflicts with its acknowledgement ` +\n `(reason differs)`,\n )\n }\n}\n\nfunction assertSameRunCancelRequest(\n existing: RunCancelRequest,\n candidate: RunCancelRequestCandidate,\n): void {\n if (existing.operationId !== candidate.operationId) {\n throw new Error(`cancelRun: operation '${candidate.operationId}' has an id collision`)\n }\n if (existing.source !== candidate.source) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its admitted request ` +\n `(source '${existing.source}' != '${candidate.source}')`,\n )\n }\n if (existing.deadlineMs !== candidate.deadlineMs) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its admitted request (deadlineMs differs)`,\n )\n }\n if (existing.reason !== candidate.reason) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its admitted request ` +\n `(reason differs)`,\n )\n }\n}\n\nfunction assertRunCancellationMatchesCandidate(\n existing: RunCancellation,\n candidate: RunCancelRequestCandidate,\n): void {\n if (existing.reason !== candidate.reason) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its acknowledgement ` +\n `(reason differs)`,\n )\n }\n}\n\nfunction isRunCancelRequest(value: Partial<RunCancelRequest>): value is RunCancelRequest {\n return (\n typeof value.operationId === 'string' &&\n value.operationId.length > 0 &&\n typeof value.at === 'string' &&\n typeof value.source === 'string' &&\n (value.deadlineMs === undefined ||\n (Number.isFinite(value.deadlineMs) && value.deadlineMs >= 0)) &&\n (value.reason === undefined || typeof value.reason === 'string')\n )\n}\n\nfunction isWorkerCancelRequest(value: Partial<WorkerCancelRequest>): value is WorkerCancelRequest {\n return (\n typeof value.operationId === 'string' &&\n value.operationId.length > 0 &&\n typeof value.at === 'string' &&\n typeof value.source === 'string' &&\n typeof value.worker === 'string' &&\n value.worker.length > 0 &&\n (value.reason === undefined || typeof value.reason === 'string')\n )\n}\n\nfunction appendWorkerControlEvent(\n eventDir: string,\n label: string,\n event: Record<string, unknown>,\n): void {\n try {\n mkdirSync(supervisorWorkersDir(eventDir), { recursive: true })\n appendFileSync(\n workerControlLogFile(eventDir, label),\n `${JSON.stringify({ at: new Date().toISOString(), label, ...event })}\\n`,\n 'utf8',\n )\n } catch {\n // Control logging is best-effort; the inbox write above is the durable part.\n }\n}\n\nfunction workerSteerRequestDigest(value: {\n readonly operationId: string\n readonly worker: string\n readonly message: string\n readonly source: string\n readonly interrupt: boolean\n}): Sha256Digest {\n return canonicalCandidateDigest({ kind: 'worker-steer-request.v1', ...value })\n}\n\nfunction operationFileHash(operationId: string): string {\n const id = operationId.trim()\n if (!id) throw new Error('steer operationId is empty')\n return createHash('sha256').update(id).digest('hex')\n}\n\nfunction admitSteerRequest(\n file: string,\n request: WorkerSteerRequest,\n): { readonly request: WorkerSteerRequest; readonly replayed: boolean } {\n const existing = readWorkerSteerRequestFile(file)\n if (existing !== undefined) {\n assertSameSteerRequest(existing, request)\n return { request: existing, replayed: true }\n }\n if (publishExclusiveDurableFile(file, `${JSON.stringify(request, null, 2)}\\n`)) {\n return { request, replayed: false }\n }\n const winner = readWorkerSteerRequestFile(file)\n if (winner === undefined) {\n throw new Error('steer request publication lost its winner')\n }\n assertSameSteerRequest(winner, request)\n return { request: winner, replayed: true }\n}\n\nfunction readWorkerSteerRequest(\n eventDir: string,\n operationId: string,\n): WorkerSteerRequest | undefined {\n const file = workerSteerRequestFile(eventDir, operationId)\n assertNoSymlinkDescendant(eventDir, file, 'steer request')\n const request = readWorkerSteerRequestFile(file)\n if (request !== undefined && request.operationId !== operationId) {\n throw new Error('steer request file belongs to another operation')\n }\n return request\n}\n\nfunction readWorkerSteerRequestFile(file: string): WorkerSteerRequest | undefined {\n if (!existsSync(file)) return undefined\n return parseWorkerSteerRequest(JSON.parse(readFileSync(file, 'utf8')))\n}\n\nfunction parseWorkerSteerRequest(value: unknown): WorkerSteerRequest {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error('steer request is malformed')\n }\n const request = value as Partial<WorkerSteerRequest>\n if (\n request.schemaVersion !== 1 ||\n typeof request.operationId !== 'string' ||\n request.operationId.length === 0 ||\n typeof request.requestDigest !== 'string' ||\n typeof request.at !== 'string' ||\n typeof request.source !== 'string' ||\n request.source.length === 0 ||\n typeof request.worker !== 'string' ||\n request.worker.length === 0 ||\n typeof request.message !== 'string' ||\n request.message.trim().length === 0 ||\n typeof request.interrupt !== 'boolean'\n ) {\n throw new Error('steer request is malformed')\n }\n const exact = request as WorkerSteerRequest\n const expected = workerSteerRequestDigest({\n operationId: exact.operationId,\n worker: exact.worker,\n message: exact.message,\n source: exact.source,\n interrupt: exact.interrupt,\n })\n if (exact.requestDigest !== expected) throw new Error('steer request digest does not match')\n return exact\n}\n\nfunction parseWorkerSteerAcknowledgement(value: unknown): WorkerSteerAcknowledgement {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error('steer acknowledgement is malformed')\n }\n const record = value as Partial<WorkerSteerAcknowledgement>\n if (\n record.schemaVersion !== 1 ||\n typeof record.operationId !== 'string' ||\n record.operationId.length === 0 ||\n typeof record.requestDigest !== 'string' ||\n typeof record.worker !== 'string' ||\n record.worker.length === 0 ||\n (record.effect !== 'unknown' &&\n record.effect !== 'delivered' &&\n record.effect !== 'not_live' &&\n record.effect !== 'unsupported' &&\n record.effect !== 'refused') ||\n typeof record.requestedAt !== 'string' ||\n typeof record.observedAt !== 'string' ||\n typeof record.detail !== 'string'\n ) {\n throw new Error('steer acknowledgement is malformed')\n }\n return record as WorkerSteerAcknowledgement\n}\n\nfunction assertSameSteerRequest(existing: WorkerSteerRequest, candidate: WorkerSteerRequest): void {\n if (existing.operationId !== candidate.operationId) {\n throw new Error('steer operation file collision')\n }\n if (existing.requestDigest !== candidate.requestDigest) {\n throw new Error(\n `writeWorkerSteer: operation '${candidate.operationId}' conflicts with its admitted request`,\n )\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiNA,SAAgB,mBAAmB,SAAyB;CAC1D,OAAO,KAAK,QAAQ,OAAO,GAAG,UAAU,YAAY;AACtD;;AAGA,SAAgB,iBAAiB,SAAiB,IAAoB;CACpE,OAAO,KAAK,mBAAmB,OAAO,GAAG,EAAE;AAC7C;;;;;;AAOA,SAAgB,uBAAuB,SAAiB,IAAoB;CAC1E,OAAO,KAAK,yBAAyB,OAAO,GAAG,EAAE;AACnD;;;;;AAMA,SAAgB,yBAAyB,SAAyB;CAChE,OAAO,KAAK,QAAQ,OAAO,GAAG,UAAU,YAAY;AACtD;;AAGA,SAAgB,eAAe,OAAuB;CACpD,MAAM,OAAO,MAAM,QAAQ,oBAAoB,GAAG;CAClD,OAAO,KAAK,SAAS,IAAI,OAAO;AAClC;;AAGA,SAAgB,qBAAqB,UAA0B;CAC7D,OAAO,KAAK,UAAU,SAAS;AACjC;;AAGA,SAAgB,gBAAgB,SAAiB,cAAsB,QAAwB;CAC7F,OAAO,4BAA4B,iBAAiB,SAAS,YAAY,GAAG,MAAM;AACpF;;AAGA,SAAgB,4BAA4B,UAAkB,QAAwB;CACpF,OAAO,KAAK,qBAAqB,QAAQ,GAAG,GAAG,eAAe,MAAM,EAAE,cAAc;AACtF;;;;;;AAOA,SAAgB,qBAAqB,UAAkB,QAAwB;CAC7E,OAAO,K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