@tangle-network/agent-runtime 0.324.0 → 0.325.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dist/{activation-CmWGOW1x.js → activation--9-iyGR8.js} +2 -2
  2. package/dist/{activation-CmWGOW1x.js.map → activation--9-iyGR8.js.map} +1 -1
  3. package/dist/{activation-CB2npL7F.d.ts → activation-Q3CJgiCu.d.ts} +2 -2
  4. package/dist/agent.d.ts +1 -1
  5. package/dist/agent.js +2 -2
  6. package/dist/{coordination-driver-CNEeqMoh.js → coordination-driver-DkkUVe9g.js} +242 -139
  7. package/dist/coordination-driver-DkkUVe9g.js.map +1 -0
  8. package/dist/{delegate-C6oOTFB6.js → delegate-BDsaIl2K.js} +2 -2
  9. package/dist/{delegate-C6oOTFB6.js.map → delegate-BDsaIl2K.js.map} +1 -1
  10. package/dist/durable.d.ts +2 -2
  11. package/dist/durable.js +60 -21
  12. package/dist/durable.js.map +1 -1
  13. package/dist/graph-Cuz6Ubzd.js +348 -0
  14. package/dist/graph-Cuz6Ubzd.js.map +1 -0
  15. package/dist/{improvement-cycle-U74a-YKi.js → improvement-cycle-B5Z8cHKx.js} +3 -3
  16. package/dist/{improvement-cycle-U74a-YKi.js.map → improvement-cycle-B5Z8cHKx.js.map} +1 -1
  17. package/dist/index.d.ts +4 -4
  18. package/dist/index.js +7 -7
  19. package/dist/intelligence.d.ts +2 -2
  20. package/dist/intelligence.js +3 -3
  21. package/dist/kernel.d.ts +1 -1
  22. package/dist/kernel.js +9 -9
  23. package/dist/{loop-runner-bin-BfcTX4-n.js → loop-runner-bin-C16VR9cI.js} +3 -3
  24. package/dist/{loop-runner-bin-BfcTX4-n.js.map → loop-runner-bin-C16VR9cI.js.map} +1 -1
  25. package/dist/{loop-runner-bin-CkchKbaB.d.ts → loop-runner-bin-Co7JKSwi.d.ts} +2 -2
  26. package/dist/loop-runner-bin.d.ts +1 -1
  27. package/dist/loop-runner-bin.js +1 -1
  28. package/dist/mcp/bin.js +3 -3
  29. package/dist/mcp/index.d.ts +3 -3
  30. package/dist/mcp/index.js +4 -4
  31. package/dist/{openai-tools-BR3rRmmC.d.ts → openai-tools-CbgZrQJ_.d.ts} +2 -2
  32. package/dist/profiles.d.ts +1 -1
  33. package/dist/{provision-supervisor-DhPJqazM.js → provision-supervisor-4BoHpGFJ.js} +3 -3
  34. package/dist/{provision-supervisor-DhPJqazM.js.map → provision-supervisor-4BoHpGFJ.js.map} +1 -1
  35. package/dist/{runtime-B9-ZiYFa.js → runtime-B9X_U-aV.js} +9 -9
  36. package/dist/{runtime-B9-ZiYFa.js.map → runtime-B9X_U-aV.js.map} +1 -1
  37. package/dist/{search-executor-CtNb_lIB.js → search-executor-C-b4NaFl.js} +2 -2
  38. package/dist/{search-executor-CtNb_lIB.js.map → search-executor-C-b4NaFl.js.map} +1 -1
  39. package/dist/{server-BLYiq6fK.js → server-CcHaXgUT.js} +3 -3
  40. package/dist/{server-BLYiq6fK.js.map → server-CcHaXgUT.js.map} +1 -1
  41. package/dist/{supervise-FOCAUADN.js → supervise-BlaB4CeL.js} +734 -18
  42. package/dist/supervise-BlaB4CeL.js.map +1 -0
  43. package/dist/{supervisor-DnKhkhKc.js → supervisor-fq4JGynd.js} +26 -9
  44. package/dist/{supervisor-DnKhkhKc.js.map → supervisor-fq4JGynd.js.map} +1 -1
  45. package/dist/testing.d.ts +1 -1
  46. package/dist/testing.js +12 -12
  47. package/dist/tui/index.d.ts +1 -1
  48. package/dist/tui/index.js +1 -1
  49. package/dist/{types-ytkoP4VV.d.ts → types-5r334mcg.d.ts} +577 -508
  50. package/package.json +1 -1
  51. package/skills/profile-authoring/SKILL.md +1 -1
  52. package/dist/coordination-driver-CNEeqMoh.js.map +0 -1
  53. package/dist/graph-BKmo7d42.js +0 -805
  54. package/dist/graph-BKmo7d42.js.map +0 -1
  55. package/dist/supervise-FOCAUADN.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-CcoARX4v.js";
