@tangle-network/agent-runtime 0.177.0 → 0.178.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 (62) hide show
  1. package/dist/{activation-XVI_z1g3.js → activation-BVTPfwty.js} +2 -2
  2. package/dist/{activation-XVI_z1g3.js.map → activation-BVTPfwty.js.map} +1 -1
  3. package/dist/agent.d.ts +1 -1
  4. package/dist/agent.js +2 -2
  5. package/dist/{authoring-bXmPNfCI.js → authoring-dQjU4WrH.js} +2 -2
  6. package/dist/{authoring-bXmPNfCI.js.map → authoring-dQjU4WrH.js.map} +1 -1
  7. package/dist/conversation.d.ts +1 -1
  8. package/dist/{coordination-driver-xO1tkxy-.js → coordination-driver-kN2_UQaP.js} +2 -2
  9. package/dist/{coordination-driver-xO1tkxy-.js.map → coordination-driver-kN2_UQaP.js.map} +1 -1
  10. package/dist/durable.d.ts +2 -2
  11. package/dist/durable.js +1 -1
  12. package/dist/{environment-provider-5E82esWE.d.ts → environment-provider-ykohtWSr.d.ts} +2 -2
  13. package/dist/environment-provider.d.ts +1 -1
  14. package/dist/{graph-DwJXa1Ph.js → graph-CseWAx9q.js} +2 -2
  15. package/dist/{graph-DwJXa1Ph.js.map → graph-CseWAx9q.js.map} +1 -1
  16. package/dist/graph.d.ts +3 -3
  17. package/dist/graph.js +3 -3
  18. package/dist/{improvement-cycle-eiSv6aH4.js → improvement-cycle-2QG2XXyK.js} +3 -3
  19. package/dist/{improvement-cycle-eiSv6aH4.js.map → improvement-cycle-2QG2XXyK.js.map} +1 -1
  20. package/dist/{index-C9XTLVP1.d.ts → index-BL5K-qBf.d.ts} +4 -4
  21. package/dist/{index-BnAiQVLD.d.ts → index-CKjkp9Uh.d.ts} +5 -5
  22. package/dist/{index-Bs0uhf-y.d.ts → index-DG48MraH.d.ts} +2 -2
  23. package/dist/index.d.ts +7 -7
  24. package/dist/index.js +7 -7
  25. package/dist/intelligence.d.ts +4 -4
  26. package/dist/intelligence.js +3 -3
  27. package/dist/kernel.d.ts +6 -6
  28. package/dist/kernel.js +8 -8
  29. package/dist/{knowledge-Bmtj_7u7.js → knowledge-Ycq1urlg.js} +3 -3
  30. package/dist/{knowledge-Bmtj_7u7.js.map → knowledge-Ycq1urlg.js.map} +1 -1
  31. package/dist/knowledge.d.ts +1 -1
  32. package/dist/knowledge.js +1 -1
  33. package/dist/{loop-runner-bin-ChS5deJ0.d.ts → loop-runner-bin-Cv8_0WCC.d.ts} +3 -3
  34. package/dist/{loop-runner-bin-GTN5wqCt.js → loop-runner-bin-DkaB5edJ.js} +3 -3
  35. package/dist/{loop-runner-bin-GTN5wqCt.js.map → loop-runner-bin-DkaB5edJ.js.map} +1 -1
  36. package/dist/loop-runner-bin.d.ts +1 -1
  37. package/dist/loop-runner-bin.js +1 -1
  38. package/dist/mcp/bin.js +3 -3
  39. package/dist/mcp/index.d.ts +3 -3
  40. package/dist/mcp/index.js +5 -5
  41. package/dist/{openai-tools-BBj1QGJp.js → openai-tools-Cv1ZVB-e.js} +2 -2
  42. package/dist/{openai-tools-BBj1QGJp.js.map → openai-tools-Cv1ZVB-e.js.map} +1 -1
  43. package/dist/primeintellect/index.d.ts +1 -1
  44. package/dist/{provision-supervisor-zA__ayUX.js → provision-supervisor-B4wOvmpW.js} +3 -3
  45. package/dist/{provision-supervisor-zA__ayUX.js.map → provision-supervisor-B4wOvmpW.js.map} +1 -1
  46. package/dist/{redact-DkRLcSiE.d.ts → redact-CptO2wfX.d.ts} +3 -3
  47. package/dist/{runtime-CJNlF5wM.js → runtime-7W9UYNMN.js} +8 -8
  48. package/dist/{runtime-CJNlF5wM.js.map → runtime-7W9UYNMN.js.map} +1 -1
  49. package/dist/{runtime-B2eZ76kG.d.ts → runtime-BhU1Bt3y.d.ts} +3 -3
  50. package/dist/{stream-agent-turn-ByY8po9W.d.ts → stream-agent-turn-CNyYxEc0.d.ts} +2 -2
  51. package/dist/{structural-rollout-BeAUK7Ta.js → structural-rollout-BSdSJ_Lr.js} +2 -2
  52. package/dist/{structural-rollout-BeAUK7Ta.js.map → structural-rollout-BSdSJ_Lr.js.map} +1 -1
  53. package/dist/{supervise-HsRKOlKY.js → supervise-DMgM9SYN.js} +3 -3
  54. package/dist/{supervise-HsRKOlKY.js.map → supervise-DMgM9SYN.js.map} +1 -1
  55. package/dist/{supervisor-ChLgoYhG.js → supervisor-DyDgxgpl.js} +175 -28
  56. package/dist/{supervisor-ChLgoYhG.js.map → supervisor-DyDgxgpl.js.map} +1 -1
  57. package/dist/testing.d.ts +2 -2
  58. package/dist/testing.js +12 -12
  59. package/dist/tui/index.d.ts +1 -1
  60. package/dist/tui/index.js +1 -1
  61. package/dist/{types-a2ZZUl80.d.ts → types-C6HjIpJ3.d.ts} +15 -3
  62. package/package.json +5 -4
