@tangle-network/agent-runtime 0.238.0 → 0.240.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-CRDZUoUE.d.ts → activation-CtkpoWet.d.ts} +2 -2
  2. package/dist/{activation-Br1FRlyB.js → activation-q224yRQK.js} +2 -2
  3. package/dist/{activation-Br1FRlyB.js.map → activation-q224yRQK.js.map} +1 -1
  4. package/dist/agent.d.ts +2 -2
  5. package/dist/agent.js +2 -2
  6. package/dist/{coordination-driver-DbiCH5be.js → coordination-driver-CMprWr0k.js} +14 -240
  7. package/dist/coordination-driver-CMprWr0k.js.map +1 -0
  8. package/dist/{delegate-C4rLxuv8.js → delegate-kwBecu_w.js} +2 -2
  9. package/dist/{delegate-C4rLxuv8.js.map → delegate-kwBecu_w.js.map} +1 -1
  10. package/dist/durable.d.ts +2 -2
  11. package/dist/durable.js +2 -2
  12. package/dist/{graph-BHU73FnA.js → graph-Bke7I2gs.js} +3 -3
  13. package/dist/{graph-BHU73FnA.js.map → graph-Bke7I2gs.js.map} +1 -1
  14. package/dist/{improvement-cycle-DkzbEzS5.js → improvement-cycle-BpSVwIJw.js} +3 -3
  15. package/dist/{improvement-cycle-DkzbEzS5.js.map → improvement-cycle-BpSVwIJw.js.map} +1 -1
  16. package/dist/{index-B8Fmz26p.d.ts → index-CbZaoYbD.d.ts} +129 -5
  17. package/dist/index.d.ts +6 -6
  18. package/dist/index.js +7 -7
  19. package/dist/intelligence.d.ts +3 -3
  20. package/dist/intelligence.js +3 -3
  21. package/dist/kernel.d.ts +3 -3
  22. package/dist/kernel.js +8 -8
  23. package/dist/{loop-runner-bin-vGFnPXLM.d.ts → loop-runner-bin-BUkkPt10.d.ts} +3 -3
  24. package/dist/{loop-runner-bin-BaQIyvh-.js → loop-runner-bin-DU8XqsGN.js} +3 -3
  25. package/dist/{loop-runner-bin-BaQIyvh-.js.map → loop-runner-bin-DU8XqsGN.js.map} +1 -1
  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 +6 -6
  30. package/dist/mcp/index.js +5 -5
  31. package/dist/{openai-tools-BPPAXxP2.d.ts → openai-tools-BI1ofIfL.d.ts} +2 -2
  32. package/dist/profiles.d.ts +2 -2
  33. package/dist/{provision-supervisor-Briw5tX4.js → provision-supervisor-DoSrqsM7.js} +3 -3
  34. package/dist/{provision-supervisor-Briw5tX4.js.map → provision-supervisor-DoSrqsM7.js.map} +1 -1
  35. package/dist/{runtime-BzGKUqqY.js → runtime-CmuAQsWI.js} +8 -8
  36. package/dist/{runtime-BzGKUqqY.js.map → runtime-CmuAQsWI.js.map} +1 -1
  37. package/dist/{server-CDn-i_GJ.js → server-shkdLqls.js} +3 -3
  38. package/dist/{server-CDn-i_GJ.js.map → server-shkdLqls.js.map} +1 -1
  39. package/dist/{stream-agent-turn-xgmm-M55.d.ts → stream-agent-turn-DayHmtvw.d.ts} +2 -2
  40. package/dist/{structural-rollout-B-EAO8C5.js → structural-rollout-CW67upUV.js} +2 -2
  41. package/dist/{structural-rollout-B-EAO8C5.js.map → structural-rollout-CW67upUV.js.map} +1 -1
  42. package/dist/{substrate-B_9stFWH.d.ts → substrate-iQOskmQ_.d.ts} +2 -2
  43. package/dist/{supervise-Dc2DjlZS.js → supervise-DzoCYAe-.js} +15 -4
  44. package/dist/supervise-DzoCYAe-.js.map +1 -0
  45. package/dist/{supervisor-BN3oMv_v.js → supervisor-CFSPj8rx.js} +407 -20
  46. package/dist/supervisor-CFSPj8rx.js.map +1 -0
  47. package/dist/testing.d.ts +2 -2
  48. package/dist/testing.js +12 -12
  49. package/dist/tui/index.d.ts +1 -1
  50. package/dist/tui/index.js +1 -1
  51. package/dist/{types-CE7ES_TD.d.ts → types-CEma9LKR.d.ts} +16 -1
  52. package/package.json +1 -1
  53. package/dist/coordination-driver-DbiCH5be.js.map +0 -1
  54. package/dist/supervise-Dc2DjlZS.js.map +0 -1
  55. package/dist/supervisor-BN3oMv_v.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { f as ExecutorConfig, i as CollectedAgentTurn, r as AgentTurnUsage } from "./stream-agent-turn-xgmm-M55.js";
