@tangle-network/agent-runtime 3.0.34 → 3.0.35

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 (48) hide show
  1. package/dist/{activation-CWOj5iZe.js → activation-B3vLJDlj.js} +2 -2
  2. package/dist/{activation-CWOj5iZe.js.map → activation-B3vLJDlj.js.map} +1 -1
  3. package/dist/agent.js +3 -3
  4. package/dist/{coordination-manager-s1hbIqXx.js → coordination-manager-CZzhPx_F.js} +4 -4
  5. package/dist/{coordination-manager-s1hbIqXx.js.map → coordination-manager-CZzhPx_F.js.map} +1 -1
  6. package/dist/{delegate-D1urT1fO.js → delegate-D0NpQF_z.js} +2 -2
  7. package/dist/{delegate-D1urT1fO.js.map → delegate-D0NpQF_z.js.map} +1 -1
  8. package/dist/durable.js +6 -6
  9. package/dist/{graph-D1lBBrG9.js → graph-BKMPvIk6.js} +5 -5
  10. package/dist/{graph-D1lBBrG9.js.map → graph-BKMPvIk6.js.map} +1 -1
  11. package/dist/{improve-CXK2GKbS.js → improve-YLCiNpX1.js} +6 -6
  12. package/dist/{improve-CXK2GKbS.js.map → improve-YLCiNpX1.js.map} +1 -1
  13. package/dist/index.js +8 -8
  14. package/dist/intelligence.js +4 -4
  15. package/dist/kernel.js +11 -11
  16. package/dist/{loop-runner-DweLgNhR.js → loop-runner-BmoENiTj.js} +2 -2
  17. package/dist/{loop-runner-DweLgNhR.js.map → loop-runner-BmoENiTj.js.map} +1 -1
  18. package/dist/loop-runner-bin.js +1 -1
  19. package/dist/mcp/bin.js +3 -3
  20. package/dist/mcp/index.js +5 -5
  21. package/dist/{provision-supervisor-B6-0_VQb.js → provision-supervisor-BqbXjSYT.js} +4 -4
  22. package/dist/{provision-supervisor-B6-0_VQb.js.map → provision-supervisor-BqbXjSYT.js.map} +1 -1
  23. package/dist/{run-cancellation-BRIB385R.js → run-cancellation-Cy8NtCtz.js} +2 -2
  24. package/dist/{run-cancellation-BRIB385R.js.map → run-cancellation-Cy8NtCtz.js.map} +1 -1
  25. package/dist/{runtime-DqTj9ahF.js → runtime-Cxlb_vie.js} +11 -11
  26. package/dist/{runtime-DqTj9ahF.js.map → runtime-Cxlb_vie.js.map} +1 -1
  27. package/dist/{scope-CCHfmCvY.js → scope-CBW-oIwP.js} +10 -2
  28. package/dist/scope-CBW-oIwP.js.map +1 -0
  29. package/dist/{search-executor-Cypg4sCQ.js → search-executor-A2dtsTlx.js} +3 -3
  30. package/dist/{search-executor-Cypg4sCQ.js.map → search-executor-A2dtsTlx.js.map} +1 -1
  31. package/dist/{server-CAxz7X8H.js → server-DINjmAT0.js} +3 -3
  32. package/dist/{server-CAxz7X8H.js.map → server-DINjmAT0.js.map} +1 -1
  33. package/dist/{structural-rollout-BS3hVAq2.js → structural-rollout-BBKSnDfB.js} +3 -3
  34. package/dist/{structural-rollout-BS3hVAq2.js.map → structural-rollout-BBKSnDfB.js.map} +1 -1
  35. package/dist/{supervise-dOLWtwyj.js → supervise-CeUM7jMe.js} +5 -5
  36. package/dist/{supervise-dOLWtwyj.js.map → supervise-CeUM7jMe.js.map} +1 -1
  37. package/dist/{supervision-discovery-DcQU64rK.js → supervision-discovery-CvXb-yDc.js} +2 -2
  38. package/dist/{supervision-discovery-DcQU64rK.js.map → supervision-discovery-CvXb-yDc.js.map} +1 -1
  39. package/dist/{supervisor-C-mx3kR8.js → supervisor-B68cSh2T.js} +11 -2
  40. package/dist/supervisor-B68cSh2T.js.map +1 -0
  41. package/dist/testing.js +11 -11
  42. package/dist/{top-web-l3naxnjo.js → top-web-C8TMsrZ6.js} +4 -4
  43. package/dist/{top-web-l3naxnjo.js.map → top-web-C8TMsrZ6.js.map} +1 -1
  44. package/dist/tui/bin.js +3 -3
  45. package/dist/tui/index.js +2 -2
  46. package/package.json +1 -1
  47. package/dist/scope-CCHfmCvY.js.map +0 -1
  48. package/dist/supervisor-C-mx3kR8.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"run-cancellation-BRIB385R.js","names":[],"sources":["../src/runtime/supervise/coordination-log.ts","../src/runtime/supervise/supervise-identity.ts","../src/runtime/supervise/run-cancellation.ts"],"sourcesContent":["/**\n * Durable side-log for coordination evidence the spawn journal does not own: questions, analyst\n * findings, answer decisions, authorized continuation receipts, delivery-attempt markers, and\n * delivery outcomes. A durable run\n * (`supervise({ runDir })`) appends them as they publish and loads them on resume, so a restarted\n * coordinator retains the exact evidence produced by prior processes.\n *\n * Answer down-events also fold status on load: a question answered before the crash reloads as\n * `answered`, not as a re-blocking `open`. Settled events are skipped (the spawn journal is their\n * ledger). A receipt followed by an attempt but no outcome proves the process died in the delivery\n * window; that outcome remains unknown and no prior instruction is auto-delivered.\n *\n * JSONL, one fsynced record per event, keyed by `runId` — several runs may share one log file\n * exactly as they share one spawn-journal file.\n *\n * @experimental\n */\n\nimport { appendCommittedJsonLine, readCommittedJsonLines } from '../../durable/jsonl-file'\nimport { captureRunWriteContext } from '../../durable/run-fence'\nimport type {\n AnalystFindingEvent,\n DefinedAnalystRecord,\n} from '../../mcp/tools/coordination-analysts'\nimport type { CoordinationEvent } from '../../mcp/tools/coordination-events'\nimport type { ContinuationInstruction } from '../../mcp/tools/coordination-messages'\nimport type {\n QuestionEscalationRecord,\n QuestionRecord,\n} from '../../mcp/tools/coordination-questions'\nimport type { BusRecord } from './event-bus'\nimport type { PeerMailEvent } from './peer-mail'\n\n/** Stable identity of the supervisor that owns one coordination stream. High-level supervision\n * derives it from the exact root/child execution identity plus its parent assignment. */\nexport type CoordinationOwnerId = string\n\n/** Durable delivery evidence retained in commit order. An attempt without a later event carrying\n * the same `receiptId` has an unknown outcome after a crash and is never replayed. */\nexport type CoordinationDeliveryEvidence = Extract<\n CoordinationEvent,\n { readonly type: 'delivery-attempt' | 'steer' | 'answer' }\n>\n\n/** Coordination evidence loaded from prior processes of one durable supervised run. */\nexport interface PriorCoordination {\n /** The owner filter used for this replay. Omitted only for the compatibility all-owner read. */\n readonly ownerId?: CoordinationOwnerId\n /** Every question the prior process raised, with answer-status folded in, raise order. */\n readonly questions: ReadonlyArray<QuestionRecord>\n /** Every analyst finding the prior process published, publish order. */\n readonly findings: ReadonlyArray<AnalystFindingEvent>\n /** Every `ask_parent` escalation the prior process made, raise order. An undelivered one names a\n * question the run raised that nothing above it received — retained so a resuming operator sees\n * it, never auto-redelivered. */\n readonly escalations: ReadonlyArray<QuestionEscalationRecord>\n /** Every lens the prior process DEFINED at run time, definition order. The exact authored bytes\n * and their digest, so an invented lens can be re-registered and any finding it produced can be\n * traced to the words that produced it. Re-registration is the owner's decision, never automatic:\n * the registry may have changed between processes. */\n readonly analystDefinitions: ReadonlyArray<DefinedAnalystRecord>\n /** Every authorized continuation, in commit order. These are evidence, never replayed to a new\n * worker automatically. */\n readonly continuations: ReadonlyArray<ContinuationInstruction>\n /** Delivery intent and result records in commit order, linked to receipts by `receiptId`. */\n readonly deliveryEvidence: ReadonlyArray<CoordinationDeliveryEvidence>\n /** Every peer-mail attempt the prior process made, delivered and refused alike, in commit order.\n * Evidence of what siblings told each other; never replayed into a new worker's inbox. */\n readonly mail: ReadonlyArray<PeerMailEvent>\n /** Exact source-bus stamps in durable append order. Bus `seq` restarts with each process; append\n * order remains the cross-process replay order. */\n readonly records: ReadonlyArray<BusRecord<CoordinationEvent>>\n}\n\n/** The durable coordination side-log seam. `append` records one bus event (kinds it does not\n * persist are ignored); `load` replays a run's prior records folded into `PriorCoordination`. */\nexport interface CoordinationLog {\n append(\n runId: string,\n record: BusRecord<CoordinationEvent>,\n ownerId?: CoordinationOwnerId,\n ): Promise<void>\n load(runId: string, ownerId?: CoordinationOwnerId): Promise<PriorCoordination>\n}\n\ntype CoordinationLogRecord = {\n readonly runId: string\n readonly ownerId?: CoordinationOwnerId\n readonly seq: number\n readonly at: number\n readonly priority: number\n readonly event: CoordinationEvent\n}\n\ntype LegacyCoordinationLogRecord = {\n readonly runId: string\n readonly ownerId?: CoordinationOwnerId\n readonly at: string\n readonly event: CoordinationEvent\n}\n\n/** Persist prior context plus exact continuation authorization, attempt, and result evidence.\n * Settlements have their own journal. */\nfunction persisted(event: CoordinationEvent): boolean {\n return event.type !== 'settled'\n}\n\n/** FS-backed `CoordinationLog`: append-only JSONL, fsynced per record. */\nexport class FileCoordinationLog implements CoordinationLog {\n private readonly writeContext = captureRunWriteContext()\n private appendTail: Promise<void> = Promise.resolve()\n\n constructor(private readonly path: string) {}\n\n async append(\n runId: string,\n record: BusRecord<CoordinationEvent>,\n ownerId?: CoordinationOwnerId,\n ): Promise<void> {\n if (!persisted(record.event)) return\n const append = this.appendTail.then(() =>\n this.writeContext(() => this.appendRecord(runId, record, ownerId)),\n )\n this.appendTail = append.catch(() => undefined)\n return append\n }\n\n private async appendRecord(\n runId: string,\n busRecord: BusRecord<CoordinationEvent>,\n ownerId?: CoordinationOwnerId,\n ): Promise<void> {\n const fs = await import('node:fs/promises')\n const { dirname } = await import('node:path')\n await fs.mkdir(dirname(this.path), { recursive: true })\n const record: CoordinationLogRecord = {\n runId,\n ...(ownerId !== undefined ? { ownerId } : {}),\n ...busRecord,\n }\n await appendCommittedJsonLine(this.path, record)\n }\n\n async load(runId: string, ownerId?: CoordinationOwnerId): Promise<PriorCoordination> {\n return foldCoordinationRecords(\n readCommittedJsonLines<CoordinationLogRecord | LegacyCoordinationLogRecord>(this.path, {\n allowMissing: true,\n }),\n runId,\n ownerId,\n )\n }\n}\n\n/** @internal Shared replay semantics for file and SQL coordination evidence. */\nexport async function foldCoordinationRecords(\n source:\n | Iterable<CoordinationLogRecord | LegacyCoordinationLogRecord>\n | AsyncIterable<CoordinationLogRecord | LegacyCoordinationLogRecord>,\n runId: string,\n ownerId?: CoordinationOwnerId,\n): Promise<PriorCoordination> {\n const byId = new Map<string, QuestionRecord>()\n const findings: AnalystFindingEvent[] = []\n const escalations: QuestionEscalationRecord[] = []\n const analystDefinitions: DefinedAnalystRecord[] = []\n const continuations: ContinuationInstruction[] = []\n const deliveryEvidence: CoordinationDeliveryEvidence[] = []\n const mail: PeerMailEvent[] = []\n const records: BusRecord<CoordinationEvent>[] = []\n let legacySeq = 0\n for await (const stored of source) {\n if (stored.runId !== runId) continue\n // Omitting ownerId preserves the historical all-run read for direct consumers. Runtime always\n // supplies one, so root and nested supervisors never receive one another's evidence.\n if (ownerId !== undefined && stored.ownerId !== ownerId) continue\n const record: BusRecord<CoordinationEvent> =\n 'seq' in stored\n ? {\n seq: stored.seq,\n at: stored.at,\n priority: stored.priority,\n event: stored.event,\n }\n : {\n seq: legacySeq++,\n at: Date.parse(stored.at),\n priority: 0,\n event: stored.event,\n }\n records.push(record)\n const ev = record.event\n if (ev.type === 'delivery-attempt' || ev.type === 'steer' || ev.type === 'answer') {\n deliveryEvidence.push(ev)\n }\n if (ev.type === 'question') {\n byId.set(ev.question.id, ev.question)\n } else if (ev.type === 'finding') {\n findings.push(ev.finding)\n } else if (ev.type === 'answer') {\n // Only accepted delivery resolves a blocking question. Authorization and an attempted\n // refusal remain evidence, but cannot turn \"worker never received the answer\" into answered\n // state on replay. `by` is not on the wire; prior-run is the honest attribution.\n const prior = byId.get(ev.questionId)\n if (prior && ev.down.delivered) {\n byId.set(ev.questionId, {\n ...prior,\n status: 'answered',\n decision: { kind: 'answer', answer: ev.down.instruction, by: 'prior-run' },\n })\n }\n } else if (ev.type === 'instruction') {\n continuations.push(ev.instruction)\n } else if (ev.type === 'mail') {\n mail.push(ev.mail)\n } else if (ev.type === 'escalation') {\n escalations.push(ev.escalation)\n } else if (ev.type === 'analyst-defined') {\n analystDefinitions.push(ev.analyst)\n }\n }\n return {\n ...(ownerId !== undefined ? { ownerId } : {}),\n questions: [...byId.values()],\n findings,\n escalations,\n analystDefinitions,\n continuations,\n deliveryEvidence,\n mail,\n records,\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport { resolve } from 'node:path'\nimport {\n type AgentProfile,\n agentProfileSchema,\n canonicalCandidateDigest,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { ValidationError } from '../../errors'\nimport type { WorkerSpawnContext } from '../../mcp/tools/coordination-contracts'\nimport type { CoordinationEvent } from '../../mcp/tools/coordination-events'\nimport { deriveNodeExecutionIdentity } from './scope'\nimport { detachedSnapshot } from './snapshot'\nimport type { SupervisorNodeContext } from './supervisor-agent'\nimport type { AgentExecutionRef, NodeExecutionIdentity } from './types'\n\nexport function externalExecutionId(kind: string, identity: unknown): string {\n const digest = canonicalCandidateDigest({ kind, identity })\n return `${kind}-${digest.slice('sha256:'.length)}`\n}\n\nexport function freezeDetached<T>(value: T): T {\n return detachedSnapshot(value, 'supervise')\n}\n\nexport function freezeDetachedProfile(value: unknown): AgentProfile {\n return freezeDetached(agentProfileSchema.parse(value))\n}\n\nexport function canonicalExecution(\n profile: AgentProfile,\n task: unknown,\n rawExecution: AgentExecutionRef | undefined,\n context: string,\n): { readonly identity: NodeExecutionIdentity; readonly ref?: AgentExecutionRef } {\n const execution = rawExecution === undefined ? undefined : freezeDetached(rawExecution)\n if (execution !== undefined) {\n if (typeof execution !== 'object' || execution === null || Array.isArray(execution)) {\n throw new ValidationError(`${context}: execution must be an object`)\n }\n const unknown = Object.keys(execution).filter(\n (key) => key !== 'candidateDigest' && key !== 'correlation',\n )\n if (unknown.length > 0) {\n throw new ValidationError(`${context}: unknown execution fields: ${unknown.join(', ')}`)\n }\n }\n const identity = deriveNodeExecutionIdentity({ profile, execution }, task)\n if (!identity?.profileDigest || !identity.taskDigest) {\n throw new ValidationError(\n `${context}: profile and task must be finite, acyclic canonical JSON for durable identity`,\n )\n }\n const ref: AgentExecutionRef | undefined =\n identity.candidateDigest || identity.correlation\n ? Object.freeze({\n ...(identity.candidateDigest ? { candidateDigest: identity.candidateDigest } : {}),\n ...(identity.correlation ? { correlation: identity.correlation } : {}),\n })\n : undefined\n return { identity, ...(ref ? { ref } : {}) }\n}\n\nexport function rootCoordinationOwner(identity: NodeExecutionIdentity): string {\n return canonicalCandidateDigest({ kind: 'supervisor-root', identity })\n}\n\nexport function childCoordinationOwner(\n parentOwnerId: string,\n identity: NodeExecutionIdentity,\n context: WorkerSpawnContext,\n depth: number,\n): string {\n return canonicalCandidateDigest({\n kind: 'supervisor-child',\n parentOwnerId,\n identity,\n assignment: {\n id: context.assignmentId,\n label: context.label,\n key: context.key ?? null,\n depth,\n },\n })\n}\n\nexport function supervisionRunNamespace(runDir: string | undefined, runId: string): string {\n return canonicalCandidateDigest(\n runDir === undefined\n ? { kind: 'supervise-ephemeral-run', runId, nonce: randomUUID() }\n : { kind: 'supervise-durable-run', runId, runDir: resolve(runDir) },\n )\n}\n\nexport function workerAssignmentNamespace(\n runNamespace: string,\n parentOwnerId: string,\n assignmentId: string,\n): string {\n return canonicalCandidateDigest({\n kind: 'supervise-worker-assignment',\n runNamespace,\n parentOwnerId,\n assignmentId,\n })\n}\n\n/** Hash only durable coordination meaning. Bus sequence/timestamp are delivery metadata and a\n * resumed projection's marker describes the reader, not the original settlement. */\nexport function coordinationEventId(\n context: SupervisorNodeContext,\n event: CoordinationEvent,\n): Sha256Digest {\n const durableEvent =\n event.type === 'settled' && event.worker.resumed === true\n ? (() => {\n const { resumed: _resumed, ...worker } = event.worker\n return { type: 'settled' as const, worker }\n })()\n : event\n return canonicalCandidateDigest({\n kind: 'supervise-coordination-event',\n runNamespace: context.runNamespace,\n ownerId: context.ownerId,\n event: detachedSnapshot(durableEvent, 'supervise coordination event identity'),\n })\n}\n","import { existsSync, mkdirSync, readFileSync, watch } from 'node:fs'\nimport { join } from 'node:path'\nimport type { RetainedRunEffect } from '../retained-run-types'\nimport { assertNoSymlinkDescendant, writeAtomicDurableFile } from './durable-file'\nimport { appendWorkerControlEvent, workerCancellationsDir } from './run-layout'\n\n/** Apply a durable request through the run's existing abort controller. */\nexport function applyRunCancellation(\n dir: string,\n abortRun: (reason: string, request?: RunCancelRequest) => void,\n now: () => string,\n path: 'observer' | 'turn-boundary' | 'fallback' = 'turn-boundary',\n): RunCancellation | undefined {\n const request = readRunCancelRequest(dir)\n if (request === undefined) return undefined\n const prior = readRunCancellation(dir, request.operationId)\n // A request acknowledged only as `cancel_requested` is still owed by this run: the process\n // that issued the abort died before the run settled. Abort again; the record stands.\n if (prior?.effect === 'cancel_requested') {\n abortRun(request.reason ?? 'run cancel requested', request)\n }\n if (prior !== undefined) return prior\n abortRun(request.reason ?? 'run cancel requested', request)\n const observedAt = now()\n const appliedAfterMs = Math.max(0, Date.parse(observedAt) - Date.parse(request.at))\n const record: RunCancellation = {\n operationId: request.operationId,\n effect: 'cancel_requested',\n path,\n appliedAfterMs,\n ...(request.deadlineMs === undefined\n ? {}\n : { deadlineExceeded: appliedAfterMs > request.deadlineMs }),\n requestedAt: request.at,\n observedAt,\n ...(request.reason === undefined ? {} : { reason: request.reason }),\n ...(request.operator === undefined ? {} : { operator: request.operator }),\n detail: 'root abort issued to the whole run; termination not yet proven',\n }\n writeRunCancellation(dir, record)\n return record\n}\n\n/** External drivers may remain silent indefinitely, so turn boundaries cannot observe control. */\nexport function watchRunCancellation(\n dir: string,\n abortRun: (reason: string, request?: RunCancelRequest) => void,\n createWatch: typeof watch = watch,\n) {\n mkdirSync(workerCancellationsDir(dir), { recursive: true })\n let active = true\n let failure: unknown\n // One observer aborts its run once: a request this process already applied, or one a dead\n // process acknowledged, is not re-issued on every poll.\n let aborted = false\n const abortOnce = (reason: string, request?: RunCancelRequest): void => {\n if (aborted) return\n aborted = true\n abortRun(reason, request)\n }\n const check = (path: 'observer' | 'fallback' = 'observer'): void => {\n if (failure !== undefined) throw failure\n if (active) applyRunCancellation(dir, abortOnce, () => new Date().toISOString(), path)\n }\n const fail = (error: unknown): void => {\n if (!active) return\n failure = error\n abortRun(`durable run cancellation observer failed: ${String(error)}`)\n }\n // The watcher is an optimization over the poll loop below (instant pickup instead of ≤100 ms).\n // Creating it can fail for reasons that say NOTHING about this run: the host's inotify budget is\n // exhausted (EMFILE — a shared box with many agents held ~110 of the 128 default user instances\n // when this was measured), or the kernel caps watches (ENOSPC). Degrading to poll-only keeps\n // every durable behavior; failing the run would make a neighboring process's resource use kill\n // runs that never touched the limit. Any other creation error still fails loudly.\n let watcher: ReturnType<typeof watch> | undefined\n try {\n watcher = createWatch(workerCancellationsDir(dir), (_event, filename) => {\n if (!active || (filename !== null && filename !== 'run.request.json')) return\n try {\n check()\n } catch (error) {\n fail(error)\n }\n })\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code !== 'EMFILE' && code !== 'ENOSPC') throw error\n }\n watcher?.on('error', fail)\n // Filesystem notifications are advisory. Scan the same durable inbox when one is dropped —\n // and carry the whole observer alone whenever the watcher above could not be created.\n const fallback = setInterval(() => {\n try {\n check('fallback')\n } catch (error) {\n fail(error)\n }\n }, 100)\n fallback.unref()\n return {\n check,\n close(): void {\n active = false\n watcher?.close()\n clearInterval(fallback)\n },\n }\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 /** Who stops the run. `cancelRun` requires it on every new request; it is optional here only\n * so a request written before that rule still reads. The settle record carries it. */\n readonly operator?: string\n readonly reason?: string\n}\n\n/**\n * The durable acknowledgement state for the run-scoped cancel operation, keyed by `operationId`.\n * The runtime is the ONLY writer; {@link cancelRun} only reads it.\n *\n * `effect` is the same {@link RetainedRunEffect} vocabulary the worker-scoped and retained-run\n * paths use, so the runtime has one spelling of the four cancellation states:\n * - `'unknown'` — no runtime has answered yet. Never a success.\n * - `'cancel_requested'` — the root manager issued the run's cascading abort; the run's terminal\n * state is not yet observed.\n * - `'cancelled'` — the run reached its terminal 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 caller's operator identity, carried verbatim from the request. */\n readonly operator?: string\n /** The runtime's explanation of how it arrived at `effect`. */\n readonly detail?: string\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, reason, deadline, or operator\n * fails closed. A request the runtime has not answered yet returns `effect: 'unknown'` (never a\n * success); call again with the same `operationId` — or {@link readRunCancellation} — to read the\n * acknowledged result after a reconnect.\n *\n * A run carries ONE run-scoped operation: a second request under a different `operationId` throws\n * rather than silently replacing the pending one, because both would claim the same single abort.\n * Reopening a settled run (`supervisePursuit`'s `reopen`) moves that operation aside.\n *\n * A NEW request must name its `operator`, so every stop says who made it. A replay of a request\n * or acknowledgement written before that rule is answered as it was.\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 readonly operator?: string\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 ...(options.operator === undefined ? {} : { operator: options.operator }),\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 // A new request names who stops the run. A replay of a request written before this rule keeps\n // its absent operator: it was admitted above against the file it replays.\n if (pending === undefined && (options.operator === undefined || options.operator.trim() === '')) {\n throw new Error('cancelRun: operator is required; name who stops the run')\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 ...(options.operator === undefined ? {} : { operator: options.operator }),\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 ...(options.operator === undefined ? {} : { operator: options.operator }),\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 ...(request.operator === undefined ? {} : { operator: request.operator }),\n detail: 'request queued; no runtime acknowledger has answered yet',\n }\n}\n\ntype RunCancelRequestCandidate = Omit<RunCancelRequest, 'at'>\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 if (existing.operator !== candidate.operator) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its admitted request ` +\n `(operator '${existing.operator}' != '${candidate.operator}')`,\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 // An acknowledgement written before acknowledgements carried the operator (0.251.0) names none\n // even when its admitted request does. The request comparator has already held the candidate\n // to that request, so a legacy record matches any candidate operator; a record that names one\n // must name the same one.\n if (existing.operator !== undefined && existing.operator !== candidate.operator) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its acknowledgement ` +\n `(operator '${existing.operator}' != '${candidate.operator}')`,\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 (value.operator === undefined || typeof value.operator === 'string')\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuGA,SAAS,UAAU,OAAmC;CACpD,OAAO,MAAM,SAAS;AACxB;;AAGA,IAAa,sBAAb,MAA4D;CAI7B;CAH7B,eAAgC,uBAAuB;CACvD,aAAoC,QAAQ,QAAQ;CAEpD,YAAY,MAA+B;EAAd,KAAA,OAAA;CAAe;CAE5C,MAAM,OACJ,OACA,QACA,SACe;EACf,IAAI,CAAC,UAAU,OAAO,KAAK,GAAG;EAC9B,MAAM,SAAS,KAAK,WAAW,WAC7B,KAAK,mBAAmB,KAAK,aAAa,OAAO,QAAQ,OAAO,CAAC,CACnE;EACA,KAAK,aAAa,OAAO,YAAY,KAAA,CAAS;EAC9C,OAAO;CACT;CAEA,MAAc,aACZ,OACA,WACA,SACe;EACf,MAAM,KAAK,MAAM,OAAO;EACxB,MAAM,EAAE,YAAY,MAAM,OAAO;EACjC,MAAM,GAAG,MAAM,QAAQ,KAAK,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;EACtD,MAAM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MF,IAAI,SAAS,aAAa,KAAA,KAAa,SAAS,aAAa,UAAU,UACrE,MAAM,IAAI,MACR,yBAAyB,UAAU,YAAY,kDAC/B,SAAS,SAAS,QAAQ,UAAU,SAAS,GAC/D;AAEJ;AAEA,SAAS,mBAAmB,OAA6D;CACvF,OACE,OAAO,MAAM,gBAAgB,YAC7B,MAAM,YAAY,SAAS,KAC3B,OAAO,MAAM,OAAO,YACpB,OAAO,MAAM,WAAW,aACvB,MAAM,eAAe,KAAA,KACnB,OAAO,SAAS,MAAM,UAAU,KAAK,MAAM,cAAc,OAC3D,MAAM,WAAW,KAAA,KAAa,OAAO,MAAM,WAAW,cACtD,MAAM,aAAa,KAAA,KAAa,OAAO,MAAM,aAAa;AAE/D"}
