@tangle-network/agent-runtime 4.0.0 → 6.0.1

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 (97) hide show
  1. package/CHANGELOG.md +5279 -0
  2. package/dist/{activation-BiQYCayd.js → activation-BRfZOfwb.js} +4 -4
  3. package/dist/{activation-BiQYCayd.js.map → activation-BRfZOfwb.js.map} +1 -1
  4. package/dist/{activation-B49A14V5.d.ts → activation-DEKw9CDD.d.ts} +2 -2
  5. package/dist/agent.d.ts +1 -1
  6. package/dist/agent.js +4 -4
  7. package/dist/{bundle-CV4Ts0cS.js → bundle-vFFiCigS.js} +2 -2
  8. package/dist/{bundle-CV4Ts0cS.js.map → bundle-vFFiCigS.js.map} +1 -1
  9. package/dist/candidate-execution/index.d.ts +71 -4
  10. package/dist/candidate-execution/index.js +4 -4
  11. package/dist/{coordination-manager-C-ZoeZ73.js → coordination-manager-RSJg5GmY.js} +12 -11
  12. package/dist/coordination-manager-RSJg5GmY.js.map +1 -0
  13. package/dist/{coordination-map-routing-SnsZp287.js → coordination-map-routing-DVjW5Gx0.js} +2 -2
  14. package/dist/coordination-map-routing-DVjW5Gx0.js.map +1 -0
  15. package/dist/{delegate-d9HcOFC5.js → delegate-C0cprMUN.js} +2 -2
  16. package/dist/{delegate-d9HcOFC5.js.map → delegate-C0cprMUN.js.map} +1 -1
  17. package/dist/durable.d.ts +5 -3
  18. package/dist/durable.js +14 -186
  19. package/dist/durable.js.map +1 -1
  20. package/dist/{graph-C_Z0Ua10.js → graph-cEg-gquv.js} +6 -8
  21. package/dist/{graph-C_Z0Ua10.js.map → graph-cEg-gquv.js.map} +1 -1
  22. package/dist/{graph-registry-CI1o16DH.js → graph-registry-B25FxBZN.js} +5 -5
  23. package/dist/graph-registry-B25FxBZN.js.map +1 -0
  24. package/dist/{graph-registry-BU7pcrUW.js → graph-registry-C-hjRx2t.js} +1 -1
  25. package/dist/{improve-B4v4S8jY.js → improve-DNl4_6lP.js} +8 -8
  26. package/dist/{improve-B4v4S8jY.js.map → improve-DNl4_6lP.js.map} +1 -1
  27. package/dist/index.d.ts +6 -6
  28. package/dist/index.js +11 -11
  29. package/dist/intelligence.d.ts +5 -5
  30. package/dist/intelligence.js +8 -8
  31. package/dist/{jsonl-file-CvPuwM0a.js → jsonl-file-CeVYTIQJ.js} +41 -32
  32. package/dist/jsonl-file-CeVYTIQJ.js.map +1 -0
  33. package/dist/kernel.d.ts +3 -3
  34. package/dist/kernel.js +14 -13
  35. package/dist/{loop-runner-DKvA0JJr.d.ts → loop-runner-CDad0CCY.d.ts} +2 -2
  36. package/dist/{loop-runner-DMZkwlND.js → loop-runner-DQJjowz0.js} +2 -2
  37. package/dist/{loop-runner-DMZkwlND.js.map → loop-runner-DQJjowz0.js.map} +1 -1
  38. package/dist/loop-runner-bin.d.ts +1 -1
  39. package/dist/loop-runner-bin.js +1 -1
  40. package/dist/mcp/bin.js +3 -3
  41. package/dist/mcp/index.d.ts +1 -1
  42. package/dist/mcp/index.js +6 -6
  43. package/dist/{prepare-DutbxpWr.js → prepare-B6SQA12v.js} +3 -3
  44. package/dist/{prepare-DutbxpWr.js.map → prepare-B6SQA12v.js.map} +1 -1
  45. package/dist/{profile-ClvuI8aY.js → profile-DN8Dw2Kp.js} +2 -2
  46. package/dist/{profile-ClvuI8aY.js.map → profile-DN8Dw2Kp.js.map} +1 -1
  47. package/dist/profiles.d.ts +1 -1
  48. package/dist/{protected-model-port-DEsNIYi1.d.ts → protected-model-port-uN4M48vT.d.ts} +2 -2
  49. package/dist/{provision-supervisor-Cjs4SQ9Q.js → provision-supervisor-CtAaJCUa.js} +6 -6
  50. package/dist/{provision-supervisor-Cjs4SQ9Q.js.map → provision-supervisor-CtAaJCUa.js.map} +1 -1
  51. package/dist/{run-cancellation-CGgk54Md.js → run-cancellation-BCuu6khW.js} +3 -3
  52. package/dist/{run-cancellation-CGgk54Md.js.map → run-cancellation-BCuu6khW.js.map} +1 -1
  53. package/dist/run-state-ByHiAjUs.js +351 -0
  54. package/dist/run-state-ByHiAjUs.js.map +1 -0
  55. package/dist/{runtime-BmxmsaNz.js → runtime-9EYvBcHG.js} +19 -18
  56. package/dist/runtime-9EYvBcHG.js.map +1 -0
  57. package/dist/runtime-hooks-CsW2pfFk.js.map +1 -1
  58. package/dist/{runtime-hooks-ZQqPw-0g.d.ts → runtime-hooks-DPghSHV7.d.ts} +11 -16
  59. package/dist/{scope-CJ7xtrs8.js → scope-DzhBJrRN.js} +3632 -3528
  60. package/dist/scope-DzhBJrRN.js.map +1 -0
  61. package/dist/{search-executor-DSB6XAl1.js → search-executor-BJRNavck.js} +4 -4
  62. package/dist/{search-executor-DSB6XAl1.js.map → search-executor-BJRNavck.js.map} +1 -1
  63. package/dist/{server-FWT2Nt_w.js → server-DH0P6OY_.js} +4 -4
  64. package/dist/{server-FWT2Nt_w.js.map → server-DH0P6OY_.js.map} +1 -1
  65. package/dist/settle-record-BSDDf9Z4.js +130 -0
  66. package/dist/settle-record-BSDDf9Z4.js.map +1 -0
  67. package/dist/{structural-rollout-Bl23HSOd.js → structural-rollout-DgvJLTO0.js} +4 -4
  68. package/dist/{structural-rollout-Bl23HSOd.js.map → structural-rollout-DgvJLTO0.js.map} +1 -1
  69. package/dist/{supervise-MAzd0hOk.js → supervise-Cqhkb2Oj.js} +402 -450
  70. package/dist/supervise-Cqhkb2Oj.js.map +1 -0
  71. package/dist/{supervision-discovery-6EtvKCsU.js → supervision-discovery-DI5GIFBJ.js} +5 -130
  72. package/dist/supervision-discovery-DI5GIFBJ.js.map +1 -0
  73. package/dist/{supervisor-CwANBb9-.js → supervisor-B6sl14OR.js} +408 -1069
  74. package/dist/supervisor-B6sl14OR.js.map +1 -0
  75. package/dist/testing.d.ts +1 -1
  76. package/dist/testing.js +13 -13
  77. package/dist/tool-loop.d.ts +1 -1
  78. package/dist/{top-web-CZP3RRhD.js → top-web-DGoXGxH8.js} +13 -9
  79. package/dist/{top-web-CZP3RRhD.js.map → top-web-DGoXGxH8.js.map} +1 -1
  80. package/dist/tui/bin.js +3 -3
  81. package/dist/tui/index.d.ts +2 -2
  82. package/dist/tui/index.js +2 -2
  83. package/dist/{types-ooyUaxq_.d.ts → types-niKnm6ux.d.ts} +270 -461
  84. package/dist/{workspace-streams-DbKiDOWA.d.ts → workspace-archive-DS9E9tUr.d.ts} +2 -69
  85. package/dist/{workspace-streams-8ALHaZzx.js → workspace-streams-BqNM06y4.js} +34 -9
  86. package/dist/workspace-streams-BqNM06y4.js.map +1 -0
  87. package/package.json +9 -10
  88. package/dist/coordination-manager-C-ZoeZ73.js.map +0 -1
  89. package/dist/coordination-map-routing-SnsZp287.js.map +0 -1
  90. package/dist/graph-registry-CI1o16DH.js.map +0 -1
  91. package/dist/jsonl-file-CvPuwM0a.js.map +0 -1
  92. package/dist/runtime-BmxmsaNz.js.map +0 -1
  93. package/dist/scope-CJ7xtrs8.js.map +0 -1
  94. package/dist/supervise-MAzd0hOk.js.map +0 -1
  95. package/dist/supervision-discovery-6EtvKCsU.js.map +0 -1
  96. package/dist/supervisor-CwANBb9-.js.map +0 -1
  97. package/dist/workspace-streams-8ALHaZzx.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"run-cancellation-CGgk54Md.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,SAAgC;GACpC;GACA,GAAI,YAAY,KAAA,IAAY,EAAE,QAAQ,IAAI,CAAC;GAC3C,GAAG;EACL;EACA,MAAM,wBAAwB,KAAK,MAAM,MAAM;CACjD;CAEA,MAAM,KAAK,OAAe,SAA2D;EACnF,OAAO,wBACL,uBAA4E,KAAK,MAAM,EACrF,cAAc,KAChB,CAAC,GACD,OACA,OACF;CACF;AACF;;AAGA,eAAsB,wBACpB,QAGA,OACA,SAC4B;CAC5B,MAAM,uBAAO,IAAI,IAA4B;CAC7C,MAAM,WAAkC,CAAC;CACzC,MAAM,cAA0C,CAAC;CACjD,MAAM,qBAA6C,CAAC;CACpD,MAAM,gBAA2C,CAAC;CAClD,MAAM,mBAAmD,CAAC;CAC1D,MA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1
