@tangle-network/agent-runtime 10.0.13 → 10.0.15

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 (61) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/{activation-D36iRata.js → activation-b0nzPqca.js} +2 -2
  3. package/dist/{activation-D36iRata.js.map → activation-b0nzPqca.js.map} +1 -1
  4. package/dist/agent.js +2 -2
  5. package/dist/{delegate-BKD8kvLL.js → delegate-CLaWDfML.js} +2 -2
  6. package/dist/{delegate-BKD8kvLL.js.map → delegate-CLaWDfML.js.map} +1 -1
  7. package/dist/{driver-control-acknowledgers-DwvOv6Hy.js → driver-control-acknowledgers-NPX-VWeS.js} +5 -5
  8. package/dist/{driver-control-acknowledgers-DwvOv6Hy.js.map → driver-control-acknowledgers-NPX-VWeS.js.map} +1 -1
  9. package/dist/durable-writer-thread.js +2 -2
  10. package/dist/durable.js +9 -9
  11. package/dist/{graph-CWtb5mlR.js → graph-B2OzHayc.js} +5 -5
  12. package/dist/{graph-CWtb5mlR.js.map → graph-B2OzHayc.js.map} +1 -1
  13. package/dist/{improve-CWX6gC3Y.js → improve-dYbnuXC8.js} +5 -5
  14. package/dist/{improve-CWX6gC3Y.js.map → improve-dYbnuXC8.js.map} +1 -1
  15. package/dist/index.js +9 -9
  16. package/dist/intelligence.js +4 -4
  17. package/dist/kernel.js +13 -13
  18. package/dist/{loop-runner-TFs-O4vJ.js → loop-runner-UfFomLu5.js} +2 -2
  19. package/dist/{loop-runner-TFs-O4vJ.js.map → loop-runner-UfFomLu5.js.map} +1 -1
  20. package/dist/loop-runner-bin.js +1 -1
  21. package/dist/mcp/bin.js +3 -3
  22. package/dist/mcp/index.js +5 -5
  23. package/dist/{provision-supervisor-DyrYiZOg.js → provision-supervisor-DSDkye8b.js} +4 -4
  24. package/dist/{provision-supervisor-DyrYiZOg.js.map → provision-supervisor-DSDkye8b.js.map} +1 -1
  25. package/dist/{run-cancellation-D2fq7jx6.js → run-cancellation-BYnz8GlN.js} +2 -2
  26. package/dist/{run-cancellation-D2fq7jx6.js.map → run-cancellation-BYnz8GlN.js.map} +1 -1
  27. package/dist/{run-reopen-CHIodC9G.js → run-reopen-CQjs4kpp.js} +5 -5
  28. package/dist/{run-reopen-CHIodC9G.js.map → run-reopen-CQjs4kpp.js.map} +1 -1
  29. package/dist/{run-state-D-rOe5N8.js → run-state-DI59zWDh.js} +5 -5
  30. package/dist/{run-state-D-rOe5N8.js.map → run-state-DI59zWDh.js.map} +1 -1
  31. package/dist/{runtime-4UPWxjjq.js → runtime-DZupdBai.js} +13 -13
  32. package/dist/{runtime-4UPWxjjq.js.map → runtime-DZupdBai.js.map} +1 -1
  33. package/dist/{search-executor-B0NdgH8a.js → search-executor-DXKX36KX.js} +3 -3
  34. package/dist/{search-executor-B0NdgH8a.js.map → search-executor-DXKX36KX.js.map} +1 -1
  35. package/dist/{server-BPYmJQvn.js → server-db_tgJ2j.js} +3 -3
  36. package/dist/{server-BPYmJQvn.js.map → server-db_tgJ2j.js.map} +1 -1
  37. package/dist/{settle-record-zm4ZDjhu.js → settle-record-DV7zCjhI.js} +2 -2
  38. package/dist/{settle-record-zm4ZDjhu.js.map → settle-record-DV7zCjhI.js.map} +1 -1
  39. package/dist/{structural-rollout-uN5x6ioB.js → structural-rollout-BgGJOWEx.js} +3 -3
  40. package/dist/{structural-rollout-uN5x6ioB.js.map → structural-rollout-BgGJOWEx.js.map} +1 -1
  41. package/dist/{supervise-identity-OkAQ-Ekg.js → supervise-identity-uI2Ke-Mm.js} +2 -2
  42. package/dist/{supervise-identity-OkAQ-Ekg.js.map → supervise-identity-uI2Ke-Mm.js.map} +1 -1
  43. package/dist/{supervise-aJRMwxRm.js → supervise-jfYp4dyB.js} +17 -9
  44. package/dist/supervise-jfYp4dyB.js.map +1 -0
  45. package/dist/{supervision-discovery-CDpfasyS.js → supervision-discovery-CHRT0UXq.js} +2 -2
  46. package/dist/{supervision-discovery-CDpfasyS.js.map → supervision-discovery-CHRT0UXq.js.map} +1 -1
  47. package/dist/{supervisor-D88YZZKa.js → supervisor-BVtN_Szy.js} +3 -3
  48. package/dist/{supervisor-D88YZZKa.js.map → supervisor-BVtN_Szy.js.map} +1 -1
  49. package/dist/{supervisor-accounting-Bnp1WYTX.js → supervisor-accounting--LFd8H4U.js} +19 -6
  50. package/dist/supervisor-accounting--LFd8H4U.js.map +1 -0
  51. package/dist/{supervisor-root-contract-C6FYJprY.js → supervisor-root-contract-xlqe8DE1.js} +2 -2
  52. package/dist/{supervisor-root-contract-C6FYJprY.js.map → supervisor-root-contract-xlqe8DE1.js.map} +1 -1
  53. package/dist/testing.js +11 -11
  54. package/dist/{top-web-C8MkFqf4.js → top-web-CRmycSiU.js} +11 -9
  55. package/dist/top-web-CRmycSiU.js.map +1 -0
  56. package/dist/tui/bin.js +3 -3
  57. package/dist/tui/index.js +2 -2
  58. package/package.json +1 -1
  59. package/dist/supervise-aJRMwxRm.js.map +0 -1
  60. package/dist/supervisor-accounting-Bnp1WYTX.js.map +0 -1
  61. package/dist/top-web-C8MkFqf4.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { rt as deriveNodeExecutionIdentity } from "./supervisor-accounting-Bnp1WYTX.js";