2
- import { A as agentImprovementTargetInput, M as agentProfileImprovementStateDigest, c as requireSealedCandidateExperiment, d as verifyAgentImprovementActivation, f as verifyAgentImprovementProposal, k as agentImprovementTargetDigest } from "./improvement-cycle-U74a-YKi.js";
2
+ import { A as agentImprovementTargetInput, M as agentProfileImprovementStateDigest, c as requireSealedCandidateExperiment, d as verifyAgentImprovementActivation, f as verifyAgentImprovementProposal, k as agentImprovementTargetDigest } from "./improvement-cycle-B5Z8cHKx.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-CmWGOW1x.js.map
234
+ //# sourceMappingURL=activation--9-iyGR8.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"activation-CmWGOW1x.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;CAC7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A;CAYN,0BAA0B,YAAY,QAAQ,IAX1B,IAClB,WAAW,QAAQ,KAAK,WAAW,CACjC,eAAe,MAAM,GACrB,sBACE,6BACE,iCAAiC,QAAQ,GACzC,WACA,OAAO,OACT,CACJ,CAAC,CAEiD,CAAC;AACvD;AAEA,SAAS,0BACP,YACA,QACA,SACM;CACN,IAAI,EAAE,aAAa,OAAO,UAAU;CACpC,IAAI,OAAO,QAAQ,WAAW,WAAW;EACvC,IACE,OAAO,QAAQ,QAAQ,MACpB,WAAW,OAAO,gBAAgB,QAAQ,IAAI,eAAe,MAAM,CAAC,CACvE,GAEA,MAAM,IAAI,MAAM,wDAAwD;EAE1E;CACF;CACA,MAAM,aAAa,OAAO,QAAQ,QAAQ,OACvC,WAAW,OAAO,kBAAkB,QAAQ,IAAI,eAAe,MAAM,CAAC,CACzE;CACA,IAAI,OAAO,QAAQ,WAAW,mBAAmB;EAC/C,IAAI,CAAC,YAAY,MAAM,IAAI,MAAM,0DAA0D;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
+ {"version":3,"file":"activation--9-iyGR8.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,aAAa,CAAC,CAAC,CAC5F;CACA,OAAO,wBAAwB,MAAM;AACvC;;;;;AAMA,SAAgB,uCAAuC,OAKlB;CACnC,MAAM,WA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,QAAwE;CAC9F,OAAO,GAAG,OAAO,QAAQ,QAAQ,OAAO;AAC1C"}
@@ -1,4 +1,4 @@
1
- import { Cc as CollectedAgentTurn, Dw as BudgetPool, Gg as SharedBoxPlacement, Kg as SharedBoxPlacementOptions, Mh as ExecutorConfig, Sc as AgentTurnUsage, Tw as WorkerSlots, zS as OtelExportConfig } from "./types-ytkoP4VV.js";
1
+ import { $s as AgentTurnUsage, Ih as ExecutorConfig, US as OtelExportConfig, Xg as SharedBoxPlacementOptions, Yg as SharedBoxPlacement, ec as CollectedAgentTurn, jw as BudgetPool, kw as WorkerSlots } from "./types-5r334mcg.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-CB2npL7F.d.ts.map
1016
+ //# sourceMappingURL=activation-Q3CJgiCu.d.ts.map
package/dist/agent.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Hw as AgentRunSpec, S as RuntimeStreamEvent, dT as OutputAdapter, pT as SandboxClient } from "./types-ytkoP4VV.js";
1
+ import { Kw as AgentRunSpec, S as RuntimeStreamEvent, _T as SandboxClient, hT as OutputAdapter } from "./types-5r334mcg.js";
2
2
  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";
3
3
  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";
4
4
  import { AgentProfile, AgentProfileFileMount, AgentProfileMcpServer } from "@tangle-network/agent-interface";