+ {"version":3,"file":"run-cancellation-BCuu6khW.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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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"}
@@ -0,0 +1,351 @@
1
+ import { H as spawnJournalRecordEvents } from "./scope-DzhBJrRN.js";
2
+ import { a as readCommittedJsonLines, t as isNoEntError } from "./jsonl-file-CeVYTIQJ.js";
3
+ import { s as readRunParking } from "./supervisor-B6sl14OR.js";
4
+ import { a as writeAtomicDurableFile, c as mutateRunClaim, l as runGenerationPath, r as publishExclusiveDurableFile, u as runWithWriteClaim } from "./durable-file-DstVeHcj.js";
5
+ import { r as readRunCancelRequest } from "./run-cancellation-BCuu6khW.js";
6
+ import { a as readFailureRecord, o as readSettleRecord } from "./settle-record-BSDDf9Z4.js";
7
+ import { isRecord } from "@tangle-network/agent-core";
8
+ import { createHash } from "node:crypto";
9
+ import { setTimeout } from "node:timers/promises";
10
+ import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, unlinkSync } from "node:fs";
11
+ import { join, resolve } from "node:path";
12
+ import { open, stat } from "node:fs/promises";
13
+ import { lockHolderVerdict, lockIdentity, parseLockHolderRecord, readLockHolderIdentity } from "@tangle-network/agent-eval/lock-holder";
14
+ // src/durable/run-lock.ts
15
+ /** The lock file `supervisePursuit` holds inside a run directory for the life of one call. */
16
+ const RUN_DIRECTORY_LOCK_FILE = "supervise.lock";
17
+ /** The directory is held by a live process. `holder` is what that process recorded. */
18
+ var RunDirectoryLockedError = class extends Error {
19
+ path;
20
+ holder;
21
+ constructor(path, holder) {
22
+ super(`supervisePursuit: ${path} is held by pid ${holder.pid} (run '${holder.runId}', since ${holder.startedAt}); one process drives a run directory at a time`);
23
+ this.name = "RunDirectoryLockedError";
24
+ this.path = path;
25
+ this.holder = holder;
26
+ }
27
+ };
28
+ /**
29
+ * Take `runDir/supervise.lock`, or refuse.
30
+ *
31
+ * The file is published with its full content or not at all, so a contender never reads a
32
+ * half-written holder. A lock whose holder is proved dead (its pid no longer exists, the pid now
33
+ * belongs to a process with a different start token, or the host rebooted) is stale and is removed
34
+ * under the mutation guard; a holder that is alive or cannot be proved dead refuses. An empty file
35
+ * names no holder and is reclaimed. A file with unreadable content is left in place and refused:
36
+ * reclaiming it could evict a live holder written by something other than this module.
37
+ */
38
+ async function acquireRunDirectoryLock(runDir, runId, now = Date.now) {
39
+ const dir = resolve(runDir);
40
+ const path = resolve(dir, RUN_DIRECTORY_LOCK_FILE);
41
+ mkdirSync(dir, { recursive: true });
42
+ const { pid, ...identity } = readLockHolderIdentity(process.pid);
43
+ const owner = {
44
+ pid,
45
+ startedAt: new Date(now()).toISOString(),
46
+ runId,
47
+ ...identity
48
+ };
49
+ return mutateRunClaim(path, () => {
50
+ const existing = readLockFile(path);
51
+ if (existing.state === "holder" && !holderIsDead(existing)) throw new RunDirectoryLockedError(path, existing.holder);
52
+ let previousGeneration = 0;
53
+ try {
54
+ previousGeneration = Number(readFileSync(runGenerationPath(dir), "utf8"));
55
+ if (!Number.isSafeInteger(previousGeneration) || previousGeneration < 1) throw new Error("invalid run directory generation counter");
56
+ } catch (error) {
57
+ if (!isNoEntError(error)) throw error;
58
+ }
59
+ const generation = Math.max(previousGeneration, existing.state === "holder" ? existing.holder.generation ?? 0 : 0) + 1;
60
+ if (!Number.isSafeInteger(generation)) throw new Error("run directory generation exhausted");
61
+ writeAtomicDurableFile(runGenerationPath(dir), `${generation}\n`);
62
+ if (existing.state !== "missing") removeIfPresent(path);
63
+ const written = {};
64
+ const published = publishExclusiveDurableFile(path, (file) => {
65
+ written.holder = Object.freeze({
66
+ ...owner,
67
+ generation,
68
+ lock: lockIdentity(file)
69
+ });
70
+ return `${JSON.stringify(written.holder)}\n`;
71
+ });
72
+ const holder = written.holder;
73
+ if (!published || holder === void 0) throw new Error(`supervisePursuit: could not take ${path}`);
74
+ let released = false;
75
+ return Object.freeze({
76
+ ...holder,
77
+ generation,
78
+ path,
79
+ run: (operation) => {
80
+ if (holder.lock === void 0) throw new Error("run lock has no inode identity");
81
+ return runWithWriteClaim({
82
+ path,
83
+ generation,
84
+ lock: holder.lock
85
+ }, operation);
86
+ },
87
+ release: async () => {
88
+ if (released) return;
89
+ await releaseHolder(path, holder);
90
+ released = true;
91
+ }
92
+ });
93
+ });
94
+ }
95
+ /** Read the holder a lock file names, or `undefined` when no lock file names one. */
96
+ async function readRunDirectoryLock(runDir) {
97
+ const existing = await readLockFile(resolve(runDir, RUN_DIRECTORY_LOCK_FILE));
98
+ return existing.state === "holder" ? existing.holder : void 0;
99
+ }
100
+ /**
101
+ * Whether a run directory is still held by the live process that took its lock.
102
+ *
103
+ * The same rule `acquireRunDirectoryLock` applies to decide whether a lock is stale, exposed so a
104
+ * caller — a supervisor picking up an abandoned directory, an operator tool listing runs — asks
105
+ * the question instead of hand-rolling `process.kill(pid, 0)`. A bare signal probe cannot tell a
106
+ * live holder from an unrelated process that later took the same pid, which is the failure this
107
+ * lock's start token exists to prevent.
108
+ *
109
+ * The answer is ADVISORY: it is read outside the mutation guard `acquireRunDirectoryLock` holds,
110
+ * so a `false` can be stale by the time the caller acts on it and a concurrent acquire can take
111
+ * the directory in between. Reporting and listing are what this is for. A caller that intends to
112
+ * TAKE the directory calls `acquireRunDirectoryLock`, which evaluates the same rule under the
113
+ * guard and refuses atomically.
114
+ */
115
+ async function runDirectoryHolderIsLive(runDir) {
116
+ const existing = await readLockFile(resolve(runDir, RUN_DIRECTORY_LOCK_FILE));
117
+ if (existing.state !== "holder") return { live: false };
118
+ const verdict = lockHolderVerdict(existing.record, existing.current);
119
+ return {
120
+ live: verdict.liveness !== "dead",
121
+ holder: existing.holder,
122
+ ...verdict.liveness === "unknown" ? { unknown: true } : {}
123
+ };
124
+ }
125
+ function readLockFile(path) {
126
+ let text;
127
+ let current;
128
+ try {
129
+ const file = openSync(path, "r");
130
+ try {
131
+ current = lockIdentity(fstatSync(file, { bigint: true }));
132
+ text = readFileSync(file, "utf8");
133
+ } finally {
134
+ closeSync(file);
135
+ }
136
+ } catch (error) {
137
+ if (isNoEntError(error)) return { state: "missing" };
138
+ throw error;
139
+ }
140
+ if (text.trim().length === 0) return { state: "empty" };
141
+ let parsed;
142
+ try {
143
+ parsed = JSON.parse(text);
144
+ } catch (cause) {
145
+ throw new Error(`supervisePursuit: ${path} is not a readable lock file; remove it by hand`, { cause });
146
+ }
147
+ const record = parsed;
148
+ if (typeof record !== "object" || record === null || typeof record.pid !== "number" || !Number.isInteger(record.pid) || record.pid <= 0 || typeof record.startedAt !== "string" || typeof record.runId !== "string" || record.processStart !== void 0 && typeof record.processStart !== "string" || record.generation !== void 0 && (!Number.isSafeInteger(record.generation) || record.generation < 1)) throw new Error(`supervisePursuit: ${path} is not a readable lock file; remove it by hand`);
149
+ const { pid, startedAt, runId, processStart } = record;
150
+ const verdictRecord = parseLockHolderRecord(parsed);
151
+ const { pid: _pid, ...identity } = verdictRecord ?? { pid };
152
+ return {
153
+ state: "holder",
154
+ holder: Object.freeze({
155
+ pid,
156
+ startedAt,
157
+ runId,
158
+ ...record.generation === void 0 ? {} : { generation: record.generation },
159
+ ...processStart === void 0 ? {} : { processStart },
160
+ ...identity
161
+ }),
162
+ record: verdictRecord,
163
+ current
164
+ };
165
+ }
166
+ /** agent-eval's dead-owner rule: only a holder proved dead is stale; alive or unknown stays held. */
167
+ function holderIsDead(existing) {
168
+ return lockHolderVerdict(existing.record, existing.current).liveness === "dead";
169
+ }
170
+ /** Remove the lock only while it still names this holder; a reclaimed lock belongs to its new owner. */
171
+ async function releaseHolder(path, holder) {
172
+ const deadline = performance.now() + 1e3;
173
+ while (existsSync(`${path}.guard`) && performance.now() < deadline) await setTimeout(10);
174
+ mutateRunClaim(path, () => {
175
+ const existing = readLockFile(path);
176
+ if (existing.state !== "holder") return;
177
+ if (existing.holder.pid !== holder.pid || existing.holder.startedAt !== holder.startedAt || existing.holder.runId !== holder.runId || existing.holder.processStart !== holder.processStart || existing.holder.generation !== holder.generation || existing.holder.lock?.dev !== holder.lock?.dev || existing.holder.lock?.ino !== holder.lock?.ino || existing.holder.lock?.birthtimeNs !== holder.lock?.birthtimeNs) return;
178
+ removeIfPresent(path);
179
+ });
180
+ }
181
+ function removeIfPresent(path) {
182
+ try {
183
+ unlinkSync(path);
184
+ } catch (error) {
185
+ if (!isNoEntError(error)) throw error;
186
+ }
187
+ }
188
+ // src/durable/spawn-journal/read.ts
189
+ /** Read a fixed journal prefix, with historical envelopes and framing owned by Runtime.
190
+ * Missing journals return an empty page. Malformed committed records fail; incomplete final
191
+ * writes remain unread for the next call. Cursors detect replacement, truncation and edits at
192
+ * their sampled opening/boundary; they are not integrity proofs against arbitrary file edits.
193
+ */
194
+ async function readSpawnJournal(runDir, options = {}) {
195
+ const { after, tailBytes } = options;
196
+ if (tailBytes !== void 0 && (!Number.isSafeInteger(tailBytes) || tailBytes < 1)) throw new RangeError("readSpawnJournal: tailBytes must be a positive safe integer");
197
+ const path = join(runDir, "spawn-journal.jsonl");
198
+ let handle;
199
+ try {
200
+ handle = await open(path, "r");
201
+ } catch (error) {
202
+ if (isNoEntError(error)) return {
203
+ records: [],
204
+ reset: after !== void 0,
205
+ truncated: false,
206
+ remainingBytes: 0
207
+ };
208
+ throw error;
209
+ }
210
+ try {
211
+ const snapshot = await handle.stat({ bigint: true });
212
+ if (!snapshot.isFile()) throw new Error(`${path}: expected a regular file`);
213
+ const size = Number(snapshot.size);
214
+ const file = identity(snapshot);
215
+ const resumed = after !== void 0 && after.file === file && Number.isSafeInteger(after.offset) && after.offset >= 0 && after.offset <= size && after.boundary === await boundary(handle, after.offset);
216
+ let offset = resumed ? after.offset : 0;
217
+ const records = [];
218
+ const read = async (start, end, firstOnly = false) => {
219
+ offset = start;
220
+ for await (const record of readCommittedJsonLines(path, {
221
+ handle,
222
+ start,
223
+ end,
224
+ strictUtf8: true,
225
+ onCommit: (committed) => {
226
+ offset = committed;
227
+ }
228
+ })) {
229
+ if (!isRecord(record) || typeof record.root !== "string") throw new Error(`${path}: spawn journal record has no root`);
230
+ if (record.kind === "begin") {
231
+ if (typeof record.at !== "string") throw new Error(`${path}: begin record has no at`);
232
+ records.push({
233
+ kind: "begin",
234
+ root: record.root,
235
+ at: record.at
236
+ });
237
+ } else for (const event of spawnJournalRecordEvents(record)) {
238
+ if (!isRecord(event) || typeof event.kind !== "string" || typeof event.id !== "string") throw new Error(`${path}: spawn journal record has no event identity`);
239
+ records.push({
240
+ kind: "event",
241
+ root: record.root,
242
+ event
243
+ });
244
+ }
245
+ if (firstOnly) break;
246
+ }
247
+ };
248
+ let truncated = false;
249
+ if (!resumed && tailBytes !== void 0 && size > tailBytes) {
250
+ await read(0, size, true);
251
+ const openingEnd = offset;
252
+ const tailStart = await lineBoundary(handle, size - tailBytes, size, -1);
253
+ truncated = tailStart > openingEnd;
254
+ await read(Math.max(openingEnd, tailStart), size);
255
+ if (offset === tailStart && tailStart > openingEnd) {
256
+ const previous = await lineBoundary(handle, tailStart - 1, size, -1);
257
+ truncated = previous > openingEnd;
258
+ await read(Math.max(openingEnd, previous), tailStart);
259
+ }
260
+ } else {
261
+ const end = resumed && tailBytes !== void 0 && size - offset > tailBytes ? await lineBoundary(handle, offset + tailBytes, size, 1) : size;
262
+ await read(offset, end);
263
+ }
264
+ if (identity(await stat(path, { bigint: true })) !== file || (await handle.stat()).size < size) throw new Error(`${path}: journal changed while reading its committed prefix`);
265
+ return {
266
+ records,
267
+ cursor: {
268
+ file,
269
+ offset,
270
+ boundary: await boundary(handle, offset)
271
+ },
272
+ reset: after !== void 0 && !resumed,
273
+ truncated,
274
+ remainingBytes: size - offset
275
+ };
276
+ } finally {
277
+ await handle.close();
278
+ }
279
+ }
280
+ function identity(info) {
281
+ return `${info.dev}:${info.ino}:${info.birthtimeNs}`;
282
+ }
283
+ async function bytes(handle, start, length) {
284
+ const buffer = Buffer.alloc(length);
285
+ const { bytesRead } = await handle.read(buffer, 0, length, start);
286
+ if (bytesRead !== length) throw new Error("spawn journal changed while reading its boundary");
287
+ return buffer;
288
+ }
289
+ async function boundary(handle, offset) {
290
+ const length = Math.min(offset, 128);
291
+ return createHash("sha256").update(await bytes(handle, 0, length)).update(await bytes(handle, offset - length, length)).digest("hex");
292
+ }
293
+ /** Include the record crossing a tail window or incremental page boundary. */
294
+ async function lineBoundary(handle, position, size, direction) {
295
+ while (position > 0 && position < size) {
296
+ const start = direction === -1 ? Math.max(0, position - 65536) : position;
297
+ const end = direction === -1 ? position : Math.min(size, position + 65536);
298
+ const part = await bytes(handle, start, end - start);
299
+ const newline = direction === -1 ? part.lastIndexOf(10) : part.indexOf(10);
300
+ if (newline !== -1) return start + newline + 1;
301
+ position = direction === -1 ? start : end;
302
+ }
303
+ return position;
304
+ }
305
+ // src/durable/run-state.ts
306
+ /** Compose maintained record readers. Terminal settlement outranks cancellation and parking;
307
+ * a request remains cancelling until settlement. An unheld run with evidence is down.
308
+ * No Runtime evidence (including a missing or empty directory) returns undefined. Reads are
309
+ * advisory snapshots across independently published files, not a transaction or a resume gate.
310
+ */
311
+ async function readRunState(runDir) {
312
+ const [settle, failure, parking, holder, journal] = await Promise.all([
313
+ readSettleRecord(runDir),
314
+ readFailureRecord(runDir),
315
+ readRunParking(runDir),
316
+ runDirectoryHolderIsLive(runDir),
317
+ readSpawnJournal(runDir, { tailBytes: 65536 })
318
+ ]);
319
+ const cancelRequest = readRunCancelRequest(runDir);
320
+ if (!settle && !failure && !parking && !holder.holder && !cancelRequest && journal.records.length === 0) return;
321
+ const holderLive = holder.unknown ? void 0 : holder.live;
322
+ const phase = settle ? "settled" : cancelRequest ? "cancelling" : parking ? "parked" : holderLive === true ? "running" : holderLive === false ? "down" : void 0;
323
+ const root = settle?.tree.nodes?.find((node) => node.id === settle.tree.root);
324
+ const failureCode = (settle?.kind === "no-winner" && settle.reason === "driver-failed" ? settle.error?.failure?.code : void 0) ?? root?.failure?.code;
325
+ let latest;
326
+ const observe = (at) => {
327
+ const timestamp = at === void 0 ? void 0 : new Date(at).getTime();
328
+ if (timestamp !== void 0 && Number.isFinite(timestamp)) latest = latest === void 0 ? timestamp : Math.max(latest, timestamp);
329
+ };
330
+ observe(failure?.at);
331
+ observe(parking?.since);
332
+ observe(cancelRequest?.at);
333
+ observe(holder.holder?.startedAt);
334
+ for (const record of journal.records) observe(record.kind === "begin" ? record.at : record.event.at);
335
+ for (const node of settle?.tree.nodes ?? []) {
336
+ observe(node.spawnedAt);
337
+ observe(node.settledAt);
338
+ }
339
+ const lastActivityAt = latest === void 0 ? void 0 : new Date(latest).toISOString();
340
+ return {
341
+ ...phase === void 0 ? {} : { phase },
342
+ ...failureCode === void 0 ? {} : { failureCode },
343
+ ...settle === void 0 ? {} : { settle },
344
+ ...cancelRequest === void 0 ? {} : { cancelRequest },
345
+ ...holderLive === void 0 ? {} : { holderLive },
346
+ ...lastActivityAt === void 0 ? {} : { lastActivityAt }
347
+ };
348
+ }
349
+ export { readRunDirectoryLock as a, acquireRunDirectoryLock as i, readSpawnJournal as n, runDirectoryHolderIsLive as o, RunDirectoryLockedError as r, readRunState as t };
350
+
351
+ //# sourceMappingURL=run-state-ByHiAjUs.js.map