1
+ import { rt as deriveNodeExecutionIdentity } from "./supervisor-accounting--LFd8H4U.js";
2
2
  import { m as ValidationError } from "./errors-DG8yufqX.js";
3
3
  import { l as appendCommittedJsonLine, o as readCommittedJsonLines } from "./jsonl-file-vE9H9UXa.js";
4
4
  import { n as detachedSnapshot } from "./snapshot-BKI_w3JD.js";
@@ -207,4 +207,4 @@ function coordinationEventId(context, event) {
207
207
  }
208
208
  export { freezeDetached as a, supervisionRunNamespace as c, foldCoordinationRecords as d, externalExecutionId as i, workerAssignmentNamespace as l, childCoordinationOwner as n, freezeDetachedProfile as o, coordinationEventId as r, rootCoordinationOwner as s, canonicalExecution as t, FileCoordinationLog as u };
209
209
 
210
- //# sourceMappingURL=supervise-identity-OkAQ-Ekg.js.map
210
+ //# sourceMappingURL=supervise-identity-uI2Ke-Mm.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"supervise-identity-OkAQ-Ekg.js","names":[],"sources":["../src/runtime/supervise/coordination-log.ts","../src/runtime/supervise/supervise-identity.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"],"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,KA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EACA;EACA;CACF,CAAC;AACH;;;AAIA,SAAgB,oBACd,SACA,OACc;CACd,MAAM,eACJ,MAAM,SAAS,aAAa,MAAM,OAAO,YAAY,cAC1C;EACL,MAAM,EAAE,SAAS,UAAU,GAAG,WAAW,MAAM;EAC/C,OAAO;GAAE,MAAM;GAAoB;EAAO;CAC5C,EAAA,CAAG,IACH;CACN,OAAO,yBAAyB;EAC9B,MAAM;EACN,cAAc,QAAQ;EACtB,SAAS,QAAQ;EACjB,OAAO,iBAAiB,cAAc,uCAAuC;CAC/E,CAAC;AACH"}
1
+ {"version":3,"file":"supervise-identity-uI2Ke-Mm.js","names":[],"sources":["../src/runtime/supervise/coordination-log.ts","../src/runtime/supervise/supervise-identity.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"],"mappings":";;;;;;;;;;;;;;;;;;;;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Q,OAAO;GACpB;EACF;CACF,CAAC;AACH;AAEA,SAAgB,wBAAwB,QAA4B,OAAuB;CACzF,OAAO,yBACL,WAAW,KAAA,IACP;EAAE,MAAM;EAA2B;EAAO,OAAO,WAAW;CAAE,IAC9D;EAAE,MAAM;EAAyB;EAAO,QAAQ,QAAQ,MAAM;CAAE,CACtE;AACF;AAEA,SAAgB,0BACd,cACA,eACA,cACQ;CACR,OAAO,yBAAyB;EAC9B,MAAM;EACN;EACA;EACA;CACF,CAAC;AACH;;;AAIA,SAAgB,oBACd,SACA,OACc;CACd,MAAM,eACJ,MAAM,SAAS,aAAa,MAAM,OAAO,YAAY,cAC1C;EACL,MAAM,EAAE,SAAS,UAAU,GAAG,WAAW,MAAM;EAC/C,OAAO;GAAE,MAAM;GAAoB;EAAO;CAC5C,EAAA,CAAG,IACH;CACN,OAAO,yBAAyB;EAC9B,MAAM;EACN,cAAc,QAAQ;EACtB,SAAS,QAAQ;EACjB,OAAO,iBAAiB,cAAc,uCAAuC;CAC/E,CAAC;AACH"}
@@ -1,14 +1,14 @@
1
1
  import { f as RuntimeRunStateError, i as ConfigError, m as ValidationError } from "./errors-DG8yufqX.js";
