@tangle-network/agent-runtime 0.320.1 → 0.322.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 (62) hide show
  1. package/dist/{activation-BKglRwjB.js → activation-CBv_0LUh.js} +2 -2
  2. package/dist/{activation-BKglRwjB.js.map → activation-CBv_0LUh.js.map} +1 -1
  3. package/dist/{activation-BSwcsNSQ.d.ts → activation-CZGz2kuu.d.ts} +2 -2
  4. package/dist/agent.d.ts +1 -1
  5. package/dist/agent.js +2 -2
  6. package/dist/candidate-execution/index.js +3 -3
  7. package/dist/{coordination-driver-D85RWATT.js → coordination-driver-C2Zm5lU4.js} +71 -3
  8. package/dist/coordination-driver-C2Zm5lU4.js.map +1 -0
  9. package/dist/{delegate-BHRR-4hh.js → delegate-BV7AVmbB.js} +2 -2
  10. package/dist/{delegate-BHRR-4hh.js.map → delegate-BV7AVmbB.js.map} +1 -1
  11. package/dist/durable.d.ts +1 -1
  12. package/dist/durable.js +3 -3
  13. package/dist/{graph-BGMcJJP1.js → graph-CH3YiPog.js} +4 -4
  14. package/dist/{graph-BGMcJJP1.js.map → graph-CH3YiPog.js.map} +1 -1
  15. package/dist/{improvement-cycle-0cnwWPFY.js → improvement-cycle-CD1h5GSM.js} +5 -5
  16. package/dist/{improvement-cycle-0cnwWPFY.js.map → improvement-cycle-CD1h5GSM.js.map} +1 -1
  17. package/dist/{index-t672ISFX.d.ts → index-CGNQWpge.d.ts} +877 -551
  18. package/dist/index.d.ts +4 -4
  19. package/dist/index.js +7 -7
  20. package/dist/intelligence.d.ts +2 -2
  21. package/dist/intelligence.js +6 -6
  22. package/dist/kernel.d.ts +2 -2
  23. package/dist/kernel.js +9 -9
  24. package/dist/{loop-runner-bin-CFudOt5T.js → loop-runner-bin-CFxE376A.js} +3 -3
  25. package/dist/{loop-runner-bin-CFudOt5T.js.map → loop-runner-bin-CFxE376A.js.map} +1 -1
  26. package/dist/{loop-runner-bin-Fgmf_PQU.d.ts → loop-runner-bin-C_jaLCUO.d.ts} +2 -2
  27. package/dist/loop-runner-bin.d.ts +1 -1
  28. package/dist/loop-runner-bin.js +1 -1
  29. package/dist/mcp/bin.js +3 -3
  30. package/dist/mcp/index.d.ts +2 -2
  31. package/dist/mcp/index.js +4 -4
  32. package/dist/{openai-tools-DCfdg0UD.d.ts → openai-tools-D1PDoBOz.d.ts} +2 -2
  33. package/dist/{prepare-DjCLEN-q.js → prepare-CFQLx9e3.js} +2 -2
  34. package/dist/{prepare-DjCLEN-q.js.map → prepare-CFQLx9e3.js.map} +1 -1
  35. package/dist/{profile-DmVM4Gxb.js → profile-BTbpdL9h.js} +40 -4
  36. package/dist/profile-BTbpdL9h.js.map +1 -0
  37. package/dist/profiles.d.ts +1 -1
  38. package/dist/{protected-model-port-D1fcnYdj.js → protected-model-port-f1N2f0Uq.js} +3 -3
  39. package/dist/{protected-model-port-D1fcnYdj.js.map → protected-model-port-f1N2f0Uq.js.map} +1 -1
  40. package/dist/{provision-supervisor-BUMhF1yb.js → provision-supervisor-ftJZhqBU.js} +3 -3
  41. package/dist/{provision-supervisor-BUMhF1yb.js.map → provision-supervisor-ftJZhqBU.js.map} +1 -1
  42. package/dist/{runtime-B47V5Omi.js → runtime-EiTCboO2.js} +465 -12
  43. package/dist/runtime-EiTCboO2.js.map +1 -0
  44. package/dist/{search-executor-DjKdQluM.js → search-executor-ECJ2TmC-.js} +2 -2
  45. package/dist/{search-executor-DjKdQluM.js.map → search-executor-ECJ2TmC-.js.map} +1 -1
  46. package/dist/{server-Gpgr0WP-.js → server-C2k5wX4k.js} +3 -3
  47. package/dist/{server-Gpgr0WP-.js.map → server-C2k5wX4k.js.map} +1 -1
  48. package/dist/{supervise-C2ThvLgZ.js → supervise-BjrRk-AN.js} +194 -133
  49. package/dist/supervise-BjrRk-AN.js.map +1 -0
  50. package/dist/{supervisor-CCtmmmOz.js → supervisor-BMMdI4T-.js} +606 -81
  51. package/dist/supervisor-BMMdI4T-.js.map +1 -0
  52. package/dist/testing.d.ts +1 -1
  53. package/dist/testing.js +13 -13
  54. package/dist/tui/index.d.ts +1 -1
  55. package/dist/tui/index.js +1 -1
  56. package/package.json +6 -6
  57. package/skills/profile-authoring/SKILL.md +1 -0
  58. package/dist/coordination-driver-D85RWATT.js.map +0 -1
  59. package/dist/profile-DmVM4Gxb.js.map +0 -1
  60. package/dist/runtime-B47V5Omi.js.map +0 -1
  61. package/dist/supervise-C2ThvLgZ.js.map +0 -1
  62. package/dist/supervisor-CCtmmmOz.js.map +0 -1
@@ -1,5 +1,5 @@
1
1
  import { B as verifyCanonicalCandidateDocument, L as immutableCandidateValue, N as canonicalCandidateDigest$1, P as canonicalCandidateDocument } from "./workspace-streams-DFAhW7hF.js";
2
- import { A as agentImprovementTargetInput, M as agentProfileImprovementStateDigest, c as requireSealedCandidateExperiment, d as verifyAgentImprovementActivation, f as verifyAgentImprovementProposal, k as agentImprovementTargetDigest } from "./improvement-cycle-0cnwWPFY.js";
2
+ import { A as agentImprovementTargetInput, M as agentProfileImprovementStateDigest, c as requireSealedCandidateExperiment, d as verifyAgentImprovementActivation, f as verifyAgentImprovementProposal, k as agentImprovementTargetDigest } from "./improvement-cycle-CD1h5GSM.js";
3
3
  import { agentImprovementActivationResultSchema, agentImprovementActivationSchema, agentProfileImprovementExperimentSchema } from "@tangle-network/agent-interface";
4
4
  //#region src/runtime-usage.ts