1
+ {"version":3,"file":"run-cancellation-Cy8NtCtz.js","names":[],"sources":["../src/runtime/supervise/coordination-log.ts","../src/runtime/supervise/supervise-identity.ts","../src/runtime/supervise/run-cancellation.ts"],"sourcesContent":["/**\n * Durable side-log for coordination evidence the spawn journal does not own: questions, analyst\n * findings, answer decisions, authorized continuation receipts, delivery-attempt markers, and\n * delivery outcomes. A durable run\n * (`supervise({ runDir })`) appends them as they publish and loads them on resume, so a restarted\n * coordinator retains the exact evidence produced by prior processes.\n *\n * Answer down-events also fold status on load: a question answered before the crash reloads as\n * `answered`, not as a re-blocking `open`. Settled events are skipped (the spawn journal is their\n * ledger). A receipt followed by an attempt but no outcome proves the process died in the delivery\n * window; that outcome remains unknown and no prior instruction is auto-delivered.\n *\n * JSONL, one fsynced record per event, keyed by `runId` — several runs may share one log file\n * exactly as they share one spawn-journal file.\n *\n * @experimental\n */\n\nimport { appendCommittedJsonLine, readCommittedJsonLines } from '../../durable/jsonl-file'\nimport { captureRunWriteContext } from '../../durable/run-fence'\nimport type {\n AnalystFindingEvent,\n DefinedAnalystRecord,\n} from '../../mcp/tools/coordination-analysts'\nimport type { CoordinationEvent } from '../../mcp/tools/coordination-events'\nimport type { ContinuationInstruction } from '../../mcp/tools/coordination-messages'\nimport type {\n QuestionEscalationRecord,\n QuestionRecord,\n} from '../../mcp/tools/coordination-questions'\nimport type { BusRecord } from './event-bus'\nimport type { PeerMailEvent } from './peer-mail'\n\n/** Stable identity of the supervisor that owns one coordination stream. High-level supervision\n * derives it from the exact root/child execution identity plus its parent assignment. */\nexport type CoordinationOwnerId = string\n\n/** Durable delivery evidence retained in commit order. An attempt without a later event carrying\n * the same `receiptId` has an unknown outcome after a crash and is never replayed. */\nexport type CoordinationDeliveryEvidence = Extract<\n CoordinationEvent,\n { readonly type: 'delivery-attempt' | 'steer' | 'answer' }\n>\n\n/** Coordination evidence loaded from prior processes of one durable supervised run. */\nexport interface PriorCoordination {\n /** The owner filter used for this replay. Omitted only for the compatibility all-owner read. */\n readonly ownerId?: CoordinationOwnerId\n /** Every question the prior process raised, with answer-status folded in, raise order. */\n readonly questions: ReadonlyArray<QuestionRecord>\n /** Every analyst finding the prior process published, publish order. */\n readonly findings: ReadonlyArray<AnalystFindingEvent>\n /** Every `ask_parent` escalation the prior process made, raise order. An undelivered one names a\n * question the run raised that nothing above it received — retained so a resuming operator sees\n * it, never auto-redelivered. */\n readonly escalations: ReadonlyArray<QuestionEscalationRecord>\n /** Every lens the prior process DEFINED at run time, definition order. The exact authored bytes\n * and their digest, so an invented lens can be re-registered and any finding it produced can be\n * traced to the words that produced it. Re-registration is the owner's decision, never automatic:\n * the registry may have changed between processes. */\n readonly analystDefinitions: ReadonlyArray<DefinedAnalystRecord>\n /** Every authorized continuation, in commit order. These are evidence, never replayed to a new\n * worker automatically. */\n readonly continuations: ReadonlyArray<ContinuationInstruction>\n /** Delivery intent and result records in commit order, linked to receipts by `receiptId`. */\n readonly deliveryEvidence: ReadonlyArray<CoordinationDeliveryEvidence>\n /** Every peer-mail attempt the prior process made, delivered and refused alike, in commit order.\n * Evidence of what siblings told each other; never replayed into a new worker's inbox. */\n readonly mail: ReadonlyArray<PeerMailEvent>\n /** Exact source-bus stamps in durable append order. Bus `seq` restarts with each process; append\n * order remains the cross-process replay order. */\n readonly records: ReadonlyArray<BusRecord<CoordinationEvent>>\n}\n\n/** The durable coordination side-log seam. `append` records one bus event (kinds it does not\n * persist are ignored); `load` replays a run's prior records folded into `PriorCoordination`. */\nexport interface CoordinationLog {\n append(\n runId: string,\n record: BusRecord<CoordinationEvent>,\n ownerId?: CoordinationOwnerId,\n ): Promise<void>\n load(runId: string, ownerId?: CoordinationOwnerId): Promise<PriorCoordination>\n}\n\ntype CoordinationLogRecord = {\n readonly runId: string\n readonly ownerId?: CoordinationOwnerId\n readonly seq: number\n readonly at: number\n readonly priority: number\n readonly event: CoordinationEvent\n}\n\ntype LegacyCoordinationLogRecord = {\n readonly runId: string\n readonly ownerId?: CoordinationOwnerId\n readonly at: string\n readonly event: CoordinationEvent\n}\n\n/** Persist prior context plus exact continuation authorization, attempt, and result evidence.\n * Settlements have their own journal. */\nfunction persisted(event: CoordinationEvent): boolean {\n return event.type !== 'settled'\n}\n\n/** FS-backed `CoordinationLog`: append-only JSONL, fsynced per record. */\nexport class FileCoordinationLog implements CoordinationLog {\n private readonly writeContext = captureRunWriteContext()\n private appendTail: Promise<void> = Promise.resolve()\n\n constructor(private readonly path: string) {}\n\n async append(\n runId: string,\n record: BusRecord<CoordinationEvent>,\n ownerId?: CoordinationOwnerId,\n ): Promise<void> {\n if (!persisted(record.event)) return\n const append = this.appendTail.then(() =>\n this.writeContext(() => this.appendRecord(runId, record, ownerId)),\n )\n this.appendTail = append.catch(() => undefined)\n return append\n }\n\n private async appendRecord(\n runId: string,\n busRecord: BusRecord<CoordinationEvent>,\n ownerId?: CoordinationOwnerId,\n ): Promise<void> {\n const fs = await import('node:fs/promises')\n const { dirname } = await import('node:path')\n await fs.mkdir(dirname(this.path), { recursive: true })\n const record: CoordinationLogRecord = {\n runId,\n ...(ownerId !== undefined ? { ownerId } : {}),\n ...busRecord,\n }\n await appendCommittedJsonLine(this.path, record)\n }\n\n async load(runId: string, ownerId?: CoordinationOwnerId): Promise<PriorCoordination> {\n return foldCoordinationRecords(\n readCommittedJsonLines<CoordinationLogRecord | LegacyCoordinationLogRecord>(this.path, {\n allowMissing: true,\n }),\n runId,\n ownerId,\n )\n }\n}\n\n/** @internal Shared replay semantics for file and SQL coordination evidence. */\nexport async function foldCoordinationRecords(\n source:\n | Iterable<CoordinationLogRecord | LegacyCoordinationLogRecord>\n | AsyncIterable<CoordinationLogRecord | LegacyCoordinationLogRecord>,\n runId: string,\n ownerId?: CoordinationOwnerId,\n): Promise<PriorCoordination> {\n const byId = new Map<string, QuestionRecord>()\n const findings: AnalystFindingEvent[] = []\n const escalations: QuestionEscalationRecord[] = []\n const analystDefinitions: DefinedAnalystRecord[] = []\n const continuations: ContinuationInstruction[] = []\n const deliveryEvidence: CoordinationDeliveryEvidence[] = []\n const mail: PeerMailEvent[] = []\n const records: BusRecord<CoordinationEvent>[] = []\n let legacySeq = 0\n for await (const stored of source) {\n if (stored.runId !== runId) continue\n // Omitting ownerId preserves the historical all-run read for direct consumers. Runtime always\n // supplies one, so root and nested supervisors never receive one another's evidence.\n if (ownerId !== undefined && stored.ownerId !== ownerId) continue\n const record: BusRecord<CoordinationEvent> =\n 'seq' in stored\n ? {\n seq: stored.seq,\n at: stored.at,\n priority: stored.priority,\n event: stored.event,\n }\n : {\n seq: legacySeq++,\n at: Date.parse(stored.at),\n priority: 0,\n event: stored.event,\n }\n records.push(record)\n const ev = record.event\n if (ev.type === 'delivery-attempt' || ev.type === 'steer' || ev.type === 'answer') {\n deliveryEvidence.push(ev)\n }\n if (ev.type === 'question') {\n byId.set(ev.question.id, ev.question)\n } else if (ev.type === 'finding') {\n findings.push(ev.finding)\n } else if (ev.type === 'answer') {\n // Only accepted delivery resolves a blocking question. Authorization and an attempted\n // refusal remain evidence, but cannot turn \"worker never received the answer\" into answered\n // state on replay. `by` is not on the wire; prior-run is the honest attribution.\n const prior = byId.get(ev.questionId)\n if (prior && ev.down.delivered) {\n byId.set(ev.questionId, {\n ...prior,\n status: 'answered',\n decision: { kind: 'answer', answer: ev.down.instruction, by: 'prior-run' },\n })\n }\n } else if (ev.type === 'instruction') {\n continuations.push(ev.instruction)\n } else if (ev.type === 'mail') {\n mail.push(ev.mail)\n } else if (ev.type === 'escalation') {\n escalations.push(ev.escalation)\n } else if (ev.type === 'analyst-defined') {\n analystDefinitions.push(ev.analyst)\n }\n }\n return {\n ...(ownerId !== undefined ? { ownerId } : {}),\n questions: [...byId.values()],\n findings,\n escalations,\n analystDefinitions,\n continuations,\n deliveryEvidence,\n mail,\n records,\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport { resolve } from 'node:path'\nimport {\n type AgentProfile,\n agentProfileSchema,\n canonicalCandidateDigest,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { ValidationError } from '../../errors'\nimport type { WorkerSpawnContext } from '../../mcp/tools/coordination-contracts'\nimport type { CoordinationEvent } from '../../mcp/tools/coordination-events'\nimport { deriveNodeExecutionIdentity } from './scope'\nimport { detachedSnapshot } from './snapshot'\nimport type { SupervisorNodeContext } from './supervisor-agent'\nimport type { AgentExecutionRef, NodeExecutionIdentity } from './types'\n\nexport function externalExecutionId(kind: string, identity: unknown): string {\n const digest = canonicalCandidateDigest({ kind, identity })\n return `${kind}-${digest.slice('sha256:'.length)}`\n}\n\nexport function freezeDetached<T>(value: T): T {\n return detachedSnapshot(value, 'supervise')\n}\n\nexport function freezeDetachedProfile(value: unknown): AgentProfile {\n return freezeDetached(agentProfileSchema.parse(value))\n}\n\nexport function canonicalExecution(\n profile: AgentProfile,\n task: unknown,\n rawExecution: AgentExecutionRef | undefined,\n context: string,\n): { readonly identity: NodeExecutionIdentity; readonly ref?: AgentExecutionRef } {\n const execution = rawExecution === undefined ? undefined : freezeDetached(rawExecution)\n if (execution !== undefined) {\n if (typeof execution !== 'object' || execution === null || Array.isArray(execution)) {\n throw new ValidationError(`${context}: execution must be an object`)\n }\n const unknown = Object.keys(execution).filter(\n (key) => key !== 'candidateDigest' && key !== 'correlation',\n )\n if (unknown.length > 0) {\n throw new ValidationError(`${context}: unknown execution fields: ${unknown.join(', ')}`)\n }\n }\n const identity = deriveNodeExecutionIdentity({ profile, execution }, task)\n if (!identity?.profileDigest || !identity.taskDigest) {\n throw new ValidationError(\n `${context}: profile and task must be finite, acyclic canonical JSON for durable identity`,\n )\n }\n const ref: AgentExecutionRef | undefined =\n identity.candidateDigest || identity.correlation\n ? Object.freeze({\n ...(identity.candidateDigest ? { candidateDigest: identity.candidateDigest } : {}),\n ...(identity.correlation ? { correlation: identity.correlation } : {}),\n })\n : undefined\n return { identity, ...(ref ? { ref } : {}) }\n}\n\nexport function rootCoordinationOwner(identity: NodeExecutionIdentity): string {\n return canonicalCandidateDigest({ kind: 'supervisor-root', identity })\n}\n\nexport function childCoordinationOwner(\n parentOwnerId: string,\n identity: NodeExecutionIdentity,\n context: WorkerSpawnContext,\n depth: number,\n): string {\n return canonicalCandidateDigest({\n kind: 'supervisor-child',\n parentOwnerId,\n identity,\n assignment: {\n id: context.assignmentId,\n label: context.label,\n key: context.key ?? null,\n depth,\n },\n })\n}\n\nexport function supervisionRunNamespace(runDir: string | undefined, runId: string): string {\n return canonicalCandidateDigest(\n runDir === undefined\n ? { kind: 'supervise-ephemeral-run', runId, nonce: randomUUID() }\n : { kind: 'supervise-durable-run', runId, runDir: resolve(runDir) },\n )\n}\n\nexport function workerAssignmentNamespace(\n runNamespace: string,\n parentOwnerId: string,\n assignmentId: string,\n): string {\n return canonicalCandidateDigest({\n kind: 'supervise-worker-assignment',\n runNamespace,\n parentOwnerId,\n assignmentId,\n })\n}\n\n/** Hash only durable coordination meaning. Bus sequence/timestamp are delivery metadata and a\n * resumed projection's marker describes the reader, not the original settlement. */\nexport function coordinationEventId(\n context: SupervisorNodeContext,\n event: CoordinationEvent,\n): Sha256Digest {\n const durableEvent =\n event.type === 'settled' && event.worker.resumed === true\n ? (() => {\n const { resumed: _resumed, ...worker } = event.worker\n return { type: 'settled' as const, worker }\n })()\n : event\n return canonicalCandidateDigest({\n kind: 'supervise-coordination-event',\n runNamespace: context.runNamespace,\n ownerId: context.ownerId,\n event: detachedSnapshot(durableEvent, 'supervise coordination event identity'),\n })\n}\n","import { existsSync, mkdirSync, readFileSync, watch } from 'node:fs'\nimport { join } from 'node:path'\nimport type { RetainedRunEffect } from '../retained-run-types'\nimport { assertNoSymlinkDescendant, writeAtomicDurableFile } from './durable-file'\nimport { appendWorkerControlEvent, workerCancellationsDir } from './run-layout'\n\n/** Apply a durable request through the run's existing abort controller. */\nexport function applyRunCancellation(\n dir: string,\n abortRun: (reason: string, request?: RunCancelRequest) => void,\n now: () => string,\n path: 'observer' | 'turn-boundary' | 'fallback' = 'turn-boundary',\n): RunCancellation | undefined {\n const request = readRunCancelRequest(dir)\n if (request === undefined) return undefined\n const prior = readRunCancellation(dir, request.operationId)\n // A request acknowledged only as `cancel_requested` is still owed by this run: the process\n // that issued the abort died before the run settled. Abort again; the record stands.\n if (prior?.effect === 'cancel_requested') {\n abortRun(request.reason ?? 'run cancel requested', request)\n }\n if (prior !== undefined) return prior\n abortRun(request.reason ?? 'run cancel requested', request)\n const observedAt = now()\n const appliedAfterMs = Math.max(0, Date.parse(observedAt) - Date.parse(request.at))\n const record: RunCancellation = {\n operationId: request.operationId,\n effect: 'cancel_requested',\n path,\n appliedAfterMs,\n ...(request.deadlineMs === undefined\n ? {}\n : { deadlineExceeded: appliedAfterMs > request.deadlineMs }),\n requestedAt: request.at,\n observedAt,\n ...(request.reason === undefined ? {} : { reason: request.reason }),\n ...(request.operator === undefined ? {} : { operator: request.operator }),\n detail: 'root abort issued to the whole run; termination not yet proven',\n }\n writeRunCancellation(dir, record)\n return record\n}\n\n/** External drivers may remain silent indefinitely, so turn boundaries cannot observe control. */\nexport function watchRunCancellation(\n dir: string,\n abortRun: (reason: string, request?: RunCancelRequest) => void,\n createWatch: typeof watch = watch,\n) {\n mkdirSync(workerCancellationsDir(dir), { recursive: true })\n let active = true\n let failure: unknown\n // One observer aborts its run once: a request this process already applied, or one a dead\n // process acknowledged, is not re-issued on every poll.\n let aborted = false\n const abortOnce = (reason: string, request?: RunCancelRequest): void => {\n if (aborted) return\n aborted = true\n abortRun(reason, request)\n }\n const check = (path: 'observer' | 'fallback' = 'observer'): void => {\n if (failure !== undefined) throw failure\n if (active) applyRunCancellation(dir, abortOnce, () => new Date().toISOString(), path)\n }\n const fail = (error: unknown): void => {\n if (!active) return\n failure = error\n abortRun(`durable run cancellation observer failed: ${String(error)}`)\n }\n // The watcher is an optimization over the poll loop below (instant pickup instead of ≤100 ms).\n // Creating it can fail for reasons that say NOTHING about this run: the host's inotify budget is\n // exhausted (EMFILE — a shared box with many agents held ~110 of the 128 default user instances\n // when this was measured), or the kernel caps watches (ENOSPC). Degrading to poll-only keeps\n // every durable behavior; failing the run would make a neighboring process's resource use kill\n // runs that never touched the limit. Any other creation error still fails loudly.\n let watcher: ReturnType<typeof watch> | undefined\n try {\n watcher = createWatch(workerCancellationsDir(dir), (_event, filename) => {\n if (!active || (filename !== null && filename !== 'run.request.json')) return\n try {\n check()\n } catch (error) {\n fail(error)\n }\n })\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code !== 'EMFILE' && code !== 'ENOSPC') throw error\n }\n watcher?.on('error', fail)\n // Filesystem notifications are advisory. Scan the same durable inbox when one is dropped —\n // and carry the whole observer alone whenever the watcher above could not be created.\n const fallback = setInterval(() => {\n try {\n check('fallback')\n } catch (error) {\n fail(error)\n }\n }, 100)\n fallback.unref()\n return {\n check,\n close(): void {\n active = false\n watcher?.close()\n clearInterval(fallback)\n },\n }\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 /** Who stops the run. `cancelRun` requires it on every new request; it is optional here only\n * so a request written before that rule still reads. The settle record carries it. */\n readonly operator?: string\n readonly reason?: string\n}\n\n/**\n * The durable acknowledgement state for the run-scoped cancel operation, keyed by `operationId`.\n * The runtime is the ONLY writer; {@link cancelRun} only reads it.\n *\n * `effect` is the same {@link RetainedRunEffect} vocabulary the worker-scoped and retained-run\n * paths use, so the runtime has one spelling of the four cancellation states:\n * - `'unknown'` — no runtime has answered yet. Never a success.\n * - `'cancel_requested'` — the root manager issued the run's cascading abort; the run's terminal\n * state is not yet observed.\n * - `'cancelled'` — the run reached its terminal 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 caller's operator identity, carried verbatim from the request. */\n readonly operator?: string\n /** The runtime's explanation of how it arrived at `effect`. */\n readonly detail?: string\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, reason, deadline, or operator\n * fails closed. A request the runtime has not answered yet returns `effect: 'unknown'` (never a\n * success); call again with the same `operationId` — or {@link readRunCancellation} — to read the\n * acknowledged result after a reconnect.\n *\n * A run carries ONE run-scoped operation: a second request under a different `operationId` throws\n * rather than silently replacing the pending one, because both would claim the same single abort.\n * Reopening a settled run (`supervisePursuit`'s `reopen`) moves that operation aside.\n *\n * A NEW request must name its `operator`, so every stop says who made it. A replay of a request\n * or acknowledgement written before that rule is answered as it was.\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 readonly operator?: string\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 ...(options.operator === undefined ? {} : { operator: options.operator }),\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 // A new request names who stops the run. A replay of a request written before this rule keeps\n // its absent operator: it was admitted above against the file it replays.\n if (pending === undefined && (options.operator === undefined || options.operator.trim() === '')) {\n throw new Error('cancelRun: operator is required; name who stops the run')\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 ...(options.operator === undefined ? {} : { operator: options.operator }),\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 ...(options.operator === undefined ? {} : { operator: options.operator }),\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 ...(request.operator === undefined ? {} : { operator: request.operator }),\n detail: 'request queued; no runtime acknowledger has answered yet',\n }\n}\n\ntype RunCancelRequestCandidate = Omit<RunCancelRequest, 'at'>\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 if (existing.operator !== candidate.operator) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its admitted request ` +\n `(operator '${existing.operator}' != '${candidate.operator}')`,\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 // An acknowledgement written before acknowledgements carried the operator (0.251.0) names none\n // even when its admitted request does. The request comparator has already held the candidate\n // to that request, so a legacy record matches any candidate operator; a record that names one\n // must name the same one.\n if (existing.operator !== undefined && existing.operator !== candidate.operator) {\n throw new Error(\n `cancelRun: operation '${candidate.operationId}' conflicts with its acknowledgement ` +\n `(operator '${existing.operator}' != '${candidate.operator}')`,\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 (value.operator === undefined || typeof value.operator === 'string')\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuGA,SAAS,UAAU,OAAmC;CACpD,OAAO,MAAM,SAAS;AACxB;;AAGA,IAAa,sBAAb,MAA4D;CAI7B;CAH7B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WAAW,UAAU,QAChC,MAAM,IAAI,MACR,yBAAyB,UAAU,YAAY,iDACjC,SAAS,OAAO,QAAQ,UAAU,OAAO,GACzD;CAEF,IAAI,SAAS,eAAe,UAAU,YACpC,MAAM,IAAI,MACR,yBAAyB,UAAU,YAAY,2DACjD;CAEF,IAAI,SAAS,WAAW,UAAU,QAChC,MAAM,IAAI,MACR,yBAAyB,UAAU,YAAY,uDAEjD;CAEF,IAAI,SAAS,aAAa,UAAU,UAClC,MAAM,IAAI,MACR,yBAAyB,UAAU,YAAY,mDAC/B,SAAS,SAAS,QAAQ,UAAU,SAAS,GAC/D;AAEJ;AAEA,SAAS,sCACP,UACA,WACM;CACN,IAAI,SAAS,WAAW,UAAU,QAChC,MAAM,IAAI,MACR,yBAAyB,UAAU,YAAY,sDAEjD;CAMF,IAAI,SAAS,aAAa,KAAA,KAAa,SAAS,aAAa,UAAU,UACrE,MAAM,IAAI,MACR,yBAAyB,UAAU,YAAY,kDAC/B,SAAS,SAAS,QAAQ,UAAU,SAAS,GAC/D;AAEJ;AAEA,SAAS,mBAAmB,OAA6D;CACvF,OACE,OAAO,MAAM,gBAAgB,YAC7B,MAAM,YAAY,SAAS,KAC3B,OAAO,MAAM,OAAO,YACpB,OAAO,MAAM,WAAW,aACvB,MAAM,eAAe,KAAA,KACnB,OAAO,SAAS,MAAM,UAAU,KAAK,MAAM,cAAc,OAC3D,MAAM,WAAW,KAAA,KAAa,OAAO,MAAM,WAAW,cACtD,MAAM,aAAa,KAAA,KAAa,OAAO,MAAM,aAAa;AAE/D"}
@@ -1,21 +1,21 @@
1
- import { $t as insideCursorNamespace, D as isTraceAnalysisStore, Hi as notifySandboxEventObserver, Hr as executableAgentSpecSnapshot, Jr as runtimeFailureCauseSchema, Ri as createSandboxTurnEventCollector, Vr as executableAgentProfileSnapshot, Z as settledToIteration, hi as contentAddress, nt as rollingDispatch, oa as runAbortable, q as coordinationProfileToolPrefix } from "./scope-CCHfmCvY.js";
1
+ import { $t as insideCursorNamespace, D as isTraceAnalysisStore, Hr as executableAgentSpecSnapshot, Jr as runtimeFailureCauseSchema, Ui as notifySandboxEventObserver, Vr as executableAgentProfileSnapshot, Z as settledToIteration, gi as contentAddress, nt as rollingDispatch, q as coordinationProfileToolPrefix, sa as runAbortable, zi as createSandboxTurnEventCollector } from "./scope-CBW-oIwP.js";
2
2
  import { i as ConfigError, m as ValidationError, n as AnalystError, s as PlannerError } from "./errors-AzSuGI23.js";
3
- import { D as runAgentic, E as refine, M as renderReport, N as profileChatClient, O as sample, j as observe, k as ObservationError, v as loadAuthoredStrategy, x as strategyAuthorContract, y as requestStrategySource } from "./structural-rollout-BS3hVAq2.js";
3
+ import { D as runAgentic, E as refine, M as renderReport, N as profileChatClient, O as sample, j as observe, k as ObservationError, v as loadAuthoredStrategy, x as strategyAuthorContract, y as requestStrategySource } from "./structural-rollout-BBKSnDfB.js";
4
4
  import { $ as isAsyncIterable, A as markPutStreamVerified, C as captureMaterializedWorkspace, G as chargedTokens, K as cloneSpend, L as immutableCandidateValue, N as canonicalCandidateDigest$1, Q as isAbortError, St as armDeadlineTimer, U as addSpend, X as fnv1a32Hex, Y as errorMessage, Z as hasCompleteCacheBreakdown, at as sleep, b as WorkspaceScanLimitError, dt as zeroSpend, et as mapWithConcurrency, nt as randomSuffix, ot as stringifySafe, z as sha256Bytes$1 } from "./workspace-streams-8ALHaZzx.js";
5
5
  import { a as readCommittedJsonFile, c as withJsonlFileLock, d as detachedSnapshot, n as isNoEntError, o as readCommittedJsonLines, s as upsertCommittedJsonLine, t as appendCommittedJsonLine, u as detachedFrozen } from "./jsonl-file-BBP9Dz9w.js";
6
- import { C as createExecutor, D as runAgentRounds, O as assertBoxlessPromptOptions, P as defaultSelectWinner, V as routerBrain, _ as withDriverExecutor, _t as CheckUnavailableError, b as createExecutorRegistry, bt as mapExecutorResult, j as createSandboxLineage, k as readPromptOptions, n as createSupervisor, q as createWorktreeCliExecutor, v as InMemoryResultBlobStore, xt as verdictFromJudgeScore, y as InMemorySpawnJournal, yt as gateOnDeliverable } from "./supervisor-C-mx3kR8.js";
6
+ import { C as createExecutor, D as runAgentRounds, O as assertBoxlessPromptOptions, P as defaultSelectWinner, V as routerBrain, _ as withDriverExecutor, _t as CheckUnavailableError, b as createExecutorRegistry, bt as mapExecutorResult, j as createSandboxLineage, k as readPromptOptions, n as createSupervisor, q as createWorktreeCliExecutor, v as InMemoryResultBlobStore, xt as verdictFromJudgeScore, y as InMemorySpawnJournal, yt as gateOnDeliverable } from "./supervisor-B68cSh2T.js";
7
7
  import { a as concreteProfileModel, c as profileModelExecutionSettings, i as concreteModelId, l as profileProviderModel, o as enforceTokenLimits, p as canonicalObservedModelParts, t as assertExecutableAgentProfile, v as harnessRunsAgent } from "./model-policy-C-RGAUW4.js";
8
8
  import { a as writeAtomicDurableFile } from "./durable-file-DstVeHcj.js";
9
9
  import { i as notifyRuntimeHookEvent } from "./runtime-hooks-CsW2pfFk.js";
10
- import { a as reconcileInterruptedSearchCalls, c as searchExecutor, r as dedicatedLane, x as runtimeShipDecision } from "./search-executor-Cypg4sCQ.js";
11
- import { y as foldCoordinationRecords } from "./run-cancellation-BRIB385R.js";
12
- import { a as downMessageRefusalReasons, p as createInMemoryRunContext } from "./coordination-manager-s1hbIqXx.js";
13
- import { E as validateFlowGraph, I as kernelPromptRegistry, _ as coordinationControlToolNames, k as validateGraphTopology, t as supervise, y as runBrainLoop } from "./supervise-dOLWtwyj.js";
10
+ import { a as reconcileInterruptedSearchCalls, c as searchExecutor, r as dedicatedLane, x as runtimeShipDecision } from "./search-executor-A2dtsTlx.js";
11
+ import { y as foldCoordinationRecords } from "./run-cancellation-Cy8NtCtz.js";
12
+ import { a as downMessageRefusalReasons, p as createInMemoryRunContext } from "./coordination-manager-CZzhPx_F.js";
13
+ import { E as validateFlowGraph, I as kernelPromptRegistry, _ as coordinationControlToolNames, k as validateGraphTopology, t as supervise, y as runBrainLoop } from "./supervise-CeUM7jMe.js";
14
14
  import { _ as compileGraphParameters, a as graphRegistry, b as graphRouteWhenSchema, d as recordGraphRun, g as bindGraphParameters, h as assertGraphTriggerBindings, i as graphFromStored, l as lookupGraph, m as taskShapeDigest, o as graphRunsFor, r as graphDigest, t as digestOfGraph, v as graphTriggerBindingsSchema, y as graphFileSchema } from "./graph-registry-D6y6zffC.js";
15
15
  import { i as redactProtectedValue, r as redactProtectedReason } from "./protected-redaction-DilFZch5.js";
16
- import "./provision-supervisor-B6-0_VQb.js";
17
- import "./delegate-D1urT1fO.js";
18
- import "./graph-D1lBBrG9.js";
16
+ import "./provision-supervisor-BqbXjSYT.js";
17
+ import "./delegate-D0NpQF_z.js";
18
+ import "./graph-BKMPvIk6.js";
19
19
  import { agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, sha256Bytes, validateAgentProfileSecurity } from "@tangle-network/agent-interface";
20
20
  import { CODING_HARNESSES, DEFAULT_TRACE_ANALYST_KINDS, InMemoryTraceStore, OUTPUT_VALUE, benjaminiHochberg, buildTrajectory, computeFindingId as computeFindingId$1, confidenceInterval, createTraceAnalyst, expandProfileAxes, makeFinding as makeFinding$1, pairedBootstrap, paretoFrontier, wilcoxonSignedRank, wilson } from "@tangle-network/agent-eval";
21
21
  import { createAgentRunOutcomeTracker } from "@tangle-network/sandbox/runtime";
@@ -10071,4 +10071,4 @@ function tail(s) {
10071
10071
  }
10072
10072
  export { runBenchmark as $, renderLeaderboardHtml as $t, searchPresets as A, sanitizeMcpToolSchema as At, graphFromSessionFacts as B, assertDeclaredCheck as Bt, withUntrackedArtifacts as C, harvestCorpus as Ct, SEARCH_SPEC_CORRELATION_KEY as D, connectStdioMcp as Dt, createFencedSqlRunContext as E, McpSpawnFault as Et, loadProfile as F, secretEnvOfMcpServer as Ft, chatWorkerSeam as G, readDeclaredCheck as Gt, loadGraphFile as H, declaredCheckDeliverable as Ht, pickBestProfile as I, inlineSandboxClient as It, strategyTournament as J, deterministicCompletion as Jt, createChatSessionStore as K, runIsolatedCheck as Kt, profileRegistry as L, loopCampaignDispatch as Lt, connectRemoteSupervisor as M, mcpSecretEnvMetadataKey as Mt, connectRemoteSupervisorControl as N, resolveMcpServerLaunch as Nt, assertSearchSpec as O, materializeLocalMcp as Ot, bestProfileFor as P, resolveSecretEnv as Pt, printBenchmarkReport as Q, pairwiseSignificance as Qt, profileRunsForName as R, loopDispatch as Rt, copyUntrackedIntoClone as S, HarvestError as St, validateStoredGraph as T, resolveSandboxClient as Tt, graphDesignerExtraTools as U, declaredCheckDigest as Ut, GraphFileResolutionError as V, checkProgramDigest as Vt, chatTransportExecutor as W, declaredCheckJudge as Wt, openSandboxRun as X, stopSentinel as Xt, SandboxRunAbortError as Y, sentinelCompletion as Yt, createS3PrivateCasStore as Z, leaderboard as Zt, NOTE_MAX_CHARS as _, buildSteerContext as _t, localShell as a, FileCorpus as at, composeWorkerEvidence as b, observationFromRegistry as bt, createVerifierEnvironment as c, fanout as ct, harvestSurfaceDiffs as d, panel as dt, renderLeaderboardMarkdown as en, createPrivateCasArtifactPort as et, analystsFromRegistry as f, pipeline as ft, EVIDENCE_MAX_CHARS as g, assertTraceDerivedFindings as gt, runCoderChecks as h, widen as ht, jjWorkspace as i, openSqlRunStore as in, runPersonified as it, searchSpecDigest as j, envKeyProvider as jt, compileSearchSpec as k, createMcpEnvironment as kt, boxSurfaceReader as l, flatWidenGate as lt, worktreeFanout as m, verify as mt, makeFinding$1 as n, renderPairwiseMarkdown as nn, trajectoryReport as nt, runInWorkspace as o, InMemoryCorpus as ot, failuresAnalyst as p, selectValidWinner as pt, runStrategyEvolution as q, completionAuthorizes as qt, gitWorkspace as r, SqlRunOwnershipError as rn, definePersona as rt, createWaterfallCollector as s, renderCorpusToInstructions as st, computeFindingId$1 as t, renderLeaderboardSvg as tn, equalKOnCost as tt, fsSurfaceReader as u, loopUntil as ut, VERIFY_TAIL_CHARS as v, createScopeAnalyst as vt, analyzeTrace as w, defineLeaderboard as wt, settledWorkerOut as x, inProcessSandboxClient as xt, closingWorkerNote as y, registryScopeAnalyst as yt, recordProfileRun as z, superviseDispatch as zt };
10073
10073
 
10074
- //# sourceMappingURL=runtime-DqTj9ahF.js.map
10074
+ //# sourceMappingURL=runtime-Cxlb_vie.js.map