1
+ import { f as ExecutorConfig, i as CollectedAgentTurn, r as AgentTurnUsage } from "./stream-agent-turn-DayHmtvw.js";
2
2
  import { AgentCandidateBundle, AgentImprovementActivation, AgentImprovementActivationOutcome, AgentImprovementActivationResult, AgentImprovementActivationTarget, AgentImprovementProposal, AgentImprovementReview, AgentImprovementSurface, AgentProfile, AgentProfileDiff, AgentProfileImprovementChange, AgentProfileImprovementExperiment, HarnessType, ReasoningEffort, Sha256Digest } from "@tangle-network/agent-interface";
3
3
  import { CostLedgerHandle, MaximumCharge, ProposalFinding } from "@tangle-network/agent-eval";
4
4
  import { CampaignScenarioIdentity, CompareOptimizationMethodsOptions, OptimizationMethod, OptimizationMethodComparison, WorktreeAdapter } from "@tangle-network/agent-eval/campaign";
@@ -658,4 +658,4 @@ declare function verifyAgentImprovementActivationResult(input: {
658
658
  declare function executeAgentImprovementActivation(input: ExecuteAgentImprovementActivationInput, options: ExecuteAgentImprovementActivationOptions): Promise<AgentImprovementActivationResult>;
659
659
  //#endregion
660
660
  export { ImprovementProfilePopulationLineageNode as $, ImproveMethodResult as A, ImproveSkillsOptions as B, ImproveCost as C, ImproveMethodFactory as D, ImproveMethodContext as E, ImproveProfileComponents as F, ImprovementProfileCandidate as G, ImprovementCandidate as H, ImproveProfileSurface as I, ImprovementProfileCandidatePopulationUnavailable as J, ImprovementProfileCandidatePopulation as K, ImproveResult as L, ImproveOptimizationRunOptions as M, ImproveOptions as N, ImproveMethodLineage as O, ImproveProfileAgent as P, ImprovementProfilePopulationLineage as Q, ImproveRuntimeCodeGeneratorOptions as R, ImproveCodeRunOptions as S, ImproveLineage as T, ImprovementCodeCandidate as U, ImproveSurface as V, ImprovementMaterializedProfilePopulationCandidate as W, ImprovementProfilePopulationCandidate as X, ImprovementProfilePopulationArtifactSource as Y, ImprovementProfilePopulationCandidateSource as Z, ImproveCandidateValidationInput as _, AgentImprovementActivationTransitionInput as a, AgenticGeneratorOptions as at, ImproveCodeOptions as b, CreateAgentImprovementActivationResultOptions as c, AgenticGeneratorShotReceipt as ct, ProfileImprovementActivationTransitionInput as d, agenticGenerator as dt, ImprovementProfilePopulationObservationSource as et, SealedCandidateActivationTransitionInput as f, commandVerifier as ft, improve as g, verifyAgentImprovementActivationResult as h, AgentImprovementActivationTransition as i, AgenticGeneratorExecutorForWorktree as it, ImproveMethodSource as j, ImproveMethodOptions as k, ExecuteAgentImprovementActivationInput as l, Verifier as lt, executeAgentImprovementActivation as m, CandidateGenerator as mt, AgentImprovementActivationResultStore as n, DeepReadonly as nt, AgentProfileImprovementActivationOperation as o, AgenticGeneratorShotDisposition as ot, createAgentImprovementActivationResult as p, defaultBuildPrompt as pt, ImprovementProfileCandidatePopulationAvailable as q, AgentImprovementActivationTargetPlan as r, ReadonlyAgentProfile as rt, AgentProfileImprovementActivationTargetPlan as s, AgenticGeneratorShotExecution as st, AgentImprovementActivationReconciliation as t, ImprovementRefusedProfilePopulationCandidate as tt, ExecuteAgentImprovementActivationOptions as u, VerifyResult as ut, ImproveCandidateValidator as v, ImproveCustomCodeGeneratorOptions as w, ImproveCodeResult as x, ImproveCodeBaseOptions as y, ImproveScenarioPartitions as z };
661
- //# sourceMappingURL=activation-CRDZUoUE.d.ts.map
661
+ //# sourceMappingURL=activation-CtkpoWet.d.ts.map
@@ -1,4 +1,4 @@
1
- import { A as agentImprovementTargetInput, M as agentProfileImprovementStateDigest, c as requireSealedCandidateExperiment, d as verifyAgentImprovementActivation, f as verifyAgentImprovementProposal, k as agentImprovementTargetDigest } from "./improvement-cycle-DkzbEzS5.js";
1
+ import { A as agentImprovementTargetInput, M as agentProfileImprovementStateDigest, c as requireSealedCandidateExperiment, d as verifyAgentImprovementActivation, f as verifyAgentImprovementProposal, k as agentImprovementTargetDigest } from "./improvement-cycle-BpSVwIJw.js";
2
2
  import { o as canonicalCandidateDigest$1, p as verifyCanonicalCandidateDocument, s as canonicalCandidateDocument, u as immutableCandidateValue } from "./protected-redaction-wGo44k2K.js";
3
3
  import { agentImprovementActivationResultSchema, agentImprovementActivationSchema, agentProfileImprovementExperimentSchema } from "@tangle-network/agent-interface";
4
4
  //#region src/intelligence/activation.ts
@@ -201,4 +201,4 @@ function targetIdentity(target) {
201
201
  //#endregion
202
202
  export { executeAgentImprovementActivation as n, verifyAgentImprovementActivationResult as r, createAgentImprovementActivationResult as t };
203
203
 
204
- //# sourceMappingURL=activation-Br1FRlyB.js.map
204
+ //# sourceMappingURL=activation-q224yRQK.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"activation-Br1FRlyB.js","names":["canonicalCandidateDigest"],"sources":["../src/intelligence/activation.ts"],"sourcesContent":["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":";;;;;AA6IA,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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AiB,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-q224yRQK.js","names":["canonicalCandidateDigest"],"sources":["../src/intelligence/activation.ts"],"sourcesContent":["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":";;;;;AA6IA,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,MAA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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"}
package/dist/agent.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { Gi as RuntimeStreamEvent, Vr as AgentRunSpec, fi as SandboxClient, ui as OutputAdapter } from "./types-CE7ES_TD.js";
1
+ import { Gi as RuntimeStreamEvent, Vr as AgentRunSpec, fi as SandboxClient, ui as OutputAdapter } from "./types-CEma9LKR.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
- import { Am as profileMaterializationAxes, Cm as ProfileMaterializationContract, Dm as controlProfileMaterialization, Em as assertProfileMaterialization, Fm as renderProfileMaterializationIssues, Im as sandboxActProfileMaterialization, Lm as validateProfileMaterialization, Mm as promptModelProfileMaterialization, Nm as promptOnlyProfileMaterialization, Om as defineProfileMaterializationContract, Pm as promptResourceProfileMaterialization, Rm as worktreeCliProfileMaterialization, Sm as KnownAgentProfileMaterializationAxis, Tm as ValidateProfileMaterializationOptions, _m as AGENT_PROFILE_MATERIALIZATION_AXES, bm as CanonicalAgentProfileMaterializationAxis, jm as promptControlProfileMaterialization, km as fullProfileMaterialization, vm as AgentProfileMaterializationAxis, wm as ProfileMaterializationIssue, xm as DefineProfileMaterializationContractOptions, ym as AssertProfileMaterializationOptions } from "./index-B8Fmz26p.js";
3
+ import { Am as DefineProfileMaterializationContractOptions, Bm as promptControlProfileMaterialization, Dm as AgentProfileMaterializationAxis, Em as AGENT_PROFILE_MATERIALIZATION_AXES, Fm as assertProfileMaterialization, Gm as sandboxActProfileMaterialization, Hm as promptOnlyProfileMaterialization, Im as controlProfileMaterialization, Km as validateProfileMaterialization, Lm as defineProfileMaterializationContract, Mm as ProfileMaterializationContract, Nm as ProfileMaterializationIssue, Om as AssertProfileMaterializationOptions, Pm as ValidateProfileMaterializationOptions, Rm as fullProfileMaterialization, Um as promptResourceProfileMaterialization, Vm as promptModelProfileMaterialization, Wm as renderProfileMaterializationIssues, jm as KnownAgentProfileMaterializationAxis, km as CanonicalAgentProfileMaterializationAxis, qm as worktreeCliProfileMaterialization, zm as profileMaterializationAxes } from "./index-CbZaoYbD.js";
4
4
  import { AgentProfile, AgentProfileFileMount, AgentProfileMcpServer } from "@tangle-network/agent-interface";
5
5
  import { TraceAnalystDefinition } from "@tangle-network/agent-eval";
6
6
  import { SandboxEvent } from "@tangle-network/sandbox";
package/dist/agent.js CHANGED
@@ -1,5 +1,5 @@
1
- import { Ar as defineProfileMaterializationContract, Ci as mapSandboxEvent, Dr as AGENT_PROFILE_MATERIALIZATION_AXES, Fr as promptOnlyProfileMaterialization, Hr as worktreeCliProfileMaterialization, Ir as promptResourceProfileMaterialization, Lr as renderProfileMaterializationIssues, Mr as profileMaterializationAxes, Nr as promptControlProfileMaterialization, Or as assertProfileMaterialization, Pr as promptModelProfileMaterialization, Vr as validateProfileMaterialization, cn as createSandboxForSpec, jr as fullProfileMaterialization, kr as controlProfileMaterialization, zr as sandboxActProfileMaterialization } from "./supervisor-BN3oMv_v.js";
2
- import "./runtime-BzGKUqqY.js";
1
+ import { Br as promptModelProfileMaterialization, Fr as controlProfileMaterialization, Gr as sandboxActProfileMaterialization, Hr as promptResourceProfileMaterialization, Ir as defineProfileMaterializationContract, Jr as worktreeCliProfileMaterialization, Lr as fullProfileMaterialization, Nr as AGENT_PROFILE_MATERIALIZATION_AXES, Pr as assertProfileMaterialization, Rr as profileMaterializationAxes, Ur as renderProfileMaterializationIssues, Vr as promptOnlyProfileMaterialization, ki as mapSandboxEvent, mn as createSandboxForSpec, qr as validateProfileMaterialization, zr as promptControlProfileMaterialization } from "./supervisor-CFSPj8rx.js";
2
+ import "./runtime-CmuAQsWI.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,12 +1,11 @@
1
- import { Ai as chargedTokens, Ct as parseWorkerToolTraceArtifact, Et as assertValidBudget, Fi as promptCacheTokenClasses, Gr as readCommittedJsonLines, Ki as withBudgetResources, Kr as writeAllBytes, Kt as createPeerMailbox, Un as resolveRedactor, Vi as unmeteredSpend, Vt as createInbox, Wi as addResourceSpend, Wr as prepareJsonlAppend, Xt as isLiveNodeStatus, Y as errMessage, Z as freeSlots, Zt as isTerminalNodeStatus, a as pickBestDelivered, at as createExecutorRegistry, dt as FileResultBlobStore, ft as FileSpawnJournal, g as withDriverExecutor, mt as InMemorySpawnJournal, o as runFinalizer, pi as detachedFrozen, pt as InMemoryResultBlobStore, r as bestDelivered, s as runTree, ti as providerAttemptEvidence, vn as runBrainLoop, wt as workerTraceAnalysisStore, x as meterRuntimeOwnedProviderAttempt } from "./supervisor-BN3oMv_v.js";
1
+ import { At as workerTraceAnalysisStore, Ii as chargedTokens, Mt as assertValidBudget, Qi as withBudgetResources, Qr as writeAllBytes, Qt as createPeerMailbox, R as scopeRetainedOwnerResourceReader, U as resolveSpawnResourcePaths, Vi as promptCacheTokenClasses, Xi as addResourceSpend, Xr as prepareJsonlAppend, Yn as resolveRedactor, Zr as readCommittedJsonLines, _t as FileResultBlobStore, a as pickBestDelivered, bt as InMemorySpawnJournal, dt as createExecutorRegistry, g as withDriverExecutor, kt as parseWorkerToolTraceArtifact, nn as isLiveNodeStatus, o as runFinalizer, qi as unmeteredSpend, qt as createInbox, r as bestDelivered, rn as isTerminalNodeStatus, rt as freeSlots, s as runTree, si as providerAttemptEvidence, tt as errMessage, vt as FileSpawnJournal, wn as runBrainLoop, x as meterRuntimeOwnedProviderAttempt, yi as detachedFrozen, yt as InMemoryResultBlobStore } from "./supervisor-CFSPj8rx.js";
2
2
  import { f as RuntimeRunStateError, m as ValidationError } from "./errors-DodWX-cb.js";
3
3
  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-hZREkcfu.js";
4
4
  import { agentProfileSchema, canonicalCandidateDigest } from "@tangle-network/agent-interface";
5
5
  import { argHash, errorStreakDetector, observeAll, repeatedActionDetector } from "@tangle-network/agent-eval";
6
- import { createHash, randomUUID } from "node:crypto";
6
+ import { randomUUID } from "node:crypto";
7
7
  import { mkdirSync, readFileSync, watch } from "node:fs";
8
- import { isAbsolute, join, relative, resolve, sep } from "node:path";
9
- import { open, realpath, stat } from "node:fs/promises";
8
+ import { join } from "node:path";
10
9
  //#region src/runtime/supervise/detector-monitor.ts
11
10
  /**
12
11
  *
@@ -121,238 +120,6 @@ function createEventBus(now = Date.now) {
121
120
  };
122
121
  }
123
122
  //#endregion
124
- //#region src/mcp/tools/spawn-resource-paths.ts
125
- /**
126
- * Inline resources a manager hands a child by PATH instead of by content.
127
- *
128
- * The canonical profile schema knows two resource kinds, `inline` (a content string) and `github`.
129
- * A manager that wants a child to receive a data file therefore had one way to do it: emit the
130
- * bytes inside its own `spawn` tool call. That is a transcription by a language model, and it does
131
- * not survive size. Measured 2026-09-12 (discovery-lab `mech-interp-foundations-glm2-b-20260912b`):
132
- * a 29,144-character base64 payload on the manager's disk reached three children as 15,928
133
- * characters with 11 substitutions, and a fourth child received the literal placeholder the
134
- * manager meant to replace. Seven blind-check attempts across two runs delivered no data.
135
- *
136
- * `{ kind: 'inline', name, path }` lets the coordination server be the transport: it reads the
137
- * file under the manager's workspace root, fills `content`, and the profile that reaches the
138
- * schema, the journal, and the provider is an ordinary inline resource. Nothing downstream
139
- * changes; the model's output stops carrying the bytes.
140
- *
141
- * Fail-closed rules, each with the reason a manager needs to fix its call:
142
- * - no root configured → refused (a nested manager in a remote sandbox has no host directory
143
- * the server may read for it)
144
- * - absolute path, `..` escape, or a symlink that resolves outside the root → refused; the
145
- * workspace root is the only directory a manager may hand out
146
- * - not a regular file → refused
147
- * - over {@link SPAWN_RESOURCE_PATH_MAX_BYTES} → refused naming the bound
148
- * - bytes that are not valid UTF-8 → refused; `content` is a string, so binary data is encoded
149
- * (base64) by the manager first, exactly as it would be for a content resource
150
- */
151
- const SPAWN_RESOURCE_PATH_MAX_BYTES = 4 * 1024 * 1024;
152
- function isRecord(value) {
153
- return typeof value === "object" && value !== null && !Array.isArray(value);
154
- }
155
- /** An inline ref that names a path and carries no content. Anything else is left untouched so the
156
- * canonical schema keeps its verdict on it. */
157
- function pathInlineRef(value) {
158
- if (!isRecord(value)) return void 0;
159
- if (value.kind !== "inline" || value.content !== void 0) return void 0;
160
- if (typeof value.path !== "string" || typeof value.name !== "string") return void 0;
161
- return {
162
- kind: "inline",
163
- name: value.name,
164
- path: value.path
165
- };
166
- }
167
- async function readUnderRoot(root, requested) {
168
- if (requested.length === 0) return {
169
- ok: false,
170
- reason: "path is empty"
171
- };
172
- if (isAbsolute(requested)) return {
173
- ok: false,
174
- reason: `path must be relative to the workspace root, not absolute (${requested})`
175
- };
176
- const rootReal = await realpath(root).catch(() => void 0);
177
- if (rootReal === void 0) return {
178
- ok: false,
179
- reason: `workspace root ${root} does not exist`
180
- };
181
- const candidate = resolve(rootReal, requested);
182
- if (!inside(rootReal, candidate)) return {
183
- ok: false,
184
- reason: `path ${requested} leaves the workspace root`
185
- };
186
- let handle;
187
- try {
188
- handle = await open(candidate, "r");
189
- } catch (error) {
190
- return {
191
- ok: false,
192
- reason: `path ${requested}: ${describe(error)}`
193
- };
194
- }
195
- try {
196
- const info = await handle.stat();
197
- if (!info.isFile()) return {
198
- ok: false,
199
- reason: `path ${requested} is not a regular file`
200
- };
201
- const real = await realpath(candidate).catch(() => void 0);
202
- if (real === void 0 || !inside(rootReal, real)) return {
203
- ok: false,
204
- reason: `path ${requested} resolves outside the workspace root`
205
- };
206
- const named = await stat(real).catch(() => void 0);
207
- if (named === void 0 || named.dev !== info.dev || named.ino !== info.ino) return {
208
- ok: false,
209
- reason: `path ${requested} changed while it was being read; retry the spawn`
210
- };
211
- if (info.size > 4194304) return {
212
- ok: false,
213
- reason: `path ${requested} is ${info.size} bytes; an inline resource is at most ${SPAWN_RESOURCE_PATH_MAX_BYTES} bytes`
214
- };
215
- const bytes = await handle.readFile();
216
- if (bytes.length > 4194304) return {
217
- ok: false,
218
- reason: `path ${requested} is ${bytes.length} bytes; an inline resource is at most ${SPAWN_RESOURCE_PATH_MAX_BYTES} bytes`
219
- };
220
- const content = bytes.toString("utf8");
221
- if (!Buffer.from(content, "utf8").equals(bytes)) return {
222
- ok: false,
223
- reason: `path ${requested} is not valid UTF-8; encode binary data (base64) before handing it to a child`
224
- };
225
- return {
226
- ok: true,
227
- content,
228
- byteLength: bytes.length,
229
- sha256: createHash("sha256").update(bytes).digest("hex")
230
- };
231
- } catch (error) {
232
- return {
233
- ok: false,
234
- reason: `path ${requested}: ${describe(error)}`
235
- };
236
- } finally {
237
- await handle.close().catch(() => void 0);
238
- }
239
- }
240
- /** `target` is `rootReal` itself or strictly below it; both must already be absolute. */
241
- function inside(rootReal, target) {
242
- const rel = relative(rootReal, target);
243
- return rel !== "" && !rel.startsWith(`..${sep}`) && rel !== ".." && !isAbsolute(rel);
244
- }
245
- function describe(error) {
246
- const code = error?.code;
247
- if (code === "ENOENT") return "does not exist under the workspace root";
248
- if (code === "EACCES" || code === "EPERM") return "is not readable by the runtime process";
249
- if (code === "EISDIR") return "is not a regular file";
250
- return error instanceof Error ? error.message : String(error);
251
- }
252
- /**
253
- * Replace every `{ kind: 'inline', name, path }` under `profile.resources` with the inline
254
- * resource its bytes make. Returns the profile unchanged (same reference) when nothing names a
255
- * path, so callers pay nothing on the common case.
256
- */
257
- async function resolveSpawnResourcePaths(profile, root) {
258
- if (!isRecord(profile) || !isRecord(profile.resources)) return {
259
- ok: true,
260
- profile,
261
- resolved: []
262
- };
263
- const resources = profile.resources;
264
- const resolved = [];
265
- let touched = false;
266
- const next = { ...resources };
267
- const substitute = async (at, ref) => {
268
- if (root === void 0) return { error: "this manager has no workspace root the coordination server may read, so a resource by path cannot be resolved; pass content, or a github resource" };
269
- const read = await readUnderRoot(root, ref.path);
270
- if (!read.ok) return { error: read.reason };
271
- resolved.push({
272
- at,
273
- path: ref.path,
274
- byteLength: read.byteLength,
275
- sha256: read.sha256
276
- });
277
- touched = true;
278
- return {
279
- kind: "inline",
280
- name: ref.name,
281
- content: read.content
282
- };
283
- };
284
- for (const list of [
285
- "tools",
286
- "skills",
287
- "agents"
288
- ]) {
289
- const entries = resources[list];
290
- if (!Array.isArray(entries)) continue;
291
- const out = [];
292
- for (const [index, entry] of entries.entries()) {
293
- const ref = pathInlineRef(entry);
294
- if (ref === void 0) {
295
- out.push(entry);
296
- continue;
297
- }
298
- const at = `${list}[${index}]`;
299
- const replaced = await substitute(at, ref);
300
- if ("error" in replaced) return {
301
- ok: false,
302
- at,
303
- reason: replaced.error
304
- };
305
- out.push(replaced);
306
- }
307
- next[list] = out;
308
- }
309
- if (Array.isArray(resources.files)) {
310
- const out = [];
311
- for (const [index, mount] of resources.files.entries()) {
312
- const ref = isRecord(mount) ? pathInlineRef(mount.resource) : void 0;
313
- if (ref === void 0 || !isRecord(mount)) {
314
- out.push(mount);
315
- continue;
316
- }
317
- const at = `files[${index}].resource`;
318
- const replaced = await substitute(at, ref);
319
- if ("error" in replaced) return {
320
- ok: false,
321
- at,
322
- reason: replaced.error
323
- };
324
- out.push({
325
- ...mount,
326
- resource: replaced
327
- });
328
- }
329
- next.files = out;
330
- }
331
- const instructions = pathInlineRef(resources.instructions);
332
- if (instructions !== void 0) {
333
- const replaced = await substitute("instructions", instructions);
334
- if ("error" in replaced) return {
335
- ok: false,
336
- at: "instructions",
337
- reason: replaced.error
338
- };
339
- next.instructions = replaced;
340
- }
341
- if (!touched) return {
342
- ok: true,
343
- profile,
344
- resolved: []
345
- };
346
- return {
347
- ok: true,
348
- profile: {
349
- ...profile,
350
- resources: next
351
- },
352
- resolved
353
- };
354
- }
355
- //#endregion
356
123
  //#region src/mcp/tools/coordination.ts
357
124
  /**
358
125
  *
@@ -1944,7 +1711,7 @@ function createCoordinationTools(opts) {
1944
1711
  live,
1945
1712
  freeSlots: freeWorkerSlots()
1946
1713
  }))(liveWorkerCount()));
1947
- const resourcePaths = await resolveSpawnResourcePaths(a.profile, opts.spawnResourceRoot);
1714
+ const resourcePaths = await resolveSpawnResourcePaths(a.profile, opts.spawnResourceReader ?? opts.spawnResourceRoot);
1948
1715
  if (!resourcePaths.ok) return {
1949
1716
  error: "invalid-profile",
1950
1717
  reason: `resources.${resourcePaths.at}: ${resourcePaths.reason}`,
@@ -2065,7 +1832,7 @@ function createCoordinationTools(opts) {
2065
1832
  },
2066
1833
  {
2067
1834
  name: "observe_agent",
2068
- description: "Inspect a worker WHILE IT RUNS, not only after it finishes: status, spend so far, and `progress` — how long since it last did anything (`idleMs`), whether that counts as stalled, how many turns it has taken, the last tools/files it touched (`recentActivity`), what its executor CHANGED about the profile you gave it (`derived` — an MCP config it materialized, an extension it had to add), whether a steer can even reach it (`steerable`), and how many steers it has not yet read (`pendingMessages`). Returns the settled output artifact once it exists. Use this BEFORE steer_agent: a steer is only worth sending when the progress says the worker is on the wrong path or has stopped making any.",
1835
+ description: "Inspect a worker WHILE IT RUNS, not only after it finishes: status, spend so far, and `progress` — how long since it last did anything (`idleMs`), whether that counts as stalled, how many turns it has taken, the last tools/files it touched (`recentActivity`), what its executor CHANGED about the profile you gave it (`derived` — an MCP config it materialized, an extension it had to add), whether a steer can even reach it (`steerable`), and how many steers it has not yet read (`pendingMessages`). A worker whose executor has FINISHED but whose settlement you have not yet drained reports `settlementPending` with its terminal kind; its `status` still reads running until await_event delivers it, so call await_event, not observe_agent again. The settled output artifact is returned once drained. Use this BEFORE steer_agent: a steer is only worth sending when the progress says the worker is on the wrong path or has stopped making any.",
2069
1836
  inputSchema: {
2070
1837
  type: "object",
2071
1838
  properties: { workerId: idArg },
@@ -2090,11 +1857,16 @@ function createCoordinationTools(opts) {
2090
1857
  }
2091
1858
  const output = node.outRef ? await opts.blobs.get(node.outRef) : void 0;
2092
1859
  const progress = readProgress(id);
1860
+ const pending = node.settlementPending;
2093
1861
  return {
2094
1862
  ...projectNodeEvidence(node),
2095
1863
  outRef: node.outRef ?? null,
2096
1864
  output: output ?? null,
2097
- progress: progress ?? null
1865
+ progress: progress ?? null,
1866
+ ...pending ? {
1867
+ settlementPending: pending,
1868
+ hint: `this worker has finished (${pending.kind}); its settlement is queued — call await_event to receive it, observing again will not change this`
1869
+ } : {}
2098
1870
  };
2099
1871
  }
2100
1872
  },
@@ -3743,6 +3515,7 @@ function driverAgent(opts) {
3743
3515
  return inbox.deliver(message);
3744
3516
  },
3745
3517
  async act(task, scope) {
3518
+ const ownerReader = opts.spawnResourceReader ?? (opts.spawnResourceRoot === void 0 ? scopeRetainedOwnerResourceReader(scope) : void 0);
3746
3519
  const coord = createCoordinationTools({
3747
3520
  scope,
3748
3521
  blobs: opts.blobs,
@@ -3759,6 +3532,7 @@ function driverAgent(opts) {
3759
3532
  ...opts.preflightSpawn ? { preflightSpawn: opts.preflightSpawn } : {},
3760
3533
  ...opts.resolveSpawnProfile ? { resolveSpawnProfile: opts.resolveSpawnProfile } : {},
3761
3534
  ...opts.spawnResourceRoot ? { spawnResourceRoot: opts.spawnResourceRoot } : {},
3535
+ ...ownerReader ? { spawnResourceReader: ownerReader } : {},
3762
3536
  ...opts.escalateQuestion ? { escalateQuestion: opts.escalateQuestion } : {},
3763
3537
  ...opts.onEvent ? { onEvent: opts.onEvent } : {},
3764
3538
  ...opts.replaySettlements ? { replaySettlements: true } : {},
@@ -4094,4 +3868,4 @@ function safeJson(v) {
4094
3868
  //#endregion
4095
3869
  export { normalizeAnalyzeOnSettle as A, ANALYST_DEFINITION_BOUNDS as C, coordinationVerbNames as D, canonicalFindingEvent as E, watchTrace as F, questionEscalationTargets as M, createEventBus as N, createCoordinationTools as O, defaultToolDetectors as P, watchRunCancellation as S, analystToolGroupNames as T, renderAnytimeTable as _, allOf as a, FileCoordinationLog as b, createProgressTracker as c, progressStop as d, sampleFromSettled as f, plateauLength as g, bestSoFar as h, finalizeBestDelivered as i, parseAuthoredAnalystDefinition as j, downMessageRefusalReasons as k, noProgressFor as l, areaUnderCurve as m, createSteerAcknowledger as n, allWorkersStalled as o, anytimeReport as p, driverAgent as r, anyOf as s, createCancelAcknowledger as t, plateau as u, createFileRunContext as v, DEFAULT_AWAIT_EVENT_TIMEOUT_MS as w, applyRunCancellation as x, createInMemoryRunContext as y };
4096
3870
 
4097
- //# sourceMappingURL=coordination-driver-DbiCH5be.js.map
3871
+ //# sourceMappingURL=coordination-driver-CMprWr0k.js.map