pi-background-tasks 2.5.0 → 2.6.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/BACKGROUND-TASKS-INSTRUCTIONS.md +1 -1
- package/README.md +70 -25
- package/TESTING.md +42 -2
- package/TEST_PLAN.md +7 -4
- package/dist/extensions/anthropic-attribution-child.js +4 -0
- package/dist/extensions/anthropic-attribution-child.js.map +1 -0
- package/dist/extensions/anthropic-attribution.js +107 -0
- package/dist/extensions/anthropic-attribution.js.map +1 -0
- package/dist/extensions/background-tasks.js +2 -0
- package/dist/extensions/background-tasks.js.map +1 -0
- package/dist/extensions/delegate-child.js +2 -0
- package/dist/extensions/delegate-child.js.map +1 -0
- package/dist/extensions/fusion-child.js +2 -0
- package/dist/extensions/fusion-child.js.map +1 -0
- package/dist/package.json +5 -0
- package/dist/src/core/anthropic-attribution-path.js +24 -0
- package/dist/src/core/anthropic-attribution-path.js.map +1 -0
- package/dist/src/core/anthropic-attribution.js +2247 -0
- package/dist/src/core/anthropic-attribution.js.map +1 -0
- package/dist/src/core/attested-pi-contract.js +5 -0
- package/dist/src/core/attested-pi-contract.js.map +1 -0
- package/dist/src/core/attested-pi-run.js +749 -0
- package/dist/src/core/attested-pi-run.js.map +1 -0
- package/dist/src/core/canonical-json.js +19 -0
- package/dist/src/core/canonical-json.js.map +1 -0
- package/dist/src/core/common.js +787 -0
- package/dist/src/core/common.js.map +1 -0
- package/dist/src/core/config.js +78 -0
- package/dist/src/core/config.js.map +1 -0
- package/dist/src/core/context/parent-snapshot.js +75 -0
- package/dist/src/core/context/parent-snapshot.js.map +1 -0
- package/dist/src/core/context/token-budget.js +631 -0
- package/dist/src/core/context/token-budget.js.map +1 -0
- package/dist/src/core/context/visible-conversation-v2.js +390 -0
- package/dist/src/core/context/visible-conversation-v2.js.map +1 -0
- package/dist/src/core/delegate/artifacts.js +357 -0
- package/dist/src/core/delegate/artifacts.js.map +1 -0
- package/dist/src/core/delegate/budget.js +266 -0
- package/dist/src/core/delegate/budget.js.map +1 -0
- package/dist/src/core/delegate/facade-contract.js +7 -0
- package/dist/src/core/delegate/facade-contract.js.map +1 -0
- package/dist/src/core/delegate/hook-contract-evidence.json +18 -0
- package/dist/src/core/delegate/hook-contract.js +124 -0
- package/dist/src/core/delegate/hook-contract.js.map +1 -0
- package/dist/src/core/delegate/launch.js +366 -0
- package/dist/src/core/delegate/launch.js.map +1 -0
- package/dist/src/core/delegate/result-package.js +293 -0
- package/dist/src/core/delegate/result-package.js.map +1 -0
- package/dist/src/core/delegate/runner.js +398 -0
- package/dist/src/core/delegate/runner.js.map +1 -0
- package/dist/src/core/delegate/seed.js +334 -0
- package/dist/src/core/delegate/seed.js.map +1 -0
- package/dist/src/core/delegate/types.js +103 -0
- package/dist/src/core/delegate/types.js.map +1 -0
- package/dist/src/core/durable-fs.js +372 -0
- package/dist/src/core/durable-fs.js.map +1 -0
- package/dist/src/core/extension-api.js +382 -0
- package/dist/src/core/extension-api.js.map +1 -0
- package/dist/src/core/fusion/artifacts.js +654 -0
- package/dist/src/core/fusion/artifacts.js.map +1 -0
- package/dist/src/core/fusion/budget.js +949 -0
- package/dist/src/core/fusion/budget.js.map +1 -0
- package/dist/src/core/fusion/child-protocol.js +176 -0
- package/dist/src/core/fusion/child-protocol.js.map +1 -0
- package/dist/src/core/fusion/claude-cache.js +156 -0
- package/dist/src/core/fusion/claude-cache.js.map +1 -0
- package/dist/src/core/fusion/clean-context.js +64 -0
- package/dist/src/core/fusion/clean-context.js.map +1 -0
- package/dist/src/core/fusion/config.js +349 -0
- package/dist/src/core/fusion/config.js.map +1 -0
- package/dist/src/core/fusion/context.js +184 -0
- package/dist/src/core/fusion/context.js.map +1 -0
- package/dist/src/core/fusion/evaluation.js +696 -0
- package/dist/src/core/fusion/evaluation.js.map +1 -0
- package/dist/src/core/fusion/facade-contract.js +3 -0
- package/dist/src/core/fusion/facade-contract.js.map +1 -0
- package/dist/src/core/fusion/orchestrator.js +867 -0
- package/dist/src/core/fusion/orchestrator.js.map +1 -0
- package/dist/src/core/fusion/output-contract.js +27 -0
- package/dist/src/core/fusion/output-contract.js.map +1 -0
- package/dist/src/core/fusion/pi-child.js +1741 -0
- package/dist/src/core/fusion/pi-child.js.map +1 -0
- package/dist/src/core/fusion/prompts.js +260 -0
- package/dist/src/core/fusion/prompts.js.map +1 -0
- package/dist/src/core/fusion/result-package.js +857 -0
- package/dist/src/core/fusion/result-package.js.map +1 -0
- package/dist/src/core/fusion/source-policy.js +259 -0
- package/dist/src/core/fusion/source-policy.js.map +1 -0
- package/dist/src/core/fusion/types.js +207 -0
- package/dist/src/core/fusion/types.js.map +1 -0
- package/dist/src/core/fusion/web-fetch.js +777 -0
- package/dist/src/core/fusion/web-fetch.js.map +1 -0
- package/dist/src/core/fusion/workflows.js +126 -0
- package/dist/src/core/fusion/workflows.js.map +1 -0
- package/dist/src/core/lazy-module.js +181 -0
- package/dist/src/core/lazy-module.js.map +1 -0
- package/dist/src/core/pi-launch.js +431 -0
- package/dist/src/core/pi-launch.js.map +1 -0
- package/dist/src/core/registry.js +3331 -0
- package/dist/src/core/registry.js.map +1 -0
- package/dist/src/core/reload-shell-owner.js +1396 -0
- package/dist/src/core/reload-shell-owner.js.map +1 -0
- package/dist/src/core/shell-policy.js +80 -0
- package/dist/src/core/shell-policy.js.map +1 -0
- package/dist/src/core/task-durable.js +51 -0
- package/dist/src/core/task-durable.js.map +1 -0
- package/dist/src/core/update-check.js +92 -0
- package/dist/src/core/update-check.js.map +1 -0
- package/dist/src/core/windows-taskkill.js +185 -0
- package/dist/src/core/windows-taskkill.js.map +1 -0
- package/dist/src/delegate-child-extension.js +776 -0
- package/dist/src/delegate-child-extension.js.map +1 -0
- package/dist/src/delegate-extension.js +746 -0
- package/dist/src/delegate-extension.js.map +1 -0
- package/dist/src/extension.js +953 -0
- package/dist/src/extension.js.map +1 -0
- package/dist/src/fusion-child-extension.js +760 -0
- package/dist/src/fusion-child-extension.js.map +1 -0
- package/dist/src/fusion-extension.js +1030 -0
- package/dist/src/fusion-extension.js.map +1 -0
- package/dist/src/ui/background-tasks-manager.js +689 -0
- package/dist/src/ui/background-tasks-manager.js.map +1 -0
- package/dist/src/ui/fusion-model-selector.js +277 -0
- package/dist/src/ui/fusion-model-selector.js.map +1 -0
- package/docs/INDEX.md +35 -33
- package/docs/api/eventbus-v1.md +21 -5
- package/docs/choose-a-workflow.md +2 -0
- package/docs/commands/bg-clear.md +3 -3
- package/docs/commands/bg-update.md +3 -3
- package/docs/commands/bg.md +18 -6
- package/docs/commands/claude-cache.md +4 -4
- package/docs/commands/fusion-models.md +49 -4
- package/docs/commands/fusion.md +3 -3
- package/docs/commands/jobs.md +3 -3
- package/docs/commands/kill.md +3 -3
- package/docs/commands/logs.md +3 -3
- package/docs/commands/task-manager.md +5 -5
- package/docs/concepts/completion-delivery.md +6 -2
- package/docs/getting-started.md +7 -1
- package/docs/manifest.json +228 -42
- package/docs/operations/configuration.md +58 -5
- package/docs/operations/releasing.md +4 -2
- package/docs/operations/testing.md +22 -0
- package/docs/operations/troubleshooting.md +6 -2
- package/docs/read-before-edit.md +44 -31
- package/docs/reference/runtime-contracts.md +87 -51
- package/docs/reference/shortcuts-and-dock.md +28 -14
- package/docs/subsystems/anthropic-attribution.md +23 -11
- package/docs/subsystems/attested-pi-runs.md +12 -7
- package/docs/subsystems/background-task-runtime.md +53 -11
- package/docs/subsystems/child-launch-durability-and-safety.md +28 -9
- package/docs/subsystems/delegation.md +16 -3
- package/docs/subsystems/docs-freshness-gate.md +14 -7
- package/docs/subsystems/fusion.md +36 -11
- package/docs/subsystems/host-ui-and-telemetry.md +22 -9
- package/docs/tools/bg_delegate.md +3 -1
- package/docs/tools/bg_kill.md +3 -1
- package/docs/tools/bg_logs.md +3 -1
- package/docs/tools/bg_result.md +5 -3
- package/docs/tools/bg_run.md +31 -5
- package/docs/tools/bg_run_pi_attested.md +3 -1
- package/docs/tools/bg_status.md +3 -1
- package/docs/tools/fusion_investigate.md +3 -1
- package/docs/tools/fusion_reason.md +3 -1
- package/docs/tools/fusion_research.md +3 -1
- package/docs/tools/fusion_validate.md +3 -1
- package/extensions/anthropic-attribution-child.ts +3 -0
- package/extensions/anthropic-attribution.ts +166 -1
- package/package.json +12 -10
- package/src/core/anthropic-attribution-path.ts +5 -4
- package/src/core/anthropic-attribution.ts +293 -113
- package/src/core/attested-pi-contract.ts +4 -0
- package/src/core/attested-pi-run.ts +468 -81
- package/src/core/canonical-json.ts +21 -0
- package/src/core/common.ts +450 -40
- package/src/core/config.ts +121 -0
- package/src/core/context/visible-conversation-v2.ts +3 -6
- package/src/core/delegate/artifacts.ts +13 -9
- package/src/core/delegate/budget.ts +13 -6
- package/src/core/delegate/facade-contract.ts +6 -0
- package/src/core/delegate/result-package.ts +32 -14
- package/src/core/delegate/runner.ts +129 -58
- package/src/core/delegate/seed.ts +5 -7
- package/src/core/durable-fs.ts +178 -30
- package/src/core/extension-api.ts +36 -8
- package/src/core/fusion/artifacts.ts +17 -16
- package/src/core/fusion/clean-context.ts +8 -5
- package/src/core/fusion/config.ts +2 -1
- package/src/core/fusion/context.ts +2 -6
- package/src/core/fusion/facade-contract.ts +2 -0
- package/src/core/fusion/orchestrator.ts +3 -3
- package/src/core/fusion/prompts.ts +1 -1
- package/src/core/fusion/result-package.ts +259 -72
- package/src/core/fusion/source-policy.ts +43 -17
- package/src/core/lazy-module.ts +215 -0
- package/src/core/pi-launch.ts +390 -65
- package/src/core/registry.ts +2010 -381
- package/src/core/reload-shell-owner.ts +1662 -0
- package/src/core/shell-policy.ts +134 -0
- package/src/core/task-durable.ts +67 -0
- package/src/delegate-extension.ts +404 -144
- package/src/extension.ts +387 -114
- package/src/fusion-extension.ts +202 -96
|
@@ -0,0 +1,949 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { TOKEN_BUDGET_AFFINE_F_TOKENS, TOKEN_BUDGET_CALIBRATION_VERSION, TOKEN_BUDGET_FAMILY_CALIBRATIONS, TOKEN_BUDGET_LARGE_PROMPT_MIN_BYTES, TOKEN_BUDGET_RATE_SCALE, estimateInputTokens, knownTextSegment, maxKnownTextBytesForTokens, resolveTokenBudgetFamily, unknownOutputContractSegment, allowedInputTokens, isUsableContextWindow, } from '../context/token-budget.js';
|
|
3
|
+
import { buildBlindEvaluationInput, buildCandidatePrompt, buildEvaluationPrompt, buildEvaluationRepairPrompt, buildMergeInput, buildMergePrompt, } from './prompts.js';
|
|
4
|
+
import { FUSION_REASON_WORKFLOW } from './workflows.js';
|
|
5
|
+
import { FUSION_CANDIDATE_MAX_OUTPUT_BYTES, FUSION_DIAGNOSTICS_MAX_BYTES, FUSION_EVALUATION_MAX_OUTPUT_BYTES, FUSION_MERGE_MAX_OUTPUT_BYTES, } from './output-contract.js';
|
|
6
|
+
export { FUSION_CANDIDATE_MAX_OUTPUT_BYTES, FUSION_DIAGNOSTICS_MAX_BYTES, FUSION_EVALUATION_MAX_OUTPUT_BYTES, FUSION_MERGE_MAX_OUTPUT_BYTES, assertChildOutputWithinContract, fusionOutputContractBytes, } from './output-contract.js';
|
|
7
|
+
import { FUSION_BUDGET_PLAN_SCHEMA_VERSION, FUSION_CALIBRATION_VIOLATION_SCHEMA_VERSION, FUSION_EVALUATION_SCHEMA_VERSION, FusionError, } from './types.js';
|
|
8
|
+
export const FUSION_CALIBRATED_BYTES_PER_TOKEN = TOKEN_BUDGET_FAMILY_CALIBRATIONS;
|
|
9
|
+
const FUSION_OUTPUT_RESERVE_RATE_X100 = 200;
|
|
10
|
+
export const FUSION_UTILIZATION_WARNING_THRESHOLD_BASIS_POINTS = 8000;
|
|
11
|
+
const BASIS_POINTS_DENOMINATOR = 10_000;
|
|
12
|
+
function ceilDiv(numerator, denominator) {
|
|
13
|
+
if (!Number.isSafeInteger(numerator) || numerator < 0) {
|
|
14
|
+
throw new TypeError('ceilDiv numerator must be a non-negative safe integer');
|
|
15
|
+
}
|
|
16
|
+
if (!Number.isSafeInteger(denominator) || denominator <= 0) {
|
|
17
|
+
throw new TypeError('ceilDiv denominator must be a positive safe integer');
|
|
18
|
+
}
|
|
19
|
+
if (numerator === 0)
|
|
20
|
+
return 0;
|
|
21
|
+
return Math.floor((numerator - 1) / denominator) + 1;
|
|
22
|
+
}
|
|
23
|
+
export const FUSION_RESERVED_OUTPUT_TOKENS = ceilDiv(FUSION_MERGE_MAX_OUTPUT_BYTES * TOKEN_BUDGET_RATE_SCALE, FUSION_OUTPUT_RESERVE_RATE_X100);
|
|
24
|
+
export const FUSION_FRAMING_RESERVE_TOKENS = 0;
|
|
25
|
+
export const FUSION_SAFETY_RESERVE_TOKENS = 4_096;
|
|
26
|
+
export const FUSION_MIN_CANONICAL_INPUT_TOKENS = 8_192;
|
|
27
|
+
export const FUSION_MIN_CONTEXT_WINDOW_TOKENS = FUSION_MIN_CANONICAL_INPUT_TOKENS +
|
|
28
|
+
FUSION_RESERVED_OUTPUT_TOKENS +
|
|
29
|
+
FUSION_FRAMING_RESERVE_TOKENS +
|
|
30
|
+
FUSION_SAFETY_RESERVE_TOKENS;
|
|
31
|
+
export const FUSION_BUDGET_POLICY = {
|
|
32
|
+
id: 'fusion-budget-policy-v4',
|
|
33
|
+
route_output_reserve_strategy: 'max_fusion_contract_or_model_max',
|
|
34
|
+
calibration_version: TOKEN_BUDGET_CALIBRATION_VERSION,
|
|
35
|
+
calibration_table: FUSION_CALIBRATED_BYTES_PER_TOKEN,
|
|
36
|
+
reserved_output_tokens: FUSION_RESERVED_OUTPUT_TOKENS,
|
|
37
|
+
framing_reserve_tokens: FUSION_FRAMING_RESERVE_TOKENS,
|
|
38
|
+
safety_reserve_tokens: FUSION_SAFETY_RESERVE_TOKENS,
|
|
39
|
+
candidate_output_contract_bytes: FUSION_CANDIDATE_MAX_OUTPUT_BYTES,
|
|
40
|
+
evaluation_output_contract_bytes: FUSION_EVALUATION_MAX_OUTPUT_BYTES,
|
|
41
|
+
merge_output_contract_bytes: FUSION_MERGE_MAX_OUTPUT_BYTES,
|
|
42
|
+
diagnostics_contract_bytes: FUSION_DIAGNOSTICS_MAX_BYTES,
|
|
43
|
+
utilization_warning_threshold_basis_points: FUSION_UTILIZATION_WARNING_THRESHOLD_BASIS_POINTS,
|
|
44
|
+
};
|
|
45
|
+
const REASON_EMPTY_REMEDIATION = Object.freeze([
|
|
46
|
+
'Start a fresh Pi conversation, or run fusion_reason earlier in the session.',
|
|
47
|
+
"Raise the route's context window with a larger-context subscription model via /fusion-models.",
|
|
48
|
+
'Restate only the required prior findings in the fusion_reason prompt.',
|
|
49
|
+
]);
|
|
50
|
+
const REASON_REQUEST_REMEDIATION = Object.freeze([
|
|
51
|
+
'Provide a shorter fusion_reason prompt.',
|
|
52
|
+
'Start a fresh Pi conversation, or run fusion_reason earlier in the session.',
|
|
53
|
+
"Raise the route's context window with a larger-context subscription model via /fusion-models.",
|
|
54
|
+
]);
|
|
55
|
+
const INVESTIGATE_EMPTY_REMEDIATION = Object.freeze([
|
|
56
|
+
'Split the repository investigation into smaller independently complete path or subsystem scopes.',
|
|
57
|
+
"Raise the route's context window with a larger-context subscription model via /fusion-models.",
|
|
58
|
+
]);
|
|
59
|
+
const INVESTIGATE_REQUEST_REMEDIATION = Object.freeze([
|
|
60
|
+
'Narrow the fusion_investigate objective, repository scope, or required evidence.',
|
|
61
|
+
"Raise the route's context window with a larger-context subscription model via /fusion-models.",
|
|
62
|
+
]);
|
|
63
|
+
const RESEARCH_EMPTY_REMEDIATION = Object.freeze([
|
|
64
|
+
'Split the research into smaller independently complete source sets.',
|
|
65
|
+
"Raise the route's context window with a larger-context subscription model via /fusion-models.",
|
|
66
|
+
]);
|
|
67
|
+
const RESEARCH_REQUEST_REMEDIATION = Object.freeze([
|
|
68
|
+
'Narrow the fusion_research question or split large declared-source sets across independent runs.',
|
|
69
|
+
"Raise the route's context window with a larger-context subscription model via /fusion-models.",
|
|
70
|
+
]);
|
|
71
|
+
const VALIDATE_EMPTY_REMEDIATION = Object.freeze([
|
|
72
|
+
'Split validation into smaller independently complete change or acceptance-criterion scopes.',
|
|
73
|
+
"Raise the route's context window with a larger-context subscription model via /fusion-models.",
|
|
74
|
+
]);
|
|
75
|
+
const VALIDATE_REQUEST_REMEDIATION = Object.freeze([
|
|
76
|
+
'Narrow the fusion_validate scope, acceptance criteria, or supplied verification evidence.',
|
|
77
|
+
"Raise the route's context window with a larger-context subscription model via /fusion-models.",
|
|
78
|
+
]);
|
|
79
|
+
function cleanRemediation(profile, requestDeterminesFeasibility) {
|
|
80
|
+
if (profile.id === 'investigate') {
|
|
81
|
+
return requestDeterminesFeasibility
|
|
82
|
+
? INVESTIGATE_REQUEST_REMEDIATION
|
|
83
|
+
: INVESTIGATE_EMPTY_REMEDIATION;
|
|
84
|
+
}
|
|
85
|
+
if (profile.id === 'research') {
|
|
86
|
+
return requestDeterminesFeasibility ? RESEARCH_REQUEST_REMEDIATION : RESEARCH_EMPTY_REMEDIATION;
|
|
87
|
+
}
|
|
88
|
+
if (profile.id === 'validate') {
|
|
89
|
+
return requestDeterminesFeasibility ? VALIDATE_REQUEST_REMEDIATION : VALIDATE_EMPTY_REMEDIATION;
|
|
90
|
+
}
|
|
91
|
+
return requestDeterminesFeasibility ? REASON_REQUEST_REMEDIATION : REASON_EMPTY_REMEDIATION;
|
|
92
|
+
}
|
|
93
|
+
const RESERVATION_REMEDIATION = Object.freeze([
|
|
94
|
+
'Route the blocking stage to a model with larger byte capacity.',
|
|
95
|
+
'Keep producer output contracts intact; do not shrink or truncate child answers.',
|
|
96
|
+
'Inspect budget-plan.json for the advisory reservation component before retrying.',
|
|
97
|
+
]);
|
|
98
|
+
const DENSE_REMEDIATION = Object.freeze([
|
|
99
|
+
'Remove or externalize low-whitespace dense ASCII payloads (base64, minified code, PEM/hex blocks), then retry.',
|
|
100
|
+
'The prompt is preserved; no content was clipped to fit.',
|
|
101
|
+
]);
|
|
102
|
+
const MULTIBYTE_REMEDIATION = Object.freeze([
|
|
103
|
+
'This rejection is dominated by multibyte UTF-8 content; use a larger-context route or split the non-Latin/CJK-heavy task.',
|
|
104
|
+
'The budget plan includes the stricter multibyte advisory ceiling separately from the fatal estimate.',
|
|
105
|
+
'The prompt is preserved; no content was clipped to fit.',
|
|
106
|
+
]);
|
|
107
|
+
const EMPTY_CANDIDATES = Object.freeze([
|
|
108
|
+
Object.freeze({ candidate_id: 'A', response: '' }),
|
|
109
|
+
Object.freeze({ candidate_id: 'B', response: '' }),
|
|
110
|
+
Object.freeze({ candidate_id: 'C', response: '' }),
|
|
111
|
+
]);
|
|
112
|
+
const EMPTY_EVALUATION = Object.freeze({
|
|
113
|
+
schema_version: FUSION_EVALUATION_SCHEMA_VERSION,
|
|
114
|
+
candidate_assessments: Object.freeze([
|
|
115
|
+
Object.freeze({
|
|
116
|
+
candidate_id: 'A',
|
|
117
|
+
summary: '',
|
|
118
|
+
strengths: Object.freeze([]),
|
|
119
|
+
limitations: Object.freeze([]),
|
|
120
|
+
useful_contributions: Object.freeze([]),
|
|
121
|
+
risks: Object.freeze([]),
|
|
122
|
+
}),
|
|
123
|
+
Object.freeze({
|
|
124
|
+
candidate_id: 'B',
|
|
125
|
+
summary: '',
|
|
126
|
+
strengths: Object.freeze([]),
|
|
127
|
+
limitations: Object.freeze([]),
|
|
128
|
+
useful_contributions: Object.freeze([]),
|
|
129
|
+
risks: Object.freeze([]),
|
|
130
|
+
}),
|
|
131
|
+
Object.freeze({
|
|
132
|
+
candidate_id: 'C',
|
|
133
|
+
summary: '',
|
|
134
|
+
strengths: Object.freeze([]),
|
|
135
|
+
limitations: Object.freeze([]),
|
|
136
|
+
useful_contributions: Object.freeze([]),
|
|
137
|
+
risks: Object.freeze([]),
|
|
138
|
+
}),
|
|
139
|
+
]),
|
|
140
|
+
agreements: Object.freeze([]),
|
|
141
|
+
conflicts: Object.freeze([]),
|
|
142
|
+
synthesis_plan: Object.freeze({
|
|
143
|
+
must_include: Object.freeze([]),
|
|
144
|
+
must_resolve: Object.freeze([]),
|
|
145
|
+
must_avoid: Object.freeze([]),
|
|
146
|
+
}),
|
|
147
|
+
});
|
|
148
|
+
export function fusionTokenUpperBound(utf8Bytes) {
|
|
149
|
+
return estimateInputTokens({
|
|
150
|
+
family: 'unknown',
|
|
151
|
+
scope: 'conservative',
|
|
152
|
+
segments: [{ kind: 'known_text', bytes: utf8Bytes, multibyteBytes: 0, denseBytes: 0 }],
|
|
153
|
+
}).tokens;
|
|
154
|
+
}
|
|
155
|
+
function utf8Bytes(value) {
|
|
156
|
+
return Buffer.byteLength(value, 'utf8');
|
|
157
|
+
}
|
|
158
|
+
function sha256Hex(value) {
|
|
159
|
+
return createHash('sha256').update(value, 'utf8').digest('hex');
|
|
160
|
+
}
|
|
161
|
+
function requirePositiveContextWindow(model, role) {
|
|
162
|
+
const value = model.contextWindow;
|
|
163
|
+
if (!isUsableContextWindow(value)) {
|
|
164
|
+
throw new FusionError(`fusion ${role} route ${model.qualifiedId} has no usable context window capacity`, { code: 'model_capacity_unknown', childCreated: false });
|
|
165
|
+
}
|
|
166
|
+
return value;
|
|
167
|
+
}
|
|
168
|
+
function formatRateX100(value) {
|
|
169
|
+
const whole = Math.floor(value / TOKEN_BUDGET_RATE_SCALE);
|
|
170
|
+
const frac = String(value % TOKEN_BUDGET_RATE_SCALE).padStart(2, '0');
|
|
171
|
+
return `${String(whole)}.${frac}`;
|
|
172
|
+
}
|
|
173
|
+
function routeCapacity(model, role) {
|
|
174
|
+
const contextWindow = requirePositiveContextWindow(model, role);
|
|
175
|
+
const reservedOutputTokens = Math.max(FUSION_RESERVED_OUTPUT_TOKENS, model.maxOutputTokens);
|
|
176
|
+
const allowed = allowedInputTokens(contextWindow, {
|
|
177
|
+
reservedOutputTokens,
|
|
178
|
+
framingReserveTokens: FUSION_FRAMING_RESERVE_TOKENS,
|
|
179
|
+
safetyReserveTokens: FUSION_SAFETY_RESERVE_TOKENS,
|
|
180
|
+
});
|
|
181
|
+
if (allowed < FUSION_MIN_CANONICAL_INPUT_TOKENS) {
|
|
182
|
+
const minimumContextWindow = reservedOutputTokens +
|
|
183
|
+
FUSION_FRAMING_RESERVE_TOKENS +
|
|
184
|
+
FUSION_SAFETY_RESERVE_TOKENS +
|
|
185
|
+
FUSION_MIN_CANONICAL_INPUT_TOKENS;
|
|
186
|
+
throw new FusionError(`fusion ${role} route ${model.qualifiedId} has a ${String(contextWindow)}-token context window, but Fusion requires at least ${String(minimumContextWindow)} tokens: ${String(reservedOutputTokens)} reserved for the route's configured maximum output + ${String(FUSION_FRAMING_RESERVE_TOKENS)} framing + ${String(FUSION_SAFETY_RESERVE_TOKENS)} safety + ${String(FUSION_MIN_CANONICAL_INPUT_TOKENS)} usable input. Choose a larger-context or lower-max-output subscription model for this slot with /fusion-models.`, { code: 'model_capacity_unknown', childCreated: false });
|
|
187
|
+
}
|
|
188
|
+
const family = resolveTokenBudgetFamily({ provider: model.provider, model: model.model });
|
|
189
|
+
const rateSource = estimateInputTokens({
|
|
190
|
+
family: family.family,
|
|
191
|
+
calibrationBacked: family.backed,
|
|
192
|
+
familyResolution: family.resolution,
|
|
193
|
+
allowedInputTokens: allowed,
|
|
194
|
+
scope: 'fusion',
|
|
195
|
+
segments: [
|
|
196
|
+
{
|
|
197
|
+
kind: 'known_text',
|
|
198
|
+
bytes: TOKEN_BUDGET_LARGE_PROMPT_MIN_BYTES,
|
|
199
|
+
multibyteBytes: 0,
|
|
200
|
+
denseBytes: 0,
|
|
201
|
+
asciiWhitespaceBytes: TOKEN_BUDGET_LARGE_PROMPT_MIN_BYTES,
|
|
202
|
+
},
|
|
203
|
+
],
|
|
204
|
+
}).rateSource;
|
|
205
|
+
return {
|
|
206
|
+
role,
|
|
207
|
+
provider: model.provider,
|
|
208
|
+
model: model.model,
|
|
209
|
+
qualified_id: model.qualifiedId,
|
|
210
|
+
context_window_tokens: contextWindow,
|
|
211
|
+
reserved_output_tokens: reservedOutputTokens,
|
|
212
|
+
framing_reserve_tokens: FUSION_FRAMING_RESERVE_TOKENS,
|
|
213
|
+
safety_reserve_tokens: FUSION_SAFETY_RESERVE_TOKENS,
|
|
214
|
+
allowed_input_tokens: allowed,
|
|
215
|
+
family: family.family,
|
|
216
|
+
rate_source: rateSource,
|
|
217
|
+
byte_capacity_utf8_bytes: Math.floor((allowed * rateSource.effective_rate_bytes_per_token_x100) / TOKEN_BUDGET_RATE_SCALE),
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
export function fusionRouteCapacities(models) {
|
|
221
|
+
return [
|
|
222
|
+
routeCapacity(models.candidates[0], 'candidate-1'),
|
|
223
|
+
routeCapacity(models.candidates[1], 'candidate-2'),
|
|
224
|
+
routeCapacity(models.candidates[2], 'candidate-3'),
|
|
225
|
+
routeCapacity(models.evaluator, 'evaluator'),
|
|
226
|
+
routeCapacity(models.merger, 'merger'),
|
|
227
|
+
];
|
|
228
|
+
}
|
|
229
|
+
export function fusionLimitingRoute(routes) {
|
|
230
|
+
let limiting;
|
|
231
|
+
for (const route of routes) {
|
|
232
|
+
if (limiting === undefined ||
|
|
233
|
+
route.byte_capacity_utf8_bytes < limiting.byte_capacity_utf8_bytes ||
|
|
234
|
+
(route.byte_capacity_utf8_bytes === limiting.byte_capacity_utf8_bytes &&
|
|
235
|
+
route.role.localeCompare(limiting.role) < 0)) {
|
|
236
|
+
limiting = route;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
if (limiting === undefined) {
|
|
240
|
+
throw new FusionError('fusion budget planning received no configured routes', {
|
|
241
|
+
code: 'model_capacity_unknown',
|
|
242
|
+
childCreated: false,
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
return limiting;
|
|
246
|
+
}
|
|
247
|
+
function routeByRole(routes, role) {
|
|
248
|
+
const route = routes.find((item) => item.role === role);
|
|
249
|
+
if (route === undefined) {
|
|
250
|
+
throw new FusionError(`fusion budget route ${role} is missing`, {
|
|
251
|
+
code: 'model_capacity_unknown',
|
|
252
|
+
childCreated: false,
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
return route;
|
|
256
|
+
}
|
|
257
|
+
function candidateRole(slot) {
|
|
258
|
+
if (slot === 1)
|
|
259
|
+
return 'candidate-1';
|
|
260
|
+
if (slot === 2)
|
|
261
|
+
return 'candidate-2';
|
|
262
|
+
return 'candidate-3';
|
|
263
|
+
}
|
|
264
|
+
function estimateRouteInput(route, segments) {
|
|
265
|
+
return estimateInputTokens({
|
|
266
|
+
family: route.family,
|
|
267
|
+
calibrationBacked: route.rate_source.backed,
|
|
268
|
+
familyResolution: route.rate_source.model_resolution,
|
|
269
|
+
allowedInputTokens: route.allowed_input_tokens,
|
|
270
|
+
scope: 'fusion',
|
|
271
|
+
segments,
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
function utilizationBasisPoints(tokens, allowed) {
|
|
275
|
+
return ceilDiv(tokens * BASIS_POINTS_DENOMINATOR, allowed);
|
|
276
|
+
}
|
|
277
|
+
function forecastEntry(draft) {
|
|
278
|
+
const inputSegments = [knownTextSegment(draft.system_prompt), knownTextSegment(draft.empty_user_prompt)];
|
|
279
|
+
const inputBytes = inputSegments.reduce((sum, segment) => sum + segment.bytes, 0);
|
|
280
|
+
const inputOnly = estimateRouteInput(draft.route, inputSegments);
|
|
281
|
+
const reservationSegments = draft.upstream_output_contract_bytes === 0
|
|
282
|
+
? inputSegments
|
|
283
|
+
: [...inputSegments, unknownOutputContractSegment(draft.upstream_output_contract_bytes)];
|
|
284
|
+
const reservation = estimateRouteInput(draft.route, reservationSegments);
|
|
285
|
+
const forecastUtf8Bytes = inputBytes + draft.upstream_output_contract_bytes;
|
|
286
|
+
const entry = {
|
|
287
|
+
budget_stage: draft.budget_stage,
|
|
288
|
+
route: draft.route,
|
|
289
|
+
conditional: draft.conditional,
|
|
290
|
+
check_kind: 'input_only_preflight',
|
|
291
|
+
input_utf8_bytes: inputBytes,
|
|
292
|
+
upstream_output_contract_bytes: draft.upstream_output_contract_bytes,
|
|
293
|
+
forecast_utf8_bytes: forecastUtf8Bytes,
|
|
294
|
+
input_only_input_tokens_upper_bound: inputOnly.tokens,
|
|
295
|
+
forecast_input_tokens_upper_bound: reservation.tokens,
|
|
296
|
+
allowed_input_tokens: draft.route.allowed_input_tokens,
|
|
297
|
+
input_only_signed_headroom_tokens: draft.route.allowed_input_tokens - inputOnly.tokens,
|
|
298
|
+
signed_headroom_tokens: draft.route.allowed_input_tokens - reservation.tokens,
|
|
299
|
+
input_only_utilization_basis_points: utilizationBasisPoints(inputOnly.tokens, draft.route.allowed_input_tokens),
|
|
300
|
+
utilization_basis_points: utilizationBasisPoints(reservation.tokens, draft.route.allowed_input_tokens),
|
|
301
|
+
input_only_estimate: inputOnly,
|
|
302
|
+
reservation_estimate: reservation,
|
|
303
|
+
fits: inputOnly.tokens <= draft.route.allowed_input_tokens,
|
|
304
|
+
reservation_fits: reservation.tokens <= draft.route.allowed_input_tokens,
|
|
305
|
+
};
|
|
306
|
+
if (draft.slot !== undefined)
|
|
307
|
+
entry.slot = draft.slot;
|
|
308
|
+
return entry;
|
|
309
|
+
}
|
|
310
|
+
function maxKnownTextBytes(route) {
|
|
311
|
+
return maxKnownTextBytesForTokens({
|
|
312
|
+
family: route.family,
|
|
313
|
+
calibrationBacked: route.rate_source.backed,
|
|
314
|
+
familyResolution: route.rate_source.model_resolution,
|
|
315
|
+
allowedInputTokens: route.allowed_input_tokens,
|
|
316
|
+
scope: 'fusion',
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
function blockerFromEntry(entry) {
|
|
320
|
+
return {
|
|
321
|
+
...entry,
|
|
322
|
+
overage_tokens: Math.max(0, entry.input_only_input_tokens_upper_bound - entry.allowed_input_tokens),
|
|
323
|
+
bytes_over: Math.max(0, entry.input_utf8_bytes - maxKnownTextBytes(entry.route)),
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
function blockerOrder(blocker) {
|
|
327
|
+
if (blocker.budget_stage === 'candidate')
|
|
328
|
+
return blocker.slot ?? 1;
|
|
329
|
+
if (blocker.budget_stage === 'evaluation')
|
|
330
|
+
return 4;
|
|
331
|
+
if (blocker.budget_stage === 'merge')
|
|
332
|
+
return 5;
|
|
333
|
+
return 6;
|
|
334
|
+
}
|
|
335
|
+
function selectBlockers(entries) {
|
|
336
|
+
return entries.filter((entry) => !entry.fits).map(blockerFromEntry).sort((left, right) => {
|
|
337
|
+
const byOrder = blockerOrder(left) - blockerOrder(right);
|
|
338
|
+
if (byOrder !== 0)
|
|
339
|
+
return byOrder;
|
|
340
|
+
return left.route.role.localeCompare(right.route.role);
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
function selectPrimaryBlocker(blockers) {
|
|
344
|
+
const mandatory = blockers.find((blocker) => !blocker.conditional);
|
|
345
|
+
return mandatory ?? blockers[0];
|
|
346
|
+
}
|
|
347
|
+
function replaceRequestText(input, text) {
|
|
348
|
+
return {
|
|
349
|
+
...input,
|
|
350
|
+
request: {
|
|
351
|
+
...input.request,
|
|
352
|
+
text,
|
|
353
|
+
sha256: sha256Hex(text),
|
|
354
|
+
},
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
function visibleTextBytes(input) {
|
|
358
|
+
const projection = input.context?.kind === 'session_projection'
|
|
359
|
+
? input.context.conversation_projection
|
|
360
|
+
: 'conversation_projection' in input
|
|
361
|
+
? input.conversation_projection
|
|
362
|
+
: undefined;
|
|
363
|
+
if (projection === undefined)
|
|
364
|
+
return 0;
|
|
365
|
+
let total = 0;
|
|
366
|
+
for (const entry of projection.entries) {
|
|
367
|
+
if (entry[0] === 't')
|
|
368
|
+
total += utf8Bytes(JSON.stringify(entry[4]));
|
|
369
|
+
}
|
|
370
|
+
return total;
|
|
371
|
+
}
|
|
372
|
+
function omissionReceiptBytes(input) {
|
|
373
|
+
const projection = input.context?.kind === 'session_projection'
|
|
374
|
+
? input.context.conversation_projection
|
|
375
|
+
: 'conversation_projection' in input
|
|
376
|
+
? input.conversation_projection
|
|
377
|
+
: undefined;
|
|
378
|
+
if (projection === undefined)
|
|
379
|
+
return 0;
|
|
380
|
+
let total = 0;
|
|
381
|
+
for (const entry of projection.entries) {
|
|
382
|
+
if (entry[0] === 'o')
|
|
383
|
+
total += utf8Bytes(JSON.stringify(entry));
|
|
384
|
+
}
|
|
385
|
+
return total;
|
|
386
|
+
}
|
|
387
|
+
function warningFromEntry(entry) {
|
|
388
|
+
if (!entry.fits)
|
|
389
|
+
return undefined;
|
|
390
|
+
if (!entry.reservation_fits) {
|
|
391
|
+
return {
|
|
392
|
+
...entry,
|
|
393
|
+
warning_kind: 'worst_case_reservation',
|
|
394
|
+
threshold_basis_points: FUSION_UTILIZATION_WARNING_THRESHOLD_BASIS_POINTS,
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
if (entry.utilization_basis_points >= FUSION_UTILIZATION_WARNING_THRESHOLD_BASIS_POINTS) {
|
|
398
|
+
return {
|
|
399
|
+
...entry,
|
|
400
|
+
warning_kind: 'input_utilization',
|
|
401
|
+
threshold_basis_points: FUSION_UTILIZATION_WARNING_THRESHOLD_BASIS_POINTS,
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
return undefined;
|
|
405
|
+
}
|
|
406
|
+
function warningsFor(entries) {
|
|
407
|
+
return entries.flatMap((entry) => {
|
|
408
|
+
const warning = warningFromEntry(entry);
|
|
409
|
+
return warning === undefined ? [] : [warning];
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
function entryLabel(entry) {
|
|
413
|
+
const slot = entry.slot === undefined ? '' : `-${String(entry.slot)}`;
|
|
414
|
+
const conditional = entry.conditional ? ' (conditional)' : '';
|
|
415
|
+
return `${entry.budget_stage}${slot}${conditional}`;
|
|
416
|
+
}
|
|
417
|
+
function blockingChildLabel(entry) {
|
|
418
|
+
if (entry.budget_stage === 'candidate')
|
|
419
|
+
return `candidate-${String(entry.slot ?? 1)}`;
|
|
420
|
+
if (entry.budget_stage === 'evaluation_repair')
|
|
421
|
+
return 'evaluator-repair';
|
|
422
|
+
if (entry.budget_stage === 'evaluation')
|
|
423
|
+
return 'evaluator';
|
|
424
|
+
return 'merger';
|
|
425
|
+
}
|
|
426
|
+
function formatTable(entries) {
|
|
427
|
+
const lines = entries.map((entry) => `${entryLabel(entry)} | route=${entry.route.qualified_id} | input=${String(entry.input_only_input_tokens_upper_bound)} | reserved=${String(entry.forecast_input_tokens_upper_bound)} | allowed=${String(entry.allowed_input_tokens)} | input_headroom=${String(entry.input_only_signed_headroom_tokens)} | reservation_headroom=${String(entry.signed_headroom_tokens)} | ${entry.fits ? 'input-fits' : 'input-over'} | ${entry.reservation_fits ? 'reservation-fits' : 'reservation-warn'}`);
|
|
428
|
+
return lines.join('\n');
|
|
429
|
+
}
|
|
430
|
+
function formatComposition(composition) {
|
|
431
|
+
return [
|
|
432
|
+
`visible text ${String(composition.visible_text_bytes)} B`,
|
|
433
|
+
`omission receipts ${String(composition.omission_receipt_bytes)} B`,
|
|
434
|
+
`projection metadata ${String(composition.projection_metadata_bytes)} B`,
|
|
435
|
+
`request ${String(composition.request_bytes)} B`,
|
|
436
|
+
`static stage framing ${String(composition.static_stage_framing_bytes)} B`,
|
|
437
|
+
`upstream output contracts ${String(composition.upstream_output_contract_bytes)} B`,
|
|
438
|
+
].join('; ');
|
|
439
|
+
}
|
|
440
|
+
function dominantRemediation(verdict, composition, dominantByteClass, profile) {
|
|
441
|
+
if (dominantByteClass === 'dense_ascii')
|
|
442
|
+
return DENSE_REMEDIATION;
|
|
443
|
+
if (dominantByteClass === 'multibyte')
|
|
444
|
+
return MULTIBYTE_REMEDIATION;
|
|
445
|
+
if (composition === undefined)
|
|
446
|
+
return remediationFor(verdict, profile);
|
|
447
|
+
const entries = [
|
|
448
|
+
{ name: 'visible', bytes: composition.visible_text_bytes },
|
|
449
|
+
{ name: 'request', bytes: composition.request_bytes },
|
|
450
|
+
{ name: 'reservation', bytes: composition.upstream_output_contract_bytes },
|
|
451
|
+
].sort((left, right) => right.bytes - left.bytes);
|
|
452
|
+
const dominant = entries[0];
|
|
453
|
+
if (dominant?.name === 'reservation')
|
|
454
|
+
return RESERVATION_REMEDIATION;
|
|
455
|
+
if (dominant?.name === 'request' && !verdict.still_fails_with_empty_request) {
|
|
456
|
+
return profile.contextKind === 'clean_task'
|
|
457
|
+
? cleanRemediation(profile, true)
|
|
458
|
+
: REASON_REQUEST_REMEDIATION;
|
|
459
|
+
}
|
|
460
|
+
if (profile.contextKind === 'clean_task')
|
|
461
|
+
return cleanRemediation(profile, false);
|
|
462
|
+
return REASON_EMPTY_REMEDIATION;
|
|
463
|
+
}
|
|
464
|
+
function remediationFor(verdict, profile) {
|
|
465
|
+
if (profile.contextKind === 'clean_task') {
|
|
466
|
+
return cleanRemediation(profile, !verdict.still_fails_with_empty_request);
|
|
467
|
+
}
|
|
468
|
+
return verdict.still_fails_with_empty_request
|
|
469
|
+
? REASON_EMPTY_REMEDIATION
|
|
470
|
+
: REASON_REQUEST_REMEDIATION;
|
|
471
|
+
}
|
|
472
|
+
function formatEmptyRequestVerdict(verdict) {
|
|
473
|
+
if (verdict.still_fails_with_empty_request) {
|
|
474
|
+
return `Empty-request counterfactual: still fails with ${String(verdict.blockers_with_empty_request.length)} blocking stage(s), so shortening the request cannot make this workflow fit.`;
|
|
475
|
+
}
|
|
476
|
+
if (verdict.minimum_request_byte_reduction === 0) {
|
|
477
|
+
return 'Empty-request counterfactual: fits; no request reduction is required by the current plan.';
|
|
478
|
+
}
|
|
479
|
+
return `Empty-request counterfactual: fits, so request size determines feasibility; reduce the request by at least ${String(verdict.minimum_request_byte_reduction)} UTF-8 bytes, leaving at most ${String(verdict.maximum_safe_request_utf8_bytes)} UTF-8 bytes.`;
|
|
480
|
+
}
|
|
481
|
+
function stageFromBudgetStage(stage) {
|
|
482
|
+
if (stage === 'merge')
|
|
483
|
+
return 'merge';
|
|
484
|
+
if (stage === 'candidate')
|
|
485
|
+
return 'candidate';
|
|
486
|
+
return 'evaluation';
|
|
487
|
+
}
|
|
488
|
+
function routeTable(routes) {
|
|
489
|
+
return [...routes]
|
|
490
|
+
.sort((left, right) => {
|
|
491
|
+
const byCapacity = left.byte_capacity_utf8_bytes - right.byte_capacity_utf8_bytes;
|
|
492
|
+
if (byCapacity !== 0)
|
|
493
|
+
return byCapacity;
|
|
494
|
+
return left.role.localeCompare(right.role);
|
|
495
|
+
})
|
|
496
|
+
.map((route) => ({
|
|
497
|
+
role: route.role,
|
|
498
|
+
qualified_id: route.qualified_id,
|
|
499
|
+
allowed_input_tokens: route.allowed_input_tokens,
|
|
500
|
+
family: route.family,
|
|
501
|
+
effective_rate_bytes_per_token_x100: route.rate_source.effective_rate_bytes_per_token_x100,
|
|
502
|
+
byte_capacity_utf8_bytes: route.byte_capacity_utf8_bytes,
|
|
503
|
+
backed: route.rate_source.backed,
|
|
504
|
+
}));
|
|
505
|
+
}
|
|
506
|
+
function segmentTokensForBytes(route, bytes) {
|
|
507
|
+
if (bytes <= 0)
|
|
508
|
+
return 0;
|
|
509
|
+
const estimate = estimateRouteInput(route, [
|
|
510
|
+
{ kind: 'known_text', bytes, multibyteBytes: 0, denseBytes: 0 },
|
|
511
|
+
]);
|
|
512
|
+
const segment = estimate.perSegment[0];
|
|
513
|
+
return segment === undefined ? 0 : segment.tokens;
|
|
514
|
+
}
|
|
515
|
+
function contractTokens(bytes) {
|
|
516
|
+
return bytes;
|
|
517
|
+
}
|
|
518
|
+
function componentBreakdown(composition, route) {
|
|
519
|
+
const empty = {
|
|
520
|
+
visible_text_bytes: 0,
|
|
521
|
+
omission_receipt_bytes: 0,
|
|
522
|
+
projection_metadata_bytes: 0,
|
|
523
|
+
request_bytes: 0,
|
|
524
|
+
static_stage_framing_bytes: 0,
|
|
525
|
+
upstream_output_contract_bytes: 0,
|
|
526
|
+
};
|
|
527
|
+
const item = composition ?? empty;
|
|
528
|
+
return {
|
|
529
|
+
visible_text: {
|
|
530
|
+
bytes: item.visible_text_bytes,
|
|
531
|
+
tokens: segmentTokensForBytes(route, item.visible_text_bytes),
|
|
532
|
+
},
|
|
533
|
+
omission_receipts: {
|
|
534
|
+
bytes: item.omission_receipt_bytes,
|
|
535
|
+
tokens: segmentTokensForBytes(route, item.omission_receipt_bytes),
|
|
536
|
+
},
|
|
537
|
+
projection_metadata: {
|
|
538
|
+
bytes: item.projection_metadata_bytes,
|
|
539
|
+
tokens: segmentTokensForBytes(route, item.projection_metadata_bytes),
|
|
540
|
+
},
|
|
541
|
+
request: {
|
|
542
|
+
bytes: item.request_bytes,
|
|
543
|
+
tokens: segmentTokensForBytes(route, item.request_bytes),
|
|
544
|
+
},
|
|
545
|
+
static_stage_framing: {
|
|
546
|
+
bytes: item.static_stage_framing_bytes,
|
|
547
|
+
tokens: segmentTokensForBytes(route, item.static_stage_framing_bytes),
|
|
548
|
+
},
|
|
549
|
+
upstream_output_contracts: {
|
|
550
|
+
bytes: item.upstream_output_contract_bytes,
|
|
551
|
+
tokens: contractTokens(item.upstream_output_contract_bytes),
|
|
552
|
+
},
|
|
553
|
+
};
|
|
554
|
+
}
|
|
555
|
+
function medianCounterfactual(primary) {
|
|
556
|
+
if (!primary.route.rate_source.backed) {
|
|
557
|
+
return { forecast_input_tokens_upper_bound: null, signed_headroom_tokens: null, fits: null };
|
|
558
|
+
}
|
|
559
|
+
const median = primary.route.rate_source.provenance.median_bpt_x1000;
|
|
560
|
+
if (median === null)
|
|
561
|
+
return { forecast_input_tokens_upper_bound: null, signed_headroom_tokens: null, fits: null };
|
|
562
|
+
const variableTokens = ceilDiv(primary.input_utf8_bytes * 1000, median);
|
|
563
|
+
const tokens = variableTokens + TOKEN_BUDGET_AFFINE_F_TOKENS;
|
|
564
|
+
return {
|
|
565
|
+
forecast_input_tokens_upper_bound: tokens,
|
|
566
|
+
signed_headroom_tokens: primary.allowed_input_tokens - tokens,
|
|
567
|
+
fits: tokens <= primary.allowed_input_tokens,
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
function inputCounterfactuals(primary, plan) {
|
|
571
|
+
return {
|
|
572
|
+
empty_request: plan.empty_request,
|
|
573
|
+
without_reservation: {
|
|
574
|
+
forecast_input_tokens_upper_bound: primary.input_only_input_tokens_upper_bound,
|
|
575
|
+
signed_headroom_tokens: primary.input_only_signed_headroom_tokens,
|
|
576
|
+
fits: primary.fits,
|
|
577
|
+
},
|
|
578
|
+
at_median_rate: medianCounterfactual(primary),
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
function budgetErrorCode(checkKind) {
|
|
582
|
+
return checkKind === 'rendered_prompt'
|
|
583
|
+
? 'prompt_budget_exceeded_measured'
|
|
584
|
+
: 'prompt_budget_exceeded_forecast';
|
|
585
|
+
}
|
|
586
|
+
export class FusionBudget {
|
|
587
|
+
routes;
|
|
588
|
+
limiting;
|
|
589
|
+
contextPolicyId;
|
|
590
|
+
candidateCapability;
|
|
591
|
+
profile;
|
|
592
|
+
constructor(models, contextPolicyId, candidateCapability = FUSION_REASON_WORKFLOW.candidateCapability, profile = FUSION_REASON_WORKFLOW) {
|
|
593
|
+
this.routes = fusionRouteCapacities(models);
|
|
594
|
+
this.limiting = fusionLimitingRoute(this.routes);
|
|
595
|
+
this.contextPolicyId = contextPolicyId;
|
|
596
|
+
this.candidateCapability = candidateCapability;
|
|
597
|
+
this.profile = profile;
|
|
598
|
+
}
|
|
599
|
+
get allowedInputTokens() {
|
|
600
|
+
return this.limiting.allowed_input_tokens;
|
|
601
|
+
}
|
|
602
|
+
get resultRateSources() {
|
|
603
|
+
return this.routes.map((route) => route.rate_source);
|
|
604
|
+
}
|
|
605
|
+
get unknownProviderWarnings() {
|
|
606
|
+
return this.routes.flatMap((route) => {
|
|
607
|
+
const warning = route.rate_source.warning;
|
|
608
|
+
return route.rate_source.backed || warning === null
|
|
609
|
+
? []
|
|
610
|
+
: [`${route.qualified_id}: ${warning}`];
|
|
611
|
+
});
|
|
612
|
+
}
|
|
613
|
+
routeForStage(stage, slot) {
|
|
614
|
+
if (stage === 'candidate')
|
|
615
|
+
return routeByRole(this.routes, candidateRole(slot ?? 1));
|
|
616
|
+
if (stage === 'merge')
|
|
617
|
+
return routeByRole(this.routes, 'merger');
|
|
618
|
+
return routeByRole(this.routes, 'evaluator');
|
|
619
|
+
}
|
|
620
|
+
drafts(input) {
|
|
621
|
+
const candidateSystemPrompt = this.profile.candidateSystemPrompt(this.candidateCapability);
|
|
622
|
+
const candidatePrompt = buildCandidatePrompt(input);
|
|
623
|
+
const blindInput = buildBlindEvaluationInput(input, EMPTY_CANDIDATES);
|
|
624
|
+
const evaluationPrompt = buildEvaluationPrompt(blindInput);
|
|
625
|
+
const repairPrompt = buildEvaluationRepairPrompt({
|
|
626
|
+
schema_version: 'pi-background-tasks.fusion-evaluation-repair-input.v1',
|
|
627
|
+
original_blind_input: blindInput,
|
|
628
|
+
invalid_output: '',
|
|
629
|
+
validation_errors: [],
|
|
630
|
+
});
|
|
631
|
+
const mergePrompt = buildMergePrompt(buildMergeInput(input, EMPTY_CANDIDATES, EMPTY_EVALUATION));
|
|
632
|
+
return [
|
|
633
|
+
{
|
|
634
|
+
budget_stage: 'candidate',
|
|
635
|
+
slot: 1,
|
|
636
|
+
route: this.routeForStage('candidate', 1),
|
|
637
|
+
conditional: false,
|
|
638
|
+
system_prompt: candidateSystemPrompt,
|
|
639
|
+
empty_user_prompt: candidatePrompt,
|
|
640
|
+
upstream_output_contract_bytes: 0,
|
|
641
|
+
},
|
|
642
|
+
{
|
|
643
|
+
budget_stage: 'candidate',
|
|
644
|
+
slot: 2,
|
|
645
|
+
route: this.routeForStage('candidate', 2),
|
|
646
|
+
conditional: false,
|
|
647
|
+
system_prompt: candidateSystemPrompt,
|
|
648
|
+
empty_user_prompt: candidatePrompt,
|
|
649
|
+
upstream_output_contract_bytes: 0,
|
|
650
|
+
},
|
|
651
|
+
{
|
|
652
|
+
budget_stage: 'candidate',
|
|
653
|
+
slot: 3,
|
|
654
|
+
route: this.routeForStage('candidate', 3),
|
|
655
|
+
conditional: false,
|
|
656
|
+
system_prompt: candidateSystemPrompt,
|
|
657
|
+
empty_user_prompt: candidatePrompt,
|
|
658
|
+
upstream_output_contract_bytes: 0,
|
|
659
|
+
},
|
|
660
|
+
{
|
|
661
|
+
budget_stage: 'evaluation',
|
|
662
|
+
route: this.routeForStage('evaluation'),
|
|
663
|
+
conditional: false,
|
|
664
|
+
system_prompt: this.profile.evaluatorSystemPrompt,
|
|
665
|
+
empty_user_prompt: evaluationPrompt,
|
|
666
|
+
upstream_output_contract_bytes: 3 * FUSION_CANDIDATE_MAX_OUTPUT_BYTES,
|
|
667
|
+
},
|
|
668
|
+
{
|
|
669
|
+
budget_stage: 'merge',
|
|
670
|
+
route: this.routeForStage('merge'),
|
|
671
|
+
conditional: false,
|
|
672
|
+
system_prompt: this.profile.mergerSystemPrompt,
|
|
673
|
+
empty_user_prompt: mergePrompt,
|
|
674
|
+
upstream_output_contract_bytes: 3 * FUSION_CANDIDATE_MAX_OUTPUT_BYTES + FUSION_EVALUATION_MAX_OUTPUT_BYTES,
|
|
675
|
+
},
|
|
676
|
+
{
|
|
677
|
+
budget_stage: 'evaluation_repair',
|
|
678
|
+
route: this.routeForStage('evaluation_repair'),
|
|
679
|
+
conditional: true,
|
|
680
|
+
system_prompt: this.profile.evaluationRepairSystemPrompt,
|
|
681
|
+
empty_user_prompt: repairPrompt,
|
|
682
|
+
upstream_output_contract_bytes: 3 * FUSION_CANDIDATE_MAX_OUTPUT_BYTES +
|
|
683
|
+
FUSION_EVALUATION_MAX_OUTPUT_BYTES +
|
|
684
|
+
FUSION_DIAGNOSTICS_MAX_BYTES,
|
|
685
|
+
},
|
|
686
|
+
];
|
|
687
|
+
}
|
|
688
|
+
entries(input) {
|
|
689
|
+
return this.drafts(input).map(forecastEntry);
|
|
690
|
+
}
|
|
691
|
+
composition(input, blocker) {
|
|
692
|
+
const canonicalBytes = utf8Bytes(buildCandidatePrompt(input));
|
|
693
|
+
const emptyRequestCanonicalBytes = utf8Bytes(buildCandidatePrompt(replaceRequestText(input, '')));
|
|
694
|
+
const requestBytes = canonicalBytes - emptyRequestCanonicalBytes;
|
|
695
|
+
const visible = visibleTextBytes(input);
|
|
696
|
+
const omissions = omissionReceiptBytes(input);
|
|
697
|
+
const projectionMetadata = canonicalBytes - requestBytes - visible - omissions;
|
|
698
|
+
const draft = this.drafts(input).find((item) => item.budget_stage === blocker.budget_stage && item.slot === blocker.slot);
|
|
699
|
+
if (draft === undefined) {
|
|
700
|
+
throw new FusionError('primary budget blocker disappeared during composition', {
|
|
701
|
+
code: 'orchestration_failed',
|
|
702
|
+
childCreated: false,
|
|
703
|
+
});
|
|
704
|
+
}
|
|
705
|
+
return {
|
|
706
|
+
visible_text_bytes: visible,
|
|
707
|
+
omission_receipt_bytes: omissions,
|
|
708
|
+
projection_metadata_bytes: projectionMetadata,
|
|
709
|
+
request_bytes: requestBytes,
|
|
710
|
+
static_stage_framing_bytes: utf8Bytes(draft.system_prompt) + utf8Bytes(draft.empty_user_prompt) - canonicalBytes,
|
|
711
|
+
upstream_output_contract_bytes: draft.upstream_output_contract_bytes,
|
|
712
|
+
};
|
|
713
|
+
}
|
|
714
|
+
emptyRequestVerdict(input, entries) {
|
|
715
|
+
const emptyEntries = this.entries(replaceRequestText(input, ''));
|
|
716
|
+
const emptyBlockers = selectBlockers(emptyEntries);
|
|
717
|
+
let reduction = 0;
|
|
718
|
+
for (const entry of entries) {
|
|
719
|
+
reduction = Math.max(reduction, entry.input_utf8_bytes - maxKnownTextBytes(entry.route));
|
|
720
|
+
}
|
|
721
|
+
reduction = Math.max(0, reduction);
|
|
722
|
+
const requestBytes = utf8Bytes(input.request.text);
|
|
723
|
+
return {
|
|
724
|
+
request_utf8_bytes: requestBytes,
|
|
725
|
+
still_fails_with_empty_request: emptyBlockers.length > 0,
|
|
726
|
+
shortening_request_can_help: emptyBlockers.length === 0,
|
|
727
|
+
minimum_request_byte_reduction: reduction,
|
|
728
|
+
maximum_safe_request_utf8_bytes: Math.max(0, requestBytes - reduction),
|
|
729
|
+
blockers_with_empty_request: emptyBlockers,
|
|
730
|
+
};
|
|
731
|
+
}
|
|
732
|
+
failure(primary, plan, artifactDir, measurementKind, checkKind) {
|
|
733
|
+
const composition = plan.primary_blocker_composition;
|
|
734
|
+
const dominantByteClass = primary.input_only_estimate.rateSource.dominant_byte_class;
|
|
735
|
+
const remediation = dominantRemediation(plan.empty_request, composition, dominantByteClass, this.profile);
|
|
736
|
+
const tokensOver = primary.input_only_input_tokens_upper_bound - primary.allowed_input_tokens;
|
|
737
|
+
const budget = {
|
|
738
|
+
budget_stage: primary.budget_stage,
|
|
739
|
+
measurement_kind: measurementKind,
|
|
740
|
+
check_kind: checkKind,
|
|
741
|
+
measured_utf8_bytes: primary.input_utf8_bytes,
|
|
742
|
+
measured_input_tokens_upper_bound: primary.input_only_input_tokens_upper_bound,
|
|
743
|
+
allowed_input_tokens: primary.allowed_input_tokens,
|
|
744
|
+
limiting_model: {
|
|
745
|
+
provider: primary.route.provider,
|
|
746
|
+
model: primary.route.model,
|
|
747
|
+
qualified_id: primary.route.qualified_id,
|
|
748
|
+
context_window_tokens: primary.route.context_window_tokens,
|
|
749
|
+
},
|
|
750
|
+
rate_source: primary.input_only_estimate.rateSource,
|
|
751
|
+
backed: primary.input_only_estimate.rateSource.backed,
|
|
752
|
+
dominant_byte_class: dominantByteClass,
|
|
753
|
+
component_breakdown: componentBreakdown(composition, primary.route),
|
|
754
|
+
byte_class_breakdown: primary.input_only_estimate.byte_class_breakdown,
|
|
755
|
+
dense_regions: [],
|
|
756
|
+
bytes_over: primary.bytes_over,
|
|
757
|
+
tokens_over: Math.max(0, tokensOver),
|
|
758
|
+
required_allowed_tokens: primary.input_only_input_tokens_upper_bound,
|
|
759
|
+
route_table: routeTable(this.routes),
|
|
760
|
+
counterfactuals: inputCounterfactuals(primary, plan),
|
|
761
|
+
stage_upstream_actuals: [],
|
|
762
|
+
policy_id: FUSION_BUDGET_POLICY.id,
|
|
763
|
+
calibration_version: TOKEN_BUDGET_CALIBRATION_VERSION,
|
|
764
|
+
context_policy_id: this.contextPolicyId,
|
|
765
|
+
remediation,
|
|
766
|
+
blockers: plan.blockers,
|
|
767
|
+
artifact_dir: artifactDir,
|
|
768
|
+
};
|
|
769
|
+
if (primary.slot !== undefined)
|
|
770
|
+
budget.slot = primary.slot;
|
|
771
|
+
const compositionText = composition === undefined ? 'unavailable' : formatComposition(composition);
|
|
772
|
+
const additional = plan.blockers
|
|
773
|
+
.filter((blocker) => blocker !== primary)
|
|
774
|
+
.map((blocker) => `${entryLabel(blocker)} route=${blocker.route.qualified_id}`)
|
|
775
|
+
.join('; ');
|
|
776
|
+
const rateText = `${primary.route.family} ${formatRateX100(primary.input_only_estimate.rateSource.effective_rate_bytes_per_token_x100)} B/tok + ${String(primary.input_only_estimate.rateSource.affine_f_tokens)} tokens (${primary.input_only_estimate.rateSource.source}, backed=${String(primary.input_only_estimate.rateSource.backed)}, dominant=${dominantByteClass})`;
|
|
777
|
+
const sourceWarning = primary.input_only_estimate.rateSource.warning;
|
|
778
|
+
const routeWarning = sourceWarning === null ? '' : ` Rate warning: ${sourceWarning}.`;
|
|
779
|
+
const checkText = checkKind === 'input_only_preflight'
|
|
780
|
+
? 'input-only preflight forecast'
|
|
781
|
+
: 'exact rendered prompt measurement';
|
|
782
|
+
const dominantText = dominantByteClass === 'multibyte'
|
|
783
|
+
? ' Dominant byte class is multibyte UTF-8; the fatal gate uses the conservative multibyte rate and the plan separately records the provable 1.00 B/tok advisory ceiling.'
|
|
784
|
+
: dominantByteClass === 'dense_ascii'
|
|
785
|
+
? ' Dominant byte class is dense ASCII/low-whitespace content; the whitespace gate is a heuristic token-density proxy, not a bound.'
|
|
786
|
+
: ` Dominant byte class is ${dominantByteClass}.`;
|
|
787
|
+
const message = `Fusion prompt budget exceeded by ${checkText} before ${blockingChildLabel(primary)} child creation. Primary blocking stage: ${entryLabel(primary)} on route ${primary.route.qualified_id}. ` +
|
|
788
|
+
`Forecast ${String(primary.input_utf8_bytes)} UTF-8 bytes (<= ${String(primary.input_only_input_tokens_upper_bound)} input tokens) against ${String(primary.allowed_input_tokens)} allowed input tokens, over by ${String(Math.max(0, tokensOver))} tokens. ` +
|
|
789
|
+
`Estimator: ${rateText}.${routeWarning}${dominantText} ` +
|
|
790
|
+
`The ${blockingChildLabel(primary)} child was not created. Nothing was clipped, dropped, or substituted. Artifact directory: ${artifactDir}.\n` +
|
|
791
|
+
`Per-stage forecast table:\n${formatTable(plan.stages)}\n` +
|
|
792
|
+
`Primary blocker byte composition: ${compositionText}.\n` +
|
|
793
|
+
`Additional blockers: ${additional.length === 0 ? 'none' : additional}.\n` +
|
|
794
|
+
`${formatEmptyRequestVerdict(plan.empty_request)}\n` +
|
|
795
|
+
`Route byte-capacity order: ${routeTable(this.routes).map((route) => `${route.qualified_id}=${String(route.byte_capacity_utf8_bytes)}B`).join(', ')}.\n` +
|
|
796
|
+
`Remediation: ${remediation.join(' ')}`;
|
|
797
|
+
const details = {
|
|
798
|
+
code: budgetErrorCode(checkKind),
|
|
799
|
+
childCreated: false,
|
|
800
|
+
budget,
|
|
801
|
+
stage: stageFromBudgetStage(primary.budget_stage),
|
|
802
|
+
};
|
|
803
|
+
if (primary.slot !== undefined)
|
|
804
|
+
return new FusionError(message, { ...details, slot: primary.slot });
|
|
805
|
+
return new FusionError(message, details);
|
|
806
|
+
}
|
|
807
|
+
planMetadata(input) {
|
|
808
|
+
return {
|
|
809
|
+
workflow: this.profile.id,
|
|
810
|
+
context: {
|
|
811
|
+
kind: this.profile.contextKind,
|
|
812
|
+
policy_id: input?.context?.policy_id ?? this.contextPolicyId,
|
|
813
|
+
},
|
|
814
|
+
fixed_candidate_policy: {
|
|
815
|
+
capability: this.candidateCapability,
|
|
816
|
+
tools: this.profile.candidateTools,
|
|
817
|
+
},
|
|
818
|
+
tool_policy: {
|
|
819
|
+
candidate_tools: this.profile.candidateTools,
|
|
820
|
+
evaluation_tools: [],
|
|
821
|
+
merge_tools: [],
|
|
822
|
+
},
|
|
823
|
+
};
|
|
824
|
+
}
|
|
825
|
+
plan(input) {
|
|
826
|
+
const stages = this.entries(input);
|
|
827
|
+
const blockers = selectBlockers(stages);
|
|
828
|
+
const primary = selectPrimaryBlocker(blockers);
|
|
829
|
+
const emptyRequest = this.emptyRequestVerdict(input, stages);
|
|
830
|
+
const base = {
|
|
831
|
+
schema_version: FUSION_BUDGET_PLAN_SCHEMA_VERSION,
|
|
832
|
+
...this.planMetadata(input),
|
|
833
|
+
policy: FUSION_BUDGET_POLICY,
|
|
834
|
+
routes: this.routes,
|
|
835
|
+
stages,
|
|
836
|
+
blockers,
|
|
837
|
+
empty_request: emptyRequest,
|
|
838
|
+
warnings: warningsFor(stages),
|
|
839
|
+
};
|
|
840
|
+
if (primary === undefined)
|
|
841
|
+
return base;
|
|
842
|
+
return {
|
|
843
|
+
...base,
|
|
844
|
+
primary_blocker: primary,
|
|
845
|
+
primary_blocker_composition: this.composition(input, primary),
|
|
846
|
+
};
|
|
847
|
+
}
|
|
848
|
+
assertPlanFits(plan, artifactDir) {
|
|
849
|
+
if (plan.primary_blocker !== undefined) {
|
|
850
|
+
throw this.failure(plan.primary_blocker, plan, artifactDir, 'stage_forecast', 'input_only_preflight');
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
assertStagePrompt(stage, systemPrompt, userPrompt, slot) {
|
|
854
|
+
const route = this.routeForStage(stage, slot);
|
|
855
|
+
const inputSegments = [knownTextSegment(systemPrompt), knownTextSegment(userPrompt)];
|
|
856
|
+
const inputBytes = inputSegments.reduce((sum, segment) => sum + segment.bytes, 0);
|
|
857
|
+
const estimate = estimateRouteInput(route, inputSegments);
|
|
858
|
+
if (estimate.tokens <= route.allowed_input_tokens)
|
|
859
|
+
return;
|
|
860
|
+
const entry = {
|
|
861
|
+
budget_stage: stage,
|
|
862
|
+
route,
|
|
863
|
+
conditional: stage === 'evaluation_repair',
|
|
864
|
+
check_kind: 'input_only_preflight',
|
|
865
|
+
input_utf8_bytes: inputBytes,
|
|
866
|
+
upstream_output_contract_bytes: 0,
|
|
867
|
+
forecast_utf8_bytes: inputBytes,
|
|
868
|
+
input_only_input_tokens_upper_bound: estimate.tokens,
|
|
869
|
+
forecast_input_tokens_upper_bound: estimate.tokens,
|
|
870
|
+
allowed_input_tokens: route.allowed_input_tokens,
|
|
871
|
+
input_only_signed_headroom_tokens: route.allowed_input_tokens - estimate.tokens,
|
|
872
|
+
signed_headroom_tokens: route.allowed_input_tokens - estimate.tokens,
|
|
873
|
+
input_only_utilization_basis_points: utilizationBasisPoints(estimate.tokens, route.allowed_input_tokens),
|
|
874
|
+
utilization_basis_points: utilizationBasisPoints(estimate.tokens, route.allowed_input_tokens),
|
|
875
|
+
input_only_estimate: estimate,
|
|
876
|
+
reservation_estimate: estimate,
|
|
877
|
+
fits: false,
|
|
878
|
+
reservation_fits: false,
|
|
879
|
+
};
|
|
880
|
+
if (slot !== undefined)
|
|
881
|
+
entry.slot = slot;
|
|
882
|
+
const blocker = blockerFromEntry(entry);
|
|
883
|
+
const plan = {
|
|
884
|
+
schema_version: FUSION_BUDGET_PLAN_SCHEMA_VERSION,
|
|
885
|
+
...this.planMetadata(),
|
|
886
|
+
policy: FUSION_BUDGET_POLICY,
|
|
887
|
+
routes: this.routes,
|
|
888
|
+
stages: [entry],
|
|
889
|
+
blockers: [blocker],
|
|
890
|
+
primary_blocker: blocker,
|
|
891
|
+
empty_request: {
|
|
892
|
+
request_utf8_bytes: 0,
|
|
893
|
+
still_fails_with_empty_request: true,
|
|
894
|
+
shortening_request_can_help: false,
|
|
895
|
+
minimum_request_byte_reduction: blocker.bytes_over,
|
|
896
|
+
maximum_safe_request_utf8_bytes: 0,
|
|
897
|
+
blockers_with_empty_request: [blocker],
|
|
898
|
+
},
|
|
899
|
+
warnings: [],
|
|
900
|
+
};
|
|
901
|
+
throw this.failure(blocker, plan, 'stage prompt re-measurement', 'rendered_prompt', 'rendered_prompt');
|
|
902
|
+
}
|
|
903
|
+
calibrationViolationForCompletedChild(stage, systemPrompt, userPrompt, result, slot) {
|
|
904
|
+
const route = this.routeForStage(stage, slot);
|
|
905
|
+
const inputSegments = [knownTextSegment(systemPrompt), knownTextSegment(userPrompt)];
|
|
906
|
+
const promptUtf8Bytes = inputSegments.reduce((sum, segment) => sum + segment.bytes, 0);
|
|
907
|
+
const estimate = estimateRouteInput(route, inputSegments);
|
|
908
|
+
// The forecast is a one-request admission estimate. Compare it only with
|
|
909
|
+
// the first provider request, never with aggregate agent-loop/cache usage.
|
|
910
|
+
// Custom child runners predating this observation field remain compatible,
|
|
911
|
+
// but cannot produce a calibration verdict without like-for-like evidence.
|
|
912
|
+
const observedUsage = result.firstRequestUsage;
|
|
913
|
+
if (observedUsage === undefined)
|
|
914
|
+
return undefined;
|
|
915
|
+
const billedInput = observedUsage.input + observedUsage.cacheRead + observedUsage.cacheWrite;
|
|
916
|
+
if (billedInput <= estimate.tokens)
|
|
917
|
+
return undefined;
|
|
918
|
+
const violation = {
|
|
919
|
+
schema_version: FUSION_CALIBRATION_VIOLATION_SCHEMA_VERSION,
|
|
920
|
+
stage,
|
|
921
|
+
attempt: result.attempt,
|
|
922
|
+
route: {
|
|
923
|
+
provider: result.provider,
|
|
924
|
+
model: result.model,
|
|
925
|
+
qualified_id: result.qualifiedId,
|
|
926
|
+
},
|
|
927
|
+
family: route.family,
|
|
928
|
+
rate_source: estimate.rateSource,
|
|
929
|
+
prompt_utf8_bytes: promptUtf8Bytes,
|
|
930
|
+
prompt_sha256: sha256Hex(`${systemPrompt}\u0000${userPrompt}`),
|
|
931
|
+
observation_scope: 'first_provider_request',
|
|
932
|
+
provider_request_count: result.providerRequestCount ?? 1,
|
|
933
|
+
forecast_input_tokens: estimate.tokens,
|
|
934
|
+
billed_input_tokens: billedInput,
|
|
935
|
+
billed_input_breakdown: {
|
|
936
|
+
input: observedUsage.input,
|
|
937
|
+
cache_read: observedUsage.cacheRead,
|
|
938
|
+
cache_write: observedUsage.cacheWrite,
|
|
939
|
+
},
|
|
940
|
+
under_forecast_tokens: billedInput - estimate.tokens,
|
|
941
|
+
byte_class_breakdown: estimate.byte_class_breakdown,
|
|
942
|
+
dominant_byte_class: estimate.rateSource.dominant_byte_class,
|
|
943
|
+
};
|
|
944
|
+
if (slot !== undefined)
|
|
945
|
+
violation.slot = slot;
|
|
946
|
+
return violation;
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
//# sourceMappingURL=budget.js.map
|