2
- import { c as budgetOverspendText, f as createFileRunContext, i as createCoordinationToolsForManager, l as coordinationVerbNames, m as withRunContext, n as createSteerAcknowledger, p as createInMemoryRunContext, r as createCoordinationTools, t as createCancelAcknowledger, u as normalizeAnalyzeOnSettle } from "./driver-control-acknowledgers-DwvOv6Hy.js";
3
- import { $t as worktreeCliProfileMaterialization, B as toolResultText, C as captureReusableExecutorConfig, Ct as bridgeAdmissionRefusal, Gt as fullProfileMaterialization, H as routerBrain, I as codeModeArguments, Jt as promptModelProfileMaterialization, K as providerOutputOptions, Kt as profileMaterializationAxes$1, L as codeModeModelOutput, Mt as bridgeRuntimeAttachmentsKey, Nt as bridgeRuntimeEnvKey, Pt as bridgeStopSignalKey, Q as createInbox, Qt as unsupportedProfileDimensions, R as createCodeModeTools, S as bindReusableExecutorExecutionId, T as snapshotExecutorConfig, Ut as controlProfileMaterialization, V as createRouterTranscript, Vt as assertProfileMaterialization, W as resolveAgentEnvironmentProvider, Wt as defineProfileMaterializationContract, Yt as renderUnsupported, Z as INBOX_RECEIPT_KEY, Zt as sandboxProfileMaterialization, _ as isDriverSpec, _t as preflightPublicCoordination, a as awaitRootWake, at as isPeerMailEnvelope, d as bestDelivered, dt as abandonablePending, f as runFinalizer, ft as classifyDriverFailure, g as driverExecutorFactory, gt as upstreamUnavailableSignal, h as driverChild, ht as undispatchedCredentialExit, i as assertRunParking, l as sleepScopeWait, lt as DriverAttemptsExhaustedError, m as createRootHandle, mt as transientFailureKind, n as createSupervisor, nt as PEER_MAIL_WIRE_KEY, o as bindScopeParkingDrain, p as runTree, pt as summarizeDriverAttempts, qt as promptControlProfileMaterialization, r as RunParkedError, s as isRunParked, u as withRunParking, ut as HarnessTurnFailedError, vt as CheckUnavailableError, w as createExecutor, wt as bridgeModelRouteRefusal, yt as gateFactoryOnDeliverable } from "./supervisor-D88YZZKa.js";
4
- import { a as freezeDetached, c as supervisionRunNamespace, i as externalExecutionId, l as workerAssignmentNamespace, n as childCoordinationOwner, o as freezeDetachedProfile, r as coordinationEventId, s as rootCoordinationOwner, t as canonicalExecution } from "./supervise-identity-OkAQ-Ekg.js";
2
+ import { c as budgetOverspendText, f as createFileRunContext, i as createCoordinationToolsForManager, l as coordinationVerbNames, m as withRunContext, n as createSteerAcknowledger, p as createInMemoryRunContext, r as createCoordinationTools, t as createCancelAcknowledger, u as normalizeAnalyzeOnSettle } from "./driver-control-acknowledgers-NPX-VWeS.js";
3
+ import { $t as worktreeCliProfileMaterialization, B as toolResultText, C as captureReusableExecutorConfig, Ct as bridgeAdmissionRefusal, Gt as fullProfileMaterialization, H as routerBrain, I as codeModeArguments, Jt as promptModelProfileMaterialization, K as providerOutputOptions, Kt as profileMaterializationAxes$1, L as codeModeModelOutput, Mt as bridgeRuntimeAttachmentsKey, Nt as bridgeRuntimeEnvKey, Pt as bridgeStopSignalKey, Q as createInbox, Qt as unsupportedProfileDimensions, R as createCodeModeTools, S as bindReusableExecutorExecutionId, T as snapshotExecutorConfig, Ut as controlProfileMaterialization, V as createRouterTranscript, Vt as assertProfileMaterialization, W as resolveAgentEnvironmentProvider, Wt as defineProfileMaterializationContract, Yt as renderUnsupported, Z as INBOX_RECEIPT_KEY, Zt as sandboxProfileMaterialization, _ as isDriverSpec, _t as preflightPublicCoordination, a as awaitRootWake, at as isPeerMailEnvelope, d as bestDelivered, dt as abandonablePending, f as runFinalizer, ft as classifyDriverFailure, g as driverExecutorFactory, gt as upstreamUnavailableSignal, h as driverChild, ht as undispatchedCredentialExit, i as assertRunParking, l as sleepScopeWait, lt as DriverAttemptsExhaustedError, m as createRootHandle, mt as transientFailureKind, n as createSupervisor, nt as PEER_MAIL_WIRE_KEY, o as bindScopeParkingDrain, p as runTree, pt as summarizeDriverAttempts, qt as promptControlProfileMaterialization, r as RunParkedError, s as isRunParked, u as withRunParking, ut as HarnessTurnFailedError, vt as CheckUnavailableError, w as createExecutor, wt as bridgeModelRouteRefusal, yt as gateFactoryOnDeliverable } from "./supervisor-BVtN_Szy.js";
4
+ import { a as freezeDetached, c as supervisionRunNamespace, i as externalExecutionId, l as workerAssignmentNamespace, n as childCoordinationOwner, o as freezeDetachedProfile, r as coordinationEventId, s as rootCoordinationOwner, t as canonicalExecution } from "./supervise-identity-uI2Ke-Mm.js";
5
5
  import { a as errMessage, c as errorStack, i as causeChain, l as errorText, n as detachedSnapshot, o as errorHttpStatus, u as defaultRedactor } from "./snapshot-BKI_w3JD.js";