package/dist/agent.js CHANGED
@@ -1,5 +1,5 @@
1
- import { $r as sandboxActProfileMaterialization, Br as AGENT_PROFILE_MATERIALIZATION_AXES, Gr as fullProfileMaterialization, Hi as mapSandboxEvent, Hr as assertProfileMaterializes, Jr as promptModelProfileMaterialization, Kr as profileMaterializationAxes, Ur as controlProfileMaterialization, Vr as assertProfileMaterialization, Wr as defineProfileMaterializationContract, Xr as promptResourceProfileMaterialization, Yr as promptOnlyProfileMaterialization, Zr as renderProfileMaterializationIssues, mn as createSandboxForSpec, ni as worktreeCliProfileMaterialization, qr as promptControlProfileMaterialization, ti as validateProfileMaterialization } from "./supervisor-DnKhkhKc.js";
2
- import "./runtime-B9-ZiYFa.js";
1
+ import { Gr as defineProfileMaterializationContract, Hr as assertProfileMaterialization, Jr as promptControlProfileMaterialization, Kr as fullProfileMaterialization, Qr as renderProfileMaterializationIssues, Ui as mapSandboxEvent, Ur as assertProfileMaterializes, Vr as AGENT_PROFILE_MATERIALIZATION_AXES, Wr as controlProfileMaterialization, Xr as promptOnlyProfileMaterialization, Yr as promptModelProfileMaterialization, Zr as promptResourceProfileMaterialization, ei as sandboxActProfileMaterialization, hn as createSandboxForSpec, ni as validateProfileMaterialization, qr as profileMaterializationAxes, ri as worktreeCliProfileMaterialization } from "./supervisor-fq4JGynd.js";
2
+ import "./runtime-B9X_U-aV.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,4 +1,4 @@
1
- import { Ca as resolveRedactor, Et as failedItems, J as scopeRetainedOwnerResourceReader, Pt as createExecutorRegistry, Qi as InMemorySpawnJournal, St as checkVerdictOf, T as meterRuntimeOwnedProviderAttempt, Tn as runBrainLoop, Xi as FileSpawnJournal, Xt as createInbox, Yi as FileResultBlobStore, Zi as InMemoryResultBlobStore, an as isLiveNodeStatus, c as runTree, ca as contentAddress, fa as errMessage, fi as providerAttemptEvidence, ha as assertValidBudget, i as bestDelivered, ki as settlementFailureCause, la as detachedFrozen, o as pickBestDelivered, oa as parseWorkerToolTraceArtifact, on as isTerminalNodeStatus, s as runFinalizer, sa as workerTraceAnalysisStore, tn as createPeerMailbox, tt as resolveSpawnResourcePaths, v as withDriverExecutor, vt as CheckUnavailableError, w as meterRuntimeOwnedAccounting, zt as createRouterTranscript } from "./supervisor-DnKhkhKc.js";
1
+ import { $i as InMemorySpawnJournal, Ai as settlementFailureCause, Bt as createRouterTranscript, Ct as checkVerdictOf, Dt as failedItems, En as runBrainLoop, Ft as createExecutorRegistry, J as scopeRetainedOwnerResourceReader, Qi as InMemoryResultBlobStore, T as meterRuntimeOwnedProviderAttempt, Xi as FileResultBlobStore, Zi as FileSpawnJournal, Zt as createInbox, at as runtimeGraphMetadataKey, c as runTree, ca as workerTraceAnalysisStore, ga as assertValidBudget, i as bestDelivered, la as contentAddress, nn as createPeerMailbox, o as pickBestDelivered, on as isLiveNodeStatus, pa as errMessage, pi as providerAttemptEvidence, s as runFinalizer, sa as parseWorkerToolTraceArtifact, sn as isTerminalNodeStatus, tt as resolveSpawnResourcePaths, ua as detachedFrozen, v as withDriverExecutor, w as meterRuntimeOwnedAccounting, wa as resolveRedactor, yt as CheckUnavailableError } from "./supervisor-fq4JGynd.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-CcoARX4v.js";
4
4
  import { a as readCommittedJsonLines, t as appendCommittedJsonLine } from "./jsonl-file-DBv31uPi.js";
@@ -550,7 +550,8 @@ const coordinationVerbNames = [
550
550
  "read_journal",
551
551
  "list_analysts",
552
552
  "run_analyst",
553
- "define_analyst"
553
+ "define_analyst",
554
+ "run_graph"
554
555
  ];
