@tangle-network/agent-runtime 0.297.7 → 0.299.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.
- package/dist/{activation-CDoUN2CT.js → activation-D0srpsxN.js} +2 -2
- package/dist/{activation-CDoUN2CT.js.map → activation-D0srpsxN.js.map} +1 -1
- package/dist/{activation-BplOD2nI.d.ts → activation-sYi0Wi1i.d.ts} +3 -3
- package/dist/agent.d.ts +2 -2
- package/dist/agent.js +2 -2
- package/dist/{coordination-driver-CeuM6euv.js → coordination-driver-c2W1hvwL.js} +124 -19
- package/dist/coordination-driver-c2W1hvwL.js.map +1 -0
- package/dist/{delegate-DII77j2f.js → delegate-VSkeG-3S.js} +2 -2
- package/dist/{delegate-DII77j2f.js.map → delegate-VSkeG-3S.js.map} +1 -1
- package/dist/durable.d.ts +2 -2
- package/dist/durable.js +2 -2
- package/dist/{graph-C_krm_xZ.js → graph-DogfdeoC.js} +4 -4
- package/dist/{graph-C_krm_xZ.js.map → graph-DogfdeoC.js.map} +1 -1
- package/dist/{improvement-cycle-WcuRt1tq.js → improvement-cycle--dmMEqKn.js} +3 -3
- package/dist/{improvement-cycle-WcuRt1tq.js.map → improvement-cycle--dmMEqKn.js.map} +1 -1
- package/dist/{index-CK0uaklJ.d.ts → index-Ciie85Mi.d.ts} +52 -6
- package/dist/index.d.ts +6 -6
- package/dist/index.js +7 -7
- package/dist/intelligence.d.ts +3 -3
- package/dist/intelligence.js +4 -4
- package/dist/kernel.d.ts +4 -4
- package/dist/kernel.js +8 -8
- package/dist/{loop-runner-bin-DdKZe6Tr.d.ts → loop-runner-bin-C1H-Ja0s.d.ts} +3 -3
- package/dist/{loop-runner-bin-QFNwSTIP.js → loop-runner-bin-CmedD2zB.js} +3 -3
- package/dist/{loop-runner-bin-QFNwSTIP.js.map → loop-runner-bin-CmedD2zB.js.map} +1 -1
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.d.ts +5 -5
- package/dist/mcp/index.js +4 -4
- package/dist/{openai-tools-CrfETZkV.d.ts → openai-tools-CPqecKak.d.ts} +2 -2
- package/dist/profiles.d.ts +2 -2
- package/dist/{provision-supervisor-B5V2xXrm.js → provision-supervisor-CsVvIDrv.js} +3 -3
- package/dist/{provision-supervisor-B5V2xXrm.js.map → provision-supervisor-CsVvIDrv.js.map} +1 -1
- package/dist/{runtime-DNjgEVSC.js → runtime-dpb0Pk4q.js} +43 -8
- package/dist/{runtime-DNjgEVSC.js.map → runtime-dpb0Pk4q.js.map} +1 -1
- package/dist/{search-method-D2CPPGVX.js → search-method-k_i6IkUT.js} +2 -2
- package/dist/{search-method-D2CPPGVX.js.map → search-method-k_i6IkUT.js.map} +1 -1
- package/dist/{server-ff1ZlYVW.js → server-BWfx2L5h.js} +3 -3
- package/dist/{server-ff1ZlYVW.js.map → server-BWfx2L5h.js.map} +1 -1
- package/dist/{stream-agent-turn-D-JUSWnD.d.ts → stream-agent-turn-ZL_mAEzE.d.ts} +2 -2
- package/dist/{substrate-Bd4FFbim.d.ts → substrate-B8IoIZwD.d.ts} +2 -2
- package/dist/{supervise-CPqRWClX.js → supervise-CFFzLFAC.js} +40 -8
- package/dist/supervise-CFFzLFAC.js.map +1 -0
- package/dist/{supervisor-Kn3lYWds.js → supervisor-CJPvBIMu.js} +139 -19
- package/dist/supervisor-CJPvBIMu.js.map +1 -0
- package/dist/testing.d.ts +2 -2
- package/dist/testing.js +12 -12
- package/dist/tui/index.d.ts +1 -1
- package/dist/tui/index.js +1 -1
- package/dist/{types-CwGpKzG1.d.ts → types-CqzsTCqn.d.ts} +27 -4
- package/package.json +1 -1
- package/dist/coordination-driver-CeuM6euv.js.map +0 -1
- package/dist/supervise-CPqRWClX.js.map +0 -1
- package/dist/supervisor-Kn3lYWds.js.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { A as canonicalCandidateDocument, I as verifyCanonicalCandidateDocument, N as immutableCandidateValue, k as canonicalCandidateDigest$1 } from "./workspace-streams-D5gHJdTb.js";
|
|
2
|
-
import { A as agentImprovementTargetInput, M as agentProfileImprovementStateDigest, c as requireSealedCandidateExperiment, d as verifyAgentImprovementActivation, f as verifyAgentImprovementProposal, k as agentImprovementTargetDigest } from "./improvement-cycle
|
|
2
|
+
import { A as agentImprovementTargetInput, M as agentProfileImprovementStateDigest, c as requireSealedCandidateExperiment, d as verifyAgentImprovementActivation, f as verifyAgentImprovementProposal, k as agentImprovementTargetDigest } from "./improvement-cycle--dmMEqKn.js";
|
|
3
3
|
import { agentImprovementActivationResultSchema, agentImprovementActivationSchema, agentProfileImprovementExperimentSchema } from "@tangle-network/agent-interface";
|
|
4
4
|
//#region src/runtime-usage.ts
|
|
5
5
|
function createRuntimeUsageTotals() {
|
|
@@ -231,4 +231,4 @@ function targetIdentity(target) {
|
|
|
231
231
|
//#endregion
|
|
232
232
|
export { createRuntimeUsageTotals as a, addRuntimeUsage as i, executeAgentImprovementActivation as n, isUsageAmount as o, verifyAgentImprovementActivationResult as r, createAgentImprovementActivationResult as t };
|
|
233
233
|
|
|
234
|
-
//# sourceMappingURL=activation-
|
|
234
|
+
//# sourceMappingURL=activation-D0srpsxN.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"activation-CDoUN2CT.js","names":["canonicalCandidateDigest"],"sources":["../src/runtime-usage.ts","../src/intelligence/activation.ts"],"sourcesContent":["import type { RuntimeStreamEvent } from './types'\n\n/** Observed subtotals, with missing measurements kept separate from measured zeroes. */\nexport interface RuntimeUsageTotals {\n /** Observed input tokens across normalized per-call events. */\n tokensIn: number\n /** Observed output tokens across normalized per-call events. */\n tokensOut: number\n /** Observed dollar subtotal; incomplete when `usdKnown` is false. */\n costUsd: number\n /** Number of observed model calls, including unpriced or incompletely metered calls. */\n llmCalls: number\n /** False when any observed call has incomplete token usage. */\n tokensKnown?: false\n /** False when any observed call lacks complete provider-billed cost. */\n usdKnown?: false\n /** Sum of reported external estimates; never included in `costUsd` or proof of complete cost. */\n estimatedCostUsd?: number\n}\n\nexport function createRuntimeUsageTotals(): RuntimeUsageTotals {\n return { tokensIn: 0, tokensOut: 0, costUsd: 0, llmCalls: 0 }\n}\n\nexport function isUsageAmount(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value) && value >= 0\n}\n\n/** Fold normalized per-call events. Backend adapters own cumulative receipt reconciliation. */\nexport function addRuntimeUsage(\n totals: RuntimeUsageTotals,\n event: Extract<RuntimeStreamEvent, { type: 'llm_call' }>,\n): void {\n totals.llmCalls += 1\n for (const key of ['tokensIn', 'tokensOut', 'costUsd'] as const) {\n const value = event[key]\n if (isUsageAmount(value)) totals[key] += value\n else if (key === 'costUsd') totals.usdKnown = false\n else totals.tokensKnown = false\n }\n if (event.tokensKnown === false) totals.tokensKnown = false\n if (event.usdKnown === false) totals.usdKnown = false\n if (isUsageAmount(event.estimatedCostUsd)) {\n totals.estimatedCostUsd = (totals.estimatedCostUsd ?? 0) + event.estimatedCostUsd\n }\n}\n","import type {\n AgentCandidateBundle,\n AgentCandidateExperiment,\n AgentImprovementActivation,\n AgentImprovementActivationOutcome,\n AgentImprovementActivationResult,\n AgentImprovementActivationTarget,\n AgentImprovementProposal,\n AgentImprovementReview,\n AgentImprovementSurface,\n AgentProfileImprovementChange,\n AgentProfileImprovementExperiment,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport {\n agentImprovementActivationResultSchema,\n agentImprovementActivationSchema,\n agentProfileImprovementExperimentSchema,\n} from '@tangle-network/agent-interface'\n\nimport {\n canonicalCandidateDigest,\n canonicalCandidateDocument,\n immutableCandidateValue,\n verifyCanonicalCandidateDocument,\n} from '../candidate-execution/digest'\nimport {\n requireSealedCandidateExperiment,\n verifyAgentImprovementActivation,\n verifyAgentImprovementProposal,\n} from './improvement-cycle'\nimport {\n agentImprovementTargetDigest,\n agentImprovementTargetInput,\n agentProfileImprovementStateDigest,\n} from './improvement-surfaces'\n\nexport interface CreateAgentImprovementActivationResultOptions {\n completedAt: string\n outcome: AgentImprovementActivationOutcome\n}\n\nexport interface AgentImprovementActivationTargetPlan extends AgentImprovementActivationTarget {\n desiredDigest: Sha256Digest\n /**\n * Exact measured input the product must apply to reach `desiredDigest`.\n * Transition surfaces such as code and knowledge are applied operations, so\n * their resulting state digest is not the digest of this input document.\n */\n desiredInput: unknown\n}\n\nexport type AgentProfileImprovementActivationOperation =\n | {\n kind: 'apply-change'\n changes: AgentProfileImprovementChange\n }\n | {\n /** The product must load its own saved state at `desiredStateDigest`. */\n kind: 'restore-state'\n }\n\nexport interface AgentProfileImprovementActivationTargetPlan\n extends AgentImprovementActivationTarget {\n desiredDigest: Sha256Digest\n desiredInput: AgentProfileImprovementActivationOperation\n}\n\nexport interface SealedCandidateActivationTransitionInput {\n kind: 'sealed-candidate'\n activation: AgentImprovementActivation\n candidateBundle: AgentCandidateBundle\n bundle: AgentCandidateBundle\n targets: [AgentImprovementActivationTargetPlan, ...AgentImprovementActivationTargetPlan[]]\n attemptedAt: string\n expired: boolean\n}\n\n/**\n * A measured profile change without raw profile bytes.\n * The product owns the private state lookup and atomic write.\n */\nexport interface ProfileImprovementActivationTransitionInput {\n kind: 'profile-improvement'\n activation: AgentImprovementActivation\n experiment: AgentProfileImprovementExperiment\n sourceStateDigest: Sha256Digest\n desiredStateDigest: Sha256Digest\n operation: AgentProfileImprovementActivationOperation\n targets: [\n AgentProfileImprovementActivationTargetPlan,\n ...AgentProfileImprovementActivationTargetPlan[],\n ]\n attemptedAt: string\n expired: boolean\n}\n\nexport type AgentImprovementActivationTransitionInput =\n | SealedCandidateActivationTransitionInput\n | ProfileImprovementActivationTransitionInput\n\nexport interface AgentImprovementActivationResultStore {\n load(idempotencyKey: Sha256Digest): Promise<unknown | undefined>\n putIfAbsent(result: AgentImprovementActivationResult): Promise<unknown>\n}\n\n/**\n * Product-owned or Runtime-composed transition.\n *\n * Implementations resolve a stored result for `activation.digest`, compare\n * every target, and make the write durably idempotent. Co-located targets store\n * the all-or-none write with its result. Other targets throw when result\n * storage fails so a retry can reconcile it. Runtime never invokes this write\n * function after authorization expires.\n */\nexport type AgentImprovementActivationTransition = (\n input: AgentImprovementActivationTransitionInput,\n) => Promise<unknown>\n\n/**\n * Target-read-only check for a prior exact write.\n * It may persist recovered result metadata, but must not change an activation target.\n * Return undefined only when no target write can have committed.\n */\nexport type AgentImprovementActivationReconciliation = (\n input: AgentImprovementActivationTransitionInput,\n) => Promise<unknown | undefined>\n\nexport interface ExecuteAgentImprovementActivationInput {\n proposal: AgentImprovementProposal\n review: AgentImprovementReview\n activation: AgentImprovementActivation\n}\n\nexport interface ExecuteAgentImprovementActivationOptions {\n transition: AgentImprovementActivationTransition\n reconcile?: AgentImprovementActivationReconciliation\n now?: () => Date\n}\n\n/** Create the exact result a product stores in the same transaction as its target write. */\nexport function createAgentImprovementActivationResult(\n transition: AgentImprovementActivationTransitionInput,\n options: CreateAgentImprovementActivationResultOptions,\n): AgentImprovementActivationResult {\n const activation = verifyCanonicalCandidateDocument(\n agentImprovementActivationSchema.parse(transition.activation),\n 'agent improvement activation',\n )\n assertTransitionInput(activation, transition)\n const result = agentImprovementActivationResultSchema.parse(\n canonicalCandidateDocument<AgentImprovementActivationResult>({\n kind: 'agent-improvement-activation-result',\n idempotencyKey: activation.digest,\n attemptedAt: transition.attemptedAt,\n completedAt: options.completedAt,\n outcome: options.outcome,\n }).value,\n )\n assertResultAgainstActivation(activation, result)\n assertOutcomeDesiredState(\n activation,\n result,\n new Map(transition.targets.map((target) => [targetIdentity(target), target.desiredDigest])),\n )\n return immutableCandidateValue(result)\n}\n\n/**\n * Recompute one historical activation result against the exact measured proposal and authority.\n * The result records that attempt; it is not a query of the target's current state.\n */\nexport function verifyAgentImprovementActivationResult(input: {\n proposal: unknown\n review: unknown\n activation: unknown\n result: unknown\n}): AgentImprovementActivationResult {\n const proposal = verifyAgentImprovementProposal(input.proposal)\n const activation = verifyAgentImprovementActivation(input)\n const result = verifyCanonicalCandidateDocument(\n agentImprovementActivationResultSchema.parse(input.result),\n 'agent improvement activation result',\n )\n assertResultAgainstActivation(activation, result)\n assertResultDesiredState(proposal, activation, result)\n return result\n}\n\n/** Validate and execute one product-owned activation transition. */\nexport async function executeAgentImprovementActivation(\n input: ExecuteAgentImprovementActivationInput,\n options: ExecuteAgentImprovementActivationOptions,\n): Promise<AgentImprovementActivationResult> {\n const proposal = verifyAgentImprovementProposal(input.proposal)\n const activation = verifyAgentImprovementActivation(input)\n const observedAt = (options.now ?? (() => new Date()))().toISOString()\n const attemptedAt =\n Date.parse(observedAt) < Date.parse(activation.authorizedAt)\n ? activation.authorizedAt\n : observedAt\n const expired = Date.parse(attemptedAt) >= Date.parse(activation.expiresAt)\n const transition = immutableCandidateValue<AgentImprovementActivationTransitionInput>(\n proposal.evaluation.kind === 'agent-improvement-measured-comparison'\n ? sealedCandidateTransition(proposal.evaluation.experiment, activation, attemptedAt, expired)\n : profileImprovementTransition(\n proposal.evaluation.experiment,\n activation,\n attemptedAt,\n expired,\n ),\n )\n\n if (transition.expired) {\n if (!options.reconcile) {\n return uncertainActivationResult(transition, 'RECONCILIATION_UNAVAILABLE')\n }\n let reconciled: unknown\n try {\n reconciled = await options.reconcile(transition)\n } catch {\n return uncertainActivationResult(transition, 'RECONCILIATION_THROW')\n }\n if (reconciled === undefined) {\n return createAgentImprovementActivationResult(transition, {\n completedAt: transition.attemptedAt,\n outcome: { status: 'expired' },\n })\n }\n try {\n return verifyAgentImprovementActivationResult({ ...input, result: reconciled })\n } catch {\n return uncertainActivationResult(transition, 'INVALID_RECONCILIATION')\n }\n }\n\n let rawResult: unknown\n try {\n rawResult = await options.transition(transition)\n } catch {\n return uncertainActivationResult(transition, 'TRANSITION_THROW')\n }\n try {\n return verifyAgentImprovementActivationResult({ ...input, result: rawResult })\n } catch {\n return uncertainActivationResult(transition, 'INVALID_RESULT')\n }\n}\n\nfunction sealedCandidateTransition(\n experiment: AgentCandidateExperiment,\n activation: AgentImprovementActivation,\n attemptedAt: string,\n expired: boolean,\n): SealedCandidateActivationTransitionInput {\n const targetArm = activation.intent === 'activate-candidate' ? 'candidate' : 'baseline'\n return {\n kind: 'sealed-candidate',\n activation,\n candidateBundle: experiment.candidate,\n bundle: experiment[targetArm],\n targets: activation.targets.map((target) => ({\n ...target,\n desiredDigest: agentImprovementTargetDigest(experiment, targetArm, target.surface),\n desiredInput: agentImprovementTargetInput(experiment[targetArm], target.surface),\n })) as SealedCandidateActivationTransitionInput['targets'],\n attemptedAt,\n expired,\n }\n}\n\nfunction profileImprovementTransition(\n experiment: AgentProfileImprovementExperiment,\n activation: AgentImprovementActivation,\n attemptedAt: string,\n expired: boolean,\n): ProfileImprovementActivationTransitionInput {\n const sourceArm = activation.intent === 'activate-candidate' ? 'baseline' : 'candidate'\n const targetArm = activation.intent === 'activate-candidate' ? 'candidate' : 'baseline'\n const operation = profileImprovementOperation(experiment, activation.intent)\n return {\n kind: 'profile-improvement',\n activation,\n experiment,\n sourceStateDigest: agentProfileImprovementStateDigest(experiment, sourceArm),\n desiredStateDigest: agentProfileImprovementStateDigest(experiment, targetArm),\n operation,\n targets: activation.targets.map((target) => ({\n ...target,\n desiredDigest: agentProfileImprovementStateDigest(experiment, targetArm),\n desiredInput: operation,\n })) as ProfileImprovementActivationTransitionInput['targets'],\n attemptedAt,\n expired,\n }\n}\n\nfunction profileImprovementOperation(\n experiment: AgentProfileImprovementExperiment,\n intent: AgentImprovementActivation['intent'],\n): AgentProfileImprovementActivationOperation {\n return intent === 'activate-candidate'\n ? { kind: 'apply-change', changes: experiment.change }\n : { kind: 'restore-state' }\n}\n\nfunction uncertainActivationResult(\n transition: AgentImprovementActivationTransitionInput,\n code: string,\n): AgentImprovementActivationResult {\n return createAgentImprovementActivationResult(transition, {\n completedAt: transition.attemptedAt,\n outcome: {\n status: 'indeterminate',\n code,\n message: 'The product transition did not return a trustworthy commit result.',\n },\n })\n}\n\nfunction assertTransitionInput(\n activation: AgentImprovementActivation,\n transition: AgentImprovementActivationTransitionInput,\n): void {\n if (transition.kind === 'sealed-candidate') {\n assertSealedCandidateTransitionInput(activation, transition)\n return\n }\n assertProfileImprovementTransitionInput(activation, transition)\n}\n\nfunction assertSealedCandidateTransitionInput(\n activation: AgentImprovementActivation,\n transition: SealedCandidateActivationTransitionInput,\n): void {\n assertAuthorizedTransitionTargets(activation, transition.targets)\n const desiredInputsMatch = transition.targets.every(\n (target) =>\n canonicalCandidateDigest(target.desiredInput) ===\n canonicalCandidateDigest(agentImprovementTargetInput(transition.bundle, target.surface)),\n )\n if (\n transition.expired !== Date.parse(transition.attemptedAt) >= Date.parse(activation.expiresAt) ||\n transition.candidateBundle.digest !== activation.candidateDigest ||\n !desiredInputsMatch ||\n (activation.intent === 'activate-candidate' &&\n transition.bundle.digest !== transition.candidateBundle.digest)\n ) {\n throw new Error('activation transition does not match its authorization')\n }\n}\n\nfunction assertProfileImprovementTransitionInput(\n activation: AgentImprovementActivation,\n transition: ProfileImprovementActivationTransitionInput,\n): void {\n assertAuthorizedTransitionTargets(activation, transition.targets)\n const targetsAgentProfile = activation.targets.some(\n (target) => target.surface === 'agent-profile',\n )\n const experiment = agentProfileImprovementExperimentSchema.parse(transition.experiment)\n const sourceArm = activation.intent === 'activate-candidate' ? 'baseline' : 'candidate'\n const targetArm = activation.intent === 'activate-candidate' ? 'candidate' : 'baseline'\n const sourceStateDigest = agentProfileImprovementStateDigest(experiment, sourceArm)\n const desiredStateDigest = agentProfileImprovementStateDigest(experiment, targetArm)\n const operation = profileImprovementOperation(experiment, activation.intent)\n const targetsMatch = transition.targets.every(\n (target) =>\n target.expectedBaseDigest === sourceStateDigest &&\n target.desiredDigest === desiredStateDigest &&\n canonicalCandidateDigest(target.desiredInput) === canonicalCandidateDigest(operation),\n )\n if (\n transition.expired !== Date.parse(transition.attemptedAt) >= Date.parse(activation.expiresAt) ||\n experiment.digest !== activation.experimentDigest ||\n experiment.candidate.stateDigest !== activation.candidateDigest ||\n (targetsAgentProfile &&\n (activation.executionRef === undefined ||\n canonicalCandidateDigest(activation.executionRef) !==\n canonicalCandidateDigest(experiment.executionRef))) ||\n transition.sourceStateDigest !== sourceStateDigest ||\n transition.desiredStateDigest !== desiredStateDigest ||\n canonicalCandidateDigest(transition.operation) !== canonicalCandidateDigest(operation) ||\n !targetsMatch\n ) {\n throw new Error('activation transition does not match its authorization')\n }\n}\n\nfunction assertAuthorizedTransitionTargets(\n activation: AgentImprovementActivation,\n targets: readonly AgentImprovementActivationTargetPlan[],\n): void {\n const authorized = targetMap(activation.targets)\n const planned = targetMap(targets)\n if (\n authorized.size !== planned.size ||\n [...authorized.entries()].some(\n ([identity, target]) =>\n planned.get(identity)?.expectedBaseDigest !== target.expectedBaseDigest,\n )\n ) {\n throw new Error('activation transition does not match its authorization')\n }\n}\n\nfunction assertResultAgainstActivation(\n activation: AgentImprovementActivation,\n result: AgentImprovementActivationResult,\n): void {\n const attemptedAt = Date.parse(result.attemptedAt)\n const completedAt = Date.parse(result.completedAt)\n const expiresAt = Date.parse(activation.expiresAt)\n if (\n result.idempotencyKey !== activation.digest ||\n attemptedAt < Date.parse(activation.authorizedAt) ||\n completedAt < attemptedAt\n ) {\n throw new Error('activation result does not bind its authorization')\n }\n const expired = attemptedAt >= expiresAt\n if (\n (result.outcome.status === 'expired' && !expired) ||\n (expired && !['expired', 'indeterminate', 'already-applied'].includes(result.outcome.status))\n ) {\n throw new Error('activation result does not honor its authorization expiry')\n }\n if (!('targets' in result.outcome)) return\n const authorized = targetMap(activation.targets)\n const observed = new Set(result.outcome.targets.map(targetIdentity))\n if (\n authorized.size !== observed.size ||\n [...authorized.keys()].some((identity) => !observed.has(identity))\n ) {\n throw new Error('activation result must cover every authorized target exactly once')\n }\n if (\n result.outcome.status === 'applied' &&\n result.outcome.targets.some(\n (target) =>\n target.beforeDigest !== authorized.get(targetIdentity(target))?.expectedBaseDigest,\n )\n ) {\n throw new Error('applied activation did not start from its authorized base state')\n }\n}\n\nfunction assertResultDesiredState(\n proposal: AgentImprovementProposal,\n activation: AgentImprovementActivation,\n result: AgentImprovementActivationResult,\n): void {\n if (!('targets' in result.outcome)) return\n const targetArm = activation.intent === 'activate-candidate' ? 'candidate' : 'baseline'\n const desiredStateDigest =\n proposal.evaluation.kind === 'agent-profile-improvement-measured-comparison'\n ? agentProfileImprovementStateDigest(proposal.evaluation.experiment, targetArm)\n : undefined\n const desired = new Map(\n activation.targets.map((target) => [\n targetIdentity(target),\n desiredStateDigest ??\n agentImprovementTargetDigest(\n requireSealedCandidateExperiment(proposal),\n targetArm,\n target.surface,\n ),\n ]),\n )\n assertOutcomeDesiredState(activation, result, desired)\n}\n\nfunction assertOutcomeDesiredState(\n activation: AgentImprovementActivation,\n result: AgentImprovementActivationResult,\n desired: ReadonlyMap<string, Sha256Digest>,\n): void {\n if (!('targets' in result.outcome)) return\n if (result.outcome.status === 'applied') {\n if (\n result.outcome.targets.some(\n (target) => target.afterDigest !== desired.get(targetIdentity(target)),\n )\n ) {\n throw new Error('applied activation does not match the requested bundle')\n }\n return\n }\n const allDesired = result.outcome.targets.every(\n (target) => target.currentDigest === desired.get(targetIdentity(target)),\n )\n if (result.outcome.status === 'already-applied') {\n if (!allDesired) throw new Error('already-applied activation is not at the requested state')\n return\n }\n const authorized = targetMap(activation.targets)\n const hasStaleTarget = result.outcome.targets.some(\n (target) => target.currentDigest !== authorized.get(targetIdentity(target))?.expectedBaseDigest,\n )\n if (allDesired || !hasStaleTarget) {\n throw new Error('activation conflict does not identify stale target state')\n }\n}\n\nfunction targetMap<T extends { surface: AgentImprovementSurface; identity: string }>(\n targets: readonly T[],\n): Map<string, T> {\n return new Map(targets.map((target) => [targetIdentity(target), target]))\n}\n\nfunction targetIdentity(target: { surface: AgentImprovementSurface; identity: string }): string {\n return `${target.surface}\\u0000${target.identity}`\n}\n"],"mappings":";;;;AAoBA,SAAgB,2BAA+C;CAC7D,OAAO;EAAE,UAAU;EAAG,WAAW;EAAG,SAAS;EAAG,UAAU;CAAE;AA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,SAAS,WAAW,YAAY,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"}
|
|
1
|
+
{"version":3,"file":"activation-D0srpsxN.js","names":["canonicalCandidateDigest"],"sources":["../src/runtime-usage.ts","../src/intelligence/activation.ts"],"sourcesContent":["import type { RuntimeStreamEvent } from './types'\n\n/** Observed subtotals, with missing measurements kept separate from measured zeroes. */\nexport interface RuntimeUsageTotals {\n /** Observed input tokens across normalized per-call events. */\n tokensIn: number\n /** Observed output tokens across normalized per-call events. */\n tokensOut: number\n /** Observed dollar subtotal; incomplete when `usdKnown` is false. */\n costUsd: number\n /** Number of observed model calls, including unpriced or incompletely metered calls. */\n llmCalls: number\n /** False when any observed call has incomplete token usage. */\n tokensKnown?: false\n /** False when any observed call lacks complete provider-billed cost. */\n usdKnown?: false\n /** Sum of reported external estimates; never included in `costUsd` or proof of complete cost. */\n estimatedCostUsd?: number\n}\n\nexport function createRuntimeUsageTotals(): RuntimeUsageTotals {\n return { tokensIn: 0, tokensOut: 0, costUsd: 0, llmCalls: 0 }\n}\n\nexport function isUsageAmount(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value) && value >= 0\n}\n\n/** Fold normalized per-call events. Backend adapters own cumulative receipt reconciliation. */\nexport function addRuntimeUsage(\n totals: RuntimeUsageTotals,\n event: Extract<RuntimeStreamEvent, { type: 'llm_call' }>,\n): void {\n totals.llmCalls += 1\n for (const key of ['tokensIn', 'tokensOut', 'costUsd'] as const) {\n const value = event[key]\n if (isUsageAmount(value)) totals[key] += value\n else if (key === 'costUsd') totals.usdKnown = false\n else totals.tokensKnown = false\n }\n if (event.tokensKnown === false) totals.tokensKnown = false\n if (event.usdKnown === false) totals.usdKnown = false\n if (isUsageAmount(event.estimatedCostUsd)) {\n totals.estimatedCostUsd = (totals.estimatedCostUsd ?? 0) + event.estimatedCostUsd\n }\n}\n","import type {\n AgentCandidateBundle,\n AgentCandidateExperiment,\n AgentImprovementActivation,\n AgentImprovementActivationOutcome,\n AgentImprovementActivationResult,\n AgentImprovementActivationTarget,\n AgentImprovementProposal,\n AgentImprovementReview,\n AgentImprovementSurface,\n AgentProfileImprovementChange,\n AgentProfileImprovementExperiment,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport {\n agentImprovementActivationResultSchema,\n agentImprovementActivationSchema,\n agentProfileImprovementExperimentSchema,\n} from '@tangle-network/agent-interface'\n\nimport {\n canonicalCandidateDigest,\n canonicalCandidateDocument,\n immutableCandidateValue,\n verifyCanonicalCandidateDocument,\n} from '../candidate-execution/digest'\nimport {\n requireSealedCandidateExperiment,\n verifyAgentImprovementActivation,\n verifyAgentImprovementProposal,\n} from './improvement-cycle'\nimport {\n agentImprovementTargetDigest,\n agentImprovementTargetInput,\n agentProfileImprovementStateDigest,\n} from './improvement-surfaces'\n\nexport interface CreateAgentImprovementActivationResultOptions {\n completedAt: string\n outcome: AgentImprovementActivationOutcome\n}\n\nexport interface AgentImprovementActivationTargetPlan extends AgentImprovementActivationTarget {\n desiredDigest: Sha256Digest\n /**\n * Exact measured input the product must apply to reach `desiredDigest`.\n * Transition surfaces such as code and knowledge are applied operations, so\n * their resulting state digest is not the digest of this input document.\n */\n desiredInput: unknown\n}\n\nexport type AgentProfileImprovementActivationOperation =\n | {\n kind: 'apply-change'\n changes: AgentProfileImprovementChange\n }\n | {\n /** The product must load its own saved state at `desiredStateDigest`. */\n kind: 'restore-state'\n }\n\nexport interface AgentProfileImprovementActivationTargetPlan\n extends AgentImprovementActivationTarget {\n desiredDigest: Sha256Digest\n desiredInput: AgentProfileImprovementActivationOperation\n}\n\nexport interface SealedCandidateActivationTransitionInput {\n kind: 'sealed-candidate'\n activation: AgentImprovementActivation\n candidateBundle: AgentCandidateBundle\n bundle: AgentCandidateBundle\n targets: [AgentImprovementActivationTargetPlan, ...AgentImprovementActivationTargetPlan[]]\n attemptedAt: string\n expired: boolean\n}\n\n/**\n * A measured profile change without raw profile bytes.\n * The product owns the private state lookup and atomic write.\n */\nexport interface ProfileImprovementActivationTransitionInput {\n kind: 'profile-improvement'\n activation: AgentImprovementActivation\n experiment: AgentProfileImprovementExperiment\n sourceStateDigest: Sha256Digest\n desiredStateDigest: Sha256Digest\n operation: AgentProfileImprovementActivationOperation\n targets: [\n AgentProfileImprovementActivationTargetPlan,\n ...AgentProfileImprovementActivationTargetPlan[],\n ]\n attemptedAt: string\n expired: boolean\n}\n\nexport type AgentImprovementActivationTransitionInput =\n | SealedCandidateActivationTransitionInput\n | ProfileImprovementActivationTransitionInput\n\nexport interface AgentImprovementActivationResultStore {\n load(idempotencyKey: Sha256Digest): Promise<unknown | undefined>\n putIfAbsent(result: AgentImprovementActivationResult): Promise<unknown>\n}\n\n/**\n * Product-owned or Runtime-composed transition.\n *\n * Implementations resolve a stored result for `activation.digest`, compare\n * every target, and make the write durably idempotent. Co-located targets store\n * the all-or-none write with its result. Other targets throw when result\n * storage fails so a retry can reconcile it. Runtime never invokes this write\n * function after authorization expires.\n */\nexport type AgentImprovementActivationTransition = (\n input: AgentImprovementActivationTransitionInput,\n) => Promise<unknown>\n\n/**\n * Target-read-only check for a prior exact write.\n * It may persist recovered result metadata, but must not change an activation target.\n * Return undefined only when no target write can have committed.\n */\nexport type AgentImprovementActivationReconciliation = (\n input: AgentImprovementActivationTransitionInput,\n) => Promise<unknown | undefined>\n\nexport interface ExecuteAgentImprovementActivationInput {\n proposal: AgentImprovementProposal\n review: AgentImprovementReview\n activation: AgentImprovementActivation\n}\n\nexport interface ExecuteAgentImprovementActivationOptions {\n transition: AgentImprovementActivationTransition\n reconcile?: AgentImprovementActivationReconciliation\n now?: () => Date\n}\n\n/** Create the exact result a product stores in the same transaction as its target write. */\nexport function createAgentImprovementActivationResult(\n transition: AgentImprovementActivationTransitionInput,\n options: CreateAgentImprovementActivationResultOptions,\n): AgentImprovementActivationResult {\n const activation = verifyCanonicalCandidateDocument(\n agentImprovementActivationSchema.parse(transition.activation),\n 'agent improvement activation',\n )\n assertTransitionInput(activation, transition)\n const result = agentImprovementActivationResultSchema.parse(\n canonicalCandidateDocument<AgentImprovementActivationResult>({\n kind: 'agent-improvement-activation-result',\n idempotencyKey: activation.digest,\n attemptedAt: transition.attemptedAt,\n completedAt: options.completedAt,\n outcome: options.outcome,\n }).value,\n )\n assertResultAgainstActivation(activation, result)\n assertOutcomeDesiredState(\n activation,\n result,\n new Map(transition.targets.map((target) => [targetIdentity(target), target.desiredDigest])),\n )\n return immutableCandidateValue(result)\n}\n\n/**\n * Recompute one historical activation result against the exact measured proposal and authority.\n * The result records that attempt; it is not a query of the target's current state.\n */\nexport function verifyAgentImprovementActivationResult(input: {\n proposal: unknown\n review: unknown\n activation: unknown\n result: unknown\n}): AgentImprovementActivationResult {\n const proposal = verifyAgentImprovementProposal(input.proposal)\n const activation = verifyAgentImprovementActivation(input)\n const result = verifyCanonicalCandidateDocument(\n agentImprovementActivationResultSchema.parse(input.result),\n 'agent improvement activation result',\n )\n assertResultAgainstActivation(activation, result)\n assertResultDesiredState(proposal, activation, result)\n return result\n}\n\n/** Validate and execute one product-owned activation transition. */\nexport async function executeAgentImprovementActivation(\n input: ExecuteAgentImprovementActivationInput,\n options: ExecuteAgentImprovementActivationOptions,\n): Promise<AgentImprovementActivationResult> {\n const proposal = verifyAgentImprovementProposal(input.proposal)\n const activation = verifyAgentImprovementActivation(input)\n const observedAt = (options.now ?? (() => new Date()))().toISOString()\n const attemptedAt =\n Date.parse(observedAt) < Date.parse(activation.authorizedAt)\n ? activation.authorizedAt\n : observedAt\n const expired = Date.parse(attemptedAt) >= Date.parse(activation.expiresAt)\n const transition = immutableCandidateValue<AgentImprovementActivationTransitionInput>(\n proposal.evaluation.kind === 'agent-improvement-measured-comparison'\n ? sealedCandidateTransition(proposal.evaluation.experiment, activation, attemptedAt, expired)\n : profileImprovementTransition(\n proposal.evaluation.experiment,\n activation,\n attemptedAt,\n expired,\n ),\n )\n\n if (transition.expired) {\n if (!options.reconcile) {\n return uncertainActivationResult(transition, 'RECONCILIATION_UNAVAILABLE')\n }\n let reconciled: unknown\n try {\n reconciled = await options.reconcile(transition)\n } catch {\n return uncertainActivationResult(transition, 'RECONCILIATION_THROW')\n }\n if (reconciled === undefined) {\n return createAgentImprovementActivationResult(transition, {\n completedAt: transition.attemptedAt,\n outcome: { status: 'expired' },\n })\n }\n try {\n return verifyAgentImprovementActivationResult({ ...input, result: reconciled })\n } catch {\n return uncertainActivationResult(transition, 'INVALID_RECONCILIATION')\n }\n }\n\n let rawResult: unknown\n try {\n rawResult = await options.transition(transition)\n } catch {\n return uncertainActivationResult(transition, 'TRANSITION_THROW')\n }\n try {\n return verifyAgentImprovementActivationResult({ ...input, result: rawResult })\n } catch {\n return uncertainActivationResult(transition, 'INVALID_RESULT')\n }\n}\n\nfunction sealedCandidateTransition(\n experiment: AgentCandidateExperiment,\n activation: AgentImprovementActivation,\n attemptedAt: string,\n expired: boolean,\n): SealedCandidateActivationTransitionInput {\n const targetArm = activation.intent === 'activate-candidate' ? 'candidate' : 'baseline'\n return {\n kind: 'sealed-candidate',\n activation,\n candidateBundle: experiment.candidate,\n bundle: experiment[targetArm],\n targets: activation.targets.map((target) => ({\n ...target,\n desiredDigest: agentImprovementTargetDigest(experiment, targetArm, target.surface),\n desiredInput: agentImprovementTargetInput(experiment[targetArm], target.surface),\n })) as SealedCandidateActivationTransitionInput['targets'],\n attemptedAt,\n expired,\n }\n}\n\nfunction profileImprovementTransition(\n experiment: AgentProfileImprovementExperiment,\n activation: AgentImprovementActivation,\n attemptedAt: string,\n expired: boolean,\n): ProfileImprovementActivationTransitionInput {\n const sourceArm = activation.intent === 'activate-candidate' ? 'baseline' : 'candidate'\n const targetArm = activation.intent === 'activate-candidate' ? 'candidate' : 'baseline'\n const operation = profileImprovementOperation(experiment, activation.intent)\n return {\n kind: 'profile-improvement',\n activation,\n experiment,\n sourceStateDigest: agentProfileImprovementStateDigest(experiment, sourceArm),\n desiredStateDigest: agentProfileImprovementStateDigest(experiment, targetArm),\n operation,\n targets: activation.targets.map((target) => ({\n ...target,\n desiredDigest: agentProfileImprovementStateDigest(experiment, targetArm),\n desiredInput: operation,\n })) as ProfileImprovementActivationTransitionInput['targets'],\n attemptedAt,\n expired,\n }\n}\n\nfunction profileImprovementOperation(\n experiment: AgentProfileImprovementExperiment,\n intent: AgentImprovementActivation['intent'],\n): AgentProfileImprovementActivationOperation {\n return intent === 'activate-candidate'\n ? { kind: 'apply-change', changes: experiment.change }\n : { kind: 'restore-state' }\n}\n\nfunction uncertainActivationResult(\n transition: AgentImprovementActivationTransitionInput,\n code: string,\n): AgentImprovementActivationResult {\n return createAgentImprovementActivationResult(transition, {\n completedAt: transition.attemptedAt,\n outcome: {\n status: 'indeterminate',\n code,\n message: 'The product transition did not return a trustworthy commit result.',\n },\n })\n}\n\nfunction assertTransitionInput(\n activation: AgentImprovementActivation,\n transition: AgentImprovementActivationTransitionInput,\n): void {\n if (transition.kind === 'sealed-candidate') {\n assertSealedCandidateTransitionInput(activation, transition)\n return\n }\n assertProfileImprovementTransitionInput(activation, transition)\n}\n\nfunction assertSealedCandidateTransitionInput(\n activation: AgentImprovementActivation,\n transition: SealedCandidateActivationTransitionInput,\n): void {\n assertAuthorizedTransitionTargets(activation, transition.targets)\n const desiredInputsMatch = transition.targets.every(\n (target) =>\n canonicalCandidateDigest(target.desiredInput) ===\n canonicalCandidateDigest(agentImprovementTargetInput(transition.bundle, target.surface)),\n )\n if (\n transition.expired !== Date.parse(transition.attemptedAt) >= Date.parse(activation.expiresAt) ||\n transition.candidateBundle.digest !== activation.candidateDigest ||\n !desiredInputsMatch ||\n (activation.intent === 'activate-candidate' &&\n transition.bundle.digest !== transition.candidateBundle.digest)\n ) {\n throw new Error('activation transition does not match its authorization')\n }\n}\n\nfunction assertProfileImprovementTransitionInput(\n activation: AgentImprovementActivation,\n transition: ProfileImprovementActivationTransitionInput,\n): void {\n assertAuthorizedTransitionTargets(activation, transition.targets)\n const targetsAgentProfile = activation.targets.some(\n (target) => target.surface === 'agent-profile',\n )\n const experiment = agentProfileImprovementExperimentSchema.parse(transition.experiment)\n const sourceArm = activation.intent === 'activate-candidate' ? 'baseline' : 'candidate'\n const targetArm = activation.intent === 'activate-candidate' ? 'candidate' : 'baseline'\n const sourceStateDigest = agentProfileImprovementStateDigest(experiment, sourceArm)\n const desiredStateDigest = agentProfileImprovementStateDigest(experiment, targetArm)\n const operation = profileImprovementOperation(experiment, activation.intent)\n const targetsMatch = transition.targets.every(\n (target) =>\n target.expectedBaseDigest === sourceStateDigest &&\n target.desiredDigest === desiredStateDigest &&\n canonicalCandidateDigest(target.desiredInput) === canonicalCandidateDigest(operation),\n )\n if (\n transition.expired !== Date.parse(transition.attemptedAt) >= Date.parse(activation.expiresAt) ||\n experiment.digest !== activation.experimentDigest ||\n experiment.candidate.stateDigest !== activation.candidateDigest ||\n (targetsAgentProfile &&\n (activation.executionRef === undefined ||\n canonicalCandidateDigest(activation.executionRef) !==\n canonicalCandidateDigest(experiment.executionRef))) ||\n transition.sourceStateDigest !== sourceStateDigest ||\n transition.desiredStateDigest !== desiredStateDigest ||\n canonicalCandidateDigest(transition.operation) !== canonicalCandidateDigest(operation) ||\n !targetsMatch\n ) {\n throw new Error('activation transition does not match its authorization')\n }\n}\n\nfunction assertAuthorizedTransitionTargets(\n activation: AgentImprovementActivation,\n targets: readonly AgentImprovementActivationTargetPlan[],\n): void {\n const authorized = targetMap(activation.targets)\n const planned = targetMap(targets)\n if (\n authorized.size !== planned.size ||\n [...authorized.entries()].some(\n ([identity, target]) =>\n planned.get(identity)?.expectedBaseDigest !== target.expectedBaseDigest,\n )\n ) {\n throw new Error('activation transition does not match its authorization')\n }\n}\n\nfunction assertResultAgainstActivation(\n activation: AgentImprovementActivation,\n result: AgentImprovementActivationResult,\n): void {\n const attemptedAt = Date.parse(result.attemptedAt)\n const completedAt = Date.parse(result.completedAt)\n const expiresAt = Date.parse(activation.expiresAt)\n if (\n result.idempotencyKey !== activation.digest ||\n attemptedAt < Date.parse(activation.authorizedAt) ||\n completedAt < attemptedAt\n ) {\n throw new Error('activation result does not bind its authorization')\n }\n const expired = attemptedAt >= expiresAt\n if (\n (result.outcome.status === 'expired' && !expired) ||\n (expired && !['expired', 'indeterminate', 'already-applied'].includes(result.outcome.status))\n ) {\n throw new Error('activation result does not honor its authorization expiry')\n }\n if (!('targets' in result.outcome)) return\n const authorized = targetMap(activation.targets)\n const observed = new Set(result.outcome.targets.map(targetIdentity))\n if (\n authorized.size !== observed.size ||\n [...authorized.keys()].some((identity) => !observed.has(identity))\n ) {\n throw new Error('activation result must cover every authorized target exactly once')\n }\n if (\n result.outcome.status === 'applied' &&\n result.outcome.targets.some(\n (target) =>\n target.beforeDigest !== authorized.get(targetIdentity(target))?.expectedBaseDigest,\n )\n ) {\n throw new Error('applied activation did not start from its authorized base state')\n }\n}\n\nfunction assertResultDesiredState(\n proposal: AgentImprovementProposal,\n activation: AgentImprovementActivation,\n result: AgentImprovementActivationResult,\n): void {\n if (!('targets' in result.outcome)) return\n const targetArm = activation.intent === 'activate-candidate' ? 'candidate' : 'baseline'\n const desiredStateDigest =\n proposal.evaluation.kind === 'agent-profile-improvement-measured-comparison'\n ? agentProfileImprovementStateDigest(proposal.evaluation.experiment, targetArm)\n : undefined\n const desired = new Map(\n activation.targets.map((target) => [\n targetIdentity(target),\n desiredStateDigest ??\n agentImprovementTargetDigest(\n requireSealedCandidateExperiment(proposal),\n targetArm,\n target.surface,\n ),\n ]),\n )\n assertOutcomeDesiredState(activation, result, desired)\n}\n\nfunction assertOutcomeDesiredState(\n activation: AgentImprovementActivation,\n result: AgentImprovementActivationResult,\n desired: ReadonlyMap<string, Sha256Digest>,\n): void {\n if (!('targets' in result.outcome)) return\n if (result.outcome.status === 'applied') {\n if (\n result.outcome.targets.some(\n (target) => target.afterDigest !== desired.get(targetIdentity(target)),\n )\n ) {\n throw new Error('applied activation does not match the requested bundle')\n }\n return\n }\n const allDesired = result.outcome.targets.every(\n (target) => target.currentDigest === desired.get(targetIdentity(target)),\n )\n if (result.outcome.status === 'already-applied') {\n if (!allDesired) throw new Error('already-applied activation is not at the requested state')\n return\n }\n const authorized = targetMap(activation.targets)\n const hasStaleTarget = result.outcome.targets.some(\n (target) => target.currentDigest !== authorized.get(targetIdentity(target))?.expectedBaseDigest,\n )\n if (allDesired || !hasStaleTarget) {\n throw new Error('activation conflict does not identify stale target state')\n }\n}\n\nfunction targetMap<T extends { surface: AgentImprovementSurface; identity: string }>(\n targets: readonly T[],\n): Map<string, T> {\n return new Map(targets.map((target) => [targetIdentity(target), target]))\n}\n\nfunction targetIdentity(target: { surface: AgentImprovementSurface; identity: string }): string {\n return `${target.surface}\\u0000${target.identity}`\n}\n"],"mappings":";;;;AAoBA,SAAgB,2BAA+C;CAC7D,OAAO;EAAE,UAAU;EAAG,WAAW;EAAG,SAAS;EAAG,UAAU;CAAE;AAC9D;AAEA,SAAgB,cAAc,OAAiC;CAC7D,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,KAAK,SAAS;AACzE;;AAGA,SAAgB,gBACd,QACA,OACM;CACN,OAAO,YAAY;CACnB,KAAK,MAAM,OAAO;EAAC;EAAY;EAAa;CAAS,GAAY;EAC/D,MAAM,QAAQ,MAAM;EACpB,IAAI,cAAc,KAAK,GAAG,OAAO,QAAQ;OACpC,IAAI,QAAQ,WAAW,OAAO,WAAW;OACzC,OAAO,cAAc;CAC5B;CACA,IAAI,MAAM,gBAAgB,OAAO,OAAO,cAAc;CACtD,IAAI,MAAM,aAAa,OAAO,OAAO,WAAW;CAChD,IAAI,cAAc,MAAM,gBAAgB,GACtC,OAAO,oBAAoB,OAAO,oBAAoB,KAAK,MAAM;AAErE;;;;ACgGA,SAAgB,uCACd,YACA,SACkC;CAClC,MAAM,aAAa,iCACjB,iCAAiC,MAAM,WAAW,UAAU,GAC5D,8BACF;CACA,sBAAsB,YAAY,UAAU;CAC5C,MAAM,SAAS,uCAAuC,MACpD,2BAA6D;EAC3D,MAAM;EACN,gBAAgB,WAAW;EAC3B,aAAa,WAAW;EACxB,aAAa,QAAQ;EACrB,SAAS,QAAQ;CACnB,CAAC,CAAC,CAAC,KACL;CACA,8BAA8B,YAAY,MAAM;CAChD,0BACE,YACA,QACA,IAAI,IAAI,WAAW,QAAQ,KAAK,WAAW,CAAC,eAAe,MAAM,GAAG,OAAO,aAAa,CAAC,CAAC,CAC5F;CACA,OAAO,wBAAwB,MAAM;AACvC;;;;;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,MAAM,CAAC,CAAC;AAC1E;AAEA,SAAS,eAAe,QAAwE;CAC9F,OAAO,GAAG,OAAO,QAAQ,QAAQ,OAAO;AAC1C"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { at as SharedBoxPlacement, f as ExecutorConfig, i as CollectedAgentTurn, ot as SharedBoxPlacementOptions, r as AgentTurnUsage } from "./stream-agent-turn-
|
|
1
|
+
import { Lt as OtelExportConfig, Yi as BudgetPool, bi as WorkerSlots } from "./types-CqzsTCqn.js";
|
|
2
|
+
import { at as SharedBoxPlacement, f as ExecutorConfig, i as CollectedAgentTurn, ot as SharedBoxPlacementOptions, r as AgentTurnUsage } from "./stream-agent-turn-ZL_mAEzE.js";
|
|
3
3
|
import { AgentCandidateBundle, AgentImprovementActivation, AgentImprovementActivationOutcome, AgentImprovementActivationResult, AgentImprovementActivationTarget, AgentImprovementProposal, AgentImprovementReview, AgentImprovementSurface, AgentProfile, AgentProfileImprovementChange, AgentProfileImprovementExperiment, AgentTrainingReceipt, AgentTrainingTask, HarnessType, ReasoningEffort, Sha256Digest } from "@tangle-network/agent-interface";
|
|
4
4
|
import { CostLedgerHandle, CostReceiptInput, MaximumCharge, PendingCostCallView, ProposalFinding, RunRecord } from "@tangle-network/agent-eval";
|
|
5
5
|
import { CampaignCellResult, CampaignScenarioIdentity, CompareOptimizationMethodsOptions, OptimizationMethod, OptimizationMethodComparison, Scenario, SearchAllocator, SearchCellResult, SearchCellStage, SearchClaim, SearchClaimVerification, SearchHistoryReceipt, SearchLane, SearchModelIdentity, SearchPolicy, SearchSourceRef, SearchSplit, SurfaceProposer, WorktreeAdapter } from "@tangle-network/agent-eval/campaign";
|
|
@@ -939,4 +939,4 @@ declare function verifyAgentImprovementActivationResult(input: {
|
|
|
939
939
|
declare function executeAgentImprovementActivation(input: ExecuteAgentImprovementActivationInput, options: ExecuteAgentImprovementActivationOptions): Promise<AgentImprovementActivationResult>;
|
|
940
940
|
//#endregion
|
|
941
941
|
export { ImproveSearchMethod as $, ImproveCodeBaseOptions as A, commandVerifier as At, ImproveMethodOptions as B, ProfileTrainer as C, AgenticGeneratorOptions as Ct, createCommandProfileTrainer as D, Verifier as Dt, TrainingDatasetDocument as E, AgenticGeneratorShotReceipt as Et, ImproveCustomCodeGeneratorOptions as F, ImproveProfileAgent as G, ImproveMethodSource as H, ImproveLineage as I, ImproveResult as J, ImproveProfileComponents as K, ImproveMethodContext as L, ImproveCodeResult as M, CandidateGenerator as Mt, ImproveCodeRunOptions as N, ImproveCandidateValidationInput as O, VerifyResult as Ot, ImproveCost as P, ImproveSearchIdentity as Q, ImproveMethodFactory as R, ImproveTrainingResult as S, AgenticGeneratorExecutorForWorktree as St, TrainingBoundaryResult as T, AgenticGeneratorShotExecution as Tt, ImproveOptimizationRunOptions as U, ImproveMethodResult as V, ImproveOptions as W, ImproveScenarioPartitions as X, ImproveRuntimeCodeGeneratorOptions as Y, ImproveSearchAgent as Z, SearchMethodOptions as _, routerLane as _t, AgentImprovementActivationTransitionInput as a, ImprovementCodeCandidate as at, ControlledTrainingCommand as b, DeepReadonly as bt, CreateAgentImprovementActivationResultOptions as c, SearchCellContext as ct, ProfileImprovementActivationTransitionInput as d, SearchLaneKind as dt, ImproveSearchOptions as et, SealedCandidateActivationTransitionInput as f, SearchLaneOptions as ft, improve as g, isSearchEnvironmentFault as gt, verifyAgentImprovementActivationResult as h, dedicatedLane as ht, AgentImprovementActivationTransition as i, ImprovementCandidate as it, ImproveCodeOptions as j, defaultBuildPrompt as jt, ImproveCandidateValidator as k, agenticGenerator as kt, ExecuteAgentImprovementActivationInput as l, SearchEnvironmentFault as lt, executeAgentImprovementActivation as m, SharedBoxSearchLane as mt, AgentImprovementActivationResultStore as n, ImproveSkillsOptions as nt, AgentProfileImprovementActivationOperation as o, ImprovementProfileCandidate as ot, createAgentImprovementActivationResult as p, SearchTraceOptions as pt, ImproveProfileSurface as q, AgentImprovementActivationTargetPlan as r, ImproveSurface as rt, AgentProfileImprovementActivationTargetPlan as s, SearchDispatchContext as st, AgentImprovementActivationReconciliation as t, ImproveSearchResult as tt, ExecuteAgentImprovementActivationOptions as u, SearchLane$1 as ut, searchMethod as v, sharedBoxLane as vt, ProfileTrainerRequest as w, AgenticGeneratorShotDisposition as wt, ImproveTrainingOptions as x, ReadonlyAgentProfile as xt, CheckpointServingPort as y, subscriptionLane as yt, ImproveMethodLineage as z };
|
|
942
|
-
//# sourceMappingURL=activation-
|
|
942
|
+
//# sourceMappingURL=activation-sYi0Wi1i.d.ts.map
|
package/dist/agent.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Fa as SandboxClient, Na as OutputAdapter, mo as RuntimeStreamEvent, ua as AgentRunSpec } from "./types-CqzsTCqn.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 { $h as
|
|
3
|
+
import { $h as ProfileMaterializationContract, Jh as AgentProfileMaterializationAxis, Qh as KnownAgentProfileMaterializationAxis, Xh as CanonicalAgentProfileMaterializationAxis, Yh as AssertProfileMaterializationOptions, Zh as DefineProfileMaterializationContractOptions, ag as fullProfileMaterialization, cg as promptModelProfileMaterialization, dg as renderProfileMaterializationIssues, eg as ProfileMaterializationIssue, fg as sandboxActProfileMaterialization, ig as defineProfileMaterializationContract, lg as promptOnlyProfileMaterialization, mg as worktreeCliProfileMaterialization, ng as assertProfileMaterialization, og as profileMaterializationAxes, pg as validateProfileMaterialization, qh as AGENT_PROFILE_MATERIALIZATION_AXES, rg as controlProfileMaterialization, sg as promptControlProfileMaterialization, tg as ValidateProfileMaterializationOptions, ug as promptResourceProfileMaterialization } from "./index-Ciie85Mi.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 { Ci as renderProfileMaterializationIssues, Di as validateProfileMaterialization, Oi as worktreeCliProfileMaterialization, Si as promptResourceProfileMaterialization, Ti as sandboxActProfileMaterialization, _i as fullProfileMaterialization, bi as promptModelProfileMaterialization, gi as defineProfileMaterializationContract, hi as controlProfileMaterialization, la as mapSandboxEvent, mi as assertProfileMaterialization, pi as AGENT_PROFILE_MATERIALIZATION_AXES, pn as createSandboxForSpec, vi as profileMaterializationAxes, xi as promptOnlyProfileMaterialization, yi as promptControlProfileMaterialization } from "./supervisor-
|
|
2
|
-
import "./runtime-
|
|
1
|
+
import { Ci as renderProfileMaterializationIssues, Di as validateProfileMaterialization, Oi as worktreeCliProfileMaterialization, Si as promptResourceProfileMaterialization, Ti as sandboxActProfileMaterialization, _i as fullProfileMaterialization, bi as promptModelProfileMaterialization, gi as defineProfileMaterializationContract, hi as controlProfileMaterialization, la as mapSandboxEvent, mi as assertProfileMaterialization, pi as AGENT_PROFILE_MATERIALIZATION_AXES, pn as createSandboxForSpec, vi as profileMaterializationAxes, xi as promptOnlyProfileMaterialization, yi as promptControlProfileMaterialization } from "./supervisor-CJPvBIMu.js";
|
|
2
|
+
import "./runtime-dpb0Pk4q.js";
|
|
3
3
|
import { createHash } from "node:crypto";
|
|
4
4
|
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
5
5
|
import { isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $i as detachedFrozen, $n as parseWorkerToolTraceArtifact, Aa as addResourceSpend, Ai as prepareJsonlAppend, Bn as InMemoryResultBlobStore, Da as unmeteredSpend, E as failedItems, It as createRouterTranscript, Lr as resolveRedactor, M as withDriverExecutor, Ma as withBudgetResources, Mi as writeAllBytes, Qt as createPeerMailbox, Rn as FileResultBlobStore, Tn as runBrainLoop, Vi as providerAttemptEvidence, Vn as InMemorySpawnJournal, _ as CheckUnavailableError, c as runTree, er as workerTraceAnalysisStore, ft as resolveSpawnResourcePaths, ga as chargedTokens, i as bestDelivered, ir as assertValidBudget, ji as readCommittedJsonLines, jt as createExecutorRegistry, nn as isLiveNodeStatus, o as pickBestDelivered, ot as scopeRetainedOwnerResourceReader, qt as createInbox, rn as isTerminalNodeStatus, s as runFinalizer, ur as errMessage, x as checkVerdictOf, xa as promptCacheTokenClasses, z as meterRuntimeOwnedProviderAttempt, zn as FileSpawnJournal } from "./supervisor-
|
|
1
|
+
import { $i as detachedFrozen, $n as parseWorkerToolTraceArtifact, Aa as addResourceSpend, Ai as prepareJsonlAppend, Ar as contentAddress, Bn as InMemoryResultBlobStore, Da as unmeteredSpend, E as failedItems, It as createRouterTranscript, Lr as resolveRedactor, M as withDriverExecutor, Ma as withBudgetResources, Mi as writeAllBytes, Qt as createPeerMailbox, Rn as FileResultBlobStore, Tn as runBrainLoop, Vi as providerAttemptEvidence, Vn as InMemorySpawnJournal, _ as CheckUnavailableError, c as runTree, er as workerTraceAnalysisStore, ft as resolveSpawnResourcePaths, ga as chargedTokens, i as bestDelivered, ir as assertValidBudget, ji as readCommittedJsonLines, jt as createExecutorRegistry, nn as isLiveNodeStatus, o as pickBestDelivered, ot as scopeRetainedOwnerResourceReader, qt as createInbox, rn as isTerminalNodeStatus, s as runFinalizer, ur as errMessage, x as checkVerdictOf, xa as promptCacheTokenClasses, z as meterRuntimeOwnedProviderAttempt, zn as FileSpawnJournal } from "./supervisor-CJPvBIMu.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-DSCWdbX2.js";
|
|
4
4
|
import { agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest } from "@tangle-network/agent-interface";
|
|
@@ -502,7 +502,11 @@ function parseAuthoredAnalystDefinition(raw) {
|
|
|
502
502
|
}
|
|
503
503
|
/** Normalize the two spellings of an analyst-on-settle entry to the route form. */
|
|
504
504
|
function normalizeAnalyzeOnSettle(entry) {
|
|
505
|
-
|
|
505
|
+
const route = typeof entry === "string" ? { kind: entry } : entry;
|
|
506
|
+
if (route.at !== void 0 && route.at !== "worker" && route.at !== "manager-end") throw new TypeError("analyzeOnSettle.at must be worker or manager-end");
|
|
507
|
+
if (route.at === "manager-end" && route.agent === void 0) throw new TypeError("manager-end analysis requires an agent profile");
|
|
508
|
+
if (route.statuses !== void 0 && (!Array.isArray(route.statuses) || route.statuses.length === 0 || route.statuses.some((status) => status !== "done" && status !== "down"))) throw new TypeError("analyzeOnSettle.statuses must contain done or down");
|
|
509
|
+
return route;
|
|
506
510
|
}
|
|
507
511
|
/**
|
|
508
512
|
* Why one parent→child delivery did not land, in the words the MANAGER needs.
|
|
@@ -880,7 +884,7 @@ function createCoordinationToolsForManager(opts, lifetime) {
|
|
|
880
884
|
let unkeyedAssignmentOrdinal = nextUnkeyedAssignmentOrdinal(opts.scope);
|
|
881
885
|
const preflightCounts = emptyPreflightCounts();
|
|
882
886
|
const nodeForWorker = (id) => opts.scope.view.nodes.find((node) => node.id === id) ?? opts.scope.resume?.view.nodes.find((node) => node.id === id);
|
|
883
|
-
const descendantOutRefs =
|
|
887
|
+
const descendantOutRefs = new Set(opts.sourceEvidenceRefs ?? []);
|
|
884
888
|
const projectSettled = (settled, resumed = false) => {
|
|
885
889
|
const node = nodeForWorker(settled.handle.id);
|
|
886
890
|
const assignmentId = settled.handle.assignmentId ?? node?.assignmentId;
|
|
@@ -920,6 +924,8 @@ function createCoordinationToolsForManager(opts, lifetime) {
|
|
|
920
924
|
reason: settled.reason
|
|
921
925
|
});
|
|
922
926
|
};
|
|
927
|
+
const analysisRoutes = (opts.analyzeOnSettle ?? []).map(normalizeAnalyzeOnSettle);
|
|
928
|
+
let finishingAnalysis = false;
|
|
923
929
|
const analystAssignments = /* @__PURE__ */ new Map();
|
|
924
930
|
for (const record of opts.priorJournal ?? []) {
|
|
925
931
|
if (record.event.type !== "analyst-assignment") continue;
|
|
@@ -1102,11 +1108,46 @@ function createCoordinationToolsForManager(opts, lifetime) {
|
|
|
1102
1108
|
} catch {
|
|
1103
1109
|
spansText = "";
|
|
1104
1110
|
}
|
|
1111
|
+
let output = null;
|
|
1112
|
+
let outputError;
|
|
1113
|
+
if (worker.outRef !== void 0) try {
|
|
1114
|
+
output = await opts.blobs.get(worker.outRef);
|
|
1115
|
+
} catch (error) {
|
|
1116
|
+
outputError = error instanceof Error ? error.message : String(error);
|
|
1117
|
+
}
|
|
1118
|
+
if (worker.outRef !== void 0 && output === void 0 && outputError === void 0) outputError = "referenced output blob unavailable";
|
|
1119
|
+
const sourceEvidence = JSON.parse(safeJsonText({
|
|
1120
|
+
worker,
|
|
1121
|
+
output: output ?? null,
|
|
1122
|
+
...outputError ? { outputError } : {},
|
|
1123
|
+
...route.at === "manager-end" ? { managerCheckpoint: {
|
|
1124
|
+
managerId: opts.scope.view.root,
|
|
1125
|
+
nodes: opts.scope.view.nodes.filter((node) => !node.assignmentId?.startsWith("analyst:")).map((node) => ({
|
|
1126
|
+
id: node.id,
|
|
1127
|
+
parent: node.parent,
|
|
1128
|
+
assignmentId: node.assignmentId,
|
|
1129
|
+
status: node.status
|
|
1130
|
+
})),
|
|
1131
|
+
settled: ledger.map(({ resumed: _resumed, ...row }) => row)
|
|
1132
|
+
} } : {}
|
|
1133
|
+
}));
|
|
1134
|
+
const sourceEvidenceRef = contentAddress(sourceEvidence);
|
|
1135
|
+
await opts.blobs.put(sourceEvidenceRef, sourceEvidence);
|
|
1136
|
+
const excerpt = (text, limit) => ({
|
|
1137
|
+
text: text.slice(0, limit),
|
|
1138
|
+
totalChars: text.length,
|
|
1139
|
+
omittedChars: Math.max(0, text.length - limit)
|
|
1140
|
+
});
|
|
1105
1141
|
const task = [
|
|
1106
1142
|
...route.directive === void 0 || route.directive.length === 0 ? [] : [route.directive],
|
|
1107
|
-
`
|
|
1108
|
-
|
|
1143
|
+
`Complete source envelope: ${sourceEvidenceRef}. Source output: ${worker.outRef ?? "(unavailable)"}.`,
|
|
1144
|
+
"When your profile grants observe_agent, fetch authorized source refs with {outRef}, following outputPage.nextOffset to read all pages. Without that tool or before fetching all pages, coverage is excerpt-only: leave claims requiring omitted evidence unassessed.",
|
|
1145
|
+
`Bounded source excerpt (omitted evidence is not inspected): ${safeJsonText(excerpt(safeJsonText(sourceEvidence), 12e3))}`,
|
|
1146
|
+
`Source tool trace: ${safeJsonText(worker.trace)} (${spanCount} spans).`,
|
|
1147
|
+
spansText.length === 0 ? "(no tool spans available)" : safeJsonText(excerpt(spansText, 8e3))
|
|
1109
1148
|
].join("\n\n");
|
|
1149
|
+
const taskDigest = canonicalCandidateDigest(task);
|
|
1150
|
+
if (route.at === "manager-end" && [...analystAssignments.values()].some((assignment) => assignment.sourceWorker === worker.id && assignment.kind === route.kind && assignment.taskDigest === taskDigest && assignment.profileDigest === canonicalAgentProfileDigest(route.agent))) return;
|
|
1110
1151
|
const assignmentId = `analyst:${route.kind}:o${analystRunOrdinal++}`;
|
|
1111
1152
|
const label = `analyst:${route.kind}`;
|
|
1112
1153
|
const assignment = detachedFrozen({
|
|
@@ -1114,9 +1155,10 @@ function createCoordinationToolsForManager(opts, lifetime) {
|
|
|
1114
1155
|
kind: route.kind,
|
|
1115
1156
|
sourceWorker: worker.id,
|
|
1116
1157
|
sourceTrace: worker.trace,
|
|
1158
|
+
sourceEvidenceRef,
|
|
1117
1159
|
...worker.outRef === void 0 ? {} : { sourceOutRef: worker.outRef },
|
|
1118
1160
|
profileDigest: canonicalAgentProfileDigest(route.agent),
|
|
1119
|
-
taskDigest
|
|
1161
|
+
taskDigest,
|
|
1120
1162
|
...route.directive === void 0 ? {} : { directive: route.directive },
|
|
1121
1163
|
...route.to === void 0 ? {} : { to: route.to }
|
|
1122
1164
|
});
|
|
@@ -1132,6 +1174,11 @@ function createCoordinationToolsForManager(opts, lifetime) {
|
|
|
1132
1174
|
task,
|
|
1133
1175
|
label,
|
|
1134
1176
|
analyst: route.kind,
|
|
1177
|
+
sourceEvidenceRefs: Object.freeze([
|
|
1178
|
+
sourceEvidenceRef,
|
|
1179
|
+
...worker.outRef === void 0 ? [] : [worker.outRef],
|
|
1180
|
+
...worker.trace.status === "available" ? [worker.trace.traceRef] : []
|
|
1181
|
+
]),
|
|
1135
1182
|
continuity: "fresh"
|
|
1136
1183
|
});
|
|
1137
1184
|
let refusal;
|
|
@@ -1167,12 +1214,10 @@ function createCoordinationToolsForManager(opts, lifetime) {
|
|
|
1167
1214
|
watchWorker(spawnedId);
|
|
1168
1215
|
};
|
|
1169
1216
|
const workerRouteNames = (workerId) => {
|
|
1170
|
-
const names = /* @__PURE__ */ new Set();
|
|
1171
1217
|
const profileName = profileNameByWorker.get(workerId);
|
|
1172
|
-
if (profileName !== void 0)
|
|
1218
|
+
if (profileName !== void 0) return /* @__PURE__ */ new Set([profileName]);
|
|
1173
1219
|
const label = nodeForWorker(workerId)?.label;
|
|
1174
|
-
|
|
1175
|
-
return names;
|
|
1220
|
+
return new Set(label === void 0 ? [] : [label]);
|
|
1176
1221
|
};
|
|
1177
1222
|
/** The LIVE worker a route destination names, by profile name first, label second. */
|
|
1178
1223
|
const liveWorkerIdNamed = (destination) => {
|
|
@@ -1311,13 +1356,12 @@ function createCoordinationToolsForManager(opts, lifetime) {
|
|
|
1311
1356
|
}
|
|
1312
1357
|
commitSettled(pending.worker);
|
|
1313
1358
|
pendingSettlement = void 0;
|
|
1314
|
-
if (pending.analyze &&
|
|
1315
|
-
const routes = opts.analyzeOnSettle.map(normalizeAnalyzeOnSettle);
|
|
1359
|
+
if (pending.analyze && !finishingAnalysis && analysisRoutes.length) {
|
|
1316
1360
|
const sourceNames = workerRouteNames(pending.worker.id);
|
|
1317
|
-
const applicable =
|
|
1361
|
+
const applicable = analysisRoutes.filter((route) => route.at !== "manager-end" && (route.statuses ?? ["done"]).includes(pending.worker.status) && (route.over === void 0 || route.over.some((name) => sourceNames.has(name))));
|
|
1318
1362
|
const lensRoutes = applicable.filter((route) => route.agent === void 0);
|
|
1319
1363
|
const agentRoutes = applicable.filter((route) => route.agent !== void 0);
|
|
1320
|
-
if (lensRoutes.length > 0 && opts.analysts) {
|
|
1364
|
+
if (lensRoutes.length > 0 && opts.analysts && pending.worker.trace.status === "available") {
|
|
1321
1365
|
const trace = await workerTraceAnalysisStore(pending.worker.trace, opts.blobs);
|
|
1322
1366
|
for (const route of lensRoutes) {
|
|
1323
1367
|
const findings = await opts.analysts.run(route.kind, trace);
|
|
@@ -1958,6 +2002,49 @@ function createCoordinationToolsForManager(opts, lifetime) {
|
|
|
1958
2002
|
});
|
|
1959
2003
|
return inFlightDrain;
|
|
1960
2004
|
};
|
|
2005
|
+
let managerAnalysis;
|
|
2006
|
+
const finishAnalysis = (input) => {
|
|
2007
|
+
if (managerAnalysis) return managerAnalysis;
|
|
2008
|
+
managerAnalysis = (async () => {
|
|
2009
|
+
const routes = analysisRoutes.filter((route) => route.at === "manager-end" && (route.statuses ?? ["done", "down"]).includes(input.status));
|
|
2010
|
+
if (routes.length === 0) return;
|
|
2011
|
+
finishingAnalysis = true;
|
|
2012
|
+
await ready();
|
|
2013
|
+
const outRef = input.output === void 0 ? void 0 : contentAddress(input.output);
|
|
2014
|
+
if (outRef !== void 0) await opts.blobs.put(outRef, input.output);
|
|
2015
|
+
const worker = detachedFrozen({
|
|
2016
|
+
id: opts.scope.view.root,
|
|
2017
|
+
status: input.status,
|
|
2018
|
+
trace: {
|
|
2019
|
+
status: "unavailable",
|
|
2020
|
+
reason: "trace-source-unavailable"
|
|
2021
|
+
},
|
|
2022
|
+
...outRef === void 0 ? {} : { outRef },
|
|
2023
|
+
...input.reason === void 0 ? {} : { reason: input.reason }
|
|
2024
|
+
});
|
|
2025
|
+
for (const route of routes) await spawnAnalystRun(route, worker);
|
|
2026
|
+
while (analystRuns.size > 0) if (!await ensureDrain()) break;
|
|
2027
|
+
})().catch(async (error) => {
|
|
2028
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
2029
|
+
try {
|
|
2030
|
+
await bus.publish({
|
|
2031
|
+
type: "finding",
|
|
2032
|
+
finding: canonicalFindingEvent({
|
|
2033
|
+
fromWorker: opts.scope.view.root,
|
|
2034
|
+
analyst: "manager-end",
|
|
2035
|
+
findings: { analystRunFailed: detail }
|
|
2036
|
+
})
|
|
2037
|
+
});
|
|
2038
|
+
} catch (recordError) {
|
|
2039
|
+
console.error("Runtime terminal analysis evidence unavailable", {
|
|
2040
|
+
managerId: opts.scope.view.root,
|
|
2041
|
+
analysisError: detail,
|
|
2042
|
+
recordError: recordError instanceof Error ? recordError.message : String(recordError)
|
|
2043
|
+
});
|
|
2044
|
+
}
|
|
2045
|
+
});
|
|
2046
|
+
return managerAnalysis;
|
|
2047
|
+
};
|
|
1961
2048
|
const awaitFenceMs = () => {
|
|
1962
2049
|
const declared = coordinationRequestAwaitFenceMs();
|
|
1963
2050
|
return declared !== void 0 && awaitTimeoutMs > 0 ? declared : awaitTimeoutMs;
|
|
@@ -2213,7 +2300,7 @@ function createCoordinationToolsForManager(opts, lifetime) {
|
|
|
2213
2300
|
workerId: idArg,
|
|
2214
2301
|
outRef: {
|
|
2215
2302
|
type: "string",
|
|
2216
|
-
description: "Instead of workerId: the content address of a result listed in a settled worker's `subtree.results
|
|
2303
|
+
description: "Instead of workerId: the content address of a result listed in a settled worker's `subtree.results` or authorized for your analyst assignment, to read it in full."
|
|
2217
2304
|
},
|
|
2218
2305
|
outputPath: {
|
|
2219
2306
|
type: "array",
|
|
@@ -2240,7 +2327,7 @@ function createCoordinationToolsForManager(opts, lifetime) {
|
|
|
2240
2327
|
const outRef = str(args.outRef, "outRef");
|
|
2241
2328
|
if (!descendantOutRefs.has(outRef)) return {
|
|
2242
2329
|
error: "unknown-result",
|
|
2243
|
-
reason: "this outRef was not listed in
|
|
2330
|
+
reason: "this outRef was not authorized as assignment evidence or listed in a subtree summary; pass an authorized source ref, a subtree.results outRef, or observe your own worker by workerId"
|
|
2244
2331
|
};
|
|
2245
2332
|
return {
|
|
2246
2333
|
outRef,
|
|
@@ -3067,6 +3154,7 @@ function createCoordinationToolsForManager(opts, lifetime) {
|
|
|
3067
3154
|
escalations: () => escalations,
|
|
3068
3155
|
definedAnalysts: () => definedAnalysts,
|
|
3069
3156
|
drainResolved,
|
|
3157
|
+
finishAnalysis,
|
|
3070
3158
|
abortWorker,
|
|
3071
3159
|
beginDriverAttempt: (attempt) => {
|
|
3072
3160
|
driverAttempt = attempt;
|
|
@@ -4325,6 +4413,7 @@ function driverAgent(opts) {
|
|
|
4325
4413
|
...opts.deliverable ? { deliverable: opts.deliverable } : {},
|
|
4326
4414
|
...opts.analysts ? { analysts: opts.analysts } : {},
|
|
4327
4415
|
...opts.analyzeOnSettle ? { analyzeOnSettle: opts.analyzeOnSettle } : {},
|
|
4416
|
+
...opts.sourceEvidenceRefs ? { sourceEvidenceRefs: opts.sourceEvidenceRefs } : {},
|
|
4328
4417
|
...opts.watchWorkers ? { watchWorkers: opts.watchWorkers } : {},
|
|
4329
4418
|
...opts.stallAfterMs !== void 0 ? { stallAfterMs: opts.stallAfterMs } : {},
|
|
4330
4419
|
...opts.awaitTimeoutMs !== void 0 ? { awaitTimeoutMs: opts.awaitTimeoutMs } : {},
|
|
@@ -4507,6 +4596,13 @@ function driverAgent(opts) {
|
|
|
4507
4596
|
...opts.compaction.preserveHead !== void 0 ? { preserveHead: opts.compaction.preserveHead } : {},
|
|
4508
4597
|
...opts.compaction.estimateTokens ? { estimateTokens: opts.compaction.estimateTokens } : {}
|
|
4509
4598
|
} : void 0;
|
|
4599
|
+
const analysisFailed = async (error) => {
|
|
4600
|
+
await coord.finishAnalysis({
|
|
4601
|
+
status: "down",
|
|
4602
|
+
reason: error instanceof Error ? error.message : String(error)
|
|
4603
|
+
});
|
|
4604
|
+
throw error;
|
|
4605
|
+
};
|
|
4510
4606
|
await runBrainLoop({
|
|
4511
4607
|
chat,
|
|
4512
4608
|
tools: toolSpecs,
|
|
@@ -4561,7 +4657,7 @@ function driverAgent(opts) {
|
|
|
4561
4657
|
return true;
|
|
4562
4658
|
}
|
|
4563
4659
|
}
|
|
4564
|
-
});
|
|
4660
|
+
}).catch(analysisFailed);
|
|
4565
4661
|
await coord.drainResolved();
|
|
4566
4662
|
await steerAcknowledger?.pass("final");
|
|
4567
4663
|
acknowledger?.pass("final");
|
|
@@ -4569,15 +4665,24 @@ function driverAgent(opts) {
|
|
|
4569
4665
|
const submitted = coord.submittedResult();
|
|
4570
4666
|
if (submitted) {
|
|
4571
4667
|
opts.onAcceptedSubmission?.(submitted.result);
|
|
4668
|
+
await coord.finishAnalysis({
|
|
4669
|
+
status: "done",
|
|
4670
|
+
output: submitted.result
|
|
4671
|
+
});
|
|
4572
4672
|
return submitted.result;
|
|
4573
4673
|
}
|
|
4574
|
-
|
|
4674
|
+
const result = await runFinalizer(opts.finalizer ?? bestDelivered, {
|
|
4575
4675
|
settled: coord.settled(),
|
|
4576
4676
|
blobs: opts.blobs,
|
|
4577
4677
|
tree: runTree(scope),
|
|
4578
4678
|
budget: scope.budget,
|
|
4579
4679
|
...opts.deliverable ? { deliverable: opts.deliverable } : {}
|
|
4680
|
+
}).catch(analysisFailed);
|
|
4681
|
+
await coord.finishAnalysis({
|
|
4682
|
+
status: "done",
|
|
4683
|
+
output: result
|
|
4580
4684
|
});
|
|
4685
|
+
return result;
|
|
4581
4686
|
}
|
|
4582
4687
|
};
|
|
4583
4688
|
}
|
|
@@ -4681,4 +4786,4 @@ function safeJson(v) {
|
|
|
4681
4786
|
//#endregion
|
|
4682
4787
|
export { createCoordinationTools as A, withCoordinationAwaitFence as B, applyRunCancellation as C, analystToolGroupNames as D, DEFAULT_AWAIT_EVENT_TIMEOUT_MS as E, questionEscalationTargets as F, defaultToolDetectors as H, COORDINATION_CLIENT_TOOL_TIMEOUT_MS as I, MCP_TOOL_TIMEOUT_HEADER as L, downMessageRefusalReasons as M, normalizeAnalyzeOnSettle as N, canonicalFindingEvent as O, parseAuthoredAnalystDefinition as P, declaredAwaitFenceMs as R, foldCoordinationRecords as S, ANALYST_DEFINITION_BOUNDS as T, watchTrace as U, createEventBus as V, renderAnytimeTable as _, allOf as a, withRunContext as b, createProgressTracker as c, progressStop as d, sampleFromSettled as f, plateauLength as g, bestSoFar as h, finalizeBestDelivered as i, createCoordinationToolsForManager as j, coordinationVerbNames 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, watchRunCancellation as w, FileCoordinationLog as x, createInMemoryRunContext as y, declaredToolTimeoutMs as z };
|
|
4683
4788
|
|
|
4684
|
-
//# sourceMappingURL=coordination-driver-
|
|
4789
|
+
//# sourceMappingURL=coordination-driver-c2W1hvwL.js.map
|