6
6
  import { t as composeRuntimeHooks } from "./runtime-hooks-CsW2pfFk.js";
7
- import { $n as generateSpanId, $r as runtimeOwnedScopeOwnerRuntime, $t as reconcileScopeRetainedOwnerEnvironment, Bt as recordScopeOwnerHarnessTranscript, Cr as isTerminalNodeStatus, Dr as authoredSeatStages, Dt as scopeRetainedOwnerResourceReader, Er as SeatPauseError, Et as releaseScopeRetainedOwnerForSeatPause, Ft as scopeRetainedOwnerResult, Gt as coordinationMcpAlias, Hr as recordRuntimeOwnedDriveHarnessProviderEvidence, Ht as restoreScopeOwnerAcceptedExecution, It as beginScopeOwnerAttempt, Jr as runtimeOwnedExecutorExecutionBinding, Jt as runtimeGraphMetadataKey, Kt as coordinationProfileToolPrefix, Mt as consumeScopeRetainedOwnerResult, Nr as attestRuntimeOwnedScopeOwner, Nt as prepareScopeRetainedOwnerTask, Or as seatExecutionProfile, Pr as authoredAgentIdentity, Pt as scopeRetainedOwnerPriorSpend, Qt as assertRetainedOwnerCoordinationRekey, Rt as holdScopeOwnerTranscript, Sr as isLiveNodeStatus, Tr as SeatChain, Tt as prepareScopeRetainedOwnerSeatSwitch, Ut as scopeOwnerExecutionObservation, V as parseWorkerToolTraceArtifact, Vn as WORKER_TRACE_PROPAGATION, Vr as providerAttemptEvidence, Vt as recordScopeOwnerMaterialization, Wt as scopeOwnerExecutorNodeContext, Xr as runtimeOwnedExecutorProviderEvidence, Yr as runtimeOwnedExecutorMaterialization, Yt as beginScopeRetainedOwnerDrive, Zn as createOtelExporter, Zr as runtimeOwnedPendingExecutorMaterialization, Zt as scopeRetainedOwnerTurnEnded, an as owners, cn as scopeRetainedOwnerJournalRoot, dr as persistHarnessTranscript, dt as meterRuntimeOwnedAccounting, en as scopeRetainedOwnerRestorePoint, fr as readHarnessTranscript, ft as meterRuntimeOwnedProviderAttempt, gt as recordScopeOwnerPause, ht as recordScopeOwnerDriverAttempt, i as ROOT_STREAM_FILE, ii as isRuntimeFlowBrain, in as bindScopeRetainedOwnerProvider, jt as abandonScopeRetainedOwnerInvocation, l as readRootStream, mt as recordScopeOwnerBarrenPause, nt as assertRecursiveReservationPolicy, o as createRootStreamSink, oi as runtimeFlowAgent, pr as settleHarnessTranscript, pt as pauseScopeSeatAdmission, qr as runtimeOwnedDriveHarnessProviderEvidence, qt as providerVisibleProfile, rn as bindScopeRetainedOwnerEnvironmentId, si as runtimeFlowBrain, sn as scopeRetainedOwnerContext, tn as noteScopeRetainedOwnerCoordination, vn as executorObservationSeamKey, wr as SEAT_RECHECK_MS, yr as createActivityLog, zt as noteScopeOwnerPlannedExecution } from "./supervisor-accounting-Bnp1WYTX.js";
7
+ import { $n as generateSpanId, $r as runtimeOwnedScopeOwnerRuntime, $t as reconcileScopeRetainedOwnerEnvironment, Bt as recordScopeOwnerHarnessTranscript, Cr as isTerminalNodeStatus, Dr as authoredSeatStages, Dt as scopeRetainedOwnerResourceReader, Er as SeatPauseError, Et as releaseScopeRetainedOwnerForSeatPause, Ft as scopeRetainedOwnerResult, Gt as coordinationMcpAlias, Hr as recordRuntimeOwnedDriveHarnessProviderEvidence, Ht as restoreScopeOwnerAcceptedExecution, It as beginScopeOwnerAttempt, Jr as runtimeOwnedExecutorExecutionBinding, Jt as runtimeGraphMetadataKey, Kt as coordinationProfileToolPrefix, Mt as consumeScopeRetainedOwnerResult, Nr as attestRuntimeOwnedScopeOwner, Nt as prepareScopeRetainedOwnerTask, Or as seatExecutionProfile, Pr as authoredAgentIdentity, Pt as scopeRetainedOwnerPriorSpend, Qt as assertRetainedOwnerCoordinationRekey, Rt as holdScopeOwnerTranscript, Sr as isLiveNodeStatus, Tr as SeatChain, Tt as prepareScopeRetainedOwnerSeatSwitch, Ut as scopeOwnerExecutionObservation, V as parseWorkerToolTraceArtifact, Vn as WORKER_TRACE_PROPAGATION, Vr as providerAttemptEvidence, Vt as recordScopeOwnerMaterialization, Wt as scopeOwnerExecutorNodeContext, Xr as runtimeOwnedExecutorProviderEvidence, Yr as runtimeOwnedExecutorMaterialization, Yt as beginScopeRetainedOwnerDrive, Zn as createOtelExporter, Zr as runtimeOwnedPendingExecutorMaterialization, Zt as scopeRetainedOwnerTurnEnded, an as owners, cn as scopeRetainedOwnerJournalRoot, dr as persistHarnessTranscript, dt as meterRuntimeOwnedAccounting, en as scopeRetainedOwnerRestorePoint, fr as readHarnessTranscript, ft as meterRuntimeOwnedProviderAttempt, gt as recordScopeOwnerPause, ht as recordScopeOwnerDriverAttempt, i as ROOT_STREAM_FILE, ii as isRuntimeFlowBrain, in as bindScopeRetainedOwnerProvider, jt as abandonScopeRetainedOwnerInvocation, l as readRootStream, mt as recordScopeOwnerBarrenPause, nt as assertRecursiveReservationPolicy, o as createRootStreamSink, oi as runtimeFlowAgent, pr as settleHarnessTranscript, pt as pauseScopeSeatAdmission, qr as runtimeOwnedDriveHarnessProviderEvidence, qt as providerVisibleProfile, rn as bindScopeRetainedOwnerEnvironmentId, si as runtimeFlowBrain, sn as scopeRetainedOwnerContext, tn as noteScopeRetainedOwnerCoordination, vn as executorObservationSeamKey, wr as SEAT_RECHECK_MS, yr as createActivityLog, zt as noteScopeOwnerPlannedExecution } from "./supervisor-accounting--LFd8H4U.js";
8
8
  import { _ as runAbortable, g as linkAbort, p as RunCancellationReason } from "./jsonl-file-vE9H9UXa.js";