555
556
  /**
556
557
  * The `CoordinationEvent` kinds that wake a waiting manager. The queue carries the UP-leg only:
@@ -569,6 +570,47 @@ const idArg = {
569
570
  type: "string",
570
571
  description: "The workerId returned by spawn_worker."
571
572
  };
573
+ /** The optional per-spawn budget `spawn_worker` and `run_graph` take. */
574
+ const spawnBudgetArg = {
575
+ type: "object",
576
+ description: "Optional per-spawn budget that merges over the per-worker default (per field). Only set the ceilings this sub-task needs raised; the conserved pool still fences.",
577
+ properties: {
578
+ maxIterations: {
579
+ type: "number",
580
+ minimum: 0
581
+ },
582
+ maxTokens: {
583
+ type: "number",
584
+ minimum: 0
585
+ },
586
+ maxUsd: {
587
+ type: "number",
588
+ minimum: 0
589
+ },
590
+ deadlineMs: {
591
+ type: "number",
592
+ minimum: 0
593
+ },
594
+ resources: {
595
+ type: "object",
596
+ additionalProperties: {
597
+ type: "object",
598
+ properties: {
599
+ unit: {
600
+ type: "string",
601
+ minLength: 1
602
+ },
603
+ limit: {
604
+ type: "integer",
605
+ minimum: 0,
606
+ maximum: Number.MAX_SAFE_INTEGER
607
+ }
608
+ },
609
+ required: ["unit", "limit"]
610
+ }
611
+ }
612
+ }
613
+ };
572
614
  /**
573
615
  * Strip zod's object-KEY CODEC artifact from a derived JSON Schema, at every depth.
574
616
  *
@@ -2136,6 +2178,107 @@ function createCoordinationToolsForManager(opts, lifetime) {
2136
2178
  idleMs: Date.now() - startedAt
2137
2179
  });
2138
2180
  };
2181
+ const admitSpawn = async (input) => {
2182
+ const { profile, key, continuity, successorOf } = input;
2183
+ const a = input.args;
2184
+ const task = detachedFrozen(input.task);
2185
+ const label = typeof a.label === "string" ? a.label : input.defaultLabel;
2186
+ if (opts.preflightSpawn) {
2187
+ const refusal = await opts.preflightSpawn(input.preflightProfile(), {
2188
+ label,
2189
+ ...key !== void 0 ? { key } : {},
2190
+ task
2191
+ });
2192
+ if (refusal) {
2193
+ preflightCounts[refusal.cause] += 1;
2194
+ return {
2195
+ error: "preflight-refused",
2196
+ reason: `the spawn pre-flight refused this profile (${refusal.cause}): ${refusal.detail}`,
2197
+ cause: refusal.cause,
2198
+ detail: refusal.detail,
2199
+ live: liveWorkerCount(),
2200
+ freeSlots: freeWorkerSlots()
2201
+ };
2202
+ }
2203
+ }
2204
+ const budget = Object.freeze(a.budget === void 0 ? opts.perWorker : mergeBudget(opts.perWorker, a.budget));
2205
+ const assignmentId = key !== void 0 ? `key:${key}` : `ordinal:${unkeyedAssignmentOrdinal++}`;
2206
+ const peerMailUrl = peerMail?.mintCapability(assignmentId);
2207
+ const context = Object.freeze({
2208
+ assignmentId,
2209
+ parentNodeId: opts.scope.view.root,
2210
+ budget,
2211
+ task,
2212
+ label,
2213
+ ...key !== void 0 ? { key } : {},
2214
+ continuity: continuity.continuity,
2215
+ ...continuity.continuity === "resume" ? { resume: continuity.resume } : {},
2216
+ ...successorOf !== void 0 ? { successorOf } : {},
2217
+ ...peerMailUrl !== void 0 ? { peerMailUrl } : {}
2218
+ });
2219
+ const res = opts.scope.spawn(() => opts.makeWorkerAgent(profile, context), task, {
2220
+ budget,
2221
+ label,
2222
+ assignmentId,
2223
+ ...key !== void 0 ? { key } : {},
2224
+ ...successorOf !== void 0 ? { successorOf } : {}
2225
+ });
2226
+ if (res.ok && res.prior?.state === "completed") {
2227
+ const s = res.prior.settled;
2228
+ const { id, status, resumed: _resumed, ...evidence } = projectSettled(s);
2229
+ return Promise.resolve({
2230
+ workerId: id,
2231
+ resumed: "completed",
2232
+ status,
2233
+ ...evidence,
2234
+ ...evidence.outRef === void 0 ? {} : { outputRead: {
2235
+ tool: "observe_agent",
2236
+ arguments: { workerId: id }
2237
+ } },
2238
+ live: liveWorkerCount(),
2239
+ freeSlots: freeWorkerSlots()
2240
+ });
2241
+ }
2242
+ if (res.ok) {
2243
+ watchWorker(res.handle.id);
2244
+ liveHandles.set(res.handle.id, res.handle);
2245
+ peerMail?.bindCapability(assignmentId, res.handle.id);
2246
+ if (typeof profile.name === "string" && profile.name.length > 0) profileNameByWorker.set(res.handle.id, profile.name);
2247
+ }
2248
+ const priorHistory = res.ok && res.prior !== void 0 && res.prior.state !== "completed" ? {
2249
+ resumed: res.prior.state,
2250
+ priorWorkerId: res.prior.priorId,
2251
+ ...res.prior.state === "retried" ? { priorReason: res.prior.reason } : {}
2252
+ } : {};
2253
+ return Promise.resolve(res.ok ? {
2254
+ workerId: res.handle.id,
2255
+ assignmentId: res.handle.assignmentId ?? assignmentId,
2256
+ ...res.handle.identity === void 0 ? {} : { identity: res.handle.identity },
2257
+ ...res.handle.materialization === void 0 ? {} : { materialization: res.handle.materialization },
2258
+ ...res.handle.executionBindings === void 0 ? {} : { executionBindings: res.handle.executionBindings },
2259
+ continuity: continuity.continuity,
2260
+ ...continuity.continuity === "resume" ? { resume: continuity.resume } : {},
2261
+ ...successorOf !== void 0 ? { successorOf } : {},
2262
+ status: res.handle.status,
2263
+ live: liveWorkerCount(),
2264
+ queued: queuedWorkerCount(),
2265
+ freeSlots: freeWorkerSlots(),
2266
+ ...priorHistory,
2267
+ ...input.resourcesFromPath.length === 0 ? {} : { resourcesFromPath: input.resourcesFromPath },
2268
+ ...input.accepted
2269
+ } : {
2270
+ error: res.reason,
2271
+ reason: spawnRefusalReason(res.reason, res.shortfalls, {
2272
+ usdUnbudgeted: "this run's root budget declares no maxUsd, so a child budget naming maxUsd can never be admitted at any amount — spawn with a budget that omits maxUsd",
2273
+ inDoubt: "this key has a prior worker recorded as started without a terminal receipt; no replacement was started because that remote worker may still be running — inspect or recover the exact prior execution before retrying",
2274
+ scopeSettled: "this run has already reached its join barrier — its driver returned and the supervisor is settling, so no further worker can be started, joined, or paid for; record this stage as not started"
2275
+ }),
2276
+ ...res.shortfalls === void 0 ? {} : { shortfalls: res.shortfalls },
2277
+ ...res.reason === "usd-unbudgeted" ? { hint: "This run's root budget declares no maxUsd, so a child budget naming maxUsd can never be admitted — at any amount. Retrying with a smaller maxUsd will fail identically. Spawn with a budget that omits maxUsd, or ask the caller to give the run a root maxUsd." } : res.reason === "in-doubt" ? { hint: "Do not retry this key. Use the recorded prior worker identity to inspect or recover that exact execution. A terminal receipt or explicit recovery is required before replacement work can start." } : {},
2278
+ live: liveWorkerCount(),
2279
+ freeSlots: freeWorkerSlots()
2280
+ });
2281
+ };
2139
2282
  const tools = [
2140
2283
  {
2141
2284
  name: "spawn_worker",
@@ -2162,46 +2305,7 @@ function createCoordinationToolsForManager(opts, lifetime) {
2162
2305
  type: "string",
2163
2306
  description: "The workerId of a SETTLED worker you spawned that this new worker replaces — for example one that failed, stalled, or finished with a weak result, restarted with a changed profile or task. The run record then names the predecessor on the new worker. Refused for an id you did not spawn (`error: \"successor-unknown\"`) and for a worker still live (`error: \"successor-live\"` — end your turn until it settles). Put what the successor needs from its predecessor in `task`."
2164
2307
  },
2165
- budget: {
2166
- type: "object",
2167
- description: "Optional per-spawn budget that merges over the per-worker default (per field). Only set the ceilings this sub-task needs raised; the conserved pool still fences.",
2168
- properties: {
2169
- maxIterations: {
2170
- type: "number",
2171
- minimum: 0
2172
- },
2173
- maxTokens: {
2174
- type: "number",
2175
- minimum: 0
2176
- },
2177
- maxUsd: {
2178
- type: "number",
2179
- minimum: 0
2180
- },
2181
- deadlineMs: {
2182
- type: "number",
2183
- minimum: 0
2184
- },
2185
- resources: {
2186
- type: "object",
2187
- additionalProperties: {
2188
- type: "object",
2189
- properties: {
2190
- unit: {
2191
- type: "string",
2192
- minLength: 1
2193
- },
2194
- limit: {
2195
- type: "integer",
2196
- minimum: 0,
2197
- maximum: Number.MAX_SAFE_INTEGER
2198
- }
2199
- },
2200
- required: ["unit", "limit"]
2201
- }
2202
- }
2203
- }
2204
- }
2308
+ budget: spawnBudgetArg
2205
2309
  },
2206
2310
  required: ["profile", "task"]
2207
2311
  },
@@ -2240,6 +2344,17 @@ function createCoordinationToolsForManager(opts, lifetime) {
2240
2344
  message: issue.message
2241
2345
  }))
2242
2346
  });
2347
+ if (parsedProfile.data.metadata?.["agentRuntimeGraph"] !== void 0) {
2348
+ const reason = `metadata.${runtimeGraphMetadataKey} is written by Runtime for the root of a run_graph subtask; call run_graph to run a graph`;
2349
+ return {
2350
+ error: "invalid-profile",
2351
+ reason,
2352
+ issues: [{
2353
+ path: `metadata.${runtimeGraphMetadataKey}`,
2354
+ message: reason
2355
+ }]
2356
+ };
2357
+ }
2243
2358
  const profile = detachedFrozen(opts.composeSpawnProfile ? agentProfileSchema.parse(opts.composeSpawnProfile(parsedProfile.data)) : parsedProfile.data);
2244
2359
  const continuity = resolveContinuity(parseContinuity(a.continuity), profile.name, key);
2245
2360
  if ("error" in continuity) return Promise.resolve({
@@ -2265,102 +2380,16 @@ function createCoordinationToolsForManager(opts, lifetime) {
2265
2380
  freeSlots: freeWorkerSlots()
2266
2381
  };
2267
2382
  }
2268
- const task = detachedFrozen(a.task);
2269
- const label = typeof a.label === "string" ? a.label : "worker";
2270
- if (opts.preflightSpawn) {
2271
- const preflightProfile = opts.resolveSpawnProfile ? detachedFrozen(opts.resolveSpawnProfile(profile)) : profile;
2272
- const refusal = await opts.preflightSpawn(preflightProfile, {
2273
- label,
2274
- ...key !== void 0 ? { key } : {},
2275
- task
2276
- });
2277
- if (refusal) {
2278
- preflightCounts[refusal.cause] += 1;
2279
- return {
2280
- error: "preflight-refused",
2281
- reason: `the spawn pre-flight refused this profile (${refusal.cause}): ${refusal.detail}`,
2282
- cause: refusal.cause,
2283
- detail: refusal.detail,
2284
- live: liveWorkerCount(),
2285
- freeSlots: freeWorkerSlots()
2286
- };
2287
- }
2288
- }
2289
- const budget = Object.freeze(a.budget === void 0 ? opts.perWorker : mergeBudget(opts.perWorker, a.budget));
2290
- const assignmentId = key !== void 0 ? `key:${key}` : `ordinal:${unkeyedAssignmentOrdinal++}`;
2291
- const peerMailUrl = peerMail?.mintCapability(assignmentId);
2292
- const context = Object.freeze({
2293
- assignmentId,
2294
- parentNodeId: opts.scope.view.root,
2295
- budget,
2296
- task,
2297
- label,
2298
- ...key !== void 0 ? { key } : {},
2299
- continuity: continuity.continuity,
2300
- ...continuity.continuity === "resume" ? { resume: continuity.resume } : {},
2301
- ...successorOf !== void 0 ? { successorOf } : {},
2302
- ...peerMailUrl !== void 0 ? { peerMailUrl } : {}
2303
- });
2304
- const res = opts.scope.spawn(() => opts.makeWorkerAgent(profile, context), task, {
2305
- budget,
2306
- label,
2307
- assignmentId,
2308
- ...key !== void 0 ? { key } : {},
2309
- ...successorOf !== void 0 ? { successorOf } : {}
2310
- });
2311
- if (res.ok && res.prior?.state === "completed") {
2312
- const s = res.prior.settled;
2313
- const { id, status, resumed: _resumed, ...evidence } = projectSettled(s);
2314
- return Promise.resolve({
2315
- workerId: id,
2316
- resumed: "completed",
2317
- status,
2318
- ...evidence,
2319
- ...evidence.outRef === void 0 ? {} : { outputRead: {
2320
- tool: "observe_agent",
2321
- arguments: { workerId: id }
2322
- } },
2323
- live: liveWorkerCount(),
2324
- freeSlots: freeWorkerSlots()
2325
- });
2326
- }
2327
- if (res.ok) {
2328
- watchWorker(res.handle.id);
2329
- liveHandles.set(res.handle.id, res.handle);
2330
- peerMail?.bindCapability(assignmentId, res.handle.id);
2331
- if (typeof profile.name === "string" && profile.name.length > 0) profileNameByWorker.set(res.handle.id, profile.name);
2332
- }
2333
- const priorHistory = res.ok && res.prior !== void 0 && res.prior.state !== "completed" ? {
2334
- resumed: res.prior.state,
2335
- priorWorkerId: res.prior.priorId,
2336
- ...res.prior.state === "retried" ? { priorReason: res.prior.reason } : {}
2337
- } : {};
2338
- return Promise.resolve(res.ok ? {
2339
- workerId: res.handle.id,
2340
- assignmentId: res.handle.assignmentId ?? assignmentId,
2341
- ...res.handle.identity === void 0 ? {} : { identity: res.handle.identity },
2342
- ...res.handle.materialization === void 0 ? {} : { materialization: res.handle.materialization },
2343
- ...res.handle.executionBindings === void 0 ? {} : { executionBindings: res.handle.executionBindings },
2344
- continuity: continuity.continuity,
2345
- ...continuity.continuity === "resume" ? { resume: continuity.resume } : {},
2346
- ...successorOf !== void 0 ? { successorOf } : {},
2347
- status: res.handle.status,
2348
- live: liveWorkerCount(),
2349
- queued: queuedWorkerCount(),
2350
- freeSlots: freeWorkerSlots(),
2351
- ...priorHistory,
2352
- ...resourcePaths.resolved.length === 0 ? {} : { resourcesFromPath: resourcePaths.resolved }
2353
- } : {
2354
- error: res.reason,
2355
- reason: spawnRefusalReason(res.reason, res.shortfalls, {
2356
- usdUnbudgeted: "this run's root budget declares no maxUsd, so a child budget naming maxUsd can never be admitted at any amount — spawn with a budget that omits maxUsd",
2357
- inDoubt: "this key has a prior worker recorded as started without a terminal receipt; no replacement was started because that remote worker may still be running — inspect or recover the exact prior execution before retrying",
2358
- scopeSettled: "this run has already reached its join barrier — its driver returned and the supervisor is settling, so no further worker can be started, joined, or paid for; record this stage as not started"
2359
- }),
2360
- ...res.shortfalls === void 0 ? {} : { shortfalls: res.shortfalls },
2361
- ...res.reason === "usd-unbudgeted" ? { hint: "This run's root budget declares no maxUsd, so a child budget naming maxUsd can never be admitted — at any amount. Retrying with a smaller maxUsd will fail identically. Spawn with a budget that omits maxUsd, or ask the caller to give the run a root maxUsd." } : res.reason === "in-doubt" ? { hint: "Do not retry this key. Use the recorded prior worker identity to inspect or recover that exact execution. A terminal receipt or explicit recovery is required before replacement work can start." } : {},
2362
- live: liveWorkerCount(),
2363
- freeSlots: freeWorkerSlots()
2383
+ return admitSpawn({
2384
+ profile,
2385
+ args: a,
2386
+ task: a.task,
2387
+ key,
2388
+ continuity,
2389
+ successorOf,
2390
+ preflightProfile: () => opts.resolveSpawnProfile ? detachedFrozen(opts.resolveSpawnProfile(profile)) : profile,
2391
+ resourcesFromPath: resourcePaths.resolved,
2392
+ defaultLabel: "worker"
2364
2393
  });
2365
2394
  }
2366
2395
  },
@@ -3031,6 +3060,79 @@ function createCoordinationToolsForManager(opts, lifetime) {
3031
3060
  handler: async (raw) => readJournal(raw, false)
3032
3061
  } : tool));
3033
3062
  }
3063
+ if (opts.graphs) {
3064
+ const graphs = opts.graphs;
3065
+ tools.push({
3066
+ name: "run_graph",
3067
+ description: "Run an agent graph as ONE subtask instead of one worker: a fixed topology whose nodes are profiles and whose edges carry directives, driven by its root node. Pass `graph` ({ nodes: [{ id, profile }], edges: [{ kind: 'delegates', from, to, directive: 'delegates/worker-brief/v1' }] }, where each profile.name equals its node id and the root node grants agent_runtime_coordination_spawn_worker) or `graphDigest` (a graph stored in this run's graph registry). `deliverable` is what the graph must deliver; it becomes the root node's task. The subtask reserves `budget` (merged over the per-worker default, as for spawn_worker) from your conserved pool, and the whole graph spends only that. Every node runs its own pinned profile; the run keeps its checks and graders, which are never graph nodes. Returns a workerId as spawn_worker does; end your turn and you are woken when the graph settles. Its output is { deliverable, edges }: the root node's result and the edge ledger (every traversal, also recorded in the run journal).",
3068
+ inputSchema: {
3069
+ type: "object",
3070
+ properties: {
3071
+ graph: {
3072
+ type: "object",
3073
+ description: "The graph as data: { nodes: [{ id, profile }], edges: [...] }. Delegates edges run from the root to each worker node; an optional analyzes edge ({ kind: 'analyzes', analyst, over, to, directive }) names an analyst node.",
3074
+ additionalProperties: true
3075
+ },
3076
+ graphDigest: {
3077
+ type: "string",
3078
+ description: "A stored graph's digest in this run's graph registry, instead of graph."
3079
+ },
3080
+ deliverable: {
3081
+ type: "string",
3082
+ description: "What the graph must deliver. It becomes the root node's task."
3083
+ },
3084
+ budget: spawnBudgetArg,
3085
+ label: {
3086
+ type: "string",
3087
+ description: "Optional trace label."
3088
+ },
3089
+ key: {
3090
+ type: "string",
3091
+ description: "Optional semantic name for this subtask. The same key never runs twice, as for spawn_worker: a completed key returns its committed result."
3092
+ }
3093
+ },
3094
+ required: ["deliverable"]
3095
+ },
3096
+ handler: async (raw) => {
3097
+ const a = obj(raw);
3098
+ const deliverable = typeof a.deliverable === "string" ? a.deliverable.trim() : "";
3099
+ if (deliverable.length === 0) return {
3100
+ error: "invalid-graph",
3101
+ reason: "deliverable must be a non-empty string: what the graph must deliver"
3102
+ };
3103
+ if (a.graph === void 0 === (a.graphDigest === void 0)) return {
3104
+ error: "invalid-graph",
3105
+ reason: "pass exactly one of graph (the graph as data) or graphDigest (a stored graph)"
3106
+ };
3107
+ if (a.graphDigest !== void 0 && typeof a.graphDigest !== "string") return {
3108
+ error: "invalid-graph",
3109
+ reason: "graphDigest must be a string"
3110
+ };
3111
+ const key = a.key === void 0 ? void 0 : str(a.key, "key");
3112
+ const prepared = await graphs.prepare(typeof a.graphDigest === "string" ? { graphDigest: a.graphDigest } : { graph: a.graph });
3113
+ if (!prepared.ok) return {
3114
+ error: "invalid-graph",
3115
+ reason: prepared.reason
3116
+ };
3117
+ const profile = detachedFrozen(prepared.profile);
3118
+ return admitSpawn({
3119
+ profile,
3120
+ args: a,
3121
+ task: deliverable,
3122
+ key,
3123
+ continuity: { continuity: "fresh" },
3124
+ successorOf: void 0,
3125
+ preflightProfile: () => opts.resolveSpawnProfile ? detachedFrozen(opts.resolveSpawnProfile(profile)) : profile,
3126
+ resourcesFromPath: [],
3127
+ defaultLabel: `graph:${prepared.root}`,
3128
+ accepted: { graph: {
3129
+ root: prepared.root,
3130
+ nodes: prepared.nodes
3131
+ } }
3132
+ });
3133
+ }
3134
+ });
3135
+ }
3034
3136
  if (opts.analysts) {
3035
3137
  tools.push({
3036
3138
  name: "list_analysts",
@@ -4600,6 +4702,7 @@ function driverAgent(opts) {
4600
4702
  scope,
4601
4703
  blobs: opts.blobs,
4602
4704
  makeWorkerAgent: opts.makeWorkerAgent,
4705
+ ...opts.graphs ? { graphs: opts.graphs } : {},
4603
4706
  ...opts.authorizeDownMessage ? { authorizeDownMessage: opts.authorizeDownMessage } : {},
4604
4707
  perWorker: opts.perWorker,
4605
4708
  ...opts.deliverable ? { deliverable: opts.deliverable } : {},
@@ -5008,4 +5111,4 @@ function safeJson(v) {
5008
5111
  //#endregion
5009
5112
  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 };
5010
5113
 
5011
- //# sourceMappingURL=coordination-driver-CNEeqMoh.js.map
5114
+ //# sourceMappingURL=coordination-driver-DkkUVe9g.js.map