5
5
  function createRuntimeUsageTotals() {
@@ -231,4 +231,4 @@ function targetIdentity(target) {
231
231
  //#endregion
232
232
  export { createRuntimeUsageTotals as a, addRuntimeUsage as i, executeAgentImprovementActivation as n, isUsageAmount as o, verifyAgentImprovementActivationResult as r, createAgentImprovementActivationResult as t };
233
233
 
234
- //# sourceMappingURL=activation-BKglRwjB.js.map
234
+ //# sourceMappingURL=activation-CBv_0LUh.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"activation-BKglRwjB.js","names":["canonicalCandidateDigest"],"sources":["../src/runtime-usage.ts","../src/intelligence/activation.ts"],"sourcesContent":["import type { RuntimeStreamEvent } from './types'\n\n/** Observed subtotals, with missing measurements kept separate from measured zeroes. */\nexport interface RuntimeUsageTotals {\n /** Observed input tokens across normalized per-call events. */\n tokensIn: number\n /** Observed output tokens across normalized per-call events. */\n tokensOut: number\n /** Observed dollar subtotal; incomplete when `usdKnown` is false. */\n costUsd: number\n /** Number of observed model calls, including unpriced or incompletely metered calls. */\n llmCalls: number\n /** False when any observed call has incomplete token usage. */\n tokensKnown?: false\n /** False when any observed call lacks complete provider-billed cost. */\n usdKnown?: false\n /** Sum of reported external estimates; never included in `costUsd` or proof of complete cost. */\n estimatedCostUsd?: number\n}\n\nexport function createRuntimeUsageTotals(): RuntimeUsageTotals {\n return { tokensIn: 0, tokensOut: 0, costUsd: 0, llmCalls: 0 }\n}\n\nexport function isUsageAmount(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value) && value >= 0\n}\n\n/** Fold normalized per-call events. Backend adapters own cumulative receipt reconciliation. */\nexport function addRuntimeUsage(\n totals: RuntimeUsageTotals,\n event: Extract<RuntimeStreamEvent, { type: 'llm_call' }>,\n): void {\n totals.llmCalls += 1\n for (const key of ['tokensIn', 'tokensOut', 'costUsd'] as const) {\n const value = event[key]\n if (isUsageAmount(value)) totals[key] += value\n else if (key === 'costUsd') totals.usdKnown = false\n else totals.tokensKnown = false\n }\n if (event.tokensKnown === false) totals.tokensKnown = false\n if (event.usdKnown === false) totals.usdKnown = false\n if (isUsageAmount(event.estimatedCostUsd)) {\n totals.estimatedCostUsd = (totals.estimatedCostUsd ?? 0) + event.estimatedCostUsd\n }\n}\n","import type {\n AgentCandidateBundle,\n AgentCandidateExperiment,\n AgentImprovementActivation,\n AgentImprovementActivationOutcome,\n AgentImprovementActivationResult,\n AgentImprovementActivationTarget,\n AgentImprovementProposal,\n AgentImprovementReview,\n AgentImprovementSurface,\n AgentProfileImprovementChange,\n AgentProfileImprovementExperiment,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport {\n agentImprovementActivationResultSchema,\n agentImprovementActivationSchema,\n agentProfileImprovementExperimentSchema,\n} from '@tangle-network/agent-interface'\n\nimport {\n canonicalCandidateDigest,\n canonicalCandidateDocument,\n immutableCandidateValue,\n verifyCanonicalCandidateDocument,\n} from '../candidate-execution/digest'\nimport {\n requireSealedCandidateExperiment,\n verifyAgentImprovementActivation,\n verifyAgentImprovementProposal,\n} from './improvement-cycle'\nimport {\n agentImprovementTargetDigest,\n agentImprovementTargetInput,\n agentProfileImprovementStateDigest,\n} from './improvement-surfaces'\n\nexport interface CreateAgentImprovementActivationResultOptions {\n completedAt: string\n outcome: AgentImprovementActivationOutcome\n}\n\nexport interface AgentImprovementActivationTargetPlan extends AgentImprovementActivationTarget {\n desiredDigest: Sha256Digest\n /**\n * Exact measured input the product must apply to reach `desiredDigest`.\n * Transition surfaces such as code and knowledge are applied operations, so\n * their resulting state digest is not the digest of this input document.\n */\n desiredInput: unknown\n}\n\nexport type AgentProfileImprovementActivationOperation =\n | {\n kind: 'apply-change'\n changes: AgentProfileImprovementChange\n }\n | {\n /** The product must load its own saved state at `desiredStateDigest`. */\n kind: 'restore-state'\n }\n\nexport interface AgentProfileImprovementActivationTargetPlan\n extends AgentImprovementActivationTarget {\n desiredDigest: Sha256Digest\n desiredInput: AgentProfileImprovementActivationOperation\n}\n\nexport interface SealedCandidateActivationTransitionInput {\n kind: 'sealed-candidate'\n activation: AgentImprovementActivation\n candidateBundle: AgentCandidateBundle\n bundle: AgentCandidateBundle\n targets: [AgentImprovementActivationTargetPlan, ...AgentImprovementActivationTargetPlan[]]\n attemptedAt: string\n expired: boolean\n}\n\n/**\n * A measured profile change without raw profile bytes.\n * The product owns the private state lookup and atomic write.\n */\nexport interface ProfileImprovementActivationTransitionInput {\n kind: 'profile-improvement'\n activation: AgentImprovementActivation\n experiment: AgentProfileImprovementExperiment\n sourceStateDigest: Sha256Digest\n desiredStateDigest: Sha256Digest\n operation: AgentProfileImprovementActivationOperation\n targets: [\n AgentProfileImprovementActivationTargetPlan,\n ...AgentProfileImprovementActivationTargetPlan[],\n ]\n attemptedAt: string\n expired: boolean\n}\n\nexport type AgentImprovementActivationTransitionInput =\n | SealedCandidateActivationTransitionInput\n | ProfileImprovementActivationTransitionInput\n\nexport interface AgentImprovementActivationResultStore {\n load(idempotencyKey: Sha256Digest): Promise<unknown | undefined>\n putIfAbsent(result: AgentImprovementActivationResult): Promise<unknown>\n}\n\n/**\n * Product-owned or Runtime-composed transition.\n *\n * Implementations resolve a stored result for `activation.digest`, compare\n * every target, and make the write durably idempotent. Co-located targets store\n * the all-or-none write with its result. Other targets throw when result\n * storage fails so a retry can reconcile it. Runtime never invokes this write\n * function after authorization expires.\n */\nexport type AgentImprovementActivationTransition = (\n input: AgentImprovementActivationTransitionInput,\n) => Promise<unknown>\n\n/**\n * Target-read-only check for a prior exact write.\n * It may persist recovered result metadata, but must not change an activation target.\n * Return undefined only when no target write can have committed.\n */\nexport type AgentImprovementActivationReconciliation = (\n input: AgentImprovementActivationTransitionInput,\n) => Promise<unknown | undefined>\n\nexport interface ExecuteAgentImprovementActivationInput {\n proposal: AgentImprovementProposal\n review: AgentImprovementReview\n activation: AgentImprovementActivation\n}\n\nexport interface ExecuteAgentImprovementActivationOptions {\n transition: AgentImprovementActivationTransition\n reconcile?: AgentImprovementActivationReconciliation\n now?: () => Date\n}\n\n/** Create the exact result a product stores in the same transaction as its target write. */\nexport function createAgentImprovementActivationResult(\n transition: AgentImprovementActivationTransitionInput,\n options: CreateAgentImprovementActivationResultOptions,\n): AgentImprovementActivationResult {\n const activation = verifyCanonicalCandidateDocument(\n agentImprovementActivationSchema.parse(transition.activation),\n 'agent improvement activation',\n )\n assertTransitionInput(activation, transition)\n const result = agentImprovementActivationResultSchema.parse(\n canonicalCandidateDocument<AgentImprovementActivationResult>({\n kind: 'agent-improvement-activation-result',\n idempotencyKey: activation.digest,\n attemptedAt: transition.attemptedAt,\n completedAt: options.completedAt,\n outcome: options.outcome,\n }).value,\n )\n assertResultAgainstActivation(activation, result)\n assertOutcomeDesiredState(\n activation,\n result,\n new Map(transition.targets.map((target) => [targetIdentity(target), target.desiredDigest])),\n )\n return immutableCandidateValue(result)\n}\n\n/**\n * Recompute one historical activation result against the exact measured proposal and authority.\n * The result records that attempt; it is not a query of the target's current state.\n */\nexport function verifyAgentImprovementActivationResult(input: {\n proposal: unknown\n review: unknown\n activation: unknown\n result: unknown\n}): AgentImprovementActivationResult {\n const proposal = verifyAgentImprovementProposal(input.proposal)\n const activation = verifyAgentImprovementActivation(input)\n const result = verifyCanonicalCandidateDocument(\n agentImprovementActivationResultSchema.parse(input.result),\n 'agent improvement activation result',\n )\n assertResultAgainstActivation(activation, result)\n assertResultDesiredState(proposal, activation, result)\n return result\n}\n\n/** Validate and execute one product-owned activation transition. */\nexport async function executeAgentImprovementActivation(\n input: ExecuteAgentImprovementActivationInput,\n options: ExecuteAgentImprovementActivationOptions,\n): Promise<AgentImprovementActivationResult> {\n const proposal = verifyAgentImprovementProposal(input.proposal)\n const activation = verifyAgentImprovementActivation(input)\n const observedAt = (options.now ?? (() => new Date()))().toISOString()\n const attemptedAt =\n Date.parse(observedAt) < Date.parse(activation.authorizedAt)\n ? activation.authorizedAt\n : observedAt\n const expired = Date.parse(attemptedAt) >= Date.parse(activation.expiresAt)\n const transition = immutableCandidateValue<AgentImprovementActivationTransitionInput>(\n proposal.evaluation.kind === 'agent-improvement-measured-comparison'\n ? sealedCandidateTransition(proposal.evaluation.experiment, activation, attemptedAt, expired)\n : profileImprovementTransition(\n proposal.evaluation.experiment,\n activation,\n attemptedAt,\n expired,\n ),\n )\n\n if (transition.expired) {\n if (!options.reconcile) {\n return uncertainActivationResult(transition, 'RECONCILIATION_UNAVAILABLE')\n }\n let reconciled: unknown\n try {\n reconciled = await options.reconcile(transition)\n } catch {\n return uncertainActivationResult(transition, 'RECONCILIATION_THROW')\n }\n if (reconciled === undefined) {\n return createAgentImprovementActivationResult(transition, {\n completedAt: transition.attemptedAt,\n outcome: { status: 'expired' },\n })\n }\n try {\n return verifyAgentImprovementActivationResult({ ...input, result: reconciled })\n } catch {\n return uncertainActivationResult(transition, 'INVALID_RECONCILIATION')\n }\n }\n\n let rawResult: unknown\n try {\n rawResult = await options.transition(transition)\n } catch {\n return uncertainActivationResult(transition, 'TRANSITION_THROW')\n }\n try {\n return verifyAgentImprovementActivationResult({ ...input, result: rawResult })\n } catch {\n return uncertainActivationResult(transition, 'INVALID_RESULT')\n }\n}\n\nfunction sealedCandidateTransition(\n experiment: AgentCandidateExperiment,\n activation: AgentImprovementActivation,\n attemptedAt: string,\n expired: boolean,\n): SealedCandidateActivationTransitionInput {\n const targetArm = activation.intent === 'activate-candidate' ? 'candidate' : 'baseline'\n return {\n kind: 'sealed-candidate',\n activation,\n candidateBundle: experiment.candidate,\n bundle: experiment[targetArm],\n targets: activation.targets.map((target) => ({\n ...target,\n desiredDigest: agentImprovementTargetDigest(experiment, targetArm, target.surface),\n desiredInput: agentImprovementTargetInput(experiment[targetArm], target.surface),\n })) as SealedCandidateActivationTransitionInput['targets'],\n attemptedAt,\n expired,\n }\n}\n\nfunction profileImprovementTransition(\n experiment: AgentProfileImprovementExperiment,\n activation: AgentImprovementActivation,\n attemptedAt: string,\n expired: boolean,\n): ProfileImprovementActivationTransitionInput {\n const sourceArm = activation.intent === 'activate-candidate' ? 'baseline' : 'candidate'\n const targetArm = activation.intent === 'activate-candidate' ? 'candidate' : 'baseline'\n const operation = profileImprovementOperation(experiment, activation.intent)\n return {\n kind: 'profile-improvement',\n activation,\n experiment,\n sourceStateDigest: agentProfileImprovementStateDigest(experiment, sourceArm),\n desiredStateDigest: agentProfileImprovementStateDigest(experiment, targetArm),\n operation,\n targets: activation.targets.map((target) => ({\n ...target,\n desiredDigest: agentProfileImprovementStateDigest(experiment, targetArm),\n desiredInput: operation,\n })) as ProfileImprovementActivationTransitionInput['targets'],\n attemptedAt,\n expired,\n }\n}\n\nfunction profileImprovementOperation(\n experiment: AgentProfileImprovementExperiment,\n intent: AgentImprovementActivation['intent'],\n): AgentProfileImprovementActivationOperation {\n return intent === 'activate-candidate'\n ? { kind: 'apply-change', changes: experiment.change }\n : { kind: 'restore-state' }\n}\n\nfunction uncertainActivationResult(\n transition: AgentImprovementActivationTransitionInput,\n code: string,\n): AgentImprovementActivationResult {\n return createAgentImprovementActivationResult(transition, {\n completedAt: transition.attemptedAt,\n outcome: {\n status: 'indeterminate',\n code,\n message: 'The product transition did not return a trustworthy commit result.',\n },\n })\n}\n\nfunction assertTransitionInput(\n activation: AgentImprovementActivation,\n transition: AgentImprovementActivationTransitionInput,\n): void {\n if (transition.kind === 'sealed-candidate') {\n assertSealedCandidateTransitionInput(activation, transition)\n return\n }\n assertProfileImprovementTransitionInput(activation, transition)\n}\n\nfunction assertSealedCandidateTransitionInput(\n activation: AgentImprovementActivation,\n transition: SealedCandidateActivationTransitionInput,\n): void {\n assertAuthorizedTransitionTargets(activation, transition.targets)\n const desiredInputsMatch = transition.targets.every(\n (target) =>\n canonicalCandidateDigest(target.desiredInput) ===\n canonicalCandidateDigest(agentImprovementTargetInput(transition.bundle, target.surface)),\n )\n if (\n transition.expired !== Date.parse(transition.attemptedAt) >= Date.parse(activation.expiresAt) ||\n transition.candidateBundle.digest !== activation.candidateDigest ||\n !desiredInputsMatch ||\n (activation.intent === 'activate-candidate' &&\n transition.bundle.digest !== transition.candidateBundle.digest)\n ) {\n throw new Error('activation transition does not match its authorization')\n }\n}\n\nfunction assertProfileImprovementTransitionInput(\n activation: AgentImprovementActivation,\n transition: ProfileImprovementActivationTransitionInput,\n): void {\n assertAuthorizedTransitionTargets(activation, transition.targets)\n const targetsAgentProfile = activation.targets.some(\n (target) => target.surface === 'agent-profile',\n )\n const experiment = agentProfileImprovementExperimentSchema.parse(transition.experiment)\n const sourceArm = activation.intent === 'activate-candidate' ? 'baseline' : 'candidate'\n const targetArm = activation.intent === 'activate-candidate' ? 'candidate' : 'baseline'\n const sourceStateDigest = agentProfileImprovementStateDigest(experiment, sourceArm)\n const desiredStateDigest = agentProfileImprovementStateDigest(experiment, targetArm)\n const operation = profileImprovementOperation(experiment, activation.intent)\n const targetsMatch = transition.targets.every(\n (target) =>\n target.expectedBaseDigest === sourceStateDigest &&\n target.desiredDigest === desiredStateDigest &&\n canonicalCandidateDigest(target.desiredInput) === canonicalCandidateDigest(operation),\n )\n if (\n transition.expired !== Date.parse(transition.attemptedAt) >= Date.parse(activation.expiresAt) ||\n experiment.digest !== activation.experimentDigest ||\n experiment.candidate.stateDigest !== activation.candidateDigest ||\n (targetsAgentProfile &&\n (activation.executionRef === undefined ||\n canonicalCandidateDigest(activation.executionRef) !==\n canonicalCandidateDigest(experiment.executionRef))) ||\n transition.sourceStateDigest !== sourceStateDigest ||\n transition.desiredStateDigest !== desiredStateDigest ||\n canonicalCandidateDigest(transition.operation) !== canonicalCandidateDigest(operation) ||\n !targetsMatch\n ) {\n throw new Error('activation transition does not match its authorization')\n }\n}\n\nfunction assertAuthorizedTransitionTargets(\n activation: AgentImprovementActivation,\n targets: readonly AgentImprovementActivationTargetPlan[],\n): void {\n const authorized = targetMap(activation.targets)\n const planned = targetMap(targets)\n if (\n authorized.size !== planned.size ||\n [...authorized.entries()].some(\n ([identity, target]) =>\n planned.get(identity)?.expectedBaseDigest !== target.expectedBaseDigest,\n )\n ) {\n throw new Error('activation transition does not match its authorization')\n }\n}\n\nfunction assertResultAgainstActivation(\n activation: AgentImprovementActivation,\n result: AgentImprovementActivationResult,\n): void {\n const attemptedAt = Date.parse(result.attemptedAt)\n const completedAt = Date.parse(result.completedAt)\n const expiresAt = Date.parse(activation.expiresAt)\n if (\n result.idempotencyKey !== activation.digest ||\n attemptedAt < Date.parse(activation.authorizedAt) ||\n completedAt < attemptedAt\n ) {\n throw new Error('activation result does not bind its authorization')\n }\n const expired = attemptedAt >= expiresAt\n if (\n (result.outcome.status === 'expired' && !expired) ||\n (expired && !['expired', 'indeterminate', 'already-applied'].includes(result.outcome.status))\n ) {\n throw new Error('activation result does not honor its authorization expiry')\n }\n if (!('targets' in result.outcome)) return\n const authorized = targetMap(activation.targets)\n const observed = new Set(result.outcome.targets.map(targetIdentity))\n if (\n authorized.size !== observed.size ||\n [...authorized.keys()].some((identity) => !observed.has(identity))\n ) {\n throw new Error('activation result must cover every authorized target exactly once')\n }\n if (\n result.outcome.status === 'applied' &&\n result.outcome.targets.some(\n (target) =>\n target.beforeDigest !== authorized.get(targetIdentity(target))?.expectedBaseDigest,\n )\n ) {\n throw new Error('applied activation did not start from its authorized base state')\n }\n}\n\nfunction assertResultDesiredState(\n proposal: AgentImprovementProposal,\n activation: AgentImprovementActivation,\n result: AgentImprovementActivationResult,\n): void {\n if (!('targets' in result.outcome)) return\n const targetArm = activation.intent === 'activate-candidate' ? 'candidate' : 'baseline'\n const desiredStateDigest =\n proposal.evaluation.kind === 'agent-profile-improvement-measured-comparison'\n ? agentProfileImprovementStateDigest(proposal.evaluation.experiment, targetArm)\n : undefined\n const desired = new Map(\n activation.targets.map((target) => [\n targetIdentity(target),\n desiredStateDigest ??\n agentImprovementTargetDigest(\n requireSealedCandidateExperiment(proposal),\n targetArm,\n target.surface,\n ),\n ]),\n )\n assertOutcomeDesiredState(activation, result, desired)\n}\n\nfunction assertOutcomeDesiredState(\n activation: AgentImprovementActivation,\n result: AgentImprovementActivationResult,\n desired: ReadonlyMap<string, Sha256Digest>,\n): void {\n if (!('targets' in result.outcome)) return\n if (result.outcome.status === 'applied') {\n if (\n result.outcome.targets.some(\n (target) => target.afterDigest !== desired.get(targetIdentity(target)),\n )\n ) {\n throw new Error('applied activation does not match the requested bundle')\n }\n return\n }\n const allDesired = result.outcome.targets.every(\n (target) => target.currentDigest === desired.get(targetIdentity(target)),\n )\n if (result.outcome.status === 'already-applied') {\n if (!allDesired) throw new Error('already-applied activation is not at the requested state')\n return\n }\n const authorized = targetMap(activation.targets)\n const hasStaleTarget = result.outcome.targets.some(\n (target) => target.currentDigest !== authorized.get(targetIdentity(target))?.expectedBaseDigest,\n )\n if (allDesired || !hasStaleTarget) {\n throw new Error('activation conflict does not identify stale target state')\n }\n}\n\nfunction targetMap<T extends { surface: AgentImprovementSurface; identity: string }>(\n targets: readonly T[],\n): Map<string, T> {\n return new Map(targets.map((target) => [targetIdentity(target), target]))\n}\n\nfunction targetIdentity(target: { surface: AgentImprovementSurface; identity: string }): string {\n return `${target.surface}\\u0000${target.identity}`\n}\n"],"mappings":";;;;AAoBA,SAAgB,2BAA+C;CAC7D,OAAO;EAAE,UAAU;EAAG,WAAW;EAAG,SAAS;EAAG,UAAU;CAAE;AAC9D;AAEA,SAAgB,cAAc,OAAiC;CAC7D,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,KAAK,SAAS;AACzE;;AAGA,SAAgB,gBACd,QACA,OACM;CACN,OAAO,YAAY;CACnB,KAAK,MAAM,OAAO;EAAC;EAAY;EAAa;CAAS,GAAY;EAC/D,MAAM,QAAQ,MAAM;EACpB,IAAI,cAAc,KAAK,GAAG,OAAO,QAAQ;OACpC,IAAI,QAAQ,WAAW,OAAO,WAAW;OACzC,OAAO,cAAc;CAC5B;CACA,IAAI,MAAM,gBAAgB,OAAO,OAAO,cAAc;CACtD,IAAI,MAAM,aAAa,OAAO,OAAO,WAAW;CAChD,IAAI,cAAc,MAAM,gBAAgB,GACtC,OAAO,oBAAoB,OAAO,oBAAoB,KAAK,MAAM;AAErE;;;;ACgGA,SAAgB,uCACd,YACA,SACkC;CAClC,MAAM,aAAa,iCACjB,iCAAiC,MAAM,WAAW,UAAU,GAC5D,8BACF;CACA,sBAAsB,YAAY,UAAU;CAC5C,MAAM,SAAS,uCAAuC,MACpD,2BAA6D;EAC3D,MAAM;EACN,gBAAgB,WAAW;EAC3B,aAAa,WAAW;EACxB,aAAa,QAAQ;EACrB,SAAS,QAAQ;CACnB,CAAC,CAAC,CAAC,KACL;CACA,8BAA8B,YAAY,MAAM;CAChD,0BACE,YACA,QACA,IAAI,IAAI,WAAW,QAAQ,KAAK,WAAW,CAAC,eAAe,MAAM,GAAG,OAAO,a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OAAO,IAAI,IAAI,QAAQ,KAAK,WAAW,CAAC,eAAe,MAAM,GAAG,MAAM,CAAC,CAAC;AAC1E;AAEA,SAAS,eAAe,QAAwE;CAC9F,OAAO,GAAG,OAAO,QAAQ,QAAQ,OAAO;AAC1C"}
1
+ {"version":3,"file":"activation-CBv_0LUh.js","names":["canonicalCandidateDigest"],"sources":["../src/runtime-usage.ts","../src/intelligence/activation.ts"],"sourcesContent":["import type { RuntimeStreamEvent } from './types'\n\n/** Observed subtotals, with missing measurements kept separate from measured zeroes. */\nexport interface RuntimeUsageTotals {\n /** Observed input tokens across normalized per-call events. */\n tokensIn: number\n /** Observed output tokens across normalized per-call events. */\n tokensOut: number\n /** Observed dollar subtotal; incomplete when `usdKnown` is false. */\n costUsd: number\n /** Number of observed model calls, including unpriced or incompletely metered calls. */\n llmCalls: number\n /** False when any observed call has incomplete token usage. */\n tokensKnown?: false\n /** False when any observed call lacks complete provider-billed cost. */\n usdKnown?: false\n /** Sum of reported external estimates; never included in `costUsd` or proof of complete cost. */\n estimatedCostUsd?: number\n}\n\nexport function createRuntimeUsageTotals(): RuntimeUsageTotals {\n return { tokensIn: 0, tokensOut: 0, costUsd: 0, llmCalls: 0 }\n}\n\nexport function isUsageAmount(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value) && value >= 0\n}\n\n/** Fold normalized per-call events. Backend adapters own cumulative receipt reconciliation. */\nexport function addRuntimeUsage(\n totals: RuntimeUsageTotals,\n event: Extract<RuntimeStreamEvent, { type: 'llm_call' }>,\n): void {\n totals.llmCalls += 1\n for (const key of ['tokensIn', 'tokensOut', 'costUsd'] as const) {\n const value = event[key]\n if (isUsageAmount(value)) totals[key] += value\n else if (key === 'costUsd') totals.usdKnown = false\n else totals.tokensKnown = false\n }\n if (event.tokensKnown === false) totals.tokensKnown = false\n if (event.usdKnown === false) totals.usdKnown = false\n if (isUsageAmount(event.estimatedCostUsd)) {\n totals.estimatedCostUsd = (totals.estimatedCostUsd ?? 0) + event.estimatedCostUsd\n }\n}\n","import type {\n AgentCandidateBundle,\n AgentCandidateExperiment,\n AgentImprovementActivation,\n AgentImprovementActivationOutcome,\n AgentImprovementActivationResult,\n AgentImprovementActivationTarget,\n AgentImprovementProposal,\n AgentImprovementReview,\n AgentImprovementSurface,\n AgentProfileImprovementChange,\n AgentProfileImprovementExperiment,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport {\n agentImprovementActivationResultSchema,\n agentImprovementActivationSchema,\n agentProfileImprovementExperimentSchema,\n} from '@tangle-network/agent-interface'\n\nimport {\n canonicalCandidateDigest,\n canonicalCandidateDocument,\n immutableCandidateValue,\n verifyCanonicalCandidateDocument,\n} from '../candidate-execution/digest'\nimport {\n requireSealedCandidateExperiment,\n verifyAgentImprovementActivation,\n verifyAgentImprovementProposal,\n} from './improvement-cycle'\nimport {\n agentImprovementTargetDigest,\n agentImprovementTargetInput,\n agentProfileImprovementStateDigest,\n} from './improvement-surfaces'\n\nexport interface CreateAgentImprovementActivationResultOptions {\n completedAt: string\n outcome: AgentImprovementActivationOutcome\n}\n\nexport interface AgentImprovementActivationTargetPlan extends AgentImprovementActivationTarget {\n desiredDigest: Sha256Digest\n /**\n * Exact measured input the product must apply to reach `desiredDigest`.\n * Transition surfaces such as code and knowledge are applied operations, so\n * their resulting state digest is not the digest of this input document.\n */\n desiredInput: unknown\n}\n\nexport type AgentProfileImprovementActivationOperation =\n | {\n kind: 'apply-change'\n changes: AgentProfileImprovementChange\n }\n | {\n /** The product must load its own saved state at `desiredStateDigest`. */\n kind: 'restore-state'\n }\n\nexport interface AgentProfileImprovementActivationTargetPlan\n extends AgentImprovementActivationTarget {\n desiredDigest: Sha256Digest\n desiredInput: AgentProfileImprovementActivationOperation\n}\n\nexport interface SealedCandidateActivationTransitionInput {\n kind: 'sealed-candidate'\n activation: AgentImprovementActivation\n candidateBundle: AgentCandidateBundle\n bundle: AgentCandidateBundle\n targets: [AgentImprovementActivationTargetPlan, ...AgentImprovementActivationTargetPlan[]]\n attemptedAt: string\n expired: boolean\n}\n\n/**\n * A measured profile change without raw profile bytes.\n * The product owns the private state lookup and atomic write.\n */\nexport interface ProfileImprovementActivationTransitionInput {\n kind: 'profile-improvement'\n activation: AgentImprovementActivation\n experiment: AgentProfileImprovementExperiment\n sourceStateDigest: Sha256Digest\n desiredStateDigest: Sha256Digest\n operation: AgentProfileImprovementActivationOperation\n targets: [\n AgentProfileImprovementActivationTargetPlan,\n ...AgentProfileImprovementActivationTargetPlan[],\n ]\n attemptedAt: string\n expired: boolean\n}\n\nexport type AgentImprovementActivationTransitionInput =\n | SealedCandidateActivationTransitionInput\n | ProfileImprovementActivationTransitionInput\n\nexport interface AgentImprovementActivationResultStore {\n load(idempotencyKey: Sha256Digest): Promise<unknown | undefined>\n putIfAbsent(result: AgentImprovementActivationResult): Promise<unknown>\n}\n\n/**\n * Product-owned or Runtime-composed transition.\n *\n * Implementations resolve a stored result for `activation.digest`, compare\n * every target, and make the write durably idempotent. Co-located targets store\n * the all-or-none write with its result. Other targets throw when result\n * storage fails so a retry can reconcile it. Runtime never invokes this write\n * function after authorization expires.\n */\nexport type AgentImprovementActivationTransition = (\n input: AgentImprovementActivationTransitionInput,\n) => Promise<unknown>\n\n/**\n * Target-read-only check for a prior exact write.\n * It may persist recovered result metadata, but must not change an activation target.\n * Return undefined only when no target write can have committed.\n */\nexport type AgentImprovementActivationReconciliation = (\n input: AgentImprovementActivationTransitionInput,\n) => Promise<unknown | undefined>\n\nexport interface ExecuteAgentImprovementActivationInput {\n proposal: AgentImprovementProposal\n review: AgentImprovementReview\n activation: AgentImprovementActivation\n}\n\nexport interface ExecuteAgentImprovementActivationOptions {\n transition: AgentImprovementActivationTransition\n reconcile?: AgentImprovementActivationReconciliation\n now?: () => Date\n}\n\n/** Create the exact result a product stores in the same transaction as its target write. */\nexport function createAgentImprovementActivationResult(\n transition: AgentImprovementActivationTransitionInput,\n options: CreateAgentImprovementActivationResultOptions,\n): AgentImprovementActivationResult {\n const activation = verifyCanonicalCandidateDocument(\n agentImprovementActivationSchema.parse(transition.activation),\n 'agent improvement activation',\n )\n assertTransitionInput(activation, transition)\n const result = agentImprovementActivationResultSchema.parse(\n canonicalCandidateDocument<AgentImprovementActivationResult>({\n kind: 'agent-improvement-activation-result',\n idempotencyKey: activation.digest,\n attemptedAt: transition.attemptedAt,\n completedAt: options.completedAt,\n outcome: options.outcome,\n }).value,\n )\n assertResultAgainstActivation(activation, result)\n assertOutcomeDesiredState(\n activation,\n result,\n new Map(transition.targets.map((target) => [targetIdentity(target), target.desiredDigest])),\n )\n return immutableCandidateValue(result)\n}\n\n/**\n * Recompute one historical activation result against the exact measured proposal and authority.\n * The result records that attempt; it is not a query of the target's current state.\n */\nexport function verifyAgentImprovementActivationResult(input: {\n proposal: unknown\n review: unknown\n activation: unknown\n result: unknown\n}): AgentImprovementActivationResult {\n const proposal = verifyAgentImprovementProposal(input.proposal)\n const activation = verifyAgentImprovementActivation(input)\n const result = verifyCanonicalCandidateDocument(\n agentImprovementActivationResultSchema.parse(input.result),\n 'agent improvement activation result',\n )\n assertResultAgainstActivation(activation, result)\n assertResultDesiredState(proposal, activation, result)\n return result\n}\n\n/** Validate and execute one product-owned activation transition. */\nexport async function executeAgentImprovementActivation(\n input: ExecuteAgentImprovementActivationInput,\n options: ExecuteAgentImprovementActivationOptions,\n): Promise<AgentImprovementActivationResult> {\n const proposal = verifyAgentImprovementProposal(input.proposal)\n const activation = verifyAgentImprovementActivation(input)\n const observedAt = (options.now ?? (() => new Date()))().toISOString()\n const attemptedAt =\n Date.parse(observedAt) < Date.parse(activation.authorizedAt)\n ? activation.authorizedAt\n : observedAt\n const expired = Date.parse(attemptedAt) >= Date.parse(activation.expiresAt)\n const transition = immutableCandidateValue<AgentImprovementActivationTransitionInput>(\n proposal.evaluation.kind === 'agent-improvement-measured-comparison'\n ? sealedCandidateTransition(proposal.evaluation.experiment, activation, attemptedAt, expired)\n : profileImprovementTransition(\n proposal.evaluation.experiment,\n activation,\n attemptedAt,\n expired,\n ),\n )\n\n if (transition.expired) {\n if (!options.reconcile) {\n return uncertainActivationResult(transition, 'RECONCILIATION_UNAVAILABLE')\n }\n let reconciled: unknown\n try {\n reconciled = await options.reconcile(transition)\n } catch {\n return uncertainActivationResult(transition, 'RECONCILIATION_THROW')\n }\n if (reconciled === undefined) {\n return createAgentImprovementActivationResult(transition, {\n completedAt: transition.attemptedAt,\n outcome: { status: 'expired' },\n })\n }\n try {\n return verifyAgentImprovementActivationResult({ ...input, result: reconciled })\n } catch {\n return uncertainActivationResult(transition, 'INVALID_RECONCILIATION')\n }\n }\n\n let rawResult: unknown\n try {\n rawResult = await options.transition(transition)\n } catch {\n return uncertainActivationResult(transition, 'TRANSITION_THROW')\n }\n try {\n return verifyAgentImprovementActivationResult({ ...input, result: rawResult })\n } catch {\n return uncertainActivationResult(transition, 'INVALID_RESULT')\n }\n}\n\nfunction sealedCandidateTransition(\n experiment: AgentCandidateExperiment,\n activation: AgentImprovementActivation,\n attemptedAt: string,\n expired: boolean,\n): SealedCandidateActivationTransitionInput {\n const targetArm = activation.intent === 'activate-candidate' ? 'candidate' : 'baseline'\n return {\n kind: 'sealed-candidate',\n activation,\n candidateBundle: experiment.candidate,\n bundle: experiment[targetArm],\n targets: activation.targets.map((target) => ({\n ...target,\n desiredDigest: agentImprovementTargetDigest(experiment, targetArm, target.surface),\n desiredInput: agentImprovementTargetInput(experiment[targetArm], target.surface),\n })) as SealedCandidateActivationTransitionInput['targets'],\n attemptedAt,\n expired,\n }\n}\n\nfunction profileImprovementTransition(\n experiment: AgentProfileImprovementExperiment,\n activation: AgentImprovementActivation,\n attemptedAt: string,\n expired: boolean,\n): ProfileImprovementActivationTransitionInput {\n const sourceArm = activation.intent === 'activate-candidate' ? 'baseline' : 'candidate'\n const targetArm = activation.intent === 'activate-candidate' ? 'candidate' : 'baseline'\n const operation = profileImprovementOperation(experiment, activation.intent)\n return {\n kind: 'profile-improvement',\n activation,\n experiment,\n sourceStateDigest: agentProfileImprovementStateDigest(experiment, sourceArm),\n desiredStateDigest: agentProfileImprovementStateDigest(experiment, targetArm),\n operation,\n targets: activation.targets.map((target) => ({\n ...target,\n desiredDigest: agentProfileImprovementStateDigest(experiment, targetArm),\n desiredInput: operation,\n })) as ProfileImprovementActivationTransitionInput['targets'],\n attemptedAt,\n expired,\n }\n}\n\nfunction profileImprovementOperation(\n experiment: AgentProfileImprovementExperiment,\n intent: AgentImprovementActivation['intent'],\n): AgentProfileImprovementActivationOperation {\n return intent === 'activate-candidate'\n ? { kind: 'apply-change', changes: experiment.change }\n : { kind: 'restore-state' }\n}\n\nfunction uncertainActivationResult(\n transition: AgentImprovementActivationTransitionInput,\n code: string,\n): AgentImprovementActivationResult {\n return createAgentImprovementActivationResult(transition, {\n completedAt: transition.attemptedAt,\n outcome: {\n status: 'indeterminate',\n code,\n message: 'The product transition did not return a trustworthy commit result.',\n },\n })\n}\n\nfunction assertTransitionInput(\n activation: AgentImprovementActivation,\n transition: AgentImprovementActivationTransitionInput,\n): void {\n if (transition.kind === 'sealed-candidate') {\n assertSealedCandidateTransitionInput(activation, transition)\n return\n }\n assertProfileImprovementTransitionInput(activation, transition)\n}\n\nfunction assertSealedCandidateTransitionInput(\n activation: AgentImprovementActivation,\n transition: SealedCandidateActivationTransitionInput,\n): void {\n assertAuthorizedTransitionTargets(activation, transition.targets)\n const desiredInputsMatch = transition.targets.every(\n (target) =>\n canonicalCandidateDigest(target.desiredInput) ===\n canonicalCandidateDigest(agentImprovementTargetInput(transition.bundle, target.surface)),\n )\n if (\n transition.expired !== Date.parse(transition.attemptedAt) >= Date.parse(activation.expiresAt) ||\n transition.candidateBundle.digest !== activation.candidateDigest ||\n !desiredInputsMatch ||\n (activation.intent === 'activate-candidate' &&\n transition.bundle.digest !== transition.candidateBundle.digest)\n ) {\n throw new Error('activation transition does not match its authorization')\n }\n}\n\nfunction assertProfileImprovementTransitionInput(\n activation: AgentImprovementActivation,\n transition: ProfileImprovementActivationTransitionInput,\n): void {\n assertAuthorizedTransitionTargets(activation, transition.targets)\n const targetsAgentProfile = activation.targets.some(\n (target) => target.surface === 'agent-profile',\n )\n const experiment = agentProfileImprovementExperimentSchema.parse(transition.experiment)\n const sourceArm = activation.intent === 'activate-candidate' ? 'baseline' : 'candidate'\n const targetArm = activation.intent === 'activate-candidate' ? 'candidate' : 'baseline'\n const sourceStateDigest = agentProfileImprovementStateDigest(experiment, sourceArm)\n const desiredStateDigest = agentProfileImprovementStateDigest(experiment, targetArm)\n const operation = profileImprovementOperation(experiment, activation.intent)\n const targetsMatch = transition.targets.every(\n (target) =>\n target.expectedBaseDigest === sourceStateDigest &&\n target.desiredDigest === desiredStateDigest &&\n canonicalCandidateDigest(target.desiredInput) === canonicalCandidateDigest(operation),\n )\n if (\n transition.expired !== Date.parse(transition.attemptedAt) >= Date.parse(activation.expiresAt) ||\n experiment.digest !== activation.experimentDigest ||\n experiment.candidate.stateDigest !== activation.candidateDigest ||\n (targetsAgentProfile &&\n (activation.executionRef === undefined ||\n canonicalCandidateDigest(activation.executionRef) !==\n canonicalCandidateDigest(experiment.executionRef))) ||\n transition.sourceStateDigest !== sourceStateDigest ||\n transition.desiredStateDigest !== desiredStateDigest ||\n canonicalCandidateDigest(transition.operation) !== canonicalCandidateDigest(operation) ||\n !targetsMatch\n ) {\n throw new Error('activation transition does not match its authorization')\n }\n}\n\nfunction assertAuthorizedTransitionTargets(\n activation: AgentImprovementActivation,\n targets: readonly AgentImprovementActivationTargetPlan[],\n): void {\n const authorized = targetMap(activation.targets)\n const planned = targetMap(targets)\n if (\n authorized.size !== planned.size ||\n [...authorized.entries()].some(\n ([identity, target]) =>\n planned.get(identity)?.expectedBaseDigest !== target.expectedBaseDigest,\n )\n ) {\n throw new Error('activation transition does not match its authorization')\n }\n}\n\nfunction assertResultAgainstActivation(\n activation: AgentImprovementActivation,\n result: AgentImprovementActivationResult,\n): void {\n const attemptedAt = Date.parse(result.attemptedAt)\n const completedAt = Date.parse(result.completedAt)\n const expiresAt = Date.parse(activation.expiresAt)\n if (\n result.idempotencyKey !== activation.digest ||\n attemptedAt < Date.parse(activation.authorizedAt) ||\n completedAt < attemptedAt\n ) {\n throw new Error('activation result does not bind its authorization')\n }\n const expired = attemptedAt >= expiresAt\n if (\n (result.outcome.status === 'expired' && !expired) ||\n (expired && !['expired', 'indeterminate', 'already-applied'].includes(result.outcome.status))\n ) {\n throw new Error('activation result does not honor its authorization expiry')\n }\n if (!('targets' in result.outcome)) return\n const authorized = targetMap(activation.targets)\n const observed = new Set(result.outcome.targets.map(targetIdentity))\n if (\n authorized.size !== observed.size ||\n [...authorized.keys()].some((identity) => !observed.has(identity))\n ) {\n throw new Error('activation result must cover every authorized target exactly once')\n }\n if (\n result.outcome.status === 'applied' &&\n result.outcome.targets.some(\n (target) =>\n target.beforeDigest !== authorized.get(targetIdentity(target))?.expectedBaseDigest,\n )\n ) {\n throw new Error('applied activation did not start from its authorized base state')\n }\n}\n\nfunction assertResultDesiredState(\n proposal: AgentImprovementProposal,\n activation: AgentImprovementActivation,\n result: AgentImprovementActivationResult,\n): void {\n if (!('targets' in result.outcome)) return\n const targetArm = activation.intent === 'activate-candidate' ? 'candidate' : 'baseline'\n const desiredStateDigest =\n proposal.evaluation.kind === 'agent-profile-improvement-measured-comparison'\n ? agentProfileImprovementStateDigest(proposal.evaluation.experiment, targetArm)\n : undefined\n const desired = new Map(\n activation.targets.map((target) => [\n targetIdentity(target),\n desiredStateDigest ??\n agentImprovementTargetDigest(\n requireSealedCandidateExperiment(proposal),\n targetArm,\n target.surface,\n ),\n ]),\n )\n assertOutcomeDesiredState(activation, result, desired)\n}\n\nfunction assertOutcomeDesiredState(\n activation: AgentImprovementActivation,\n result: AgentImprovementActivationResult,\n desired: ReadonlyMap<string, Sha256Digest>,\n): void {\n if (!('targets' in result.outcome)) return\n if (result.outcome.status === 'applied') {\n if (\n result.outcome.targets.some(\n (target) => target.afterDigest !== desired.get(targetIdentity(target)),\n )\n ) {\n throw new Error('applied activation does not match the requested bundle')\n }\n return\n }\n const allDesired = result.outcome.targets.every(\n (target) => target.currentDigest === desired.get(targetIdentity(target)),\n )\n if (result.outcome.status === 'already-applied') {\n if (!allDesired) throw new Error('already-applied activation is not at the requested state')\n return\n }\n const authorized = targetMap(activation.targets)\n const hasStaleTarget = result.outcome.targets.some(\n (target) => target.currentDigest !== authorized.get(targetIdentity(target))?.expectedBaseDigest,\n )\n if (allDesired || !hasStaleTarget) {\n throw new Error('activation conflict does not identify stale target state')\n }\n}\n\nfunction targetMap<T extends { surface: AgentImprovementSurface; identity: string }>(\n targets: readonly T[],\n): Map<string, T> {\n return new Map(targets.map((target) => [targetIdentity(target), target]))\n}\n\nfunction targetIdentity(target: { surface: AgentImprovementSurface; identity: string }): string {\n return `${target.surface}\\u0000${target.identity}`\n}\n"],"mappings":";;;;AAoBA,SAAgB,2BAA+C;CAC7D,OAAO;EAAE,UAAU;EAAG,WAAW;EAAG,SAAS;EAAG,UAAU;CAAE;AAC9D;AAEA,SAAgB,cAAc,OAAiC;CAC7D,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,KAAK,SAAS;AACzE;;AAGA,SAAgB,gBACd,QACA,OACM;CACN,OAAO,YAAY;CACnB,KAAK,MAAM,OAAO;EAAC;EAAY;EAAa;CAAS,GAAY;EAC/D,MAAM,QAAQ,MAAM;EACpB,IAAI,cAAc,KAAK,GAAG,OAAO,QAAQ;OACpC,IAAI,QAAQ,WAAW,OAAO,WAAW;OACzC,OAAO,cAAc;CAC5B;CACA,IAAI,MAAM,gBAAgB,OAAO,OAAO,cAAc;CACtD,IAAI,MAAM,aAAa,OAAO,OAAO,WAAW;CAChD,IAAI,cAAc,MAAM,gBAAgB,GACtC,OAAO,oBAAoB,OAAO,oBAAoB,KAAK,MAAM;AAErE;;;;ACgGA,SAAgB,uCACd,YACA,SACkC;CAClC,MAAM,aAAa,iCACjB,iCAAiC,MAAM,WAAW,UAAU,GAC5D,8BACF;CACA,sBAAsB,YAAY,UAAU;CAC5C,MAAM,SA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;EAC3F;CACF;CACA,MAAM,aAAa,UAAU,WAAW,OAAO;CAC/C,MAAM,iBAAiB,OAAO,QAAQ,QAAQ,MAC3C,WAAW,OAAO,kBAAkB,WAAW,IAAI,eAAe,MAAM,CAAC,CAAC,EAAE,kBAC/E;CACA,IAAI,cAAc,CAAC,gBACjB,MAAM,IAAI,MAAM,0DAA0D;AAE9E;AAEA,SAAS,UACP,SACgB;CAChB,OAAO,IAAI,IAAI,QAAQ,KAAK,WAAW,CAAC,eAAe,MAAM,GAAG,MAAM,CAAC,CAAC;AAC1E;AAEA,SAAS,eAAe,QAAwE;CAC9F,OAAO,GAAG,OAAO,QAAQ,QAAQ,OAAO;AAC1C"}
@@ -1,4 +1,4 @@
1
- import { Fi as AgentTurnUsage, Ii as CollectedAgentTurn, OC as WorkerSlots, f_ as SharedBoxPlacement, ix as OtelExportConfig, p_ as SharedBoxPlacementOptions, rw as BudgetPool, ug as ExecutorConfig } from "./index-t672ISFX.js";
1
+ import { Hi as CollectedAgentTurn, N_ as SharedBoxPlacement, P_ as SharedBoxPlacementOptions, Tx as OtelExportConfig, Vi as AgentTurnUsage, YC as WorkerSlots, jg as ExecutorConfig, ww as BudgetPool } from "./index-CGNQWpge.js";
2
2
  import { AgentCandidateBundle, AgentImprovementActivation, AgentImprovementActivationOutcome, AgentImprovementActivationResult, AgentImprovementActivationTarget, AgentImprovementProposal, AgentImprovementReview, AgentImprovementSurface, AgentProfile, AgentProfileImprovementChange, AgentProfileImprovementExperiment, AgentTrainingReceipt, AgentTrainingTask, HarnessType, ReasoningEffort, Sha256Digest } from "@tangle-network/agent-interface";
3
3
  import { CostLedgerHandle, CostReceiptInput, MaximumCharge, PairedPromotionDecision, PendingCostCallView, ProposalFinding, RunRecord } from "@tangle-network/agent-eval";
4
4
  import { CampaignCellResult, CampaignScenarioIdentity, CampaignStorage, CompareOptimizationMethodsOptions, OptimizationMethod, OptimizationMethodComparison, Scenario, SearchAllocator, SearchCellResult, SearchCellStage, SearchClaim, SearchClaimVerification, SearchHistoryReceipt, SearchLane, SearchModelIdentity, SearchPolicy, SearchSourceRef, SearchSplit, SearchStateView, SurfaceProposer, WorktreeAdapter } from "@tangle-network/agent-eval/campaign";
@@ -1013,4 +1013,4 @@ declare function verifyAgentImprovementActivationResult(input: {
1013
1013
  declare function executeAgentImprovementActivation(input: ExecuteAgentImprovementActivationInput, options: ExecuteAgentImprovementActivationOptions): Promise<AgentImprovementActivationResult>;
1014
1014
  //#endregion
1015
1015
  export { ImproveScenarioPartitions as $, createCommandProfileTrainer as A, AgenticGeneratorShotReceipt as At, ImproveMethodContext as B, ControlledTrainingCommand as C, subscriptionLane as Ct, ProfileTrainerRequest as D, AgenticGeneratorOptions as Dt, ProfileTrainer as E, AgenticGeneratorExecutorForWorktree as Et, ImproveCodeResult as F, defaultBuildPrompt as Ft, ImproveMethodSource as G, ImproveMethodLineage as H, ImproveCodeRunOptions as I, CandidateGenerator as It, ImproveProfileAgent as J, ImproveOptimizationRunOptions as K, ImproveCost as L, ImproveCandidateValidator as M, VerifyResult as Mt, ImproveCodeBaseOptions as N, agenticGenerator as Nt, TrainingBoundaryResult as O, AgenticGeneratorShotDisposition as Ot, ImproveCodeOptions as P, commandVerifier as Pt, ImproveRuntimeCodeGeneratorOptions as Q, ImproveCustomCodeGeneratorOptions as R, CheckpointServingPort as S, sharedBoxLane as St, ImproveTrainingResult as T, ReadonlyAgentProfile as Tt, ImproveMethodOptions as U, ImproveMethodFactory as V, ImproveMethodResult as W, ImproveProfileSurface as X, ImproveProfileComponents as Y, ImproveResult as Z, SearchMethodOptions as _, SearchTraceOptions as _t, AgentImprovementActivationTransitionInput as a, ImproveSkillsOptions as at, SearchImprovementDecision as b, isSearchEnvironmentFault as bt, CreateAgentImprovementActivationResultOptions as c, ImprovementCodeCandidate as ct, ProfileImprovementActivationTransitionInput as d, SearchPromotion as dt, ImproveSearchAgent as et, SealedCandidateActivationTransitionInput as f, SearchCellContext as ft, improve as g, SearchLaneOptions as gt, verifyAgentImprovementActivationResult as h, SearchLaneKind as ht, AgentImprovementActivationTransition as i, ImproveSearchResult as it, ImproveCandidateValidationInput as j, Verifier as jt, TrainingDatasetDocument as k, AgenticGeneratorShotExecution as kt, ExecuteAgentImprovementActivationInput as l, ImprovementProfileCandidate as lt, executeAgentImprovementActivation as m, SearchLane$1 as mt, AgentImprovementActivationResultStore as n, ImproveSearchMethod as nt, AgentProfileImprovementActivationOperation as o, ImproveSurface as ot, createAgentImprovementActivationResult as p, SearchEnvironmentFault as pt, ImproveOptions as q, AgentImprovementActivationTargetPlan as r, ImproveSearchOptions as rt, AgentProfileImprovementActivationTargetPlan as s, ImprovementCandidate as st, AgentImprovementActivationReconciliation as t, ImproveSearchIdentity as tt, ExecuteAgentImprovementActivationOptions as u, SearchDispatchContext as ut, searchMethod as v, SharedBoxSearchLane as vt, ImproveTrainingOptions as w, DeepReadonly as wt, decideSearchImprovement as x, routerLane as xt, DecideSearchImprovementOptions as y, dedicatedLane as yt, ImproveLineage as z };
1016
- //# sourceMappingURL=activation-BSwcsNSQ.d.ts.map
1016
+ //# sourceMappingURL=activation-CZGz2kuu.d.ts.map
package/dist/agent.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ST as RuntimeStreamEvent, Uw as SandboxClient, Vw as OutputAdapter, vw as AgentRunSpec } from "./index-t672ISFX.js";
1
+ import { KT as RuntimeStreamEvent, cT as OutputAdapter, uT as SandboxClient, zw as AgentRunSpec } from "./index-CGNQWpge.js";
2
2
  import { a as createSurfaceImprovementProposer, c as SurfaceValidationIssue, d as validateSurfaces, i as SurfaceImprovementEdit, l as renderSurfaceIssues, n as DraftPatchInput, o as AgentSurfaces, r as DraftPatchOutput, s as ResolvedSurface, t as CreateSurfaceImprovementProposerOptions, u as resolveSubjectPath } from "./improvement-adapter-D5gwwoXQ.js";
3
3
  import { C as worktreeCliProfileMaterialization, S as validateProfileMaterialization, _ as promptModelProfileMaterialization, a as DefineProfileMaterializationContractOptions, b as renderProfileMaterializationIssues, c as ProfileMaterializationIssue, d as assertProfileMaterializes, f as controlProfileMaterialization, g as promptControlProfileMaterialization, h as profileMaterializationAxes, i as CanonicalAgentProfileMaterializationAxis, l as ValidateProfileMaterializationOptions, m as fullProfileMaterialization, n as AgentProfileMaterializationAxis, o as KnownAgentProfileMaterializationAxis, p as defineProfileMaterializationContract, r as AssertProfileMaterializationOptions, s as ProfileMaterializationContract, t as AGENT_PROFILE_MATERIALIZATION_AXES, u as assertProfileMaterialization, v as promptOnlyProfileMaterialization, x as sandboxActProfileMaterialization, y as promptResourceProfileMaterialization } from "./profile-materialization-C5-t3HJ7.js";
4
4
  import { AgentProfile, AgentProfileFileMount, AgentProfileMcpServer } from "@tangle-network/agent-interface";
package/dist/agent.js CHANGED
@@ -1,5 +1,5 @@
1
- import { Ai as promptOnlyProfileMaterialization, Ci as assertProfileMaterializes, Di as profileMaterializationAxes, Ei as fullProfileMaterialization, Ii as validateProfileMaterialization, Li as worktreeCliProfileMaterialization, Mi as renderProfileMaterializationIssues, Oi as promptControlProfileMaterialization, Pi as sandboxActProfileMaterialization, Si as assertProfileMaterialization, Ti as defineProfileMaterializationContract, ji as promptResourceProfileMaterialization, ki as promptModelProfileMaterialization, ma as mapSandboxEvent, mn as createSandboxForSpec, wi as controlProfileMaterialization, xi as AGENT_PROFILE_MATERIALIZATION_AXES } from "./supervisor-CCtmmmOz.js";
2
- import "./runtime-B47V5Omi.js";
1
+ import { Ai as promptControlProfileMaterialization, Ci as AGENT_PROFILE_MATERIALIZATION_AXES, Di as defineProfileMaterializationContract, Ei as controlProfileMaterialization, Ii as sandboxActProfileMaterialization, Mi as promptOnlyProfileMaterialization, Ni as promptResourceProfileMaterialization, Oi as fullProfileMaterialization, Pi as renderProfileMaterializationIssues, Ri as validateProfileMaterialization, Ti as assertProfileMaterializes, ga as mapSandboxEvent, ji as promptModelProfileMaterialization, ki as profileMaterializationAxes, mn as createSandboxForSpec, wi as assertProfileMaterialization, zi as worktreeCliProfileMaterialization } from "./supervisor-BMMdI4T-.js";
2
+ import "./runtime-EiTCboO2.js";
3
3
  import { createHash } from "node:crypto";
4
4
  import { existsSync, readFileSync, statSync } from "node:fs";
5
5
  import { isAbsolute, join, relative, resolve, sep } from "node:path";
@@ -1,8 +1,8 @@
1
1
  import { F as deepFreezeCandidate, I as embeddedCandidateArtifact, M as canonicalCandidateBytes$1, O as verifyMaterializedWorkspace, T as scanMaterializedWorkspaceManifest, a as verifyAgentCandidateWorkspaceArtifacts, c as captureAgentCandidateWorkspaceFiles, d as workspaceLimits, f as persistCandidateOutputArtifact, j as verifiedArtifactChunks, l as createAgentCandidateWorkspacePort, n as captureAgentCandidateWorkspaceTreeToArtifacts, o as verifyAgentCandidateWorkspaceTree, r as materializeAgentCandidateWorkspaceFromArtifacts, s as captureAgentCandidateWorkspace, t as captureAgentCandidateWorkspaceToArtifacts, w as readVerifiedArtifact, x as candidateWorkspaceManifest } from "../workspace-streams-DFAhW7hF.js";
2
- import { A as recoveredTerminalRecord, C as candidateCleanupDeadline, D as assertTerminalAllowedInPhase, E as assertRecoveryMatchesStaged, F as terminalRecord, M as rejectedStage, N as requireStagedTerminal, O as assertTerminalMatchesClaim, P as sealTerminalDigest, S as candidateClaimFileInternals, T as withinCandidateCleanupDeadline, _ as consumePreparedCandidateExecution, a as AGENT_CANDIDATE_EXECUTION_SUPPORT, c as executePreparedAgentCandidate, d as sealAgentCandidateModelSettlement, g as beginPreparedCandidateDisposal, h as assertPreparedCandidateIntegrity, i as candidateKnowledgeExecutionPaths, j as rejectedFinish, k as assertTerminalMatchesStaged, l as RecoveryAgentCandidateTraceStore, m as candidateExecutionClaim, n as CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV, p as sealAgentCandidateExecutorStopAcknowledgement, r as CANDIDATE_KNOWLEDGE_ROOT_ENV, s as verifyAgentCandidateBundle, t as prepareAgentCandidateExecution, u as persistCandidateModelSettlementEvidence, v as CANDIDATE_TRACE_ENV, w as candidateCleanupTimeout, x as InMemoryAgentCandidateExecutionClaimStore, y as CANDIDATE_TRACE_TAGS } from "../prepare-DjCLEN-q.js";
3
- import { a as assertCandidateProfileBinding, d as omitUndefinedObjectFields, h as parseExactCandidateProfile, i as applyExactAgentProfileDiff, l as freezeGenericAgentCandidateProfile, m as parseExactAgentProfileDiff, p as parseExactAgentProfile, r as agentCandidateProfileAsAgentProfile } from "../profile-DmVM4Gxb.js";
2
+ import { A as recoveredTerminalRecord, C as candidateCleanupDeadline, D as assertTerminalAllowedInPhase, E as assertRecoveryMatchesStaged, F as terminalRecord, M as rejectedStage, N as requireStagedTerminal, O as assertTerminalMatchesClaim, P as sealTerminalDigest, S as candidateClaimFileInternals, T as withinCandidateCleanupDeadline, _ as consumePreparedCandidateExecution, a as AGENT_CANDIDATE_EXECUTION_SUPPORT, c as executePreparedAgentCandidate, d as sealAgentCandidateModelSettlement, g as beginPreparedCandidateDisposal, h as assertPreparedCandidateIntegrity, i as candidateKnowledgeExecutionPaths, j as rejectedFinish, k as assertTerminalMatchesStaged, l as RecoveryAgentCandidateTraceStore, m as candidateExecutionClaim, n as CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV, p as sealAgentCandidateExecutorStopAcknowledgement, r as CANDIDATE_KNOWLEDGE_ROOT_ENV, s as verifyAgentCandidateBundle, t as prepareAgentCandidateExecution, u as persistCandidateModelSettlementEvidence, v as CANDIDATE_TRACE_ENV, w as candidateCleanupTimeout, x as InMemoryAgentCandidateExecutionClaimStore, y as CANDIDATE_TRACE_TAGS } from "../prepare-CFQLx9e3.js";
3
+ import { a as assertCandidateProfileBinding, d as omitUndefinedObjectFields, h as parseExactCandidateProfile, i as applyExactAgentProfileDiff, l as freezeGenericAgentCandidateProfile, m as parseExactAgentProfileDiff, p as parseExactAgentProfile, r as agentCandidateProfileAsAgentProfile } from "../profile-BTbpdL9h.js";
4
4
  import { t as sealAgentCandidateBundle } from "../bundle-Cw-QdGmH.js";
5
- import { n as exactProcessProviderAsCandidateExecutor, t as createProtectedAgentCandidateModelPort } from "../protected-model-port-D1fcnYdj.js";
5
+ import { n as exactProcessProviderAsCandidateExecutor, t as createProtectedAgentCandidateModelPort } from "../protected-model-port-f1N2f0Uq.js";
6
6
  import { agentCandidateArtifactRefSchema, agentCandidateExecutionPlanMaterialSchema, agentCandidateMaterializationReceiptSchema, agentCandidateWorkspaceManifestMaterialSchema, agentCandidateWorkspaceSnapshotEvidenceSchema } from "@tangle-network/agent-interface";
7
7
  import { createHash, randomUUID } from "node:crypto";
8
8
  import { constants, linkSync } from "node:fs";
@@ -1,4 +1,4 @@
1
- import { $n as parseWorkerToolTraceArtifact, Bn as InMemoryResultBlobStore, Et as failedItems, Gr as resolveRedactor, J as scopeRetainedOwnerResourceReader, Jn as readCommittedJsonLines, Ki as providerAttemptEvidence, Mr as contentAddress, Pt as createExecutorRegistry, Rn as FileResultBlobStore, St as checkVerdictOf, T as meterRuntimeOwnedProviderAttempt, Tn as runBrainLoop, Vn as InMemorySpawnJournal, Xt as createInbox, Yn as writeAllBytes, an as isLiveNodeStatus, c as runTree, er as workerTraceAnalysisStore, fr as errMessage, i as bestDelivered, ia as detachedFrozen, ir as assertValidBudget, o as pickBestDelivered, on as isTerminalNodeStatus, qn as prepareJsonlAppend, s as runFinalizer, tn as createPeerMailbox, tt as resolveSpawnResourcePaths, v as withDriverExecutor, vt as CheckUnavailableError, zn as FileSpawnJournal, zt as createRouterTranscript } from "./supervisor-CCtmmmOz.js";
1
+ import { Bn as FileResultBlobStore, Et as failedItems, Hn as InMemoryResultBlobStore, J as scopeRetainedOwnerResourceReader, Ji as providerAttemptEvidence, Pr as contentAddress, Pt as createExecutorRegistry, St as checkVerdictOf, T as meterRuntimeOwnedProviderAttempt, Tn as runBrainLoop, Un as InMemorySpawnJournal, Vn as FileSpawnJournal, Xn as readCommittedJsonLines, Xt as createInbox, Yn as prepareJsonlAppend, Zn as writeAllBytes, an as isLiveNodeStatus, c as runTree, i as bestDelivered, mr as errMessage, nr as workerTraceAnalysisStore, o as pickBestDelivered, oa as detachedFrozen, on as isTerminalNodeStatus, or as assertValidBudget, qr as resolveRedactor, s as runFinalizer, tn as createPeerMailbox, tr as parseWorkerToolTraceArtifact, tt as resolveSpawnResourcePaths, v as withDriverExecutor, vt as CheckUnavailableError, zt as createRouterTranscript } from "./supervisor-BMMdI4T-.js";
2
2
  import { f as RuntimeRunStateError, m as ValidationError } from "./errors-DodWX-cb.js";
3
3
  import { $ as promptCacheTokenClasses, U as chargedTokens, dt as addResourceSpend, mt as withBudgetResources, st as unmeteredSpend } from "./workspace-streams-DFAhW7hF.js";
4
4
  import { A as writeWorkerCancellation, M as writeWorkerSteerAcknowledgement, b as workerCancellationsDir, c as readWorkerCancelRequests, d as readWorkerSteerRequests, k as writeRunCancellation, l as readWorkerCancellation, o as readRunCancelRequest, r as claimWorkerSteerDelivery, s as readRunCancellation, u as readWorkerSteerAcknowledgement } from "./run-layout-DSCWdbX2.js";
@@ -1891,11 +1891,12 @@ function createCoordinationToolsForManager(opts, lifetime) {
1891
1891
  const openWorkRefusal = (verb) => {
1892
1892
  if (deadlineNoticeDelivered) return void 0;
1893
1893
  const { running, unqueued, queued } = openWork();
1894
- if (running.length === 0 && unqueued.length === 0 && queued.length === 0) return void 0;
1894
+ if (running.length === 0 && unqueued.length === 0 && queued.length === 0 && leadPublishing === 0) return void 0;
1895
1895
  const parts = [];
1896
1896
  if (running.length > 0) parts.push(`${running.length} worker${running.length === 1 ? " is" : "s are"} still running (${running.map((node) => node.id).join(", ")})`);
1897
1897
  const waiting = unqueued.length + queued.length;
1898
1898
  if (waiting > 0) parts.push(`${waiting} event${waiting === 1 ? " is" : "s are"} waiting for you`);
1899
+ if (leadPublishing > 0) parts.push(`${leadPublishing} lead message${leadPublishing === 1 ? " is" : "s are"} still being published`);
1899
1900
  return {
1900
1901
  error: "open-work",
1901
1902
  reason: `${parts.join(" and ")}. End your turn to wait: you will be woken with each result. Read each settled worker's output, and then call ${verb} again. Nothing was ${verb === "stop" ? "stopped" : "checked"}.`,
@@ -2350,6 +2351,29 @@ function createCoordinationToolsForManager(opts, lifetime) {
2350
2351
  inputSchema: {
2351
2352
  type: "object",
2352
2353
  properties: {
2354
+ events: {
2355
+ type: "boolean",
2356
+ description: "Read bounded live output for an owned descendant."
2357
+ },
2358
+ tree: {
2359
+ type: "boolean",
2360
+ description: "Read this manager's complete owned tree without reading state files."
2361
+ },
2362
+ eventCursor: {
2363
+ type: "object",
2364
+ properties: {
2365
+ epoch: {
2366
+ type: "string",
2367
+ minLength: 1
2368
+ },
2369
+ next: {
2370
+ type: "integer",
2371
+ minimum: 0
2372
+ }
2373
+ },
2374
+ required: ["epoch", "next"],
2375
+ additionalProperties: false
2376
+ },
2353
2377
  workerId: idArg,
2354
2378
  outRef: {
2355
2379
  type: "string",
@@ -2375,6 +2399,46 @@ function createCoordinationToolsForManager(opts, lifetime) {
2375
2399
  },
2376
2400
  handler: async (raw) => {
2377
2401
  const args = obj(raw);
2402
+ if (args.tree === true) {
2403
+ const tree = opts.scope.observeTree?.() ?? opts.scope.view;
2404
+ return redactJournalEvent({ tree: {
2405
+ root: tree.root,
2406
+ inFlight: tree.inFlight,
2407
+ nodes: tree.nodes.map((node) => ({
2408
+ id: node.id,
2409
+ parent: node.parent,
2410
+ label: node.label,
2411
+ status: node.status,
2412
+ runtime: node.runtime,
2413
+ spawnedAt: node.spawnedAt,
2414
+ settledAt: node.settledAt
2415
+ }))
2416
+ } });
2417
+ }
2418
+ const eventCursor = args.eventCursor === void 0 ? void 0 : (() => {
2419
+ const cursor = obj(args.eventCursor);
2420
+ if (typeof cursor.epoch !== "string" || cursor.epoch.length === 0 || !Number.isSafeInteger(cursor.next) || Number(cursor.next) < 0) throw new Error("eventCursor must name an epoch and a non-negative safe integer");
2421
+ return {
2422
+ epoch: cursor.epoch,
2423
+ next: Number(cursor.next)
2424
+ };
2425
+ })();
2426
+ if (args.events === true) {
2427
+ const id = str(args.workerId, "workerId");
2428
+ const node = (opts.scope.observeTree?.() ?? opts.scope.view).nodes.find((candidate) => candidate.id === id);
2429
+ if (!node) return { error: "unknown-worker" };
2430
+ return redactJournalEvent({
2431
+ id: node.id,
2432
+ parent: node.parent,
2433
+ label: node.label,
2434
+ status: node.status,
2435
+ runtime: node.runtime,
2436
+ events: opts.scope.observeEvents?.(id, eventCursor) ?? {
2437
+ status: "unavailable",
2438
+ reason: "not-captured"
2439
+ }
2440
+ });
2441
+ }
2378
2442
  const outputRead = workerOutputReadOptions(args);
2379
2443
  if (args.outRef !== void 0 && args.workerId === void 0) {
2380
2444
  const outRef = str(args.outRef, "outRef");
@@ -2406,6 +2470,10 @@ function createCoordinationToolsForManager(opts, lifetime) {
2406
2470
  const pending = node.settlementPending;
2407
2471
  return {
2408
2472
  ...projectNodeEvidence(node),
2473
+ events: opts.scope.observeEvents?.(node.id, eventCursor) ?? {
2474
+ status: "unavailable",
2475
+ reason: "not-captured"
2476
+ },
2409
2477
  outRef: node.outRef ?? null,
2410
2478
  ...await readWorkerOutput(node.outRef, outputRead),
2411
2479
  progress: progress ?? null,
@@ -4901,4 +4969,4 @@ function safeJson(v) {
4901
4969
  //#endregion
4902
4970
  export { ANALYST_DEFINITION_BOUNDS as A, createEventBus as B, createFileRunContext as C, foldCoordinationRecords as D, FileCoordinationLog as E, createCoordinationToolsForManager as F, watchTrace as H, downMessageRefusalReasons as I, normalizeAnalyzeOnSettle as L, canonicalFindingEvent as M, coordinationVerbNames as N, applyRunCancellation as O, createCoordinationTools as P, parseAuthoredAnalystDefinition as R, renderAnytimeTable as S, withRunContext as T, defaultToolDetectors as V, sampleFromSettled as _, DEFAULT_DEADLINE_WARNING_MS as a, bestSoFar as b, refreshedWake as c, allWorkersStalled as d, anyOf as f, progressStop as g, plateau as h, finalizeBestDelivered as i, analystToolGroupNames as j, watchRunCancellation as k, resolveWakePolicy as l, noProgressFor as m, createSteerAcknowledger as n, composeWakeInput as o, createProgressTracker as p, driverAgent as r, deadlineWarningAt as s, createCancelAcknowledger as t, allOf as u, anytimeReport as v, createInMemoryRunContext as w, plateauLength as x, areaUnderCurve as y, questionEscalationTargets as z };
4903
4971
 
4904
- //# sourceMappingURL=coordination-driver-D85RWATT.js.map
4972
+ //# sourceMappingURL=coordination-driver-C2Zm5lU4.js.map