9
9
  import { a as createContinuationKeeper, i as checkVerdictOf, n as admitContinuationPolicy, r as bestComposite, t as CONTINUATIONS_DIR } from "./continuation-Bccak14N.js";
10
10
  import { At as recordValue, C as cappedDoublingMs, D as reportedResetAt, H as turnFailurePolicy, I as executorFailure, O as unavailablePauseMs, P as contentAddress, V as turnFailureOf, b as RATE_LIMIT_SIGNALS, et as meterUsageEvent, g as registerRetainedExecutorPreparation, it as assertValidBudget, k as unavailableResumeAt, l as RetainedExecutionPendingError, rt as spendFromUsageTotals, tt as newUsageTotals, v as retainedExecutorSeamKey, w as jitteredMs, y as PLACEMENT_SIGNALS, z as harnessProcessDied } from "./failure-cause-B2TBXIu-.js";
11
- import { a as readRunCancelRequest, d as writeRunCancellationAsync, l as watchRunCancellation, n as applyRunCancellationAsync, o as readRunCancellation, t as applyRunCancellation } from "./run-cancellation-D2fq7jx6.js";
11
+ import { a as readRunCancelRequest, d as writeRunCancellationAsync, l as watchRunCancellation, n as applyRunCancellationAsync, o as readRunCancellation, t as applyRunCancellation } from "./run-cancellation-BYnz8GlN.js";
12
12
  import { o as safeJsonText } from "./coordination-map-routing-XZXTlCmn.js";
