@tangle-network/agent-runtime 0.337.2 → 0.339.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-DRHM55Oo.d.ts → activation-CJIIl_Ey.d.ts} +90 -22
- package/dist/activation-CVSFxis9.js +876 -0
- package/dist/activation-CVSFxis9.js.map +1 -0
- package/dist/agent.d.ts +4 -4
- package/dist/agent.js +4 -7
- package/dist/agent.js.map +1 -1
- package/dist/{bundle-BPGjESee.js → bundle-DVOhBTic.js} +2 -2
- package/dist/{bundle-BPGjESee.js.map → bundle-DVOhBTic.js.map} +1 -1
- package/dist/candidate-execution/index.d.ts +4 -63
- package/dist/candidate-execution/index.js +6 -146
- package/dist/candidate-execution/index.js.map +1 -1
- package/dist/content-digest-sBTLujlK.js +9 -0
- package/dist/content-digest-sBTLujlK.js.map +1 -0
- package/dist/{delegate-B-T_ZB50.js → delegate-CCWE_AkU.js} +2 -2
- package/dist/{delegate-B-T_ZB50.js.map → delegate-CCWE_AkU.js.map} +1 -1
- package/dist/{coordination-driver-BHkFVqIq.js → driver-control-acknowledgers-C53ggdJ6.js} +4520 -4442
- package/dist/driver-control-acknowledgers-C53ggdJ6.js.map +1 -0
- package/dist/{durable-file-B_eJr6Mb.js → durable-file-gNI9ILAn.js} +1 -3
- package/dist/durable-file-gNI9ILAn.js.map +1 -0
- package/dist/durable.d.ts +3 -35
- package/dist/durable.js +225 -229
- package/dist/durable.js.map +1 -1
- package/dist/{graph-C4RFlWAJ.js → graph-CI9JXKqO.js} +65 -18
- package/dist/graph-CI9JXKqO.js.map +1 -0
- package/dist/{graph-registry-DAI6KNXB.js → graph-registry-BnO64cn8.js} +18 -17
- package/dist/graph-registry-BnO64cn8.js.map +1 -0
- package/dist/{improvement-cycle-D1I4hQvf.js → improve-BOXTLWJ3.js} +76 -1248
- package/dist/improve-BOXTLWJ3.js.map +1 -0
- package/dist/{improvement-adapter-D5gwwoXQ.d.ts → improvement-adapter-HUt_-cWA.d.ts} +2 -20
- package/dist/index.d.ts +10 -207
- package/dist/index.js +91 -305
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +10 -229
- package/dist/intelligence.js +506 -88
- package/dist/intelligence.js.map +1 -1
- package/dist/{jsonl-file-DBv31uPi.js → jsonl-file-C9Kde_0Z.js} +2 -2
- package/dist/{jsonl-file-DBv31uPi.js.map → jsonl-file-C9Kde_0Z.js.map} +1 -1
- package/dist/kernel.d.ts +4 -3
- package/dist/kernel.js +12 -13
- package/dist/loop-runner-CWzG1bH4.d.ts +32 -0
- package/dist/loop-runner-bin.d.ts +32 -2
- package/dist/loop-runner-bin.js +93 -1
- package/dist/loop-runner-bin.js.map +1 -0
- package/dist/loop-runner-pmPIHFVY.js +59 -0
- package/dist/loop-runner-pmPIHFVY.js.map +1 -0
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/bin.js.map +1 -1
- package/dist/mcp/index.d.ts +101 -416
- package/dist/mcp/index.js +122 -206
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/memory-bin.js +231 -1
- package/dist/mcp/memory-bin.js.map +1 -1
- package/dist/model-policy-CyCUwHed.js.map +1 -1
- package/dist/placement.d.ts +2 -9
- package/dist/placement.js +1 -1
- package/dist/placement.js.map +1 -1
- package/dist/platform.d.ts +194 -2
- package/dist/platform.js +145 -9
- package/dist/platform.js.map +1 -1
- package/dist/{prepare-CER-ZkPp.js → prepare-bXkvPMJA.js} +1213 -710
- package/dist/prepare-bXkvPMJA.js.map +1 -0
- package/dist/{profile-gNUsHNIJ.js → profile-Dpei_Sq0.js} +89 -3
- package/dist/profile-Dpei_Sq0.js.map +1 -0
- package/dist/{profile-materialization-BnoEf1co.d.ts → profile-materialization-B1wm2SPT.d.ts} +3 -5
- package/dist/profiles.d.ts +2 -2
- package/dist/profiles.js +4 -43
- package/dist/profiles.js.map +1 -1
- package/dist/{protected-model-port-BhpQRTw-.d.ts → protected-model-port-BGgpy2r9.d.ts} +4 -30
- package/dist/protected-redaction-DFCeo4vg.js.map +1 -1
- package/dist/{provision-supervisor-DGegCUH4.js → provision-supervisor-CJ6Zz6dz.js} +13 -10
- package/dist/provision-supervisor-CJ6Zz6dz.js.map +1 -0
- package/dist/record-value-B6bwJxLa.js +12 -0
- package/dist/record-value-B6bwJxLa.js.map +1 -0
- package/dist/{run-layout-Cu8H7aeh.js → run-cancellation-C9oL62sW.js} +175 -100
- package/dist/run-cancellation-C9oL62sW.js.map +1 -0
- package/dist/{runtime-BOGpotnH.js → runtime-B2fjL9Oi.js} +2639 -3187
- package/dist/runtime-B2fjL9Oi.js.map +1 -0
- package/dist/{runtime-hooks-Bj6wJHlH.d.ts → runtime-hooks-nsqxSUFL.d.ts} +2 -6
- package/dist/{sandbox-profile-compat-QTkLe1Z6.js → sandbox-profile-compat-BzVBFqrz.js} +690 -699
- package/dist/sandbox-profile-compat-BzVBFqrz.js.map +1 -0
- package/dist/search-executor-zMumiak_.js +1916 -0
- package/dist/search-executor-zMumiak_.js.map +1 -0
- package/dist/{server-hZWM-G8w.js → server-_4voDNrl.js} +362 -67
- package/dist/server-_4voDNrl.js.map +1 -0
- package/dist/{search-executor-Cm1WZmL-.js → structural-rollout-DpLCXzaL.js} +1680 -3403
- package/dist/structural-rollout-DpLCXzaL.js.map +1 -0
- package/dist/{substrate-B0TYNrXn.js → substrate-CGDFTSRh.js} +2 -9
- package/dist/substrate-CGDFTSRh.js.map +1 -0
- package/dist/{supervise-CvAKVfue.js → supervise-qAwXmPtD.js} +7768 -5360
- package/dist/supervise-qAwXmPtD.js.map +1 -0
- package/dist/{supervisor-Rz8AGpYb.js → supervisor-DHrUJhEZ.js} +26301 -26964
- package/dist/supervisor-DHrUJhEZ.js.map +1 -0
- package/dist/testing.d.ts +227 -2
- package/dist/testing.js +13 -14
- package/dist/testing.js.map +1 -1
- package/dist/tool-loop.d.ts +1 -1
- package/dist/{tool-server-Dqer2M4_.js → tool-server-XV4aJwoQ.js} +2 -2
- package/dist/tool-server-XV4aJwoQ.js.map +1 -0
- package/dist/top-snapshot-CbZE1JsU.js +502 -0
- package/dist/top-snapshot-CbZE1JsU.js.map +1 -0
- package/dist/tui/bin.js +711 -1
- package/dist/tui/bin.js.map +1 -1
- package/dist/tui/index.d.ts +5 -71
- package/dist/tui/index.js +3 -3
- package/dist/{types-Dl5L4r8Z.d.ts → types-CaOXqRTq.d.ts} +16230 -17376
- package/dist/workspace-store/index.d.ts +2 -27
- package/dist/workspace-store/index.js +2 -2
- package/dist/workspace-store/index.js.map +1 -1
- package/dist/{workspace-streams-JLjh5DC6.d.ts → workspace-streams-BiS4ABah.d.ts} +19 -32
- package/package.json +2 -2
- package/skills/agent-graphs/SKILL.md +10 -3
- package/skills/agent-graphs/references/authoring.md +18 -0
- package/skills/profile-authoring/SKILL.md +3 -3
- package/skills/supervise/SKILL.md +2 -2
- package/dist/activation-BDP6Eivv.js +0 -234
- package/dist/activation-BDP6Eivv.js.map +0 -1
- package/dist/coder-yhVWbdWc.js +0 -40
- package/dist/coder-yhVWbdWc.js.map +0 -1
- package/dist/coordination-driver-BHkFVqIq.js.map +0 -1
- package/dist/delegation-status-CF4D0NZ_.js +0 -358
- package/dist/delegation-status-CF4D0NZ_.js.map +0 -1
- package/dist/durable-file-B_eJr6Mb.js.map +0 -1
- package/dist/graph-C4RFlWAJ.js.map +0 -1
- package/dist/graph-registry-DAI6KNXB.js.map +0 -1
- package/dist/improvement-cycle-D1I4hQvf.js.map +0 -1
- package/dist/integrations-DopfCC2a.d.ts +0 -190
- package/dist/integrations-dFi-ALk7.js +0 -132
- package/dist/integrations-dFi-ALk7.js.map +0 -1
- package/dist/kb-gate-C8z2juK8.d.ts +0 -80
- package/dist/kb-gate-DpaSwXVx.js +0 -80
- package/dist/kb-gate-DpaSwXVx.js.map +0 -1
- package/dist/loop-runner-bin-DOuBIJ2O.d.ts +0 -164
- package/dist/loop-runner-bin-Dv5QvYDH.js +0 -246
- package/dist/loop-runner-bin-Dv5QvYDH.js.map +0 -1
- package/dist/memory-server-DXQ8IxGR.js +0 -234
- package/dist/memory-server-DXQ8IxGR.js.map +0 -1
- package/dist/openai-tools-DoQ32vpe.js +0 -44
- package/dist/openai-tools-DoQ32vpe.js.map +0 -1
- package/dist/openai-tools-Oxk4KQrY.d.ts +0 -24
- package/dist/prepare-CER-ZkPp.js.map +0 -1
- package/dist/profile-gNUsHNIJ.js.map +0 -1
- package/dist/protected-model-port-BuRsviSL.js +0 -766
- package/dist/protected-model-port-BuRsviSL.js.map +0 -1
- package/dist/provision-supervisor-DGegCUH4.js.map +0 -1
- package/dist/run-layout-Cu8H7aeh.js.map +0 -1
- package/dist/runtime-BOGpotnH.js.map +0 -1
- package/dist/sandbox-profile-compat-QTkLe1Z6.js.map +0 -1
- package/dist/search-executor-Cm1WZmL-.js.map +0 -1
- package/dist/server-hZWM-G8w.js.map +0 -1
- package/dist/substrate-B0TYNrXn.js.map +0 -1
- package/dist/supervise-CvAKVfue.js.map +0 -1
- package/dist/supervisor-Rz8AGpYb.js.map +0 -1
- package/dist/tool-server-Dqer2M4_.js.map +0 -1
- package/dist/top-app-BaMw1W2z.js +0 -1212
- package/dist/top-app-BaMw1W2z.js.map +0 -1
|
@@ -0,0 +1,876 @@
|
|
|
1
|
+
import { a as defaultStructuralRolloutPolicy } from "./structural-rollout-DpLCXzaL.js";
|
|
2
|
+
import { B as omitTopLevelDigest, F as canonicalCandidateDigest$1, H as verifyCanonicalCandidateDocument, I as canonicalCandidateDocument, z as immutableCandidateValue } from "./sandbox-profile-compat-BzVBFqrz.js";
|
|
3
|
+
import { a as applyExactAgentProfileDiff, g as omitUndefinedObjectFields, i as agentCandidateProfileAsAgentProfile, v as parseExactAgentProfile } from "./profile-Dpei_Sq0.js";
|
|
4
|
+
import { agentImprovementActivationResultSchema, agentImprovementActivationSchema, agentImprovementProposalSchema, agentImprovementReviewSchema, agentProfileDiffSchema, agentProfileImprovementExecutionRefSchema, agentProfileImprovementExperimentSchema, agentProfileModelHintsSchema, agentProfileSchema, canonicalAgentProfileDigest, changedProfileImprovementSurfaces, defineAgentProfileDiff, diffAgentProfiles } from "@tangle-network/agent-interface";
|
|
5
|
+
import { assertProposalFindings } from "@tangle-network/agent-eval/analyst";
|
|
6
|
+
import { campaignSplitDigestFromIdentities } from "@tangle-network/agent-eval/campaign";
|
|
7
|
+
import { verifyAgentProfileImprovementExperimentComparison, verifyCandidateExperimentComparison } from "@tangle-network/agent-eval/contract";
|
|
8
|
+
//#region src/improvement/rollout-policy.ts
|
|
9
|
+
/** The profile extensions namespace the policy persists under. */
|
|
10
|
+
const ROLLOUT_POLICY_EXTENSION = "structural-rollout";
|
|
11
|
+
const isBoundedInt = (v, min) => typeof v === "number" && Number.isInteger(v) && v >= min;
|
|
12
|
+
/** Normalize an untyped policy bag (a parsed surface or a profile extension) into
|
|
13
|
+
* a full `StructuralRolloutPolicy`, defaults merged. Returns `undefined` when any
|
|
14
|
+
* present dial violates the policy invariants (mirrors `resolvePolicy`: integer
|
|
15
|
+
* k ≥ 1, repairRounds ≥ 0, testgen ≥ 0) — a corrupt config must read as "not
|
|
16
|
+
* configured", never as a fabricated recipe. */
|
|
17
|
+
function normalizeRolloutPolicy(raw) {
|
|
18
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return void 0;
|
|
19
|
+
const bag = raw;
|
|
20
|
+
const k = bag.k ?? defaultStructuralRolloutPolicy.k;
|
|
21
|
+
const repairRounds = bag.repairRounds ?? defaultStructuralRolloutPolicy.repairRounds;
|
|
22
|
+
const testgen = bag.testgen ?? defaultStructuralRolloutPolicy.testgen;
|
|
23
|
+
if (!isBoundedInt(k, 1) || !isBoundedInt(repairRounds, 0) || !isBoundedInt(testgen, 0)) return;
|
|
24
|
+
return {
|
|
25
|
+
k,
|
|
26
|
+
repairRounds,
|
|
27
|
+
testgen,
|
|
28
|
+
...typeof bag.diverse === "boolean" ? { diverse: bag.diverse } : {}
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
/** Stable serialization with fixed field order. */
|
|
32
|
+
function serializeRolloutPolicy(policy) {
|
|
33
|
+
return JSON.stringify({
|
|
34
|
+
k: policy.k,
|
|
35
|
+
repairRounds: policy.repairRounds,
|
|
36
|
+
testgen: policy.testgen,
|
|
37
|
+
...policy.diverse !== void 0 ? { diverse: policy.diverse } : {}
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
/** Read the persisted policy off the profile. `undefined` when the profile does
|
|
41
|
+
* not opt into structural rollout. */
|
|
42
|
+
function structuralRolloutPolicyFromProfile(profile) {
|
|
43
|
+
const bag = profile.extensions?.[ROLLOUT_POLICY_EXTENSION];
|
|
44
|
+
if (bag === void 0) return void 0;
|
|
45
|
+
return normalizeRolloutPolicy(bag);
|
|
46
|
+
}
|
|
47
|
+
/** Persist a detached policy under the profile extension without mutating the input. */
|
|
48
|
+
function applyRolloutPolicyToProfile(profile, policy) {
|
|
49
|
+
const candidate = structuredClone(profile);
|
|
50
|
+
const bag = {
|
|
51
|
+
k: policy.k,
|
|
52
|
+
repairRounds: policy.repairRounds,
|
|
53
|
+
testgen: policy.testgen,
|
|
54
|
+
...policy.diverse !== void 0 ? { diverse: policy.diverse } : {}
|
|
55
|
+
};
|
|
56
|
+
return {
|
|
57
|
+
...candidate,
|
|
58
|
+
extensions: {
|
|
59
|
+
...candidate.extensions,
|
|
60
|
+
[ROLLOUT_POLICY_EXTENSION]: bag
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
//#endregion
|
|
65
|
+
//#region src/intelligence/improvement-surfaces.ts
|
|
66
|
+
const changedSurfaceOrder = [
|
|
67
|
+
"prompt",
|
|
68
|
+
"skills",
|
|
69
|
+
"tools",
|
|
70
|
+
"mcp",
|
|
71
|
+
"hooks",
|
|
72
|
+
"subagents",
|
|
73
|
+
"agent-profile",
|
|
74
|
+
"memory",
|
|
75
|
+
"code",
|
|
76
|
+
"knowledge",
|
|
77
|
+
"rollout-policy"
|
|
78
|
+
];
|
|
79
|
+
/** Agent improvement surfaces delivered as exact `AgentProfileDiff` replacements. */
|
|
80
|
+
const AGENT_IMPROVEMENT_PROFILE_SURFACES = [
|
|
81
|
+
"prompt",
|
|
82
|
+
"skills",
|
|
83
|
+
"tools",
|
|
84
|
+
"mcp",
|
|
85
|
+
"hooks",
|
|
86
|
+
"subagents"
|
|
87
|
+
];
|
|
88
|
+
/**
|
|
89
|
+
* Profile changes eligible for the product-owned measured comparison path.
|
|
90
|
+
* The six directly deliverable profile surfaces retain their granular labels;
|
|
91
|
+
* any residual profile axis also adds the complete `agent-profile` surface.
|
|
92
|
+
*/
|
|
93
|
+
const AGENT_PROFILE_MEASURED_SURFACES = [...AGENT_IMPROVEMENT_PROFILE_SURFACES, "agent-profile"];
|
|
94
|
+
function deriveChangedSurfaces(baselineBundle, candidateBundle) {
|
|
95
|
+
if (baselineBundle.knowledge || candidateBundle.knowledge) assertKnowledgeCandidatePair(baselineBundle, candidateBundle);
|
|
96
|
+
assertCodeCandidatePair(baselineBundle, candidateBundle);
|
|
97
|
+
const baseline = improvementSurfaceValues(baselineBundle);
|
|
98
|
+
const candidate = improvementSurfaceValues(candidateBundle);
|
|
99
|
+
const changed = changedSurfaceOrder.filter((surface) => canonicalCandidateDigest$1(baseline[surface]) !== canonicalCandidateDigest$1(candidate[surface]));
|
|
100
|
+
if (changed.length === 0) throw new Error("candidate experiment does not change an agent surface");
|
|
101
|
+
return changed;
|
|
102
|
+
}
|
|
103
|
+
function assertAgentImprovementActivationTargets(surfaces, experiment, intent, targets) {
|
|
104
|
+
if (isProfileImprovementExperiment(experiment)) assertProfileImprovementTargetsShareIdentity(targets);
|
|
105
|
+
const expected = new Set(surfaces);
|
|
106
|
+
const actual = new Set(targets.map((target) => target.surface));
|
|
107
|
+
const sourceArm = intent === "activate-candidate" ? "baseline" : "candidate";
|
|
108
|
+
if (!(isProfileImprovementExperiment(experiment) ? sameAgentImprovementSurfaceSet(surfaces, activationExperimentChangedSurfaces(experiment)) : sameOrderedSurfaces(surfaces, activationExperimentChangedSurfaces(experiment))) || targets.some((target) => !target.identity.trim()) || targets.some((target) => target.expectedBaseDigest !== activationTargetDigest(experiment, sourceArm, target.surface)) || targets.length !== surfaces.length || expected.size !== actual.size || [...expected].some((surface) => !actual.has(surface))) throw new Error("agent improvement activation targets must cover exactly the changed surfaces");
|
|
109
|
+
}
|
|
110
|
+
/** One opaque profile-state transition can change only one complete profile record. */
|
|
111
|
+
function assertProfileImprovementTargetsShareIdentity(targets) {
|
|
112
|
+
if (new Set(targets.map((target) => target.identity)).size !== 1) throw new Error("profile improvement activation targets must name one profile identity");
|
|
113
|
+
}
|
|
114
|
+
/** Bind caller-owned target identities to the exact source state Runtime measured. */
|
|
115
|
+
function buildAgentImprovementActivationTargets(surfaces, experiment, intent, identities) {
|
|
116
|
+
const sourceArm = intent === "activate-candidate" ? "baseline" : "candidate";
|
|
117
|
+
const targets = identities.map((target) => ({
|
|
118
|
+
...target,
|
|
119
|
+
expectedBaseDigest: activationTargetDigest(experiment, sourceArm, target.surface)
|
|
120
|
+
}));
|
|
121
|
+
assertAgentImprovementActivationTargets(surfaces, experiment, intent, targets);
|
|
122
|
+
return targets;
|
|
123
|
+
}
|
|
124
|
+
/** Exact host-owned profile state for every changed profile surface. */
|
|
125
|
+
function agentProfileImprovementStateDigest(experiment, arm) {
|
|
126
|
+
return experiment[arm].stateDigest;
|
|
127
|
+
}
|
|
128
|
+
/** Map Interface's current profile-improvement contract to Runtime-deliverable surfaces. */
|
|
129
|
+
function profileImprovementChangedSurfaces(change) {
|
|
130
|
+
const surfaces = changedProfileImprovementSurfaces(change);
|
|
131
|
+
if (surfaces.length === 0 || !surfaces.every((surface) => isAgentProfileMeasuredSurface(surface))) throw new Error("profile improvement experiment does not change a supported surface");
|
|
132
|
+
return surfaces;
|
|
133
|
+
}
|
|
134
|
+
function agentImprovementTargetDigest(experiment, arm, surface) {
|
|
135
|
+
if (surface === "knowledge") {
|
|
136
|
+
const knowledge = assertKnowledgeCandidatePair(experiment.baseline, experiment.candidate);
|
|
137
|
+
return arm === "baseline" ? knowledge.candidate.baseHash : knowledge.candidate.candidateHash;
|
|
138
|
+
}
|
|
139
|
+
if (surface === "code") assertCodeCandidatePair(experiment.baseline, experiment.candidate);
|
|
140
|
+
return canonicalCandidateDigest$1(improvementSurfaceValues(experiment[arm])[surface]);
|
|
141
|
+
}
|
|
142
|
+
function agentImprovementTargetInput(bundle, surface) {
|
|
143
|
+
return improvementSurfaceValues(bundle)[surface];
|
|
144
|
+
}
|
|
145
|
+
function activationTargetDigest(experiment, arm, surface) {
|
|
146
|
+
if (isProfileImprovementExperiment(experiment)) {
|
|
147
|
+
if (!activationExperimentChangedSurfaces(experiment).includes(surface)) throw new Error("profile improvement activation targets an unchanged surface");
|
|
148
|
+
return agentProfileImprovementStateDigest(experiment, arm);
|
|
149
|
+
}
|
|
150
|
+
return agentImprovementTargetDigest(experiment, arm, surface);
|
|
151
|
+
}
|
|
152
|
+
function activationExperimentChangedSurfaces(experiment) {
|
|
153
|
+
if (!isProfileImprovementExperiment(experiment)) return deriveChangedSurfaces(experiment.baseline, experiment.candidate);
|
|
154
|
+
return profileImprovementChangedSurfaces(experiment.change);
|
|
155
|
+
}
|
|
156
|
+
function isProfileImprovementExperiment(experiment) {
|
|
157
|
+
return experiment.kind === "agent-profile-improvement-experiment";
|
|
158
|
+
}
|
|
159
|
+
function sameOrderedSurfaces(left, right) {
|
|
160
|
+
return left.length === right.length && left.every((surface, index) => surface === right[index]);
|
|
161
|
+
}
|
|
162
|
+
/** Profile-change surface order is presentation only; its measured contract is set-based. */
|
|
163
|
+
function sameAgentImprovementSurfaceSet(left, right) {
|
|
164
|
+
return left.length === right.length && left.every((surface) => right.includes(surface));
|
|
165
|
+
}
|
|
166
|
+
/** Return whether a measured surface can be delivered through an agent profile. */
|
|
167
|
+
function isAgentImprovementProfileSurface(surface) {
|
|
168
|
+
return AGENT_IMPROVEMENT_PROFILE_SURFACES.includes(surface);
|
|
169
|
+
}
|
|
170
|
+
/** Return whether a surface is eligible for shared profile measurement. */
|
|
171
|
+
function isAgentProfileMeasuredSurface(surface) {
|
|
172
|
+
return AGENT_PROFILE_MEASURED_SURFACES.includes(surface);
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Return the canonical current-state input for one profile-deliverable improvement target.
|
|
176
|
+
* Missing slots become `null`; tools and subagents include both their direct and resource slots.
|
|
177
|
+
* Unrelated profile fields are excluded. The result matches `agentImprovementTargetInput` for the
|
|
178
|
+
* same profile inside a candidate bundle.
|
|
179
|
+
*/
|
|
180
|
+
function agentImprovementProfileSurfaceInput(profile, surface) {
|
|
181
|
+
return immutableCandidateValue(profileSurfaceInput(parseExactAgentProfile(omitUndefinedObjectFields(profile, "agent improvement profile"), "agent improvement profile"), surface));
|
|
182
|
+
}
|
|
183
|
+
function profileSurfaceInput(profile, surface) {
|
|
184
|
+
switch (surface) {
|
|
185
|
+
case "prompt": return { prompt: profile.prompt ?? null };
|
|
186
|
+
case "skills": return profile.resources?.skills ?? null;
|
|
187
|
+
case "tools": return {
|
|
188
|
+
tools: profile.tools ?? null,
|
|
189
|
+
resources: profile.resources?.tools ?? null
|
|
190
|
+
};
|
|
191
|
+
case "mcp": return profile.mcp ?? null;
|
|
192
|
+
case "hooks": return profile.hooks ?? null;
|
|
193
|
+
case "subagents": return {
|
|
194
|
+
subagents: profile.subagents ?? null,
|
|
195
|
+
resources: profile.resources?.agents ?? null
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
/** Return the `Sha256Digest` of one profile surface using Runtime's canonical candidate digest. */
|
|
200
|
+
function agentImprovementProfileSurfaceDigest(profile, surface) {
|
|
201
|
+
return canonicalCandidateDigest$1(agentImprovementProfileSurfaceInput(profile, surface));
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Replace one measured profile surface exactly, including array-valued resources.
|
|
205
|
+
* Apply the returned diffs in order: a diff applies its set before its removal,
|
|
206
|
+
* so exact replacement requires a reset record followed by a set record.
|
|
207
|
+
*/
|
|
208
|
+
function agentImprovementTargetProfileDiffs(target, options) {
|
|
209
|
+
const { remove, set } = improvementSurfaceReplacement(target);
|
|
210
|
+
const common = {
|
|
211
|
+
kind: "agent-profile-diff",
|
|
212
|
+
...options.source ? { source: options.source } : {},
|
|
213
|
+
metadata: {
|
|
214
|
+
...options.metadata ?? {},
|
|
215
|
+
surface: target.surface
|
|
216
|
+
}
|
|
217
|
+
};
|
|
218
|
+
const reset = agentProfileDiffSchema.parse(defineAgentProfileDiff({
|
|
219
|
+
...common,
|
|
220
|
+
id: `${options.id}:${target.surface}:reset`,
|
|
221
|
+
title: `Replace active ${target.surface}`,
|
|
222
|
+
remove
|
|
223
|
+
}));
|
|
224
|
+
if (!set) return [reset];
|
|
225
|
+
return [reset, agentProfileDiffSchema.parse(defineAgentProfileDiff({
|
|
226
|
+
...common,
|
|
227
|
+
id: `${options.id}:${target.surface}:set`,
|
|
228
|
+
title: `Activate measured ${target.surface}`,
|
|
229
|
+
set
|
|
230
|
+
}))];
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Derive the ordered profile patch that changes one executable profile into
|
|
234
|
+
* another, then prove the patch preserves the complete candidate state.
|
|
235
|
+
*/
|
|
236
|
+
function agentImprovementProfileDiffs(baselineInput, candidateInput, options) {
|
|
237
|
+
const baseline = parseExactAgentProfile(omitUndefinedObjectFields(baselineInput, "profile improvement baseline"), "profile improvement baseline");
|
|
238
|
+
const candidate = parseExactAgentProfile(omitUndefinedObjectFields(candidateInput, "profile improvement candidate"), "profile improvement candidate");
|
|
239
|
+
if (canonicalAgentProfileDigest(baseline) === canonicalAgentProfileDigest(candidate)) throw new Error("profile improvement candidate does not change the profile");
|
|
240
|
+
const completeChanges = completeAgentProfileReplacementDiffs(baseline, candidate, options);
|
|
241
|
+
if (canonicalAgentProfileDigest(completeChanges.reduce((profile, change) => applyExactAgentProfileDiff(profile, change, "complete profile improvement candidate change"), baseline)) !== canonicalAgentProfileDigest(candidate)) throw new Error("complete profile improvement change did not reproduce the candidate");
|
|
242
|
+
return completeChanges;
|
|
243
|
+
}
|
|
244
|
+
function completeAgentProfileReplacementDiffs(baseline, candidate, options) {
|
|
245
|
+
const [first, ...rest] = diffAgentProfiles(baseline, candidate).map((change) => {
|
|
246
|
+
const reset = change.remove !== void 0;
|
|
247
|
+
return agentProfileDiffSchema.parse({
|
|
248
|
+
...change,
|
|
249
|
+
...options.source ? { source: options.source } : {},
|
|
250
|
+
metadata: {
|
|
251
|
+
...options.metadata ?? {},
|
|
252
|
+
surface: "agent-profile"
|
|
253
|
+
},
|
|
254
|
+
id: `${options.id}:agent-profile:${reset ? "reset" : "set"}`,
|
|
255
|
+
title: reset ? "Reset changed agent profile fields" : "Set changed agent profile fields"
|
|
256
|
+
});
|
|
257
|
+
});
|
|
258
|
+
if (!first) throw new Error("complete profile differ found no changed fields");
|
|
259
|
+
return [first, ...rest];
|
|
260
|
+
}
|
|
261
|
+
function improvementSurfaceReplacement(target) {
|
|
262
|
+
const value = target.desiredInput;
|
|
263
|
+
switch (target.surface) {
|
|
264
|
+
case "prompt": {
|
|
265
|
+
const prompt = exactObject(value, ["prompt"], "prompt activation input").prompt;
|
|
266
|
+
assertDefined(prompt, "prompt activation input.prompt");
|
|
267
|
+
return {
|
|
268
|
+
remove: { prompt: true },
|
|
269
|
+
...prompt === null ? {} : { set: parseProfileSet({ prompt }) }
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
case "skills":
|
|
273
|
+
assertDefined(value, "skills activation input");
|
|
274
|
+
return {
|
|
275
|
+
remove: { resources: { skills: true } },
|
|
276
|
+
...value === null ? {} : { set: parseProfileSet({ resources: { skills: value } }) }
|
|
277
|
+
};
|
|
278
|
+
case "tools": {
|
|
279
|
+
const parsed = exactObject(value, ["tools", "resources"], "tools activation input");
|
|
280
|
+
assertDefined(parsed.tools, "tools activation input.tools");
|
|
281
|
+
assertDefined(parsed.resources, "tools activation input.resources");
|
|
282
|
+
const set = {
|
|
283
|
+
...parsed.tools === null ? {} : { tools: parsed.tools },
|
|
284
|
+
...parsed.resources === null ? {} : { resources: { tools: parsed.resources } }
|
|
285
|
+
};
|
|
286
|
+
return {
|
|
287
|
+
remove: {
|
|
288
|
+
tools: true,
|
|
289
|
+
resources: { tools: true }
|
|
290
|
+
},
|
|
291
|
+
...Object.keys(set).length === 0 ? {} : { set: parseProfileSet(set) }
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
case "mcp":
|
|
295
|
+
assertDefined(value, "mcp activation input");
|
|
296
|
+
return {
|
|
297
|
+
remove: { mcp: true },
|
|
298
|
+
...value === null ? {} : { set: parseProfileSet({ mcp: value }) }
|
|
299
|
+
};
|
|
300
|
+
case "hooks":
|
|
301
|
+
assertDefined(value, "hooks activation input");
|
|
302
|
+
return {
|
|
303
|
+
remove: { hooks: true },
|
|
304
|
+
...value === null ? {} : { set: parseProfileSet({ hooks: value }) }
|
|
305
|
+
};
|
|
306
|
+
case "subagents": {
|
|
307
|
+
const parsed = exactObject(value, ["subagents", "resources"], "subagents activation input");
|
|
308
|
+
assertDefined(parsed.subagents, "subagents activation input.subagents");
|
|
309
|
+
assertDefined(parsed.resources, "subagents activation input.resources");
|
|
310
|
+
const set = {
|
|
311
|
+
...parsed.subagents === null ? {} : { subagents: parsed.subagents },
|
|
312
|
+
...parsed.resources === null ? {} : { resources: { agents: parsed.resources } }
|
|
313
|
+
};
|
|
314
|
+
return {
|
|
315
|
+
remove: {
|
|
316
|
+
subagents: true,
|
|
317
|
+
resources: { agents: true }
|
|
318
|
+
},
|
|
319
|
+
...Object.keys(set).length === 0 ? {} : { set: parseProfileSet(set) }
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
function assertDefined(value, label) {
|
|
325
|
+
if (value === void 0) throw new Error(`${label} must not be undefined`);
|
|
326
|
+
}
|
|
327
|
+
function exactObject(value, keys, label) {
|
|
328
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label} must be an object`);
|
|
329
|
+
const record = value;
|
|
330
|
+
const actual = Object.keys(record).sort();
|
|
331
|
+
const expected = [...keys].sort();
|
|
332
|
+
if (actual.length !== expected.length || actual.some((key, index) => key !== expected[index])) throw new Error(`${label} must contain exactly: ${expected.join(", ")}`);
|
|
333
|
+
return record;
|
|
334
|
+
}
|
|
335
|
+
function parseProfileSet(value) {
|
|
336
|
+
return agentProfileSchema.parse(value);
|
|
337
|
+
}
|
|
338
|
+
function assertKnowledgeCandidatePair(baselineBundle, candidateBundle) {
|
|
339
|
+
const baseline = baselineBundle.knowledge;
|
|
340
|
+
const candidate = candidateBundle.knowledge;
|
|
341
|
+
if (!baseline && !candidate) throw new Error("knowledge candidate pair is not present");
|
|
342
|
+
if (!baseline || !candidate || canonicalCandidateDigest$1({
|
|
343
|
+
candidate: baseline.candidate,
|
|
344
|
+
evaluation: baseline.evaluation
|
|
345
|
+
}) !== canonicalCandidateDigest$1({
|
|
346
|
+
candidate: candidate.candidate,
|
|
347
|
+
evaluation: candidate.evaluation
|
|
348
|
+
})) throw new Error("knowledge experiment arms must share one measured candidate and evaluation identity");
|
|
349
|
+
return candidate;
|
|
350
|
+
}
|
|
351
|
+
function assertCodeCandidatePair(baselineBundle, candidateBundle) {
|
|
352
|
+
const baseline = baselineBundle.code;
|
|
353
|
+
const candidate = candidateBundle.code;
|
|
354
|
+
if (canonicalCandidateDigest$1(baseline) === canonicalCandidateDigest$1(candidate) || candidate.kind !== "git-patch") return;
|
|
355
|
+
const baselineTree = baseline.kind === "no-op" ? baseline.baseTree : baseline.kind === "git-patch" ? baseline.candidateTree : void 0;
|
|
356
|
+
const baselineRepository = baseline.kind === "disabled" ? void 0 : baseline.repository;
|
|
357
|
+
if (baselineTree !== candidate.baseTree || !baselineRepository || canonicalCandidateDigest$1(baselineRepository) !== canonicalCandidateDigest$1(candidate.repository)) throw new Error("code candidate must be based on the exact repository tree measured by the baseline arm");
|
|
358
|
+
}
|
|
359
|
+
function improvementSurfaceValues(bundle) {
|
|
360
|
+
const profile = agentCandidateProfileAsAgentProfile(bundle.profile);
|
|
361
|
+
return {
|
|
362
|
+
prompt: agentImprovementProfileSurfaceInput(profile, "prompt"),
|
|
363
|
+
skills: agentImprovementProfileSurfaceInput(profile, "skills"),
|
|
364
|
+
tools: agentImprovementProfileSurfaceInput(profile, "tools"),
|
|
365
|
+
mcp: agentImprovementProfileSurfaceInput(profile, "mcp"),
|
|
366
|
+
hooks: agentImprovementProfileSurfaceInput(profile, "hooks"),
|
|
367
|
+
subagents: agentImprovementProfileSurfaceInput(profile, "subagents"),
|
|
368
|
+
"agent-profile": {
|
|
369
|
+
profile: opaqueProfileSlice(profile),
|
|
370
|
+
execution: bundle.execution
|
|
371
|
+
},
|
|
372
|
+
memory: {
|
|
373
|
+
instructions: profile.resources?.instructions ?? null,
|
|
374
|
+
executionPolicy: bundle.memory
|
|
375
|
+
},
|
|
376
|
+
code: bundle.code,
|
|
377
|
+
knowledge: bundle.knowledge ?? null,
|
|
378
|
+
"rollout-policy": structuralRolloutPolicyFromProfile(profile) ?? null
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
function opaqueProfileSlice(profile) {
|
|
382
|
+
const { prompt: _prompt, tools: _tools, mcp: _mcp, hooks: _hooks, subagents: _subagents, extensions, resources, ...opaqueProfile } = profile;
|
|
383
|
+
const { [ROLLOUT_POLICY_EXTENSION]: _rolloutPolicy, ...opaqueExtensions } = extensions ?? {};
|
|
384
|
+
const { instructions: _instructions, skills: _skills, tools: _resourceTools, agents: _agents, ...opaqueResources } = resources ?? {};
|
|
385
|
+
return {
|
|
386
|
+
...opaqueProfile,
|
|
387
|
+
...Object.keys(opaqueExtensions).length > 0 ? { extensions: opaqueExtensions } : {},
|
|
388
|
+
...Object.keys(opaqueResources).length > 0 ? { resources: opaqueResources } : {}
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
//#endregion
|
|
392
|
+
//#region src/intelligence/optimization-receipt.ts
|
|
393
|
+
const optimizationReceiptMetadataKey = "optimizationReceipt";
|
|
394
|
+
/** Build a detached receipt only for methods backed by an identified external optimizer. */
|
|
395
|
+
function createOptimizationActivationReceipt(improvement) {
|
|
396
|
+
const provenance = improvement.provenance;
|
|
397
|
+
if (!provenance) return void 0;
|
|
398
|
+
const finalTestDataDigest = improvement.lineage.finalTestSplitDigest;
|
|
399
|
+
if (!finalTestDataDigest) throw new Error("method improvement does not retain its final-test split digest");
|
|
400
|
+
const optimizerModel = provenance.optimizerModel;
|
|
401
|
+
const candidateModel = improvement.candidate.profile.model;
|
|
402
|
+
return canonicalCandidateDocument({
|
|
403
|
+
kind: "optimization-activation-receipt",
|
|
404
|
+
method: improvement.method,
|
|
405
|
+
source: provenance.source,
|
|
406
|
+
...provenance.bridge ? { bridge: provenance.bridge } : {},
|
|
407
|
+
...provenance.modules ? { modules: provenance.modules } : {},
|
|
408
|
+
...provenance.python ? { python: provenance.python } : {},
|
|
409
|
+
...candidateModel || optimizerModel ? { models: {
|
|
410
|
+
...candidateModel ? { candidate: candidateModel } : {},
|
|
411
|
+
...optimizerModel ? { optimizer: optimizerModel } : {}
|
|
412
|
+
} } : {},
|
|
413
|
+
usage: {
|
|
414
|
+
optimizerEvaluations: provenance.evaluationCount,
|
|
415
|
+
...provenance.tokenUsage ? { optimizerTokens: provenance.tokenUsage } : {}
|
|
416
|
+
},
|
|
417
|
+
cost: {
|
|
418
|
+
optimization: receiptCost(improvement.raw.optimizationCost),
|
|
419
|
+
finalTest: receiptCost(improvement.raw.testCost),
|
|
420
|
+
total: receiptCost(improvement.raw.totalCost)
|
|
421
|
+
},
|
|
422
|
+
invocation: {
|
|
423
|
+
runtimeInvocationId: improvement.lineage.invocationId,
|
|
424
|
+
optimizerRunId: provenance.runId,
|
|
425
|
+
...provenance.compatibleRunId ? { compatibleOptimizerRunId: provenance.compatibleRunId } : {},
|
|
426
|
+
resumed: provenance.resumed,
|
|
427
|
+
artifactDir: provenance.artifactDir
|
|
428
|
+
},
|
|
429
|
+
developmentDataDigest: improvement.lineage.developmentSplitDigest,
|
|
430
|
+
finalTestDataDigest,
|
|
431
|
+
scenarioPartitions: improvement.lineage.scenarioPartitions
|
|
432
|
+
}).value;
|
|
433
|
+
}
|
|
434
|
+
/** Add Runtime-owned optimizer evidence without aliasing caller metadata. */
|
|
435
|
+
function attachOptimizationActivationReceipt(metadata, receipt) {
|
|
436
|
+
assertNoCallerOptimizationReceipt(metadata);
|
|
437
|
+
return immutableCandidateValue({
|
|
438
|
+
...metadata ?? {},
|
|
439
|
+
[optimizationReceiptMetadataKey]: receipt
|
|
440
|
+
});
|
|
441
|
+
}
|
|
442
|
+
function assertNoCallerOptimizationReceipt(metadata) {
|
|
443
|
+
if (metadata && Object.hasOwn(metadata, "optimizationReceipt")) throw new Error(`candidate metadata reserves '${optimizationReceiptMetadataKey}' for Runtime`);
|
|
444
|
+
}
|
|
445
|
+
/** Read and verify the optimizer evidence carried by a measured proposal. */
|
|
446
|
+
function optimizationActivationReceiptFromMetadata(metadata) {
|
|
447
|
+
const value = metadata?.[optimizationReceiptMetadataKey];
|
|
448
|
+
if (value === void 0) return void 0;
|
|
449
|
+
return immutableCandidateValue(parseOptimizationActivationReceipt(value));
|
|
450
|
+
}
|
|
451
|
+
function parseOptimizationActivationReceipt(value) {
|
|
452
|
+
if (!isRecord(value) || value.kind !== "optimization-activation-receipt") throw new Error("optimization receipt must be an optimization-activation-receipt");
|
|
453
|
+
if (!isNonEmptyString(value.method) || !isPackageSource(value.source) || value.bridge !== void 0 && !isPackageSource(value.bridge) || !isModules(value.modules) || !isPythonRuntime(value.python) || !isModels(value.models) || !isUsage(value.usage) || !isCost(value.cost) || !isInvocation(value.invocation) || !isSha256Digest(value.developmentDataDigest) || !isSha256Digest(value.finalTestDataDigest) || !isScenarioPartitions(value.scenarioPartitions) || !isSha256Digest(value.digest)) throw new Error("optimization receipt contains invalid evidence");
|
|
454
|
+
const receipt = value;
|
|
455
|
+
if (!hasMatchingScenarioPartitionDigests(receipt)) throw new Error("optimization receipt task identities do not match its split digests");
|
|
456
|
+
if (canonicalCandidateDigest$1(omitTopLevelDigest(receipt)) !== receipt.digest) throw new Error("optimization receipt digest does not match its evidence");
|
|
457
|
+
return receipt;
|
|
458
|
+
}
|
|
459
|
+
function isScenarioPartitions(value) {
|
|
460
|
+
if (!isRecord(value)) return false;
|
|
461
|
+
return isScenarioIdentityList(value.train) && isScenarioIdentityList(value.selection) && isScenarioIdentityList(value.finalTest) && isPositiveSafeInteger(value.optimizationReps) && isPositiveSafeInteger(value.finalTestReps);
|
|
462
|
+
}
|
|
463
|
+
function isScenarioIdentityList(value) {
|
|
464
|
+
return Array.isArray(value) && value.every((scenario) => isRecord(scenario) && isNonEmptyString(scenario.id) && isNonEmptyString(scenario.kind) && isSha256Digest(scenario.scenarioDigest));
|
|
465
|
+
}
|
|
466
|
+
function hasMatchingScenarioPartitionDigests(receipt) {
|
|
467
|
+
try {
|
|
468
|
+
const { scenarioPartitions } = receipt;
|
|
469
|
+
const developmentDataDigest = canonicalCandidateDigest$1({
|
|
470
|
+
train: campaignSplitDigestFromIdentities(scenarioPartitions.train, scenarioPartitions.optimizationReps),
|
|
471
|
+
selection: campaignSplitDigestFromIdentities(scenarioPartitions.selection, scenarioPartitions.optimizationReps)
|
|
472
|
+
});
|
|
473
|
+
const finalTestDataDigest = campaignSplitDigestFromIdentities(scenarioPartitions.finalTest, scenarioPartitions.finalTestReps);
|
|
474
|
+
return receipt.developmentDataDigest === developmentDataDigest && receipt.finalTestDataDigest === finalTestDataDigest;
|
|
475
|
+
} catch {
|
|
476
|
+
return false;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
function isPackageSource(value) {
|
|
480
|
+
if (!isRecord(value) || value.kind !== "package" || value.evidence !== "observed" && value.evidence !== "declared" || !isNonEmptyString(value.package) || !isNonEmptyString(value.version)) return false;
|
|
481
|
+
return isOptionalNonEmptyString(value.sourceUrl) && isOptionalNonEmptyString(value.revision) && (value.sourceSha256 === void 0 || typeof value.sourceSha256 === "string" && /^[0-9a-f]{64}$/.test(value.sourceSha256));
|
|
482
|
+
}
|
|
483
|
+
function isModules(value) {
|
|
484
|
+
return value === void 0 || Array.isArray(value) && value.every((module) => isRecord(module) && isNonEmptyString(module.module) && typeof module.sourceSha256 === "string" && /^[0-9a-f]{64}$/.test(module.sourceSha256));
|
|
485
|
+
}
|
|
486
|
+
function isPythonRuntime(value) {
|
|
487
|
+
return value === void 0 || isRecord(value) && isNonEmptyString(value.implementation) && isNonEmptyString(value.version);
|
|
488
|
+
}
|
|
489
|
+
function isModels(value) {
|
|
490
|
+
return value === void 0 || isRecord(value) && (value.candidate === void 0 || agentProfileModelHintsSchema.safeParse(value.candidate).success) && isOptionalNonEmptyString(value.optimizer) && (value.candidate !== void 0 || value.optimizer !== void 0);
|
|
491
|
+
}
|
|
492
|
+
function isUsage(value) {
|
|
493
|
+
if (!isRecord(value) || !isNonNegativeInteger(value.optimizerEvaluations)) return false;
|
|
494
|
+
if (value.optimizerTokens === void 0) return true;
|
|
495
|
+
const tokens = value.optimizerTokens;
|
|
496
|
+
if (!isRecord(tokens)) return false;
|
|
497
|
+
const inputTokens = tokens.inputTokens;
|
|
498
|
+
const outputTokens = tokens.outputTokens;
|
|
499
|
+
const totalTokens = tokens.totalTokens;
|
|
500
|
+
const calls = tokens.calls;
|
|
501
|
+
if (!isNonNegativeInteger(inputTokens) || !isNonNegativeInteger(outputTokens) || !isNonNegativeInteger(totalTokens) || !isNonNegativeInteger(calls)) return false;
|
|
502
|
+
if (!isOptionalNonNegativeInteger(tokens.cachedInputTokens) || !isOptionalNonNegativeInteger(tokens.cacheWriteInputTokens) || !isOptionalNonNegativeInteger(tokens.reasoningTokens)) return false;
|
|
503
|
+
const cachedInputTokens = typeof tokens.cachedInputTokens === "number" ? tokens.cachedInputTokens : 0;
|
|
504
|
+
const cacheWriteInputTokens = typeof tokens.cacheWriteInputTokens === "number" ? tokens.cacheWriteInputTokens : 0;
|
|
505
|
+
const reasoningTokens = typeof tokens.reasoningTokens === "number" ? tokens.reasoningTokens : 0;
|
|
506
|
+
return totalTokens === inputTokens + outputTokens && cachedInputTokens + cacheWriteInputTokens <= inputTokens && reasoningTokens <= outputTokens && (totalTokens === 0 || calls > 0);
|
|
507
|
+
}
|
|
508
|
+
function isCost(value) {
|
|
509
|
+
if (!isRecord(value) || !isCostPart(value.optimization) || !isCostPart(value.finalTest) || !isCostPart(value.total)) return false;
|
|
510
|
+
const optimization = value.optimization;
|
|
511
|
+
const finalTest = value.finalTest;
|
|
512
|
+
const total = value.total;
|
|
513
|
+
return approximatelyEqual(total.totalUsd, optimization.totalUsd + finalTest.totalUsd) && total.accountingComplete === (optimization.accountingComplete && finalTest.accountingComplete);
|
|
514
|
+
}
|
|
515
|
+
function isCostPart(value) {
|
|
516
|
+
return isRecord(value) && typeof value.totalUsd === "number" && Number.isFinite(value.totalUsd) && value.totalUsd >= 0 && typeof value.accountingComplete === "boolean" && Array.isArray(value.incompleteReasons) && value.incompleteReasons.every((reason) => typeof reason === "string");
|
|
517
|
+
}
|
|
518
|
+
function receiptCost(value) {
|
|
519
|
+
return {
|
|
520
|
+
totalUsd: value.totalCostUsd,
|
|
521
|
+
accountingComplete: value.accountingComplete,
|
|
522
|
+
incompleteReasons: [...value.incompleteReasons]
|
|
523
|
+
};
|
|
524
|
+
}
|
|
525
|
+
function approximatelyEqual(left, right) {
|
|
526
|
+
const tolerance = Number.EPSILON * Math.max(1, Math.abs(left), Math.abs(right)) * 8;
|
|
527
|
+
return Math.abs(left - right) <= tolerance;
|
|
528
|
+
}
|
|
529
|
+
function isInvocation(value) {
|
|
530
|
+
return isRecord(value) && isNonEmptyString(value.runtimeInvocationId) && isNonEmptyString(value.optimizerRunId) && isOptionalNonEmptyString(value.compatibleOptimizerRunId) && typeof value.resumed === "boolean" && isNonEmptyString(value.artifactDir);
|
|
531
|
+
}
|
|
532
|
+
function isRecord(value) {
|
|
533
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
534
|
+
}
|
|
535
|
+
function isNonEmptyString(value) {
|
|
536
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
537
|
+
}
|
|
538
|
+
function isOptionalNonEmptyString(value) {
|
|
539
|
+
return value === void 0 || isNonEmptyString(value);
|
|
540
|
+
}
|
|
541
|
+
function isNonNegativeInteger(value) {
|
|
542
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
543
|
+
}
|
|
544
|
+
function isPositiveSafeInteger(value) {
|
|
545
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
|
|
546
|
+
}
|
|
547
|
+
function isOptionalNonNegativeInteger(value) {
|
|
548
|
+
return value === void 0 || isNonNegativeInteger(value);
|
|
549
|
+
}
|
|
550
|
+
function isSha256Digest(value) {
|
|
551
|
+
return typeof value === "string" && /^sha256:[0-9a-f]{64}$/.test(value);
|
|
552
|
+
}
|
|
553
|
+
//#endregion
|
|
554
|
+
//#region src/intelligence/activation.ts
|
|
555
|
+
/** Create the exact result a product stores in the same transaction as its target write. */
|
|
556
|
+
function createAgentImprovementActivationResult(transition, options) {
|
|
557
|
+
const activation = verifyCanonicalCandidateDocument(agentImprovementActivationSchema.parse(transition.activation), "agent improvement activation");
|
|
558
|
+
assertTransitionInput(activation, transition);
|
|
559
|
+
const result = agentImprovementActivationResultSchema.parse(canonicalCandidateDocument({
|
|
560
|
+
kind: "agent-improvement-activation-result",
|
|
561
|
+
idempotencyKey: activation.digest,
|
|
562
|
+
attemptedAt: transition.attemptedAt,
|
|
563
|
+
completedAt: options.completedAt,
|
|
564
|
+
outcome: options.outcome
|
|
565
|
+
}).value);
|
|
566
|
+
assertResultAgainstActivation(activation, result);
|
|
567
|
+
assertOutcomeDesiredState(activation, result, new Map(transition.targets.map((target) => [targetIdentity(target), target.desiredDigest])));
|
|
568
|
+
return immutableCandidateValue(result);
|
|
569
|
+
}
|
|
570
|
+
/**
|
|
571
|
+
* Recompute one historical activation result against the exact measured proposal and authority.
|
|
572
|
+
* The result records that attempt; it is not a query of the target's current state.
|
|
573
|
+
*/
|
|
574
|
+
function verifyAgentImprovementActivationResult(input) {
|
|
575
|
+
const proposal = verifyAgentImprovementProposal(input.proposal);
|
|
576
|
+
const activation = verifyAgentImprovementActivation(input);
|
|
577
|
+
const result = verifyCanonicalCandidateDocument(agentImprovementActivationResultSchema.parse(input.result), "agent improvement activation result");
|
|
578
|
+
assertResultAgainstActivation(activation, result);
|
|
579
|
+
assertResultDesiredState(proposal, activation, result);
|
|
580
|
+
return result;
|
|
581
|
+
}
|
|
582
|
+
/** Validate and execute one product-owned activation transition. */
|
|
583
|
+
async function executeAgentImprovementActivation(input, options) {
|
|
584
|
+
const proposal = verifyAgentImprovementProposal(input.proposal);
|
|
585
|
+
const activation = verifyAgentImprovementActivation(input);
|
|
586
|
+
const observedAt = (options.now ?? (() => /* @__PURE__ */ new Date()))().toISOString();
|
|
587
|
+
const attemptedAt = Date.parse(observedAt) < Date.parse(activation.authorizedAt) ? activation.authorizedAt : observedAt;
|
|
588
|
+
const expired = Date.parse(attemptedAt) >= Date.parse(activation.expiresAt);
|
|
589
|
+
const transition = immutableCandidateValue(proposal.evaluation.kind === "agent-improvement-measured-comparison" ? sealedCandidateTransition(proposal.evaluation.experiment, activation, attemptedAt, expired) : profileImprovementTransition(proposal.evaluation.experiment, activation, attemptedAt, expired));
|
|
590
|
+
if (transition.expired) {
|
|
591
|
+
if (!options.reconcile) return uncertainActivationResult(transition, "RECONCILIATION_UNAVAILABLE");
|
|
592
|
+
let reconciled;
|
|
593
|
+
try {
|
|
594
|
+
reconciled = await options.reconcile(transition);
|
|
595
|
+
} catch {
|
|
596
|
+
return uncertainActivationResult(transition, "RECONCILIATION_THROW");
|
|
597
|
+
}
|
|
598
|
+
if (reconciled === void 0) return createAgentImprovementActivationResult(transition, {
|
|
599
|
+
completedAt: transition.attemptedAt,
|
|
600
|
+
outcome: { status: "expired" }
|
|
601
|
+
});
|
|
602
|
+
try {
|
|
603
|
+
return verifyAgentImprovementActivationResult({
|
|
604
|
+
...input,
|
|
605
|
+
result: reconciled
|
|
606
|
+
});
|
|
607
|
+
} catch {
|
|
608
|
+
return uncertainActivationResult(transition, "INVALID_RECONCILIATION");
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
let rawResult;
|
|
612
|
+
try {
|
|
613
|
+
rawResult = await options.transition(transition);
|
|
614
|
+
} catch {
|
|
615
|
+
return uncertainActivationResult(transition, "TRANSITION_THROW");
|
|
616
|
+
}
|
|
617
|
+
try {
|
|
618
|
+
return verifyAgentImprovementActivationResult({
|
|
619
|
+
...input,
|
|
620
|
+
result: rawResult
|
|
621
|
+
});
|
|
622
|
+
} catch {
|
|
623
|
+
return uncertainActivationResult(transition, "INVALID_RESULT");
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
function sealedCandidateTransition(experiment, activation, attemptedAt, expired) {
|
|
627
|
+
const targetArm = activation.intent === "activate-candidate" ? "candidate" : "baseline";
|
|
628
|
+
return {
|
|
629
|
+
kind: "sealed-candidate",
|
|
630
|
+
activation,
|
|
631
|
+
candidateBundle: experiment.candidate,
|
|
632
|
+
bundle: experiment[targetArm],
|
|
633
|
+
targets: activation.targets.map((target) => ({
|
|
634
|
+
...target,
|
|
635
|
+
desiredDigest: agentImprovementTargetDigest(experiment, targetArm, target.surface),
|
|
636
|
+
desiredInput: agentImprovementTargetInput(experiment[targetArm], target.surface)
|
|
637
|
+
})),
|
|
638
|
+
attemptedAt,
|
|
639
|
+
expired
|
|
640
|
+
};
|
|
641
|
+
}
|
|
642
|
+
function profileImprovementTransition(experiment, activation, attemptedAt, expired) {
|
|
643
|
+
const sourceArm = activation.intent === "activate-candidate" ? "baseline" : "candidate";
|
|
644
|
+
const targetArm = activation.intent === "activate-candidate" ? "candidate" : "baseline";
|
|
645
|
+
const operation = profileImprovementOperation(experiment, activation.intent);
|
|
646
|
+
return {
|
|
647
|
+
kind: "profile-improvement",
|
|
648
|
+
activation,
|
|
649
|
+
experiment,
|
|
650
|
+
sourceStateDigest: agentProfileImprovementStateDigest(experiment, sourceArm),
|
|
651
|
+
desiredStateDigest: agentProfileImprovementStateDigest(experiment, targetArm),
|
|
652
|
+
operation,
|
|
653
|
+
targets: activation.targets.map((target) => ({
|
|
654
|
+
...target,
|
|
655
|
+
desiredDigest: agentProfileImprovementStateDigest(experiment, targetArm),
|
|
656
|
+
desiredInput: operation
|
|
657
|
+
})),
|
|
658
|
+
attemptedAt,
|
|
659
|
+
expired
|
|
660
|
+
};
|
|
661
|
+
}
|
|
662
|
+
function profileImprovementOperation(experiment, intent) {
|
|
663
|
+
return intent === "activate-candidate" ? {
|
|
664
|
+
kind: "apply-change",
|
|
665
|
+
changes: experiment.change
|
|
666
|
+
} : { kind: "restore-state" };
|
|
667
|
+
}
|
|
668
|
+
function uncertainActivationResult(transition, code) {
|
|
669
|
+
return createAgentImprovementActivationResult(transition, {
|
|
670
|
+
completedAt: transition.attemptedAt,
|
|
671
|
+
outcome: {
|
|
672
|
+
status: "indeterminate",
|
|
673
|
+
code,
|
|
674
|
+
message: "The product transition did not return a trustworthy commit result."
|
|
675
|
+
}
|
|
676
|
+
});
|
|
677
|
+
}
|
|
678
|
+
function assertTransitionInput(activation, transition) {
|
|
679
|
+
if (transition.kind === "sealed-candidate") {
|
|
680
|
+
assertSealedCandidateTransitionInput(activation, transition);
|
|
681
|
+
return;
|
|
682
|
+
}
|
|
683
|
+
assertProfileImprovementTransitionInput(activation, transition);
|
|
684
|
+
}
|
|
685
|
+
function assertSealedCandidateTransitionInput(activation, transition) {
|
|
686
|
+
assertAuthorizedTransitionTargets(activation, transition.targets);
|
|
687
|
+
const desiredInputsMatch = transition.targets.every((target) => canonicalCandidateDigest$1(target.desiredInput) === canonicalCandidateDigest$1(agentImprovementTargetInput(transition.bundle, target.surface)));
|
|
688
|
+
if (transition.expired !== Date.parse(transition.attemptedAt) >= Date.parse(activation.expiresAt) || transition.candidateBundle.digest !== activation.candidateDigest || !desiredInputsMatch || activation.intent === "activate-candidate" && transition.bundle.digest !== transition.candidateBundle.digest) throw new Error("activation transition does not match its authorization");
|
|
689
|
+
}
|
|
690
|
+
function assertProfileImprovementTransitionInput(activation, transition) {
|
|
691
|
+
assertAuthorizedTransitionTargets(activation, transition.targets);
|
|
692
|
+
const targetsAgentProfile = activation.targets.some((target) => target.surface === "agent-profile");
|
|
693
|
+
const experiment = agentProfileImprovementExperimentSchema.parse(transition.experiment);
|
|
694
|
+
const sourceArm = activation.intent === "activate-candidate" ? "baseline" : "candidate";
|
|
695
|
+
const targetArm = activation.intent === "activate-candidate" ? "candidate" : "baseline";
|
|
696
|
+
const sourceStateDigest = agentProfileImprovementStateDigest(experiment, sourceArm);
|
|
697
|
+
const desiredStateDigest = agentProfileImprovementStateDigest(experiment, targetArm);
|
|
698
|
+
const operation = profileImprovementOperation(experiment, activation.intent);
|
|
699
|
+
const targetsMatch = transition.targets.every((target) => target.expectedBaseDigest === sourceStateDigest && target.desiredDigest === desiredStateDigest && canonicalCandidateDigest$1(target.desiredInput) === canonicalCandidateDigest$1(operation));
|
|
700
|
+
if (transition.expired !== Date.parse(transition.attemptedAt) >= Date.parse(activation.expiresAt) || experiment.digest !== activation.experimentDigest || experiment.candidate.stateDigest !== activation.candidateDigest || targetsAgentProfile && (activation.executionRef === void 0 || canonicalCandidateDigest$1(activation.executionRef) !== canonicalCandidateDigest$1(experiment.executionRef)) || transition.sourceStateDigest !== sourceStateDigest || transition.desiredStateDigest !== desiredStateDigest || canonicalCandidateDigest$1(transition.operation) !== canonicalCandidateDigest$1(operation) || !targetsMatch) throw new Error("activation transition does not match its authorization");
|
|
701
|
+
}
|
|
702
|
+
function assertAuthorizedTransitionTargets(activation, targets) {
|
|
703
|
+
const authorized = targetMap(activation.targets);
|
|
704
|
+
const planned = targetMap(targets);
|
|
705
|
+
if (authorized.size !== planned.size || [...authorized.entries()].some(([identity, target]) => planned.get(identity)?.expectedBaseDigest !== target.expectedBaseDigest)) throw new Error("activation transition does not match its authorization");
|
|
706
|
+
}
|
|
707
|
+
function assertResultAgainstActivation(activation, result) {
|
|
708
|
+
const attemptedAt = Date.parse(result.attemptedAt);
|
|
709
|
+
const completedAt = Date.parse(result.completedAt);
|
|
710
|
+
const expiresAt = Date.parse(activation.expiresAt);
|
|
711
|
+
if (result.idempotencyKey !== activation.digest || attemptedAt < Date.parse(activation.authorizedAt) || completedAt < attemptedAt) throw new Error("activation result does not bind its authorization");
|
|
712
|
+
const expired = attemptedAt >= expiresAt;
|
|
713
|
+
if (result.outcome.status === "expired" && !expired || expired && ![
|
|
714
|
+
"expired",
|
|
715
|
+
"indeterminate",
|
|
716
|
+
"already-applied"
|
|
717
|
+
].includes(result.outcome.status)) throw new Error("activation result does not honor its authorization expiry");
|
|
718
|
+
if (!("targets" in result.outcome)) return;
|
|
719
|
+
const authorized = targetMap(activation.targets);
|
|
720
|
+
const observed = new Set(result.outcome.targets.map(targetIdentity));
|
|
721
|
+
if (authorized.size !== observed.size || [...authorized.keys()].some((identity) => !observed.has(identity))) throw new Error("activation result must cover every authorized target exactly once");
|
|
722
|
+
if (result.outcome.status === "applied" && result.outcome.targets.some((target) => target.beforeDigest !== authorized.get(targetIdentity(target))?.expectedBaseDigest)) throw new Error("applied activation did not start from its authorized base state");
|
|
723
|
+
}
|
|
724
|
+
function assertResultDesiredState(proposal, activation, result) {
|
|
725
|
+
if (!("targets" in result.outcome)) return;
|
|
726
|
+
const targetArm = activation.intent === "activate-candidate" ? "candidate" : "baseline";
|
|
727
|
+
const desiredStateDigest = proposal.evaluation.kind === "agent-profile-improvement-measured-comparison" ? agentProfileImprovementStateDigest(proposal.evaluation.experiment, targetArm) : void 0;
|
|
728
|
+
assertOutcomeDesiredState(activation, result, new Map(activation.targets.map((target) => [targetIdentity(target), desiredStateDigest ?? agentImprovementTargetDigest(requireSealedCandidateExperiment(proposal), targetArm, target.surface)])));
|
|
729
|
+
}
|
|
730
|
+
function assertOutcomeDesiredState(activation, result, desired) {
|
|
731
|
+
if (!("targets" in result.outcome)) return;
|
|
732
|
+
if (result.outcome.status === "applied") {
|
|
733
|
+
if (result.outcome.targets.some((target) => target.afterDigest !== desired.get(targetIdentity(target)))) throw new Error("applied activation does not match the requested bundle");
|
|
734
|
+
return;
|
|
735
|
+
}
|
|
736
|
+
const allDesired = result.outcome.targets.every((target) => target.currentDigest === desired.get(targetIdentity(target)));
|
|
737
|
+
if (result.outcome.status === "already-applied") {
|
|
738
|
+
if (!allDesired) throw new Error("already-applied activation is not at the requested state");
|
|
739
|
+
return;
|
|
740
|
+
}
|
|
741
|
+
const authorized = targetMap(activation.targets);
|
|
742
|
+
const hasStaleTarget = result.outcome.targets.some((target) => target.currentDigest !== authorized.get(targetIdentity(target))?.expectedBaseDigest);
|
|
743
|
+
if (allDesired || !hasStaleTarget) throw new Error("activation conflict does not identify stale target state");
|
|
744
|
+
}
|
|
745
|
+
function targetMap(targets) {
|
|
746
|
+
return new Map(targets.map((target) => [targetIdentity(target), target]));
|
|
747
|
+
}
|
|
748
|
+
function targetIdentity(target) {
|
|
749
|
+
return `${target.surface}\u0000${target.identity}`;
|
|
750
|
+
}
|
|
751
|
+
/** Create the reviewable record only from a complete, recomputable experiment result. */
|
|
752
|
+
function createAgentImprovementProposal(options) {
|
|
753
|
+
const findings = assertProposalFindings(options.findings, "createAgentImprovementProposal findings");
|
|
754
|
+
const { evaluation, changedSurfaces } = validateShippableAgentImprovementEvaluation(options.evaluation, options.runId, "agent improvement proposal");
|
|
755
|
+
return agentImprovementProposalSchema.parse(canonicalCandidateDocument({
|
|
756
|
+
kind: "agent-improvement-proposal",
|
|
757
|
+
runId: options.runId,
|
|
758
|
+
changedSurfaces,
|
|
759
|
+
proposedAt: (options.now ?? (() => /* @__PURE__ */ new Date()))().toISOString(),
|
|
760
|
+
findings: [...findings],
|
|
761
|
+
evaluation
|
|
762
|
+
}).value);
|
|
763
|
+
}
|
|
764
|
+
/** Persist a human or tenant-policy decision bound to one exact proposal. */
|
|
765
|
+
function reviewAgentImprovementProposal(inputProposal, input) {
|
|
766
|
+
const proposal = verifyAgentImprovementProposal(inputProposal);
|
|
767
|
+
if (!input.reviewedBy.trim()) throw new Error("candidate review requires reviewedBy");
|
|
768
|
+
if (!input.reason.trim()) throw new Error("candidate review requires a reason");
|
|
769
|
+
if (input.decision === "approve" && proposal.evaluation.decision.outcome !== "ship") throw new Error("candidate cannot be approved without a passing experiment");
|
|
770
|
+
const reviewedAt = (input.now ?? (() => /* @__PURE__ */ new Date()))().toISOString();
|
|
771
|
+
if (Date.parse(reviewedAt) < Date.parse(proposal.proposedAt)) throw new Error("candidate review cannot predate its proposal");
|
|
772
|
+
return agentImprovementReviewSchema.parse(canonicalCandidateDocument({
|
|
773
|
+
kind: "agent-improvement-review",
|
|
774
|
+
proposalDigest: proposal.digest,
|
|
775
|
+
decision: input.decision,
|
|
776
|
+
reviewedBy: input.reviewedBy,
|
|
777
|
+
reviewedAt,
|
|
778
|
+
reason: input.reason,
|
|
779
|
+
...input.feedback === void 0 ? {} : { feedback: input.feedback }
|
|
780
|
+
}).value);
|
|
781
|
+
}
|
|
782
|
+
/** Authorize product-owned writes only after the exact candidate was measured and approved. */
|
|
783
|
+
function createAgentImprovementActivation(inputProposal, inputReview, options) {
|
|
784
|
+
const proposal = verifyAgentImprovementProposal(inputProposal);
|
|
785
|
+
const review = verifyAgentImprovementReview(inputReview);
|
|
786
|
+
if (review.decision !== "approve" || review.proposalDigest !== proposal.digest) throw new Error("candidate activation requires an approval for the exact proposal");
|
|
787
|
+
if (!options.fundingOwner.trim() || !options.authorizedBy.trim()) throw new Error("candidate activation authority must be non-empty");
|
|
788
|
+
const experiment = proposal.evaluation.experiment;
|
|
789
|
+
const authorizedAt = (options.now ?? (() => /* @__PURE__ */ new Date()))().toISOString();
|
|
790
|
+
if (Date.parse(authorizedAt) < Date.parse(review.reviewedAt)) throw new Error("candidate activation cannot predate its approval");
|
|
791
|
+
const targets = buildAgentImprovementActivationTargets(proposal.changedSurfaces, experiment, options.intent, options.targets);
|
|
792
|
+
const executionRef = profileActivationExecutionRef(experiment, targets, options.executionRef);
|
|
793
|
+
return agentImprovementActivationSchema.parse(canonicalCandidateDocument({
|
|
794
|
+
kind: "agent-improvement-activation",
|
|
795
|
+
proposalDigest: proposal.digest,
|
|
796
|
+
reviewDigest: review.digest,
|
|
797
|
+
experimentDigest: experiment.digest,
|
|
798
|
+
candidateDigest: measuredCandidateDigest(proposal),
|
|
799
|
+
...executionRef ? { executionRef } : {},
|
|
800
|
+
intent: options.intent,
|
|
801
|
+
targets,
|
|
802
|
+
fundingOwner: options.fundingOwner,
|
|
803
|
+
authorizedBy: options.authorizedBy,
|
|
804
|
+
authorizedAt,
|
|
805
|
+
expiresAt: options.expiresAt
|
|
806
|
+
}).value);
|
|
807
|
+
}
|
|
808
|
+
/** Validate a proposal and recompute every binding to its measured experiment. */
|
|
809
|
+
function verifyAgentImprovementProposal(input) {
|
|
810
|
+
const proposal = verifyCanonicalCandidateDocument(agentImprovementProposalSchema.parse(input), "agent improvement proposal");
|
|
811
|
+
const { changedSurfaces } = validateShippableAgentImprovementEvaluation(proposal.evaluation, proposal.runId, "agent improvement proposal");
|
|
812
|
+
if (!(proposal.evaluation.kind === "agent-profile-improvement-measured-comparison" ? sameAgentImprovementSurfaceSet(proposal.changedSurfaces, changedSurfaces) : sameOrderedValues(proposal.changedSurfaces, changedSurfaces))) throw new Error("proposal changed surfaces do not match its exact experiment");
|
|
813
|
+
assertProposalFindings(proposal.findings, "agent improvement proposal findings");
|
|
814
|
+
return proposal;
|
|
815
|
+
}
|
|
816
|
+
/** Return a sealed bundle experiment; ordinary profile changes need a product-owned executor. */
|
|
817
|
+
function requireSealedCandidateExperiment(proposal) {
|
|
818
|
+
if (proposal.evaluation.kind !== "agent-improvement-measured-comparison") throw new Error("agent profile improvement activation requires a product profile-diff executor, not a sealed candidate bundle");
|
|
819
|
+
return proposal.evaluation.experiment;
|
|
820
|
+
}
|
|
821
|
+
function measuredCandidateDigest(proposal) {
|
|
822
|
+
return proposal.evaluation.kind === "agent-profile-improvement-measured-comparison" ? proposal.evaluation.experiment.candidate.stateDigest : proposal.evaluation.experiment.candidate.digest;
|
|
823
|
+
}
|
|
824
|
+
function profileActivationExecutionRef(experiment, targets, executionRef) {
|
|
825
|
+
if (!targets.some((target) => target.surface === "agent-profile")) {
|
|
826
|
+
if (executionRef !== void 0) throw new Error("profile activation executionRef is valid only for agent-profile targets");
|
|
827
|
+
return;
|
|
828
|
+
}
|
|
829
|
+
if (experiment.kind !== "agent-profile-improvement-experiment") throw new Error("agent-profile activation requires a measured profile experiment");
|
|
830
|
+
if (executionRef === void 0) throw new Error("profile improvement activation requires the measured executor");
|
|
831
|
+
const parsed = agentProfileImprovementExecutionRefSchema.parse(executionRef);
|
|
832
|
+
if (canonicalCandidateDigest$1(parsed) !== canonicalCandidateDigest$1(experiment.executionRef)) throw new Error("profile improvement activation executor does not match the measurement");
|
|
833
|
+
return parsed;
|
|
834
|
+
}
|
|
835
|
+
function validateShippableAgentImprovementEvaluation(input, runId, subject) {
|
|
836
|
+
const evaluation = verifyAgentImprovementEvaluation(input);
|
|
837
|
+
if (evaluation.decision.outcome !== "ship") throw new Error(`${subject} requires a passing experiment`);
|
|
838
|
+
if (runId !== evaluation.provenance.runId) throw new Error("proposal runId does not match its measured experiment");
|
|
839
|
+
return {
|
|
840
|
+
evaluation,
|
|
841
|
+
changedSurfaces: evaluation.kind === "agent-profile-improvement-measured-comparison" ? profileImprovementChangedSurfaces(evaluation.experiment.change) : deriveChangedSurfaces(evaluation.experiment.baseline, evaluation.experiment.candidate)
|
|
842
|
+
};
|
|
843
|
+
}
|
|
844
|
+
/** Use each owning package's complete measurement validator before a proposal is persisted. */
|
|
845
|
+
function verifyAgentImprovementEvaluation(input) {
|
|
846
|
+
if (typeof input === "object" && input !== null && "kind" in input && input.kind === "agent-profile-improvement-measured-comparison") {
|
|
847
|
+
const evaluation = verifyAgentProfileImprovementExperimentComparison(input);
|
|
848
|
+
optimizationActivationReceiptFromMetadata(evaluation.metadata);
|
|
849
|
+
return evaluation;
|
|
850
|
+
}
|
|
851
|
+
const evaluation = verifyCandidateExperimentComparison(input);
|
|
852
|
+
optimizationActivationReceiptFromMetadata(evaluation.metadata);
|
|
853
|
+
return evaluation;
|
|
854
|
+
}
|
|
855
|
+
/** Validate the canonical identity and wire shape of an improvement review. */
|
|
856
|
+
function verifyAgentImprovementReview(input) {
|
|
857
|
+
return verifyCanonicalCandidateDocument(agentImprovementReviewSchema.parse(input), "agent improvement review");
|
|
858
|
+
}
|
|
859
|
+
/** Validate activation authority against the exact proposal, review, experiment, and base state. */
|
|
860
|
+
function verifyAgentImprovementActivation(input) {
|
|
861
|
+
const proposal = verifyAgentImprovementProposal(input.proposal);
|
|
862
|
+
const review = verifyAgentImprovementReview(input.review);
|
|
863
|
+
const activation = verifyCanonicalCandidateDocument(agentImprovementActivationSchema.parse(input.activation), "agent improvement activation");
|
|
864
|
+
const experiment = proposal.evaluation.experiment;
|
|
865
|
+
if (review.decision !== "approve" || review.proposalDigest !== proposal.digest || activation.proposalDigest !== proposal.digest || activation.reviewDigest !== review.digest || activation.experimentDigest !== experiment.digest || activation.candidateDigest !== measuredCandidateDigest(proposal) || Date.parse(review.reviewedAt) < Date.parse(proposal.proposedAt) || Date.parse(activation.authorizedAt) < Date.parse(review.reviewedAt)) throw new Error("candidate activation does not bind the measured and approved candidate");
|
|
866
|
+
if (activation.targets.some((target) => target.surface === "agent-profile") && (proposal.evaluation.kind !== "agent-profile-improvement-measured-comparison" || activation.executionRef === void 0 || canonicalCandidateDigest$1(activation.executionRef) !== canonicalCandidateDigest$1(proposal.evaluation.experiment.executionRef))) throw new Error("profile activation does not bind the measured executor");
|
|
867
|
+
assertAgentImprovementActivationTargets(proposal.changedSurfaces, experiment, activation.intent, activation.targets);
|
|
868
|
+
return activation;
|
|
869
|
+
}
|
|
870
|
+
function sameOrderedValues(left, right) {
|
|
871
|
+
return left.length === right.length && left.every((value, index) => value === right[index]);
|
|
872
|
+
}
|
|
873
|
+
//#endregion
|
|
874
|
+
export { serializeRolloutPolicy as C, normalizeRolloutPolicy as S, agentImprovementTargetProfileDiffs as _, reviewAgentImprovementProposal as a, isAgentProfileMeasuredSurface as b, verifyAgentImprovementProposal as c, attachOptimizationActivationReceipt as d, createOptimizationActivationReceipt as f, agentImprovementProfileSurfaceInput as g, agentImprovementProfileSurfaceDigest as h, executeAgentImprovementActivation as i, verifyAgentImprovementReview as l, agentImprovementProfileDiffs as m, createAgentImprovementActivationResult as n, verifyAgentImprovementActivation as o, optimizationActivationReceiptFromMetadata as p, createAgentImprovementProposal as r, verifyAgentImprovementActivationResult as s, createAgentImprovementActivation as t, assertNoCallerOptimizationReceipt as u, assertProfileImprovementTargetsShareIdentity as v, structuralRolloutPolicyFromProfile as w, applyRolloutPolicyToProfile as x, isAgentImprovementProfileSurface as y };
|
|
875
|
+
|
|
876
|
+
//# sourceMappingURL=activation-CVSFxis9.js.map
|