@pi-unipi/background-tasks 2.6.1
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/README.md +87 -0
- package/extensions/anthropic-attribution.ts +1 -0
- package/extensions/delegate-child.ts +1 -0
- package/extensions/fusion-child.ts +1 -0
- package/package.json +40 -0
- package/src/__tests__/anthropic-attribution.test.ts +195 -0
- package/src/__tests__/config.test.ts +137 -0
- package/src/__tests__/core.test.ts +493 -0
- package/src/__tests__/delegate-artifacts.test.ts +528 -0
- package/src/__tests__/delegate-budget.test.ts +456 -0
- package/src/__tests__/delegate-launch.test.ts +676 -0
- package/src/__tests__/delegate-result-package.test.ts +350 -0
- package/src/__tests__/delegate-seed.test.ts +392 -0
- package/src/__tests__/durable-fs.test.ts +559 -0
- package/src/__tests__/extension-api.test.ts +579 -0
- package/src/__tests__/fusion-artifacts.test.ts +1039 -0
- package/src/__tests__/fusion-budget.test.ts +1356 -0
- package/src/__tests__/fusion-claude-cache.test.ts +320 -0
- package/src/__tests__/fusion-config.test.ts +335 -0
- package/src/__tests__/fusion-context-prompts.test.ts +670 -0
- package/src/__tests__/fusion-evaluation.test.ts +315 -0
- package/src/__tests__/fusion-extraction-equivalence.test.ts +58 -0
- package/src/__tests__/fusion-golden-bytes.test.ts +35 -0
- package/src/__tests__/fusion-high-cardinality.test.ts +192 -0
- package/src/__tests__/fusion-model-selector.test.ts +205 -0
- package/src/__tests__/fusion-orchestrator.test.ts +1194 -0
- package/src/__tests__/fusion-rpc.test.ts +369 -0
- package/src/__tests__/fusion-sdk.test.ts +1226 -0
- package/src/__tests__/fusion-v5-core.test.ts +219 -0
- package/src/__tests__/fusion-validate-orchestrator.test.ts +240 -0
- package/src/__tests__/fusion-web-fetch.test.ts +485 -0
- package/src/__tests__/fusion-workflows.test.ts +59 -0
- package/src/__tests__/helpers/delegate-deterministic-seed.ts +109 -0
- package/src/__tests__/helpers/delegate-seed-subprocess.ts +10 -0
- package/src/__tests__/helpers/fusion-canonical-subprocess.ts +21 -0
- package/src/__tests__/helpers/fusion-canonical.ts +140 -0
- package/src/__tests__/helpers/fusion-fake-pi.ts +279 -0
- package/src/__tests__/helpers/fusion-golden-corpus.ts +500 -0
- package/src/__tests__/helpers/fusion-high-cardinality.ts +140 -0
- package/src/__tests__/helpers/normalize.ts +22 -0
- package/src/__tests__/helpers/pi-hook-contract-evidence.json +18 -0
- package/src/__tests__/pi-launch.test.ts +202 -0
- package/src/__tests__/registry.test.ts +1580 -0
- package/src/__tests__/scripted-provider/delegate-ambient-provider.test.ts +130 -0
- package/src/__tests__/scripted-provider/delegate-child-guard.test.ts +631 -0
- package/src/__tests__/scripted-provider/delegate-guard-provider.ts +403 -0
- package/src/__tests__/scripted-provider/follow-up.test.ts +448 -0
- package/src/__tests__/scripted-provider/fusion-output-recovery.test.ts +132 -0
- package/src/__tests__/scripted-provider/fusion-reason.test.ts +310 -0
- package/src/__tests__/scripted-provider/fusion-runtime-guard.test.ts +163 -0
- package/src/__tests__/scripted-provider/hook-contract-provider.ts +179 -0
- package/src/__tests__/scripted-provider/hook-probe-a.ts +3 -0
- package/src/__tests__/scripted-provider/hook-probe-b.ts +3 -0
- package/src/__tests__/scripted-provider/hook-probe-extension.ts +126 -0
- package/src/__tests__/scripted-provider/output-recovery-provider.ts +153 -0
- package/src/__tests__/scripted-provider/pi-hook-contract-evidence.json +18 -0
- package/src/__tests__/scripted-provider/pi-hook-contract.test.ts +477 -0
- package/src/__tests__/scripted-provider/runtime-guard-probe.ts +28 -0
- package/src/__tests__/scripted-provider/runtime-guard-provider.ts +49 -0
- package/src/__tests__/scripted-provider/scripted-provider-extension.ts +408 -0
- package/src/__tests__/task-manager.test.ts +479 -0
- package/src/__tests__/windows-taskkill.test.ts +161 -0
- package/src/anthropic-attribution-path.ts +21 -0
- package/src/anthropic-attribution.ts +1983 -0
- package/src/attested-pi-run.ts +612 -0
- package/src/child-process.ts +55 -0
- package/src/common.ts +8 -0
- package/src/config.ts +292 -0
- package/src/context-parent-snapshot.ts +142 -0
- package/src/context-token-budget.ts +903 -0
- package/src/context-visible-conversation-v2.ts +551 -0
- package/src/delegate/artifacts.ts +487 -0
- package/src/delegate/budget.ts +415 -0
- package/src/delegate/hook-contract-evidence.json +18 -0
- package/src/delegate/hook-contract.ts +154 -0
- package/src/delegate/launch.ts +497 -0
- package/src/delegate/result-package.ts +459 -0
- package/src/delegate/runner.ts +449 -0
- package/src/delegate/seed.ts +423 -0
- package/src/delegate/types.ts +323 -0
- package/src/delegate-child-extension.ts +978 -0
- package/src/delegate-extension.ts +806 -0
- package/src/durable-fs.ts +386 -0
- package/src/extension-api.ts +548 -0
- package/src/fixtures/delegate-context-incident.json +17 -0
- package/src/fixtures/fusion-golden-bytes.json +310 -0
- package/src/fixtures/fusion-validate-golden-bytes.json +282 -0
- package/src/fusion/artifacts.ts +967 -0
- package/src/fusion/budget.ts +1162 -0
- package/src/fusion/child-protocol.ts +305 -0
- package/src/fusion/claude-cache.ts +207 -0
- package/src/fusion/clean-context.ts +91 -0
- package/src/fusion/config.ts +449 -0
- package/src/fusion/context.ts +265 -0
- package/src/fusion/evaluation.ts +800 -0
- package/src/fusion/orchestrator.ts +1288 -0
- package/src/fusion/output-contract.ts +34 -0
- package/src/fusion/pi-child.ts +2373 -0
- package/src/fusion/prompts.ts +345 -0
- package/src/fusion/result-package.ts +959 -0
- package/src/fusion/source-policy.ts +257 -0
- package/src/fusion/types.ts +1139 -0
- package/src/fusion/web-fetch.ts +1060 -0
- package/src/fusion/workflows.ts +184 -0
- package/src/fusion-child-extension.ts +1052 -0
- package/src/fusion-extension.ts +1293 -0
- package/src/index.ts +295 -0
- package/src/pi-launch.ts +225 -0
- package/src/registry.ts +2424 -0
- package/src/settings-overlay.ts +208 -0
- package/src/task-manager.ts +774 -0
- package/src/tools.ts +530 -0
- package/src/turndown.d.ts +15 -0
- package/src/types.ts +963 -0
- package/src/ui/fusion-model-selector.ts +322 -0
- package/src/windows-taskkill.ts +250 -0
|
@@ -0,0 +1,903 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared, dependency-free size arithmetic for prompt budgeting.
|
|
3
|
+
*
|
|
4
|
+
* Fusion and delegate both use the same pure estimator, but they pass distinct
|
|
5
|
+
* scope profiles. Fusion may use a calibrated family rate only for measured
|
|
6
|
+
* large prompts that remain in the calibration domain. Delegate uses a stricter
|
|
7
|
+
* byte-ceiling profile because its 8,192-token floor is too small for relaxed
|
|
8
|
+
* rates.
|
|
9
|
+
*
|
|
10
|
+
* Calibration basis: 882 real large Fusion prompts. The observed floors are
|
|
11
|
+
* 2.047 B/tok for Anthropic and 3.400 B/tok for Codex. The shipped rates apply
|
|
12
|
+
* a 15% haircut and add a provisional 512-token affine intercept. The
|
|
13
|
+
* low-whitespace gate below is a corpus-derived heuristic proxy for dense ASCII
|
|
14
|
+
* token density; it is not a tokenizer bound or guarantee.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
export const TOKEN_BUDGET_CALIBRATION_VERSION =
|
|
18
|
+
'pi-background-tasks.input-token-calibration.v1' as const;
|
|
19
|
+
export const TOKEN_BUDGET_RATE_SCALE = 100;
|
|
20
|
+
export const TOKEN_BUDGET_PROVENANCE_SCALE = 1000;
|
|
21
|
+
export const TOKEN_BUDGET_HAIRCUT_BASIS_POINTS = 1500;
|
|
22
|
+
export const TOKEN_BUDGET_LARGE_PROMPT_MIN_BYTES = 50 * 1024;
|
|
23
|
+
export const TOKEN_BUDGET_CONSERVATIVE_RATE_X100 = 200;
|
|
24
|
+
export const TOKEN_BUDGET_PROVABLE_RATE_X100 = 100;
|
|
25
|
+
export const TOKEN_BUDGET_DELEGATE_CONSERVATIVE_RATE_X100 = TOKEN_BUDGET_PROVABLE_RATE_X100;
|
|
26
|
+
export const TOKEN_BUDGET_MULTIBYTE_FATAL_RATE_X100 = TOKEN_BUDGET_CONSERVATIVE_RATE_X100;
|
|
27
|
+
export const TOKEN_BUDGET_AFFINE_F_TOKENS = 512;
|
|
28
|
+
export const TOKEN_BUDGET_WHITESPACE_FRACTION_SCALE = 10_000;
|
|
29
|
+
/**
|
|
30
|
+
* Floor of the observed large-prompt calibration corpus, scaled by
|
|
31
|
+
* TOKEN_BUDGET_WHITESPACE_FRACTION_SCALE and rounded down. The gate threshold is
|
|
32
|
+
* deliberately below this value; it catches near-zero-whitespace OOD payloads
|
|
33
|
+
* without claiming to bound tokenizer density.
|
|
34
|
+
*/
|
|
35
|
+
export const TOKEN_BUDGET_CALIBRATION_CORPUS_MIN_WHITESPACE_FRACTION_X10000 = 18;
|
|
36
|
+
export const TOKEN_BUDGET_DENSE_ASCII_WHITESPACE_THRESHOLD_X10000 = 10;
|
|
37
|
+
|
|
38
|
+
export const TOKEN_BUDGET_FAMILIES = ['anthropic', 'openai-codex', 'unknown'] as const;
|
|
39
|
+
export type TokenBudgetFamily = (typeof TOKEN_BUDGET_FAMILIES)[number];
|
|
40
|
+
|
|
41
|
+
export const TOKEN_BUDGET_SEGMENT_KINDS = [
|
|
42
|
+
'known_text',
|
|
43
|
+
'known_json',
|
|
44
|
+
'unknown_output_contract',
|
|
45
|
+
] as const;
|
|
46
|
+
export type TokenBudgetSegmentKind = (typeof TOKEN_BUDGET_SEGMENT_KINDS)[number];
|
|
47
|
+
|
|
48
|
+
export type TokenBudgetEstimatorScope =
|
|
49
|
+
| 'fusion'
|
|
50
|
+
| 'delegate_launch'
|
|
51
|
+
| 'delegate'
|
|
52
|
+
| 'conservative';
|
|
53
|
+
export type TokenBudgetDominantByteClass =
|
|
54
|
+
| 'normal'
|
|
55
|
+
| 'dense_ascii'
|
|
56
|
+
| 'multibyte'
|
|
57
|
+
| 'unknown_output_contract';
|
|
58
|
+
|
|
59
|
+
export interface TokenBudgetCalibrationProvenance {
|
|
60
|
+
n: number;
|
|
61
|
+
observed_min_bpt_x1000: number | null;
|
|
62
|
+
median_bpt_x1000: number | null;
|
|
63
|
+
max_bpt_x1000: number | null;
|
|
64
|
+
corpus_sha256: string | null;
|
|
65
|
+
corpus_date: string;
|
|
66
|
+
haircut_basis_points: number;
|
|
67
|
+
backed: boolean;
|
|
68
|
+
byte_level_bpe: boolean;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface TokenBudgetFamilyCalibration {
|
|
72
|
+
family: TokenBudgetFamily;
|
|
73
|
+
rate_bytes_per_token_x100: number;
|
|
74
|
+
affine_f_tokens: number;
|
|
75
|
+
provenance: TokenBudgetCalibrationProvenance;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const ANTHROPIC_PROVENANCE: TokenBudgetCalibrationProvenance = Object.freeze({
|
|
79
|
+
n: 85,
|
|
80
|
+
observed_min_bpt_x1000: 2047,
|
|
81
|
+
median_bpt_x1000: 2217,
|
|
82
|
+
max_bpt_x1000: 2481,
|
|
83
|
+
corpus_sha256: 'sha256:large-fusion-prompts-2026-08-02',
|
|
84
|
+
corpus_date: '2026-08-02',
|
|
85
|
+
haircut_basis_points: TOKEN_BUDGET_HAIRCUT_BASIS_POINTS,
|
|
86
|
+
backed: true,
|
|
87
|
+
byte_level_bpe: true,
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
const OPENAI_CODEX_PROVENANCE: TokenBudgetCalibrationProvenance = Object.freeze({
|
|
91
|
+
n: 797,
|
|
92
|
+
observed_min_bpt_x1000: 3400,
|
|
93
|
+
median_bpt_x1000: 3721,
|
|
94
|
+
max_bpt_x1000: 4526,
|
|
95
|
+
corpus_sha256: 'sha256:large-fusion-prompts-2026-08-02',
|
|
96
|
+
corpus_date: '2026-08-02',
|
|
97
|
+
haircut_basis_points: TOKEN_BUDGET_HAIRCUT_BASIS_POINTS,
|
|
98
|
+
backed: true,
|
|
99
|
+
byte_level_bpe: true,
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
const UNKNOWN_PROVENANCE: TokenBudgetCalibrationProvenance = Object.freeze({
|
|
103
|
+
n: 0,
|
|
104
|
+
observed_min_bpt_x1000: null,
|
|
105
|
+
median_bpt_x1000: null,
|
|
106
|
+
max_bpt_x1000: null,
|
|
107
|
+
corpus_sha256: null,
|
|
108
|
+
corpus_date: 'unbacked',
|
|
109
|
+
haircut_basis_points: TOKEN_BUDGET_HAIRCUT_BASIS_POINTS,
|
|
110
|
+
backed: false,
|
|
111
|
+
byte_level_bpe: true,
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
export const TOKEN_BUDGET_FAMILY_CALIBRATIONS: Readonly<
|
|
115
|
+
Record<TokenBudgetFamily, TokenBudgetFamilyCalibration>
|
|
116
|
+
> = Object.freeze({
|
|
117
|
+
anthropic: Object.freeze({
|
|
118
|
+
family: 'anthropic',
|
|
119
|
+
rate_bytes_per_token_x100: 173,
|
|
120
|
+
affine_f_tokens: TOKEN_BUDGET_AFFINE_F_TOKENS,
|
|
121
|
+
provenance: ANTHROPIC_PROVENANCE,
|
|
122
|
+
}),
|
|
123
|
+
'openai-codex': Object.freeze({
|
|
124
|
+
family: 'openai-codex',
|
|
125
|
+
rate_bytes_per_token_x100: 289,
|
|
126
|
+
affine_f_tokens: TOKEN_BUDGET_AFFINE_F_TOKENS,
|
|
127
|
+
provenance: OPENAI_CODEX_PROVENANCE,
|
|
128
|
+
}),
|
|
129
|
+
unknown: Object.freeze({
|
|
130
|
+
family: 'unknown',
|
|
131
|
+
rate_bytes_per_token_x100: 100,
|
|
132
|
+
affine_f_tokens: TOKEN_BUDGET_AFFINE_F_TOKENS,
|
|
133
|
+
provenance: UNKNOWN_PROVENANCE,
|
|
134
|
+
}),
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
const MODEL_OVERRIDES: Readonly<Record<string, TokenBudgetFamily>> = Object.freeze({
|
|
138
|
+
'anthropic/claude-opus-5': 'anthropic',
|
|
139
|
+
'anthropic/claude-fable-5': 'anthropic',
|
|
140
|
+
'openai-codex/gpt-5.6-sol': 'openai-codex',
|
|
141
|
+
'openai-codex/gpt-5.6-terra': 'openai-codex',
|
|
142
|
+
'openai-codex/gpt-5.5': 'openai-codex',
|
|
143
|
+
'openai-codex/gpt-5.4-mini': 'openai-codex',
|
|
144
|
+
});
|
|
145
|
+
const PROVIDER_DEFAULTS: Readonly<Record<string, TokenBudgetFamily>> = Object.freeze({
|
|
146
|
+
anthropic: 'anthropic',
|
|
147
|
+
'openai-codex': 'openai-codex',
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
export interface TokenBudgetRouteLike {
|
|
151
|
+
provider: string;
|
|
152
|
+
model: string;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export interface ResolvedTokenBudgetFamily {
|
|
156
|
+
family: TokenBudgetFamily;
|
|
157
|
+
provider: string;
|
|
158
|
+
model: string;
|
|
159
|
+
qualified_id: string;
|
|
160
|
+
backed: boolean;
|
|
161
|
+
resolution: 'model_override' | 'known_provider_unbacked_model' | 'unknown_provider_floor';
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export function resolveTokenBudgetFamily(route: TokenBudgetRouteLike): ResolvedTokenBudgetFamily {
|
|
165
|
+
const qualified = `${route.provider}/${route.model}`;
|
|
166
|
+
const overridden = MODEL_OVERRIDES[qualified];
|
|
167
|
+
if (overridden !== undefined) {
|
|
168
|
+
return {
|
|
169
|
+
family: overridden,
|
|
170
|
+
provider: route.provider,
|
|
171
|
+
model: route.model,
|
|
172
|
+
qualified_id: qualified,
|
|
173
|
+
backed: true,
|
|
174
|
+
resolution: 'model_override',
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
const providerDefault = PROVIDER_DEFAULTS[route.provider];
|
|
178
|
+
if (providerDefault !== undefined) {
|
|
179
|
+
return {
|
|
180
|
+
family: providerDefault,
|
|
181
|
+
provider: route.provider,
|
|
182
|
+
model: route.model,
|
|
183
|
+
qualified_id: qualified,
|
|
184
|
+
backed: false,
|
|
185
|
+
resolution: 'known_provider_unbacked_model',
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
return {
|
|
189
|
+
family: 'unknown',
|
|
190
|
+
provider: route.provider,
|
|
191
|
+
model: route.model,
|
|
192
|
+
qualified_id: qualified,
|
|
193
|
+
backed: false,
|
|
194
|
+
resolution: 'unknown_provider_floor',
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
export interface TokenBudgetSegment {
|
|
199
|
+
kind: TokenBudgetSegmentKind;
|
|
200
|
+
bytes: number;
|
|
201
|
+
multibyteBytes?: number | undefined;
|
|
202
|
+
denseBytes?: number | undefined;
|
|
203
|
+
asciiWhitespaceBytes?: number | undefined;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export interface TokenBudgetByteClassBreakdown {
|
|
207
|
+
total_bytes: number;
|
|
208
|
+
normal_bytes: number;
|
|
209
|
+
multibyte_bytes: number;
|
|
210
|
+
dense_bytes: number;
|
|
211
|
+
unknown_output_contract_bytes: number;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export interface TokenBudgetPromptProfile extends TokenBudgetByteClassBreakdown {
|
|
215
|
+
concrete_known_bytes: number;
|
|
216
|
+
ascii_whitespace_bytes: number;
|
|
217
|
+
whitespace_fraction_x10000: number | null;
|
|
218
|
+
whitespace_fraction_scale: typeof TOKEN_BUDGET_WHITESPACE_FRACTION_SCALE;
|
|
219
|
+
whitespace_fraction_available: boolean;
|
|
220
|
+
dominant_byte_class: TokenBudgetDominantByteClass;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
export interface TokenBudgetDenseAsciiGate {
|
|
224
|
+
heuristic: 'low_whitespace_fraction_proxy_not_tokenizer_bound';
|
|
225
|
+
corpus_min_whitespace_fraction_x10000: number;
|
|
226
|
+
threshold_whitespace_fraction_x10000: number;
|
|
227
|
+
measured_whitespace_fraction_x10000: number | null;
|
|
228
|
+
evaluated: boolean;
|
|
229
|
+
out_of_distribution: boolean;
|
|
230
|
+
decision: 'not_evaluated' | 'calibrated_allowed' | 'conservative_fallback';
|
|
231
|
+
reason: 'prompt_below_large_prompt_floor' | 'multibyte_or_non_ascii_dominant' | 'whitespace_fraction_unavailable' | 'below_threshold' | 'at_or_above_threshold' | null;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export interface TokenBudgetRateBucketEstimate {
|
|
235
|
+
rate_bytes_per_token_x100: number;
|
|
236
|
+
bytes: number;
|
|
237
|
+
tokens: number;
|
|
238
|
+
byte_classes: readonly TokenBudgetDominantByteClass[];
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
export interface TokenBudgetAdvisoryEstimate {
|
|
242
|
+
multibyte_provable_rate_bytes_per_token_x100: typeof TOKEN_BUDGET_PROVABLE_RATE_X100;
|
|
243
|
+
multibyte_provable_tokens: number;
|
|
244
|
+
input_tokens_if_multibyte_used_provable_ceiling: number;
|
|
245
|
+
rate_buckets: readonly TokenBudgetRateBucketEstimate[];
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
export interface TokenBudgetPerSegmentEstimate extends TokenBudgetByteClassBreakdown {
|
|
249
|
+
kind: TokenBudgetSegmentKind;
|
|
250
|
+
ascii_whitespace_bytes: number;
|
|
251
|
+
normal_rate_bytes_per_token_x100: number;
|
|
252
|
+
normal_tokens: number;
|
|
253
|
+
multibyte_rate_bytes_per_token_x100: typeof TOKEN_BUDGET_MULTIBYTE_FATAL_RATE_X100;
|
|
254
|
+
multibyte_tokens: number;
|
|
255
|
+
multibyte_provable_tokens: number;
|
|
256
|
+
dense_tokens: number;
|
|
257
|
+
unknown_output_contract_tokens: number;
|
|
258
|
+
tokens: number;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export interface TokenBudgetRateSource {
|
|
262
|
+
calibration_version: typeof TOKEN_BUDGET_CALIBRATION_VERSION;
|
|
263
|
+
family: TokenBudgetFamily;
|
|
264
|
+
configured_rate_bytes_per_token_x100: number;
|
|
265
|
+
effective_rate_bytes_per_token_x100: number;
|
|
266
|
+
conservative_rate_bytes_per_token_x100: number;
|
|
267
|
+
delegate_conservative_rate_bytes_per_token_x100: typeof TOKEN_BUDGET_DELEGATE_CONSERVATIVE_RATE_X100;
|
|
268
|
+
affine_f_tokens: number;
|
|
269
|
+
scope: TokenBudgetEstimatorScope;
|
|
270
|
+
source:
|
|
271
|
+
| 'calibrated_large_window'
|
|
272
|
+
| 'conservative_small_prompt'
|
|
273
|
+
| 'conservative_capacity_guard'
|
|
274
|
+
| 'conservative_dense_ascii_whitespace_gate'
|
|
275
|
+
| 'delegate_conservative'
|
|
276
|
+
| 'explicit_conservative'
|
|
277
|
+
| 'unknown_provider_floor'
|
|
278
|
+
| 'unbacked_model_floor';
|
|
279
|
+
backed: boolean;
|
|
280
|
+
provenance: TokenBudgetCalibrationProvenance;
|
|
281
|
+
model_resolution: ResolvedTokenBudgetFamily['resolution'] | 'family_direct';
|
|
282
|
+
scope_guard_min_bytes: typeof TOKEN_BUDGET_LARGE_PROMPT_MIN_BYTES;
|
|
283
|
+
calibration_applied: boolean;
|
|
284
|
+
prompt_profile: TokenBudgetPromptProfile;
|
|
285
|
+
dense_ascii_gate: TokenBudgetDenseAsciiGate;
|
|
286
|
+
dominant_byte_class: TokenBudgetDominantByteClass;
|
|
287
|
+
warning: string | null;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
export interface EstimateInputTokensInput {
|
|
291
|
+
family: TokenBudgetFamily;
|
|
292
|
+
segments: readonly TokenBudgetSegment[];
|
|
293
|
+
allowedInputTokens?: number | undefined;
|
|
294
|
+
scope?: TokenBudgetEstimatorScope | undefined;
|
|
295
|
+
calibrationBacked?: boolean | undefined;
|
|
296
|
+
familyResolution?: ResolvedTokenBudgetFamily['resolution'] | 'family_direct' | undefined;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
export interface EstimateInputTokensResult {
|
|
300
|
+
tokens: number;
|
|
301
|
+
fixed_tokens: number;
|
|
302
|
+
perSegment: readonly TokenBudgetPerSegmentEstimate[];
|
|
303
|
+
byte_class_breakdown: TokenBudgetByteClassBreakdown;
|
|
304
|
+
rate_buckets: readonly TokenBudgetRateBucketEstimate[];
|
|
305
|
+
advisory: TokenBudgetAdvisoryEstimate;
|
|
306
|
+
rateSource: TokenBudgetRateSource;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function assertSafeNonNegativeInteger(value: number, label: string): void {
|
|
310
|
+
if (!Number.isSafeInteger(value) || value < 0) {
|
|
311
|
+
throw new TypeError(`${label} must be a non-negative safe integer`);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function assertPositiveInteger(value: number, label: string): void {
|
|
316
|
+
if (!Number.isSafeInteger(value) || value <= 0) {
|
|
317
|
+
throw new TypeError(`${label} must be a positive safe integer`);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function calibrationFor(family: TokenBudgetFamily): TokenBudgetFamilyCalibration {
|
|
322
|
+
return TOKEN_BUDGET_FAMILY_CALIBRATIONS[family];
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function ceilDiv(numerator: number, denominator: number): number {
|
|
326
|
+
assertSafeNonNegativeInteger(numerator, 'division numerator');
|
|
327
|
+
assertPositiveInteger(denominator, 'division denominator');
|
|
328
|
+
if (numerator === 0) return 0;
|
|
329
|
+
return Math.floor((numerator - 1) / denominator) + 1;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
function tokensAtRate(bytes: number, rateBytesPerTokenX100: number): number {
|
|
333
|
+
assertSafeNonNegativeInteger(bytes, 'bytes');
|
|
334
|
+
assertPositiveInteger(rateBytesPerTokenX100, 'rateBytesPerTokenX100');
|
|
335
|
+
return ceilDiv(bytes * TOKEN_BUDGET_RATE_SCALE, rateBytesPerTokenX100);
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
function conservativeFusionRate(configured: number): number {
|
|
339
|
+
return Math.min(configured, TOKEN_BUDGET_CONSERVATIVE_RATE_X100);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
interface NormalizedTokenBudgetSegment {
|
|
343
|
+
kind: TokenBudgetSegmentKind;
|
|
344
|
+
bytes: number;
|
|
345
|
+
multibyteBytes: number;
|
|
346
|
+
denseBytes: number;
|
|
347
|
+
asciiWhitespaceBytes: number;
|
|
348
|
+
whitespaceKnown: boolean;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
function normalizeSegment(
|
|
352
|
+
segment: TokenBudgetSegment,
|
|
353
|
+
index: number,
|
|
354
|
+
): NormalizedTokenBudgetSegment {
|
|
355
|
+
assertSafeNonNegativeInteger(segment.bytes, `segments[${String(index)}].bytes`);
|
|
356
|
+
const denseBytes = segment.denseBytes ?? 0;
|
|
357
|
+
assertSafeNonNegativeInteger(denseBytes, `segments[${String(index)}].denseBytes`);
|
|
358
|
+
if (segment.kind === 'unknown_output_contract') {
|
|
359
|
+
if (segment.multibyteBytes !== undefined) {
|
|
360
|
+
throw new TypeError(
|
|
361
|
+
`segments[${String(index)}].multibyteBytes must not be set for unknown_output_contract`,
|
|
362
|
+
);
|
|
363
|
+
}
|
|
364
|
+
if (segment.asciiWhitespaceBytes !== undefined) {
|
|
365
|
+
throw new TypeError(
|
|
366
|
+
`segments[${String(index)}].asciiWhitespaceBytes must not be set for unknown_output_contract`,
|
|
367
|
+
);
|
|
368
|
+
}
|
|
369
|
+
if (denseBytes !== 0) {
|
|
370
|
+
throw new TypeError(
|
|
371
|
+
`segments[${String(index)}].denseBytes must be zero for unknown_output_contract`,
|
|
372
|
+
);
|
|
373
|
+
}
|
|
374
|
+
return {
|
|
375
|
+
kind: segment.kind,
|
|
376
|
+
bytes: segment.bytes,
|
|
377
|
+
multibyteBytes: 0,
|
|
378
|
+
denseBytes,
|
|
379
|
+
asciiWhitespaceBytes: 0,
|
|
380
|
+
whitespaceKnown: true,
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
if (segment.kind !== 'known_text' && segment.kind !== 'known_json') {
|
|
384
|
+
throw new TypeError(`segments[${String(index)}].kind is not supported`);
|
|
385
|
+
}
|
|
386
|
+
if (segment.multibyteBytes === undefined) {
|
|
387
|
+
throw new TypeError(`segments[${String(index)}].multibyteBytes is required`);
|
|
388
|
+
}
|
|
389
|
+
assertSafeNonNegativeInteger(segment.multibyteBytes, `segments[${String(index)}].multibyteBytes`);
|
|
390
|
+
if (segment.multibyteBytes + denseBytes > segment.bytes) {
|
|
391
|
+
throw new TypeError(
|
|
392
|
+
`segments[${String(index)}] byte classes exceed segment byte length`,
|
|
393
|
+
);
|
|
394
|
+
}
|
|
395
|
+
const whitespaceKnown = segment.asciiWhitespaceBytes !== undefined;
|
|
396
|
+
const asciiWhitespaceBytes = segment.asciiWhitespaceBytes ?? 0;
|
|
397
|
+
assertSafeNonNegativeInteger(
|
|
398
|
+
asciiWhitespaceBytes,
|
|
399
|
+
`segments[${String(index)}].asciiWhitespaceBytes`,
|
|
400
|
+
);
|
|
401
|
+
if (asciiWhitespaceBytes > segment.bytes - segment.multibyteBytes) {
|
|
402
|
+
throw new TypeError(
|
|
403
|
+
`segments[${String(index)}].asciiWhitespaceBytes exceeds ASCII byte length`,
|
|
404
|
+
);
|
|
405
|
+
}
|
|
406
|
+
return {
|
|
407
|
+
kind: segment.kind,
|
|
408
|
+
bytes: segment.bytes,
|
|
409
|
+
multibyteBytes: segment.multibyteBytes,
|
|
410
|
+
denseBytes,
|
|
411
|
+
asciiWhitespaceBytes,
|
|
412
|
+
whitespaceKnown,
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
function addBreakdown(
|
|
417
|
+
target: TokenBudgetByteClassBreakdown,
|
|
418
|
+
delta: TokenBudgetByteClassBreakdown,
|
|
419
|
+
): void {
|
|
420
|
+
target.total_bytes += delta.total_bytes;
|
|
421
|
+
target.normal_bytes += delta.normal_bytes;
|
|
422
|
+
target.multibyte_bytes += delta.multibyte_bytes;
|
|
423
|
+
target.dense_bytes += delta.dense_bytes;
|
|
424
|
+
target.unknown_output_contract_bytes += delta.unknown_output_contract_bytes;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
function dominantByteClass(breakdown: TokenBudgetByteClassBreakdown): TokenBudgetDominantByteClass {
|
|
428
|
+
const entries: Array<{ byteClass: TokenBudgetDominantByteClass; bytes: number; order: number }> = [
|
|
429
|
+
{ byteClass: 'dense_ascii', bytes: breakdown.dense_bytes, order: 0 },
|
|
430
|
+
{ byteClass: 'multibyte', bytes: breakdown.multibyte_bytes, order: 1 },
|
|
431
|
+
{ byteClass: 'unknown_output_contract', bytes: breakdown.unknown_output_contract_bytes, order: 2 },
|
|
432
|
+
{ byteClass: 'normal', bytes: breakdown.normal_bytes, order: 3 },
|
|
433
|
+
];
|
|
434
|
+
entries.sort((left, right) => right.bytes - left.bytes || left.order - right.order);
|
|
435
|
+
return entries[0]?.byteClass ?? 'normal';
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
function profileForSegments(
|
|
439
|
+
segments: readonly NormalizedTokenBudgetSegment[],
|
|
440
|
+
breakdown: TokenBudgetByteClassBreakdown,
|
|
441
|
+
): TokenBudgetPromptProfile {
|
|
442
|
+
let asciiWhitespaceBytes = 0;
|
|
443
|
+
let whitespaceKnown = true;
|
|
444
|
+
for (const segment of segments) {
|
|
445
|
+
if (segment.kind === 'unknown_output_contract') continue;
|
|
446
|
+
asciiWhitespaceBytes += segment.asciiWhitespaceBytes;
|
|
447
|
+
if (!segment.whitespaceKnown) whitespaceKnown = false;
|
|
448
|
+
}
|
|
449
|
+
const concreteKnownBytes = breakdown.total_bytes - breakdown.unknown_output_contract_bytes;
|
|
450
|
+
const whitespaceFraction =
|
|
451
|
+
whitespaceKnown && concreteKnownBytes > 0
|
|
452
|
+
? Math.floor((asciiWhitespaceBytes * TOKEN_BUDGET_WHITESPACE_FRACTION_SCALE) / concreteKnownBytes)
|
|
453
|
+
: null;
|
|
454
|
+
return {
|
|
455
|
+
...breakdown,
|
|
456
|
+
concrete_known_bytes: concreteKnownBytes,
|
|
457
|
+
ascii_whitespace_bytes: asciiWhitespaceBytes,
|
|
458
|
+
whitespace_fraction_x10000: whitespaceFraction,
|
|
459
|
+
whitespace_fraction_scale: TOKEN_BUDGET_WHITESPACE_FRACTION_SCALE,
|
|
460
|
+
whitespace_fraction_available: whitespaceKnown,
|
|
461
|
+
dominant_byte_class: dominantByteClass(breakdown),
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
function denseAsciiGate(profile: TokenBudgetPromptProfile): TokenBudgetDenseAsciiGate {
|
|
466
|
+
const base = {
|
|
467
|
+
heuristic: 'low_whitespace_fraction_proxy_not_tokenizer_bound' as const,
|
|
468
|
+
corpus_min_whitespace_fraction_x10000:
|
|
469
|
+
TOKEN_BUDGET_CALIBRATION_CORPUS_MIN_WHITESPACE_FRACTION_X10000,
|
|
470
|
+
threshold_whitespace_fraction_x10000:
|
|
471
|
+
TOKEN_BUDGET_DENSE_ASCII_WHITESPACE_THRESHOLD_X10000,
|
|
472
|
+
measured_whitespace_fraction_x10000: profile.whitespace_fraction_x10000,
|
|
473
|
+
};
|
|
474
|
+
if (profile.concrete_known_bytes < TOKEN_BUDGET_LARGE_PROMPT_MIN_BYTES) {
|
|
475
|
+
return {
|
|
476
|
+
...base,
|
|
477
|
+
evaluated: false,
|
|
478
|
+
out_of_distribution: false,
|
|
479
|
+
decision: 'not_evaluated',
|
|
480
|
+
reason: 'prompt_below_large_prompt_floor',
|
|
481
|
+
};
|
|
482
|
+
}
|
|
483
|
+
if (profile.normal_bytes === 0 || profile.multibyte_bytes > profile.normal_bytes) {
|
|
484
|
+
return {
|
|
485
|
+
...base,
|
|
486
|
+
evaluated: false,
|
|
487
|
+
out_of_distribution: false,
|
|
488
|
+
decision: 'not_evaluated',
|
|
489
|
+
reason: 'multibyte_or_non_ascii_dominant',
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
if (!profile.whitespace_fraction_available || profile.whitespace_fraction_x10000 === null) {
|
|
493
|
+
return {
|
|
494
|
+
...base,
|
|
495
|
+
evaluated: true,
|
|
496
|
+
out_of_distribution: true,
|
|
497
|
+
decision: 'conservative_fallback',
|
|
498
|
+
reason: 'whitespace_fraction_unavailable',
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
if (profile.whitespace_fraction_x10000 < TOKEN_BUDGET_DENSE_ASCII_WHITESPACE_THRESHOLD_X10000) {
|
|
502
|
+
return {
|
|
503
|
+
...base,
|
|
504
|
+
evaluated: true,
|
|
505
|
+
out_of_distribution: true,
|
|
506
|
+
decision: 'conservative_fallback',
|
|
507
|
+
reason: 'below_threshold',
|
|
508
|
+
};
|
|
509
|
+
}
|
|
510
|
+
return {
|
|
511
|
+
...base,
|
|
512
|
+
evaluated: true,
|
|
513
|
+
out_of_distribution: false,
|
|
514
|
+
decision: 'calibrated_allowed',
|
|
515
|
+
reason: 'at_or_above_threshold',
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
function rateSourceWarning(input: {
|
|
520
|
+
source: TokenBudgetRateSource['source'];
|
|
521
|
+
family: TokenBudgetFamily;
|
|
522
|
+
profile: TokenBudgetPromptProfile;
|
|
523
|
+
gate: TokenBudgetDenseAsciiGate;
|
|
524
|
+
scope: TokenBudgetEstimatorScope;
|
|
525
|
+
}): string | null {
|
|
526
|
+
if (input.source === 'unknown_provider_floor') {
|
|
527
|
+
return `unknown provider family uses the provable 1.00 B/tok floor; no calibration backs ${input.family}`;
|
|
528
|
+
}
|
|
529
|
+
if (input.source === 'unbacked_model_floor') {
|
|
530
|
+
return `model is not in the exact calibration backing set for family ${input.family}; using the provable 1.00 B/tok floor`;
|
|
531
|
+
}
|
|
532
|
+
if (input.source === 'delegate_conservative') {
|
|
533
|
+
return 'delegate launch/runtime uses the provable 1.00 B/tok profile when the prompt or route is below the backed large-prompt calibration domain';
|
|
534
|
+
}
|
|
535
|
+
if (input.source === 'explicit_conservative') {
|
|
536
|
+
return 'explicit conservative scope uses the provable 1.00 B/tok profile';
|
|
537
|
+
}
|
|
538
|
+
if (input.source === 'conservative_small_prompt') {
|
|
539
|
+
return `calibrated rate withheld because measured prompt bytes ${String(input.profile.concrete_known_bytes)} are below the ${String(TOKEN_BUDGET_LARGE_PROMPT_MIN_BYTES)}-byte calibration floor; using conservative profile`;
|
|
540
|
+
}
|
|
541
|
+
if (input.source === 'conservative_capacity_guard') {
|
|
542
|
+
return `calibrated rate withheld because route capacity evaluated at the conservative rate cannot hold the ${String(TOKEN_BUDGET_LARGE_PROMPT_MIN_BYTES)}-byte calibration floor`;
|
|
543
|
+
}
|
|
544
|
+
if (input.source === 'conservative_dense_ascii_whitespace_gate') {
|
|
545
|
+
if (input.gate.reason === 'whitespace_fraction_unavailable') {
|
|
546
|
+
return 'calibrated rate withheld because known-text whitespace bytes were not supplied; provide asciiWhitespaceBytes from a one-pass UTF-8 measurement to use calibrated rates';
|
|
547
|
+
}
|
|
548
|
+
return `calibrated rate withheld because whitespace fraction ${String(input.gate.measured_whitespace_fraction_x10000 ?? 0)}/${String(TOKEN_BUDGET_WHITESPACE_FRACTION_SCALE)} is below the dense-ASCII gate ${String(TOKEN_BUDGET_DENSE_ASCII_WHITESPACE_THRESHOLD_X10000)}/${String(TOKEN_BUDGET_WHITESPACE_FRACTION_SCALE)}; this is a heuristic token-density proxy, not a bound`;
|
|
549
|
+
}
|
|
550
|
+
return null;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
function effectiveRateSource(input: {
|
|
554
|
+
family: TokenBudgetFamily;
|
|
555
|
+
allowedInputTokens: number | undefined;
|
|
556
|
+
scope: TokenBudgetEstimatorScope;
|
|
557
|
+
profile: TokenBudgetPromptProfile;
|
|
558
|
+
calibrationBacked: boolean;
|
|
559
|
+
familyResolution: ResolvedTokenBudgetFamily['resolution'] | 'family_direct';
|
|
560
|
+
}): TokenBudgetRateSource {
|
|
561
|
+
const calibration = calibrationFor(input.family);
|
|
562
|
+
const configured = calibration.rate_bytes_per_token_x100;
|
|
563
|
+
const familyBacked = calibration.provenance.backed;
|
|
564
|
+
const backed = familyBacked && input.calibrationBacked;
|
|
565
|
+
const conservativeRate = conservativeFusionRate(configured);
|
|
566
|
+
const gate = denseAsciiGate(input.profile);
|
|
567
|
+
let source: TokenBudgetRateSource['source'];
|
|
568
|
+
let effective: number;
|
|
569
|
+
let calibrationApplied = false;
|
|
570
|
+
|
|
571
|
+
if (!backed) {
|
|
572
|
+
source = input.familyResolution === 'known_provider_unbacked_model'
|
|
573
|
+
? 'unbacked_model_floor'
|
|
574
|
+
: 'unknown_provider_floor';
|
|
575
|
+
effective = TOKEN_BUDGET_PROVABLE_RATE_X100;
|
|
576
|
+
} else if (
|
|
577
|
+
input.scope === 'delegate' ||
|
|
578
|
+
(input.scope === 'delegate_launch' &&
|
|
579
|
+
(input.profile.concrete_known_bytes < TOKEN_BUDGET_LARGE_PROMPT_MIN_BYTES ||
|
|
580
|
+
(input.allowedInputTokens !== undefined &&
|
|
581
|
+
Math.floor(
|
|
582
|
+
(input.allowedInputTokens * TOKEN_BUDGET_DELEGATE_CONSERVATIVE_RATE_X100) /
|
|
583
|
+
TOKEN_BUDGET_RATE_SCALE,
|
|
584
|
+
) < TOKEN_BUDGET_LARGE_PROMPT_MIN_BYTES)))
|
|
585
|
+
) {
|
|
586
|
+
source = 'delegate_conservative';
|
|
587
|
+
effective = Math.min(configured, TOKEN_BUDGET_DELEGATE_CONSERVATIVE_RATE_X100);
|
|
588
|
+
} else if (input.scope === 'conservative') {
|
|
589
|
+
source = 'explicit_conservative';
|
|
590
|
+
effective = Math.min(configured, TOKEN_BUDGET_PROVABLE_RATE_X100);
|
|
591
|
+
} else if (input.profile.concrete_known_bytes < TOKEN_BUDGET_LARGE_PROMPT_MIN_BYTES) {
|
|
592
|
+
source = 'conservative_small_prompt';
|
|
593
|
+
effective = conservativeRate;
|
|
594
|
+
} else if (
|
|
595
|
+
input.allowedInputTokens !== undefined &&
|
|
596
|
+
Math.floor((input.allowedInputTokens * conservativeRate) / TOKEN_BUDGET_RATE_SCALE) <
|
|
597
|
+
TOKEN_BUDGET_LARGE_PROMPT_MIN_BYTES
|
|
598
|
+
) {
|
|
599
|
+
assertSafeNonNegativeInteger(input.allowedInputTokens, 'allowedInputTokens');
|
|
600
|
+
source = 'conservative_capacity_guard';
|
|
601
|
+
effective = conservativeRate;
|
|
602
|
+
} else if (gate.out_of_distribution) {
|
|
603
|
+
source = 'conservative_dense_ascii_whitespace_gate';
|
|
604
|
+
effective = conservativeRate;
|
|
605
|
+
} else {
|
|
606
|
+
source = 'calibrated_large_window';
|
|
607
|
+
effective = configured;
|
|
608
|
+
calibrationApplied = true;
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
const dominant = gate.out_of_distribution && input.profile.normal_bytes >= input.profile.multibyte_bytes
|
|
612
|
+
? 'dense_ascii'
|
|
613
|
+
: input.profile.dominant_byte_class;
|
|
614
|
+
const rateSourceInput = {
|
|
615
|
+
source,
|
|
616
|
+
family: input.family,
|
|
617
|
+
profile: input.profile,
|
|
618
|
+
gate,
|
|
619
|
+
scope: input.scope,
|
|
620
|
+
};
|
|
621
|
+
return {
|
|
622
|
+
calibration_version: TOKEN_BUDGET_CALIBRATION_VERSION,
|
|
623
|
+
family: input.family,
|
|
624
|
+
configured_rate_bytes_per_token_x100: configured,
|
|
625
|
+
effective_rate_bytes_per_token_x100: effective,
|
|
626
|
+
conservative_rate_bytes_per_token_x100: conservativeRate,
|
|
627
|
+
delegate_conservative_rate_bytes_per_token_x100: TOKEN_BUDGET_DELEGATE_CONSERVATIVE_RATE_X100,
|
|
628
|
+
affine_f_tokens: calibration.affine_f_tokens,
|
|
629
|
+
scope: input.scope,
|
|
630
|
+
source,
|
|
631
|
+
backed,
|
|
632
|
+
provenance: calibration.provenance,
|
|
633
|
+
model_resolution: input.familyResolution,
|
|
634
|
+
scope_guard_min_bytes: TOKEN_BUDGET_LARGE_PROMPT_MIN_BYTES,
|
|
635
|
+
calibration_applied: calibrationApplied,
|
|
636
|
+
prompt_profile: { ...input.profile, dominant_byte_class: dominant },
|
|
637
|
+
dense_ascii_gate: gate,
|
|
638
|
+
dominant_byte_class: dominant,
|
|
639
|
+
warning: rateSourceWarning(rateSourceInput),
|
|
640
|
+
};
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
interface MutableRateBucket {
|
|
644
|
+
rate: number;
|
|
645
|
+
bytes: number;
|
|
646
|
+
classes: TokenBudgetDominantByteClass[];
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
function addBucket(
|
|
650
|
+
buckets: Map<number, MutableRateBucket>,
|
|
651
|
+
rate: number,
|
|
652
|
+
bytes: number,
|
|
653
|
+
byteClass: TokenBudgetDominantByteClass,
|
|
654
|
+
): void {
|
|
655
|
+
if (bytes === 0) return;
|
|
656
|
+
const existing = buckets.get(rate);
|
|
657
|
+
if (existing === undefined) {
|
|
658
|
+
buckets.set(rate, { rate, bytes, classes: [byteClass] });
|
|
659
|
+
return;
|
|
660
|
+
}
|
|
661
|
+
existing.bytes += bytes;
|
|
662
|
+
if (!existing.classes.includes(byteClass)) existing.classes.push(byteClass);
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
function finalizeBuckets(buckets: Map<number, MutableRateBucket>): TokenBudgetRateBucketEstimate[] {
|
|
666
|
+
return [...buckets.values()]
|
|
667
|
+
.sort((left, right) => left.rate - right.rate)
|
|
668
|
+
.map((bucket) => ({
|
|
669
|
+
rate_bytes_per_token_x100: bucket.rate,
|
|
670
|
+
bytes: bucket.bytes,
|
|
671
|
+
tokens: tokensAtRate(bucket.bytes, bucket.rate),
|
|
672
|
+
byte_classes: [...bucket.classes].sort(),
|
|
673
|
+
}));
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
function bucketTokenTotal(buckets: readonly TokenBudgetRateBucketEstimate[]): number {
|
|
677
|
+
return buckets.reduce((sum, bucket) => sum + bucket.tokens, 0);
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
export function estimateInputTokens(input: EstimateInputTokensInput): EstimateInputTokensResult {
|
|
681
|
+
const scope = input.scope ?? 'fusion';
|
|
682
|
+
const normalized: NormalizedTokenBudgetSegment[] = [];
|
|
683
|
+
const total: TokenBudgetByteClassBreakdown = {
|
|
684
|
+
total_bytes: 0,
|
|
685
|
+
normal_bytes: 0,
|
|
686
|
+
multibyte_bytes: 0,
|
|
687
|
+
dense_bytes: 0,
|
|
688
|
+
unknown_output_contract_bytes: 0,
|
|
689
|
+
};
|
|
690
|
+
for (const [index, rawSegment] of input.segments.entries()) {
|
|
691
|
+
const segment = normalizeSegment(rawSegment, index);
|
|
692
|
+
const unknownBytes = segment.kind === 'unknown_output_contract' ? segment.bytes : 0;
|
|
693
|
+
const normalBytes =
|
|
694
|
+
segment.kind === 'unknown_output_contract'
|
|
695
|
+
? 0
|
|
696
|
+
: segment.bytes - segment.multibyteBytes - segment.denseBytes;
|
|
697
|
+
const breakdown: TokenBudgetByteClassBreakdown = {
|
|
698
|
+
total_bytes: segment.bytes,
|
|
699
|
+
normal_bytes: normalBytes,
|
|
700
|
+
multibyte_bytes: segment.multibyteBytes,
|
|
701
|
+
dense_bytes: segment.denseBytes,
|
|
702
|
+
unknown_output_contract_bytes: unknownBytes,
|
|
703
|
+
};
|
|
704
|
+
addBreakdown(total, breakdown);
|
|
705
|
+
normalized.push(segment);
|
|
706
|
+
}
|
|
707
|
+
if (input.allowedInputTokens !== undefined) {
|
|
708
|
+
assertSafeNonNegativeInteger(input.allowedInputTokens, 'allowedInputTokens');
|
|
709
|
+
}
|
|
710
|
+
const profile = profileForSegments(normalized, total);
|
|
711
|
+
const rateSource = effectiveRateSource({
|
|
712
|
+
family: input.family,
|
|
713
|
+
allowedInputTokens: input.allowedInputTokens,
|
|
714
|
+
scope,
|
|
715
|
+
profile,
|
|
716
|
+
calibrationBacked: input.calibrationBacked ?? true,
|
|
717
|
+
familyResolution: input.familyResolution ?? 'family_direct',
|
|
718
|
+
});
|
|
719
|
+
|
|
720
|
+
const perSegment: TokenBudgetPerSegmentEstimate[] = [];
|
|
721
|
+
const fatalBuckets = new Map<number, MutableRateBucket>();
|
|
722
|
+
const advisoryBuckets = new Map<number, MutableRateBucket>();
|
|
723
|
+
let multibyteAdvisoryTotal = 0;
|
|
724
|
+
|
|
725
|
+
for (const segment of normalized) {
|
|
726
|
+
const unknownBytes = segment.kind === 'unknown_output_contract' ? segment.bytes : 0;
|
|
727
|
+
const normalBytes =
|
|
728
|
+
segment.kind === 'unknown_output_contract'
|
|
729
|
+
? 0
|
|
730
|
+
: segment.bytes - segment.multibyteBytes - segment.denseBytes;
|
|
731
|
+
const normalRate =
|
|
732
|
+
segment.kind === 'unknown_output_contract'
|
|
733
|
+
? TOKEN_BUDGET_PROVABLE_RATE_X100
|
|
734
|
+
: rateSource.effective_rate_bytes_per_token_x100;
|
|
735
|
+
const normalTokens = tokensAtRate(normalBytes, normalRate);
|
|
736
|
+
const unknownTokens = tokensAtRate(unknownBytes, TOKEN_BUDGET_PROVABLE_RATE_X100);
|
|
737
|
+
const multibyteTokens = tokensAtRate(segment.multibyteBytes, TOKEN_BUDGET_MULTIBYTE_FATAL_RATE_X100);
|
|
738
|
+
const multibyteProvableTokens = tokensAtRate(segment.multibyteBytes, TOKEN_BUDGET_PROVABLE_RATE_X100);
|
|
739
|
+
const denseTokens = tokensAtRate(segment.denseBytes, TOKEN_BUDGET_PROVABLE_RATE_X100);
|
|
740
|
+
const tokens = normalTokens + unknownTokens + multibyteTokens + denseTokens;
|
|
741
|
+
const breakdown: TokenBudgetByteClassBreakdown = {
|
|
742
|
+
total_bytes: segment.bytes,
|
|
743
|
+
normal_bytes: normalBytes,
|
|
744
|
+
multibyte_bytes: segment.multibyteBytes,
|
|
745
|
+
dense_bytes: segment.denseBytes,
|
|
746
|
+
unknown_output_contract_bytes: unknownBytes,
|
|
747
|
+
};
|
|
748
|
+
addBucket(fatalBuckets, normalRate, normalBytes, 'normal');
|
|
749
|
+
addBucket(fatalBuckets, TOKEN_BUDGET_MULTIBYTE_FATAL_RATE_X100, segment.multibyteBytes, 'multibyte');
|
|
750
|
+
addBucket(fatalBuckets, TOKEN_BUDGET_PROVABLE_RATE_X100, segment.denseBytes, 'dense_ascii');
|
|
751
|
+
addBucket(fatalBuckets, TOKEN_BUDGET_PROVABLE_RATE_X100, unknownBytes, 'unknown_output_contract');
|
|
752
|
+
addBucket(advisoryBuckets, normalRate, normalBytes, 'normal');
|
|
753
|
+
addBucket(advisoryBuckets, TOKEN_BUDGET_PROVABLE_RATE_X100, segment.multibyteBytes, 'multibyte');
|
|
754
|
+
addBucket(advisoryBuckets, TOKEN_BUDGET_PROVABLE_RATE_X100, segment.denseBytes, 'dense_ascii');
|
|
755
|
+
addBucket(advisoryBuckets, TOKEN_BUDGET_PROVABLE_RATE_X100, unknownBytes, 'unknown_output_contract');
|
|
756
|
+
multibyteAdvisoryTotal += multibyteProvableTokens;
|
|
757
|
+
perSegment.push({
|
|
758
|
+
kind: segment.kind,
|
|
759
|
+
...breakdown,
|
|
760
|
+
ascii_whitespace_bytes: segment.asciiWhitespaceBytes,
|
|
761
|
+
normal_rate_bytes_per_token_x100: normalRate,
|
|
762
|
+
normal_tokens: normalTokens,
|
|
763
|
+
multibyte_rate_bytes_per_token_x100: TOKEN_BUDGET_MULTIBYTE_FATAL_RATE_X100,
|
|
764
|
+
multibyte_tokens: multibyteTokens,
|
|
765
|
+
multibyte_provable_tokens: multibyteProvableTokens,
|
|
766
|
+
dense_tokens: denseTokens,
|
|
767
|
+
unknown_output_contract_tokens: unknownTokens,
|
|
768
|
+
tokens,
|
|
769
|
+
});
|
|
770
|
+
}
|
|
771
|
+
const rateBuckets = finalizeBuckets(fatalBuckets);
|
|
772
|
+
const advisoryRateBuckets = finalizeBuckets(advisoryBuckets);
|
|
773
|
+
const variableTokenTotal = bucketTokenTotal(rateBuckets);
|
|
774
|
+
return {
|
|
775
|
+
tokens: variableTokenTotal + rateSource.affine_f_tokens,
|
|
776
|
+
fixed_tokens: rateSource.affine_f_tokens,
|
|
777
|
+
perSegment,
|
|
778
|
+
byte_class_breakdown: total,
|
|
779
|
+
rate_buckets: rateBuckets,
|
|
780
|
+
advisory: {
|
|
781
|
+
multibyte_provable_rate_bytes_per_token_x100: TOKEN_BUDGET_PROVABLE_RATE_X100,
|
|
782
|
+
multibyte_provable_tokens: multibyteAdvisoryTotal,
|
|
783
|
+
input_tokens_if_multibyte_used_provable_ceiling:
|
|
784
|
+
bucketTokenTotal(advisoryRateBuckets) + rateSource.affine_f_tokens,
|
|
785
|
+
rate_buckets: advisoryRateBuckets,
|
|
786
|
+
},
|
|
787
|
+
rateSource,
|
|
788
|
+
};
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
export function utf8ByteLength(value: string): number {
|
|
792
|
+
return Buffer.byteLength(value, 'utf8');
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
function isAsciiWhitespace(byte: number): boolean {
|
|
796
|
+
return byte === 0x20 || (byte >= 0x09 && byte <= 0x0d);
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
export function utf8ByteClassBreakdown(value: string): {
|
|
800
|
+
bytes: number;
|
|
801
|
+
multibyteBytes: number;
|
|
802
|
+
denseBytes: 0;
|
|
803
|
+
asciiWhitespaceBytes: number;
|
|
804
|
+
} {
|
|
805
|
+
const bytes = Buffer.from(value, 'utf8');
|
|
806
|
+
let multibyteBytes = 0;
|
|
807
|
+
let asciiWhitespaceBytes = 0;
|
|
808
|
+
for (const byte of bytes) {
|
|
809
|
+
if (byte >= 0x80) multibyteBytes += 1;
|
|
810
|
+
else if (isAsciiWhitespace(byte)) asciiWhitespaceBytes += 1;
|
|
811
|
+
}
|
|
812
|
+
return { bytes: bytes.length, multibyteBytes, denseBytes: 0, asciiWhitespaceBytes };
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
export function knownTextSegment(value: string): TokenBudgetSegment {
|
|
816
|
+
const breakdown = utf8ByteClassBreakdown(value);
|
|
817
|
+
return {
|
|
818
|
+
kind: 'known_text',
|
|
819
|
+
bytes: breakdown.bytes,
|
|
820
|
+
multibyteBytes: breakdown.multibyteBytes,
|
|
821
|
+
denseBytes: breakdown.denseBytes,
|
|
822
|
+
asciiWhitespaceBytes: breakdown.asciiWhitespaceBytes,
|
|
823
|
+
};
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
export function knownJsonSegment(value: string): TokenBudgetSegment {
|
|
827
|
+
const breakdown = utf8ByteClassBreakdown(value);
|
|
828
|
+
return {
|
|
829
|
+
kind: 'known_json',
|
|
830
|
+
bytes: breakdown.bytes,
|
|
831
|
+
multibyteBytes: breakdown.multibyteBytes,
|
|
832
|
+
denseBytes: breakdown.denseBytes,
|
|
833
|
+
asciiWhitespaceBytes: breakdown.asciiWhitespaceBytes,
|
|
834
|
+
};
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
export function unknownOutputContractSegment(bytes: number): TokenBudgetSegment {
|
|
838
|
+
assertSafeNonNegativeInteger(bytes, 'unknown output contract bytes');
|
|
839
|
+
return { kind: 'unknown_output_contract', bytes, denseBytes: 0 };
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
export function tokenUpperBound(utf8Bytes: number): number {
|
|
843
|
+
return estimateInputTokens({
|
|
844
|
+
family: 'unknown',
|
|
845
|
+
scope: 'conservative',
|
|
846
|
+
calibrationBacked: false,
|
|
847
|
+
segments: [{ kind: 'known_text', bytes: utf8Bytes, multibyteBytes: 0, denseBytes: 0 }],
|
|
848
|
+
}).tokens;
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
export function maxKnownTextBytesForTokens(input: {
|
|
852
|
+
family: TokenBudgetFamily;
|
|
853
|
+
allowedInputTokens: number;
|
|
854
|
+
scope?: TokenBudgetEstimatorScope | undefined;
|
|
855
|
+
calibrationBacked?: boolean | undefined;
|
|
856
|
+
familyResolution?: ResolvedTokenBudgetFamily['resolution'] | 'family_direct' | undefined;
|
|
857
|
+
}): number {
|
|
858
|
+
assertSafeNonNegativeInteger(input.allowedInputTokens, 'allowedInputTokens');
|
|
859
|
+
const rate = effectiveRateSource({
|
|
860
|
+
family: input.family,
|
|
861
|
+
allowedInputTokens: input.allowedInputTokens,
|
|
862
|
+
scope: input.scope ?? 'fusion',
|
|
863
|
+
profile: profileForSegments([], {
|
|
864
|
+
total_bytes: 0,
|
|
865
|
+
normal_bytes: 0,
|
|
866
|
+
multibyte_bytes: 0,
|
|
867
|
+
dense_bytes: 0,
|
|
868
|
+
unknown_output_contract_bytes: 0,
|
|
869
|
+
}),
|
|
870
|
+
calibrationBacked: input.calibrationBacked ?? true,
|
|
871
|
+
familyResolution: input.familyResolution ?? 'family_direct',
|
|
872
|
+
});
|
|
873
|
+
const variableTokens = input.allowedInputTokens - rate.affine_f_tokens;
|
|
874
|
+
if (variableTokens <= 0) return 0;
|
|
875
|
+
return Math.floor((variableTokens * rate.effective_rate_bytes_per_token_x100) / TOKEN_BUDGET_RATE_SCALE);
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
export interface RouteReserves {
|
|
879
|
+
reservedOutputTokens: number;
|
|
880
|
+
framingReserveTokens: number;
|
|
881
|
+
safetyReserveTokens: number;
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
/**
|
|
885
|
+
* Usable input tokens for one route.
|
|
886
|
+
*
|
|
887
|
+
* Returns a signed value. A caller that requires a minimum must check it and
|
|
888
|
+
* fail loudly; this helper never clamps, never substitutes a default window, and
|
|
889
|
+
* never silently returns zero for an unusable route.
|
|
890
|
+
*/
|
|
891
|
+
export function allowedInputTokens(contextWindowTokens: number, reserves: RouteReserves): number {
|
|
892
|
+
return (
|
|
893
|
+
contextWindowTokens -
|
|
894
|
+
reserves.reservedOutputTokens -
|
|
895
|
+
reserves.framingReserveTokens -
|
|
896
|
+
reserves.safetyReserveTokens
|
|
897
|
+
);
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
/** True only for a positive, finite, integral context window. */
|
|
901
|
+
export function isUsableContextWindow(value: number): boolean {
|
|
902
|
+
return Number.isFinite(value) && Number.isInteger(value) && value > 0;
|
|
903
|
+
}
|