13
13
  import { n as createStdioToolServer } from "./tool-server-B_cNseNf.js";
14
14
  import { A as withBudgetResources, D as addResourceSpend, S as unmeteredSpend, T as zeroSpend, c as errorMessage, f as isAsyncIterable, i as chargedTokens, k as resourceTelemetry, m as promptCacheTokenClasses, n as addSpend, v as sleep, w as withTimeout } from "./util-qsH5cC9S.js";
@@ -5096,6 +5096,13 @@ function budgetStop(budget, atMs) {
5096
5096
  if (budget.deadlineMs > 0 && atMs >= budget.deadlineMs) return "deadline";
5097
5097
  return budget.tokensCapped !== false && budget.tokensLeft <= 0 || budget.iterationsCapped !== false && budget.iterationsLeft <= 0 || budget.usdCapped && (budget.usdLeft <= 0 || budget.usdKnown === false) || Object.values(budget.resources ?? {}).some((r) => !r.known || r.remaining <= 0) ? "budget-exhausted" : void 0;
5098
5098
  }
5099
+ /** A spent channel that nothing can refill. A live run regains budget only from a settling child's
5100
+ * refund, so a spent token or known resource channel with nothing reserved stays spent until a
5101
+ * cancel or the deadline; pausing on it only holds the root for an operator. */
5102
+ function budgetCannotRefill(budget) {
5103
+ if (budget.tokensCapped !== false && budget.tokensLeft <= 0 && budget.reservedTokens <= 0) return true;
5104
+ return Object.values(budget.resources ?? {}).some((r) => r.known && r.remaining <= 0 && r.reserved <= 0);
5105
+ }
5099
5106
  /** The cause an admission or continuation refusal carries: it has no failure of its own. */