@@ -1,5 +1,5 @@
1
1
  import { at as canonicalCandidateDocument, ct as immutableCandidateValue, dt as verifyCanonicalCandidateDocument, it as canonicalCandidateDigest$1 } from "./prepare-Tip-2ZoZ.js";
2
- import { A as agentImprovementTargetInput, M as agentProfileImprovementStateDigest, c as requireSealedCandidateExperiment, d as verifyAgentImprovementActivation, f as verifyAgentImprovementProposal, k as agentImprovementTargetDigest } from "./improvement-cycle-eiSv6aH4.js";
2
+ import { A as agentImprovementTargetInput, M as agentProfileImprovementStateDigest, c as requireSealedCandidateExperiment, d as verifyAgentImprovementActivation, f as verifyAgentImprovementProposal, k as agentImprovementTargetDigest } from "./improvement-cycle-2QG2XXyK.js";
3
3
  import { agentImprovementActivationResultSchema, agentImprovementActivationSchema, agentProfileImprovementExperimentSchema } from "@tangle-network/agent-interface";
4
4
  //#region src/intelligence/activation.ts
5
5
  /** Create the exact result a product stores in the same transaction as its target write. */
@@ -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-XVI_z1g3.js.map
204
+ //# sourceMappingURL=activation-BVTPfwty.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"activation-XVI_z1g3.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,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,WAAW,+BAA+B,MAAM,QAAQ;CAC9D,MAAM,aAAa,iCAAiC,KAAK;CACzD,MAAM,SAAS,iCACb,uCAAuC,MAAM,MAAM,MAAM,GACzD,qCACF;CACA,8BAA8B,Y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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,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,WAAW,+BAA+B,MAAM,QAAQ;CAC9D,MAAM,aAAa,iCAAiC,KAAK;CACzD,MAAM,SAAS,iCACb,uCAAuC,MAAM,MAAM,MAAM,GACzD,qCACF;CACA,8BAA8B,YAAY,MAAM;CAChD,yBAAyB,UAAU,YAAY,MAAM;CACrD,OAAO;AACT;;AAGA,eAAsB,kCACpB,OACA,SAC2C;CAC3C,M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AAY,SAAS,IAC5E,KAAA;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"}
package/dist/agent.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { E as SandboxClient, at as RuntimeStreamEvent, t as AgentRunSpec, w as OutputAdapter } from "./types-DpdfZoQ3.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 { $p as promptResourceProfileMaterialization, Bp as DefineProfileMaterializationContractOptions, Gp as assertProfileMaterialization, Hp as ProfileMaterializationContract, Ip as AGENT_PROFILE_MATERIALIZATION_AXES, Jp as fullProfileMaterialization, Kp as controlProfileMaterialization, Lp as AgentProfileMaterializationAxis, Qp as promptOnlyProfileMaterialization, Rp as AssertProfileMaterializationOptions, Up as ProfileMaterializationIssue, Vp as KnownAgentProfileMaterializationAxis, Wp as ValidateProfileMaterializationOptions, Xp as promptControlProfileMaterialization, Yp as profileMaterializationAxes, Zp as promptModelProfileMaterialization, em as renderProfileMaterializationIssues, nm as validateProfileMaterialization, qp as defineProfileMaterializationContract, rm as worktreeCliProfileMaterialization, tm as sandboxActProfileMaterialization, zp as CanonicalAgentProfileMaterializationAxis } from "./index-BnAiQVLD.js";
3
+ import { $p as promptResourceProfileMaterialization, Bp as DefineProfileMaterializationContractOptions, Gp as assertProfileMaterialization, Hp as ProfileMaterializationContract, Ip as AGENT_PROFILE_MATERIALIZATION_AXES, Jp as fullProfileMaterialization, Kp as controlProfileMaterialization, Lp as AgentProfileMaterializationAxis, Qp as promptOnlyProfileMaterialization, Rp as AssertProfileMaterializationOptions, Up as ProfileMaterializationIssue, Vp as KnownAgentProfileMaterializationAxis, Wp as ValidateProfileMaterializationOptions, Xp as promptControlProfileMaterialization, Yp as profileMaterializationAxes, Zp as promptModelProfileMaterialization, em as renderProfileMaterializationIssues, nm as validateProfileMaterialization, qp as defineProfileMaterializationContract, rm as worktreeCliProfileMaterialization, tm as sandboxActProfileMaterialization, zp as CanonicalAgentProfileMaterializationAxis } from "./index-CKjkp9Uh.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,6 +1,6 @@
1
1
  import { o as mapSandboxEvent } from "./sandbox-events-BVjstFgb.js";
2
- import { An as profileMaterializationAxes, Bn as worktreeCliProfileMaterialization, Dn as controlProfileMaterialization, En as assertProfileMaterialization, Fn as renderProfileMaterializationIssues, Ft as createSandboxForSpec, Ln as sandboxActProfileMaterialization, Mn as promptModelProfileMaterialization, Nn as promptOnlyProfileMaterialization, On as defineProfileMaterializationContract, Pn as promptResourceProfileMaterialization, Tn as AGENT_PROFILE_MATERIALIZATION_AXES, jn as promptControlProfileMaterialization, kn as fullProfileMaterialization, zn as validateProfileMaterialization } from "./supervisor-ChLgoYhG.js";
3
- import "./runtime-CJNlF5wM.js";
2
+ import { An as profileMaterializationAxes, Bn as worktreeCliProfileMaterialization, Dn as controlProfileMaterialization, En as assertProfileMaterialization, Fn as renderProfileMaterializationIssues, Ft as createSandboxForSpec, Ln as sandboxActProfileMaterialization, Mn as promptModelProfileMaterialization, Nn as promptOnlyProfileMaterialization, On as defineProfileMaterializationContract, Pn as promptResourceProfileMaterialization, Tn as AGENT_PROFILE_MATERIALIZATION_AXES, jn as promptControlProfileMaterialization, kn as fullProfileMaterialization, zn as validateProfileMaterialization } from "./supervisor-DyDgxgpl.js";
3
+ import "./runtime-7W9UYNMN.js";
4
4
  import { createHash } from "node:crypto";
5
5
  import { isAbsolute, join, relative, resolve, sep } from "node:path";
6
6
  import { existsSync, readFileSync, statSync } from "node:fs";
@@ -1,4 +1,4 @@
1
- import { v as supervisorPolicyPrompt } from "./supervise-HsRKOlKY.js";
1
+ import { v as supervisorPolicyPrompt } from "./supervise-DMgM9SYN.js";
2
2
  import { agentProfileSchema } from "@tangle-network/agent-interface";
3
3
  import { computeFindingId, makeFinding } from "@tangle-network/agent-eval";
4
4
  //#region src/runtime/supervise/authoring.ts
@@ -160,4 +160,4 @@ function profileRichnessFinding(richness, opts) {
160
160
  //#endregion
161
161
  export { supervisorInstructions as a, profileRichnessFinding as i, assessAuthoredProfile as n, defaultProfileRichnessThresholds as r, asAuthoredProfile as t };
162
162
 
163
- //# sourceMappingURL=authoring-bXmPNfCI.js.map
163
+ //# sourceMappingURL=authoring-dQjU4WrH.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"authoring-bXmPNfCI.js","names":[],"sources":["../src/runtime/supervise/authoring.ts"],"sourcesContent":["/**\n *\n * The supervisor's intelligence is AUTHORING the agents it spawns — not pressing buttons.\n *\n * Every agent here is three things: instructions (system prompt), tools, and a model — its\n * `AgentProfile`. The supervisor's job is to WRITE those profiles: read the task, decompose it,\n * and for each sub-task author a tailored worker recipe. `supervisorInstructions` is the how-to the\n * supervisor reads; canonical Runtime executors materialize the resulting profile.\n *\n * The skill is the single OPTIMIZABLE surface: edit it → the supervisor designs better agents.\n * That is the self-improvement lever (the prompt/skill lever), not the execution plumbing.\n *\n * @experimental\n */\n\nimport { type AnalystFinding, computeFindingId, makeFinding } from '@tangle-network/agent-eval'\nimport {\n type AgentProfile,\n type AgentProfilePrompt,\n agentProfileSchema,\n} from '@tangle-network/agent-interface'\nimport { supervisorPolicyPrompt } from './prompt-registry'\n\n/** What the supervisor AUTHORS per sub-task: one complete canonical profile whose name and\n * task-specific system prompt are present. Every other `AgentProfile` axis is preserved exactly. */\nexport type AuthoredProfile = AgentProfile & {\n readonly name: string\n readonly prompt: AgentProfilePrompt & { readonly systemPrompt: string }\n}\n\n/** Narrow an untyped `spawn_agent` profile argument to an `AuthoredProfile`, or null if the\n * supervisor failed to author one (empty/placeholder profile — a skill violation worth catching). */\nexport function asAuthoredProfile(raw: unknown): AuthoredProfile | null {\n const parsed = agentProfileSchema.safeParse(raw)\n if (!parsed.success) return null\n const systemPrompt = parsed.data.prompt?.systemPrompt\n if (typeof systemPrompt !== 'string' || systemPrompt.trim().length === 0) return null\n return {\n ...parsed.data,\n name:\n typeof parsed.data.name === 'string' && parsed.data.name.length > 0\n ? parsed.data.name\n : 'worker',\n prompt: { ...parsed.data.prompt, systemPrompt },\n }\n}\n\n/** The supervisor SKILL — the how-to the supervisor reads (its system prompt). THE optimizable\n * surface: editing this changes how the supervisor designs every agent it spawns.\n *\n * The POLICY paragraph is the registry's one `supervisor/policy` entry — the same stance\n * `defaultSupervisorPrompt` carries — so both front doors run the same work-vs-delegate rule;\n * this function ADDS the profile-authoring skill (how to WRITE the workers it spawns), which is\n * additive craft, not a different policy. */\nexport function supervisorInstructions(opts?: { goal?: string }): string {\n return [\n supervisorPolicyPrompt.text,\n '',\n 'Your delegation craft is AUTHORING: a spawned worker is exactly as good as the profile you write.',\n '',\n 'For the task you are given:',\n '1. DECOMPOSE it into the smallest set of sub-tasks a single focused worker can each deliver.',\n '2. For EACH sub-task, AUTHOR a worker by calling spawn_agent with a COMPLETE `profile`:',\n ' • name and description: who this specialist is and why it exists.',\n ' • prompt.systemPrompt: rich instructions for THIS sub-task — exact output, process, evidence, and what \"done\" means.',\n ' • model.default, model.reasoningEffort, and harness: choose the execution system deliberately when the task benefits from it.',\n ' • tools, mcp, resources.skills/files/instructions, hooks, subagents, permissions, and modes: grant or attach every capability the worker needs; omit an axis only when it is intentionally unnecessary.',\n ' • metadata.role=\"driver\" when this child should be a sub-supervisor that may author and drive its own children.',\n ' NEVER spawn a worker with an empty profile. The quality of the worker IS the quality of the profile you write.',\n \"3. await_event (kinds:['settled']) to collect each worker. Its result says valid:true only if the deployable check passed.\",\n '4. If a worker did NOT deliver, AUTHOR A NEW profile whose prompt.systemPrompt names the SPECIFIC failure and how to fix it — never just retry the same profile.',\n '5. Stop (reply with no tool call) once the work is delivered.',\n ...(opts?.goal ? ['', `The goal: ${opts.goal}`] : []),\n ].join('\\n')\n}\n\n// ── Profile-richness gate ────────────────────────────────────────────────────\n//\n// The supervisor's product is the worker PROFILE it authors. The failure mode the existing\n// gates miss: `asAuthoredProfile` / `local-harness` only reject a FULLY EMPTY system prompt —\n// a two-sentence stub passes. `assessAuthoredProfile` OBSERVES the authored artifact (it reads\n// no judge verdict, so it steers cleanly past `assertTraceDerivedFindings`) and flags THIN:\n// a short/few-line system prompt, OR no tools, OR no skills, OR no MCP when the task needs one.\n// It emits a real `AnalystFinding` so it rides the SAME coordination bus the driver pulls via\n// `await_event({kinds:['finding']})` — the supervisor can self-correct and re-author richer.\n\n/** Thresholds below which a system prompt is treated as a thin stub. Tunable per call. */\nexport interface ProfileRichnessThresholds {\n /** A prompt shorter than this many characters is thin (default 600). */\n readonly minSystemPromptChars: number\n /** A prompt with fewer than this many non-blank lines is thin (default 6). */\n readonly minSystemPromptLines: number\n}\n\n/** Default thresholds for `ProfileRichnessThresholds` — 600 chars / 6 lines minimum system prompt. */\nexport const defaultProfileRichnessThresholds: ProfileRichnessThresholds = {\n minSystemPromptChars: 600,\n minSystemPromptLines: 6,\n}\n\n/** Per-field verdict on one authored profile — the raw material the bench renders + scores. */\nexport interface ProfileRichness {\n readonly name: string\n /** The resolved system prompt (canonical `prompt.systemPrompt`, the sandbox `prompt.system`\n * convention, or a bare-string prompt — whichever the author used). */\n readonly systemPrompt: string\n readonly systemPromptChars: number\n readonly systemPromptLines: number\n readonly sentenceCount: number\n readonly hasDescription: boolean\n readonly hasTools: boolean\n readonly hasSkills: boolean\n readonly hasMcp: boolean\n readonly hasSubagents: boolean\n /** 0..1 — fraction of richness signals present (prompt-depth + the four levers). */\n readonly richness: number\n /** True when the supervisor authored a stub instead of a real profile. */\n readonly thin: boolean\n /** The specific reasons it is thin (empty when rich) — used in the finding's action. */\n readonly reasons: string[]\n}\n\n/** Read the system prompt from any authored shape: canonical `prompt.systemPrompt`, the sandbox\n * `prompt.system` convention, or a bare-string `prompt`. */\nfunction resolveSystemPrompt(profile: AgentProfile): string {\n const pr = (profile as { prompt?: unknown }).prompt\n if (typeof pr === 'string') return pr\n if (pr && typeof pr === 'object') {\n const o = pr as { systemPrompt?: unknown; system?: unknown }\n if (typeof o.systemPrompt === 'string') return o.systemPrompt\n if (typeof o.system === 'string') return o.system\n }\n return ''\n}\n\n/** OBSERVE one authored `AgentProfile` and score its richness (no judge verdict is read). The task\n * context (`needsMcp`) lets a domain say \"this work needs a data/tool MCP\" so a missing MCP counts. */\nexport function assessAuthoredProfile(\n profile: AgentProfile,\n opts?: { needsMcp?: boolean; thresholds?: Partial<ProfileRichnessThresholds> },\n): ProfileRichness {\n const th = { ...defaultProfileRichnessThresholds, ...(opts?.thresholds ?? {}) }\n const systemPrompt = resolveSystemPrompt(profile)\n const trimmed = systemPrompt.trim()\n const systemPromptChars = trimmed.length\n const systemPromptLines = trimmed\n ? trimmed.split('\\n').filter((l) => l.trim().length > 0).length\n : 0\n const sentenceCount = trimmed\n ? (trimmed.match(/[.!?](\\s|$)/g) ?? []).length || (trimmed ? 1 : 0)\n : 0\n const hasDescription =\n typeof profile.description === 'string' && profile.description.trim().length > 0\n const tools = (profile as { tools?: Record<string, unknown> }).tools\n const hasTools = !!tools && Object.keys(tools).length > 0\n const skills = (profile.resources as { skills?: unknown[] } | undefined)?.skills\n const hasSkills = Array.isArray(skills) && skills.length > 0\n const mcp = (profile as { mcp?: Record<string, unknown> }).mcp\n const hasMcp = !!mcp && Object.keys(mcp).length > 0\n const subagents = (profile as { subagents?: Record<string, unknown> }).subagents\n const hasSubagents = !!subagents && Object.keys(subagents).length > 0\n\n const reasons: string[] = []\n const promptThin =\n systemPromptChars < th.minSystemPromptChars || systemPromptLines < th.minSystemPromptLines\n if (promptThin)\n reasons.push(\n `system prompt is thin (${systemPromptChars} chars, ${systemPromptLines} lines; need ≥${th.minSystemPromptChars} chars and ≥${th.minSystemPromptLines} lines)`,\n )\n if (!hasTools)\n reasons.push('no tools granted (a worker can only act through the tools you grant it)')\n if (!hasSkills) reasons.push('no skills attached (no reusable how-to notes injected)')\n if (opts?.needsMcp && !hasMcp) reasons.push('no MCP server, but the task needs data/tool access')\n\n // Richness = fraction of signals present. Prompt-depth is one signal; the four levers are the rest.\n const signals = [!promptThin, hasTools, hasSkills, hasDescription, opts?.needsMcp ? hasMcp : true]\n const richness = signals.filter(Boolean).length / signals.length\n // THIN ⟺ the prompt is a stub OR the worker has no levers at all (no tools AND no skills AND no mcp).\n const thin = promptThin || (!hasTools && !hasSkills && !hasMcp)\n\n return {\n name: profile.name ?? 'worker',\n systemPrompt,\n systemPromptChars,\n systemPromptLines,\n sentenceCount,\n hasDescription,\n hasTools,\n hasSkills,\n hasMcp,\n hasSubagents,\n richness,\n thin,\n reasons,\n }\n}\n\n/** Turn a {@link ProfileRichness} verdict into a bus-routable `AnalystFinding` (area `profile-quality`).\n * Severity scales with thinness; the recommended action names the MISSING lever so the supervisor can\n * re-author. `subject` = the worker name so per-worker findings diff cleanly across re-authors. */\nexport function profileRichnessFinding(\n richness: ProfileRichness,\n opts?: { analystId?: string; runId?: string },\n): AnalystFinding {\n const analyst_id = opts?.analystId ?? 'profile-richness'\n const subject = richness.name\n const claim = richness.thin\n ? `Worker \"${richness.name}\" was authored as a THIN profile: ${richness.reasons.join('; ')}.`\n : `Worker \"${richness.name}\" was authored as a rich profile (richness ${(richness.richness * 100).toFixed(0)}%).`\n const severity: AnalystFinding['severity'] = richness.thin\n ? richness.richness < 0.25\n ? 'high'\n : 'medium'\n : 'info'\n return makeFinding({\n analyst_id,\n severity,\n area: 'profile-quality',\n claim,\n subject,\n confidence: 0.9,\n evidence_refs: [\n {\n kind: 'metric',\n uri: `profile:${subject}`,\n excerpt: `chars=${richness.systemPromptChars} lines=${richness.systemPromptLines} tools=${richness.hasTools} skills=${richness.hasSkills} mcp=${richness.hasMcp} richness=${richness.richness.toFixed(2)}`,\n },\n ],\n ...(richness.thin\n ? { recommended_action: `Re-author \"${richness.name}\" with: ${richness.reasons.join('; ')}.` }\n : {}),\n id_basis: computeFindingId({\n analyst_id,\n area: 'profile-quality',\n subject,\n claim: `richness:${richness.thin ? 'thin' : 'rich'}`,\n }),\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB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ACF;AACF;;;;AAKA,SAAgB,uBACd,UACA,MACgB;CAChB,MAAM,aAAa,MAAM,aAAa;CACtC,MAAM,UAAU,SAAS;CACzB,MAAM,QAAQ,SAAS,OACnB,WAAW,SAAS,KAAK,oCAAoC,SAAS,QAAQ,KAAK,IAAI,EAAE,KACzF,WAAW,SAAS,KAAK,8CAA8C,SAAS,WAAW,IAAA,CAAK,QAAQ,CAAC,EAAE;CAM/G,OAAO,YAAY;EACjB;EACA,UAP2C,SAAS,OAClD,SAAS,WAAW,MAClB,SACA,WACF;EAIF,MAAM;EACN;EACA;EACA,YAAY;EACZ,eAAe,CACb;GACE,MAAM;GACN,KAAK,WAAW;GAChB,SAAS,SAAS,SAAS,kBAAkB,SAAS,SAAS,kBAAkB,SAAS,SAAS,SAAS,UAAU,SAAS,UAAU,OAAO,SAAS,OAAO,YAAY,SAAS,SAAS,QAAQ,CAAC;EACzM,CACF;EACA,GAAI,SAAS,OACT,EAAE,oBAAoB,cAAc,SAAS,KAAK,UAAU,SAAS,QAAQ,KAAK,IAAI,EAAE,GAAG,IAC3F,CAAC;EACL,UAAU,iBAAiB;GACzB;GACA,MAAM;GACN;GACA,OAAO,YAAY,SAAS,OAAO,SAAS;EAC9C,CAAC;CACH,CAAC;AACH"}
1
+ {"version":3,"file":"authoring-dQjU4WrH.js","names":[],"sources":["../src/runtime/supervise/authoring.ts"],"sourcesContent":["/**\n *\n * The supervisor's intelligence is AUTHORING the agents it spawns — not pressing buttons.\n *\n * Every agent here is three things: instructions (system prompt), tools, and a model — its\n * `AgentProfile`. The supervisor's job is to WRITE those profiles: read the task, decompose it,\n * and for each sub-task author a tailored worker recipe. `supervisorInstructions` is the how-to the\n * supervisor reads; canonical Runtime executors materialize the resulting profile.\n *\n * The skill is the single OPTIMIZABLE surface: edit it → the supervisor designs better agents.\n * That is the self-improvement lever (the prompt/skill lever), not the execution plumbing.\n *\n * @experimental\n */\n\nimport { type AnalystFinding, computeFindingId, makeFinding } from '@tangle-network/agent-eval'\nimport {\n type AgentProfile,\n type AgentProfilePrompt,\n agentProfileSchema,\n} from '@tangle-network/agent-interface'\nimport { supervisorPolicyPrompt } from './prompt-registry'\n\n/** What the supervisor AUTHORS per sub-task: one complete canonical profile whose name and\n * task-specific system prompt are present. Every other `AgentProfile` axis is preserved exactly. */\nexport type AuthoredProfile = AgentProfile & {\n readonly name: string\n readonly prompt: AgentProfilePrompt & { readonly systemPrompt: string }\n}\n\n/** Narrow an untyped `spawn_agent` profile argument to an `AuthoredProfile`, or null if the\n * supervisor failed to author one (empty/placeholder profile — a skill violation worth catching). */\nexport function asAuthoredProfile(raw: unknown): AuthoredProfile | null {\n const parsed = agentProfileSchema.safeParse(raw)\n if (!parsed.success) return null\n const systemPrompt = parsed.data.prompt?.systemPrompt\n if (typeof systemPrompt !== 'string' || systemPrompt.trim().length === 0) return null\n return {\n ...parsed.data,\n name:\n typeof parsed.data.name === 'string' && parsed.data.name.length > 0\n ? parsed.data.name\n : 'worker',\n prompt: { ...parsed.data.prompt, systemPrompt },\n }\n}\n\n/** The supervisor SKILL — the how-to the supervisor reads (its system prompt). THE optimizable\n * surface: editing this changes how the supervisor designs every agent it spawns.\n *\n * The POLICY paragraph is the registry's one `supervisor/policy` entry — the same stance\n * `defaultSupervisorPrompt` carries — so both front doors run the same work-vs-delegate rule;\n * this function ADDS the profile-authoring skill (how to WRITE the workers it spawns), which is\n * additive craft, not a different policy. */\nexport function supervisorInstructions(opts?: { goal?: string }): string {\n return [\n supervisorPolicyPrompt.text,\n '',\n 'Your delegation craft is AUTHORING: a spawned worker is exactly as good as the profile you write.',\n '',\n 'For the task you are given:',\n '1. DECOMPOSE it into the smallest set of sub-tasks a single focused worker can each deliver.',\n '2. For EACH sub-task, AUTHOR a worker by calling spawn_agent with a COMPLETE `profile`:',\n ' • name and description: who this specialist is and why it exists.',\n ' • prompt.systemPrompt: rich instructions for THIS sub-task — exact output, process, evidence, and what \"done\" means.',\n ' • model.default, model.reasoningEffort, and harness: choose the execution system deliberately when the task benefits from it.',\n ' • tools, mcp, resources.skills/files/instructions, hooks, subagents, permissions, and modes: grant or attach every capability the worker needs; omit an axis only when it is intentionally unnecessary.',\n ' • metadata.role=\"driver\" when this child should be a sub-supervisor that may author and drive its own children.',\n ' NEVER spawn a worker with an empty profile. The quality of the worker IS the quality of the profile you write.',\n \"3. await_event (kinds:['settled']) to collect each worker. Its result says valid:true only if the deployable check passed.\",\n '4. If a worker did NOT deliver, AUTHOR A NEW profile whose prompt.systemPrompt names the SPECIFIC failure and how to fix it — never just retry the same profile.',\n '5. Stop (reply with no tool call) once the work is delivered.',\n ...(opts?.goal ? ['', `The goal: ${opts.goal}`] : []),\n ].join('\\n')\n}\n\n// ── Profile-richness gate ────────────────────────────────────────────────────\n//\n// The supervisor's product is the worker PROFILE it authors. The failure mode the existing\n// gates miss: `asAuthoredProfile` / `local-harness` only reject a FULLY EMPTY system prompt —\n// a two-sentence stub passes. `assessAuthoredProfile` OBSERVES the authored artifact (it reads\n// no judge verdict, so it steers cleanly past `assertTraceDerivedFindings`) and flags THIN:\n// a short/few-line system prompt, OR no tools, OR no skills, OR no MCP when the task needs one.\n// It emits a real `AnalystFinding` so it rides the SAME coordination bus the driver pulls via\n// `await_event({kinds:['finding']})` — the supervisor can self-correct and re-author richer.\n\n/** Thresholds below which a system prompt is treated as a thin stub. Tunable per call. */\nexport interface ProfileRichnessThresholds {\n /** A prompt shorter than this many characters is thin (default 600). */\n readonly minSystemPromptChars: number\n /** A prompt with fewer than this many non-blank lines is thin (default 6). */\n readonly minSystemPromptLines: number\n}\n\n/** Default thresholds for `ProfileRichnessThresholds` — 600 chars / 6 lines minimum system prompt. */\nexport const defaultProfileRichnessThresholds: ProfileRichnessThresholds = {\n minSystemPromptChars: 600,\n minSystemPromptLines: 6,\n}\n\n/** Per-field verdict on one authored profile — the raw material the bench renders + scores. */\nexport interface ProfileRichness {\n readonly name: string\n /** The resolved system prompt (canonical `prompt.systemPrompt`, the sandbox `prompt.system`\n * convention, or a bare-string prompt — whichever the author used). */\n readonly systemPrompt: string\n readonly systemPromptChars: number\n readonly systemPromptLines: number\n readonly sentenceCount: number\n readonly hasDescription: boolean\n readonly hasTools: boolean\n readonly hasSkills: boolean\n readonly hasMcp: boolean\n readonly hasSubagents: boolean\n /** 0..1 — fraction of richness signals present (prompt-depth + the four levers). */\n readonly richness: number\n /** True when the supervisor authored a stub instead of a real profile. */\n readonly thin: boolean\n /** The specific reasons it is thin (empty when rich) — used in the finding's action. */\n readonly reasons: string[]\n}\n\n/** Read the system prompt from any authored shape: canonical `prompt.systemPrompt`, the sandbox\n * `prompt.system` convention, or a bare-string `prompt`. */\nfunction resolveSystemPrompt(profile: AgentProfile): string {\n const pr = (profile as { prompt?: unknown }).prompt\n if (typeof pr === 'string') return pr\n if (pr && typeof pr === 'object') {\n const o = pr as { systemPrompt?: unknown; system?: unknown }\n if (typeof o.systemPrompt === 'string') return o.systemPrompt\n if (typeof o.system === 'string') return o.system\n }\n return ''\n}\n\n/** OBSERVE one authored `AgentProfile` and score its richness (no judge verdict is read). The task\n * context (`needsMcp`) lets a domain say \"this work needs a data/tool MCP\" so a missing MCP counts. */\nexport function assessAuthoredProfile(\n profile: AgentProfile,\n opts?: { needsMcp?: boolean; thresholds?: Partial<ProfileRichnessThresholds> },\n): ProfileRichness {\n const th = { ...defaultProfileRichnessThresholds, ...(opts?.thresholds ?? {}) }\n const systemPrompt = resolveSystemPrompt(profile)\n const trimmed = systemPrompt.trim()\n const systemPromptChars = trimmed.length\n const systemPromptLines = trimmed\n ? trimmed.split('\\n').filter((l) => l.trim().length > 0).length\n : 0\n const sentenceCount = trimmed\n ? (trimmed.match(/[.!?](\\s|$)/g) ?? []).length || (trimmed ? 1 : 0)\n : 0\n const hasDescription =\n typeof profile.description === 'string' && profile.description.trim().length > 0\n const tools = (profile as { tools?: Record<string, unknown> }).tools\n const hasTools = !!tools && Object.keys(tools).length > 0\n const skills = (profile.resources as { skills?: unknown[] } | undefined)?.skills\n const hasSkills = Array.isArray(skills) && skills.length > 0\n const mcp = (profile as { mcp?: Record<string, unknown> }).mcp\n const hasMcp = !!mcp && Object.keys(mcp).length > 0\n const subagents = (profile as { subagents?: Record<string, unknown> }).subagents\n const hasSubagents = !!subagents && Object.keys(subagents).length > 0\n\n const reasons: string[] = []\n const promptThin =\n systemPromptChars < th.minSystemPromptChars || systemPromptLines < th.minSystemPromptLines\n if (promptThin)\n reasons.push(\n `system prompt is thin (${systemPromptChars} chars, ${systemPromptLines} lines; need ≥${th.minSystemPromptChars} chars and ≥${th.minSystemPromptLines} lines)`,\n )\n if (!hasTools)\n reasons.push('no tools granted (a worker can only act through the tools you grant it)')\n if (!hasSkills) reasons.push('no skills attached (no reusable how-to notes injected)')\n if (opts?.needsMcp && !hasMcp) reasons.push('no MCP server, but the task needs data/tool access')\n\n // Richness = fraction of signals present. Prompt-depth is one signal; the four levers are the rest.\n const signals = [!promptThin, hasTools, hasSkills, hasDescription, opts?.needsMcp ? hasMcp : true]\n const richness = signals.filter(Boolean).length / signals.length\n // THIN ⟺ the prompt is a stub OR the worker has no levers at all (no tools AND no skills AND no mcp).\n const thin = promptThin || (!hasTools && !hasSkills && !hasMcp)\n\n return {\n name: profile.name ?? 'worker',\n systemPrompt,\n systemPromptChars,\n systemPromptLines,\n sentenceCount,\n hasDescription,\n hasTools,\n hasSkills,\n hasMcp,\n hasSubagents,\n richness,\n thin,\n reasons,\n }\n}\n\n/** Turn a {@link ProfileRichness} verdict into a bus-routable `AnalystFinding` (area `profile-quality`).\n * Severity scales with thinness; the recommended action names the MISSING lever so the supervisor can\n * re-author. `subject` = the worker name so per-worker findings diff cleanly across re-authors. */\nexport function profileRichnessFinding(\n richness: ProfileRichness,\n opts?: { analystId?: string; runId?: string },\n): AnalystFinding {\n const analyst_id = opts?.analystId ?? 'profile-richness'\n const subject = richness.name\n const claim = richness.thin\n ? `Worker \"${richness.name}\" was authored as a THIN profile: ${richness.reasons.join('; ')}.`\n : `Worker \"${richness.name}\" was authored as a rich profile (richness ${(richness.richness * 100).toFixed(0)}%).`\n const severity: AnalystFinding['severity'] = richness.thin\n ? richness.richness < 0.25\n ? 'high'\n : 'medium'\n : 'info'\n return makeFinding({\n analyst_id,\n severity,\n area: 'profile-quality',\n claim,\n subject,\n confidence: 0.9,\n evidence_refs: [\n {\n kind: 'metric',\n uri: `profile:${subject}`,\n excerpt: `chars=${richness.systemPromptChars} lines=${richness.systemPromptLines} tools=${richness.hasTools} skills=${richness.hasSkills} mcp=${richness.hasMcp} richness=${richness.richness.toFixed(2)}`,\n },\n ],\n ...(richness.thin\n ? { recommended_action: `Re-author \"${richness.name}\" with: ${richness.reasons.join('; ')}.` }\n : {}),\n id_basis: computeFindingId({\n analyst_id,\n area: 'profile-quality',\n subject,\n claim: `richness:${richness.thin ? 'thin' : 'rich'}`,\n }),\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,kBAAkB,KAAsC;CACtE,MAAM,SAAS,mBAAmB,UAAU,GAAG;CAC/C,IAAI,CAAC,OAAO,SAAS,OAAO;CAC5B,MAAM,eAAe,OAAO,KAAK,QAAQ;CACzC,IAAI,OAAO,iBAAiB,YAAY,aAAa,KAAK,CAAC,CAAC,WAAW,GAAG,OAAO;CACjF,OAAO;EACL,GAAG,OAAO;EACV,MACE,OAAO,OAAO,KAAK,SAAS,YAAY,OAAO,KAAK,KAAK,SAAS,IAC9D,OAAO,KAAK,OACZ;EACN,QAAQ;GAAE,GAAG,OAAO,KAAK;GAAQ;EAAa;CAChD;AACF;;;;;;;;AASA,SAAgB,uBAAuB,MAAkC;CACvE,OAAO;EACL,uBAAuB;EACvB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,GAAI,MAAM,OAAO,CAAC,IAAI,aAAa,KAAK,MAAM,IAAI,CAAC;CACrD,CAAC,CAAC,KAAK,IAAI;AACb;;AAqBA,MAAa,mCAA8D;CACzE,sBAAsB;CACtB,sBAAsB;A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AC;EACL,UAAU,iBAAiB;GACzB;GACA,MAAM;GACN;GACA,OAAO,YAAY,SAAS,OAAO,SAAS;EAC9C,CAAC;CACH,CAAC;AACH"}
@@ -1,2 +1,2 @@
1
- import { $ as sleep, A as RunConversationOptions, B as buildForwardHeaders, C as ConversationResult, D as HaltPredicate, E as HaltContext, F as InMemoryConversationJournal, G as CircuitBreakerState, H as readDepth, I as DEFAULT_MAX_DEPTH, J as RetryBackoff, K as CircuitOpenError, L as FORWARD_HEADERS, M as ConversationJournal, N as ConversationJournalEntry, O as HaltReason, P as FileConversationJournal, Q as makePerAttemptSignal, R as ForwardHeaderName, S as ConversationPolicy, T as ConversationTurn, U as BackendCallPolicy, V as isDepthExceeded, W as CircuitBreakerConfig, X as computeBackoff, Y as RetryableErrorPredicate, Z as defaultIsRetryable, _ as createConversationBackend, a as RunPersonaConfig, b as ConversationDriveState, c as runPersonaDispatch, d as D1DatabaseLike, et as createProfileExecutionBackend, f as D1StmtLike, g as defineConversation, h as d1ToSqlAdapter, i as PersonaDriver, j as TurnOrder, k as HaltSignal, l as runConversation, m as SqlConversationJournal, n as turnId, o as RunPersonaConversationOptions, p as SqlAdapter, q as DeadlineExceededError, r as PersonaConversationResult, s as runPersonaConversation, t as slugifySpeaker, u as runConversationStream, v as AuthSource, w as ConversationStreamEvent, x as ConversationParticipant, y as Conversation, z as PropagatedHeaders } from "./index-Bs0uhf-y.js";
1
+ import { $ as sleep, A as RunConversationOptions, B as buildForwardHeaders, C as ConversationResult, D as HaltPredicate, E as HaltContext, F as InMemoryConversationJournal, G as CircuitBreakerState, H as readDepth, I as DEFAULT_MAX_DEPTH, J as RetryBackoff, K as CircuitOpenError, L as FORWARD_HEADERS, M as ConversationJournal, N as ConversationJournalEntry, O as HaltReason, P as FileConversationJournal, Q as makePerAttemptSignal, R as ForwardHeaderName, S as ConversationPolicy, T as ConversationTurn, U as BackendCallPolicy, V as isDepthExceeded, W as CircuitBreakerConfig, X as computeBackoff, Y as RetryableErrorPredicate, Z as defaultIsRetryable, _ as createConversationBackend, a as RunPersonaConfig, b as ConversationDriveState, c as runPersonaDispatch, d as D1DatabaseLike, et as createProfileExecutionBackend, f as D1StmtLike, g as defineConversation, h as d1ToSqlAdapter, i as PersonaDriver, j as TurnOrder, k as HaltSignal, l as runConversation, m as SqlConversationJournal, n as turnId, o as RunPersonaConversationOptions, p as SqlAdapter, q as DeadlineExceededError, r as PersonaConversationResult, s as runPersonaConversation, t as slugifySpeaker, u as runConversationStream, v as AuthSource, w as ConversationStreamEvent, x as ConversationParticipant, y as Conversation, z as PropagatedHeaders } from "./index-DG48MraH.js";
2
2
  export { type AuthSource, type BackendCallPolicy, type CircuitBreakerConfig, CircuitBreakerState, CircuitOpenError, type Conversation, type ConversationDriveState, type ConversationJournal, type ConversationJournalEntry, type ConversationParticipant, type ConversationPolicy, type ConversationResult, type ConversationStreamEvent, type ConversationTurn, type D1DatabaseLike, type D1StmtLike, DEFAULT_MAX_DEPTH, DeadlineExceededError, FORWARD_HEADERS, FileConversationJournal, type ForwardHeaderName, type HaltContext, type HaltPredicate, type HaltReason, type HaltSignal, InMemoryConversationJournal, type PersonaConversationResult, type PersonaDriver, type PropagatedHeaders, type RetryBackoff, type RetryableErrorPredicate, type RunConversationOptions, type RunPersonaConfig, type RunPersonaConversationOptions, type SqlAdapter, SqlConversationJournal, type TurnOrder, buildForwardHeaders, computeBackoff, createConversationBackend, createProfileExecutionBackend, d1ToSqlAdapter, defaultIsRetryable, defineConversation, isDepthExceeded, makePerAttemptSignal, readDepth, runConversation, runConversationStream, runPersonaConversation, runPersonaDispatch, sleep, slugifySpeaker, turnId };
@@ -4,7 +4,7 @@ import { t as detachedFrozen } from "./snapshot-CTAf4uuA.js";
4
4
  import { b as workerTraceAnalysisStore, i as InMemorySpawnJournal, n as FileSpawnJournal, r as InMemoryResultBlobStore, t as FileResultBlobStore, y as parseWorkerToolTraceArtifact } from "./spawn-journal--N8Ten1q.js";
5
5
  import { _ as unmeteredSpend, r as chargedTokens, u as promptCacheTokenClasses } from "./util-D6ZEuBMi.js";
6
6
  import { i as writeAllBytes, n as parseCommittedJsonLines, r as prepareJsonlAppend, t as isNoEntError } from "./jsonl-file-CDfsCI5s.js";
7
- import { At as isLiveNodeStatus, Et as createPeerMailbox, H as freeSlots, Ut as runBrainLoop, at as createExecutorRegistry, c as pickBestDelivered, f as withDriverExecutor, g as meterRuntimeOwnedProviderAttempt, jt as isTerminalNodeStatus, l as runFinalizer, o as bestDelivered, q as assertValidBudget, u as runTree, xt as createInbox } from "./supervisor-ChLgoYhG.js";
7
+ import { At as isLiveNodeStatus, Et as createPeerMailbox, H as freeSlots, Ut as runBrainLoop, at as createExecutorRegistry, c as pickBestDelivered, f as withDriverExecutor, g as meterRuntimeOwnedProviderAttempt, jt as isTerminalNodeStatus, l as runFinalizer, o as bestDelivered, q as assertValidBudget, u as runTree, xt as createInbox } from "./supervisor-DyDgxgpl.js";
8
8
  import { A as writeWorkerCancellation, M as writeWorkerSteerAcknowledgement, 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-Cd_l2XWV.js";
9
9
  import { agentProfileSchema, canonicalCandidateDigest } from "@tangle-network/agent-interface";
10
10
  import { argHash, errorStreakDetector, observeAll, repeatedActionDetector } from "@tangle-network/agent-eval";
@@ -3060,4 +3060,4 @@ function errMessage(e) {
3060
3060
  //#endregion
3061
3061
  export { coordinationVerbNames as C, createEventBus as D, questionEscalationTargets as E, defaultToolDetectors as O, canonicalFindingEvent as S, normalizeAnalyzeOnSettle 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, watchTrace 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, createCoordinationTools as w, DEFAULT_AWAIT_EVENT_TIMEOUT_MS as x, createInMemoryRunContext as y };
3062
3062
 
3063
- //# sourceMappingURL=coordination-driver-xO1tkxy-.js.map
3063
+ //# sourceMappingURL=coordination-driver-kN2_UQaP.js.map