5100
5107
  function admissionError(stop) {
5101
5108
  return new ValidationError(`driver admission: ${stop}`);
@@ -5213,11 +5220,11 @@ var DriverRetryLoop = class {
5213
5220
  madeProgress: false
5214
5221
  });
5215
5222
  }
5216
- /** True when `stop` becomes a pause: the caller opted in, the stop is one the header names, and
5217
- * neither the run nor the manager's own stop has fired. */
5223
+ /** True when `stop` becomes a pause: the caller opted in, the stop is one the header names, a
5224
+ * spent budget could still be refunded, and neither the run nor the manager's own stop has fired. */
5218
5225
  pausesStop(stop) {
5219
5226
  const { run } = this;
5220
- return run.stopPause !== void 0 && PAUSED_STOPS.has(stop) && !run.signal.aborted && run.stopSignal?.aborted !== true;
5227
+ return run.stopPause !== void 0 && PAUSED_STOPS.has(stop) && !(stop === "budget-exhausted" && budgetCannotRefill(run.budget())) && !run.signal.aborted && run.stopSignal?.aborted !== true;
5221
5228
  }
5222
5229
  /** End the loop on `stop` with `record` (when the stop has one), or pause an opted-in root. */
5223
5230
  async stopOrPause(error, stop, record) {
@@ -5660,6 +5667,7 @@ var DriverRetryLoop = class {
5660
5667
  * open workers, and counts barren drives only after a model event in this process.
5661
5668
  *
5662
5669
  * Root stop-pauses wait on recoverable stops; they cannot reset an unchanged failure streak.
5670
+ * A spent budget pauses only while a reservation could refund it.
5663
5671
  * Cancellation ends the wait; a steer wakes it but grants no admission.
5664
5672
  */
5665
5673
  function assertContinuationPolicy(continuation) {
@@ -9502,4 +9510,4 @@ function superviseWithContext(profile, task, opts, brain) {
9502
9510
  }
9503
9511
  export { validateGraphTopology as A, allWorkersStalled as B, createFlowRun as C, validateFlowGraph as D, routeFlowOf as E, dumbContinuationPassPrompt as F, areaUnderCurve as G, noProgressFor as H, formatPromptHandle as I, renderAnytimeTable as J, bestSoFar as K, kernelPromptRegistry as L, createPromptRegistry as M, delegatesWorkerBriefPrompt as N, defaultEdgeTraversalCap as O, dumbContinuationFailPrompt as P, naiveContinuationPrompt as R, GraphRouteError as S, journaledGateDecider as T, plateau as U, anyOf as V, anytimeReport as W, createSupervisorSpanRecorder as Y, graphFlowSpawnProfile as _, bridgeProfileRefusal as a, serveCoordinationMcp as b, ASSISTANT_REASONING_SPAN as c, runToolSpans as d, UNPROVEN_CONTINUITY as f, createGraphOverlay as g, runBrainLoop as h, workerFromBackend as i, analyzesFindingsReportPrompt as j, graphRootProfile as k, ASSISTANT_TEXT_SPAN as l, driverAgent as m, superviseFleetCapabilities as n, supervisorAgent as o, composeReentryTask as p, plateauLength as q, superviseWithTestBrain as r, supervisorAgentWithTestBrain as s, supervise as t, rootStreamToolSpans as u, profileGuidanceComposer as v, flowRootProfile as w, coordinationControlToolNames as x, superviseRootProfile as y, promptHandle as z };
9504
9512
 
9505
- //# sourceMappingURL=supervise-aJRMwxRm.js.map
9513
+ //# sourceMappingURL=supervise-jfYp4dyB.js.map