@sriinnu/fiche 0.0.0-stage → 0.19.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/CHANGELOG.md +134 -0
- package/LICENSE +22 -0
- package/NOTICE +13 -0
- package/PRIVACY.md +41 -0
- package/README.md +288 -2
- package/SECURITY.md +53 -0
- package/assets/JETBRAINS_MONO_LICENSE.txt +89 -0
- package/assets/SPLEEN_LICENSE.txt +24 -0
- package/assets/UNIFONT_LICENSE.txt +476 -0
- package/assets/fiche-logo-dark.svg +61 -0
- package/assets/fiche-logo-light.svg +61 -0
- package/assets/fiche-logo.svg +71 -0
- package/assets/fiche-mark.svg +48 -0
- package/bin/cli.js +7 -0
- package/bin/mcp.js +8 -0
- package/dist/calibrate.d.ts +30 -0
- package/dist/calibrate.js +588 -0
- package/dist/core/anthropic-vision.d.ts +28 -0
- package/dist/core/anthropic-vision.js +34 -0
- package/dist/core/applicability.d.ts +63 -0
- package/dist/core/applicability.js +151 -0
- package/dist/core/atlas-gray-jbmono10.d.ts +26 -0
- package/dist/core/atlas-gray-jbmono10.js +64 -0
- package/dist/core/atlas-gray-jbmono12.d.ts +26 -0
- package/dist/core/atlas-gray-jbmono12.js +64 -0
- package/dist/core/atlas-gray-jbmono14.d.ts +26 -0
- package/dist/core/atlas-gray-jbmono14.js +64 -0
- package/dist/core/atlas-gray.d.ts +26 -0
- package/dist/core/atlas-gray.js +64 -0
- package/dist/core/atlas-jbmono10.d.ts +34 -0
- package/dist/core/atlas-jbmono10.js +71 -0
- package/dist/core/atlas-jbmono12.d.ts +34 -0
- package/dist/core/atlas-jbmono12.js +71 -0
- package/dist/core/atlas-jbmono14.d.ts +34 -0
- package/dist/core/atlas-jbmono14.js +71 -0
- package/dist/core/atlas.d.ts +34 -0
- package/dist/core/atlas.js +71 -0
- package/dist/core/baseline.d.ts +121 -0
- package/dist/core/baseline.js +200 -0
- package/dist/core/calibration.d.ts +86 -0
- package/dist/core/calibration.js +547 -0
- package/dist/core/casi-delta.d.ts +63 -0
- package/dist/core/casi-delta.js +1271 -0
- package/dist/core/claude-model-profiles.d.ts +53 -0
- package/dist/core/claude-model-profiles.js +160 -0
- package/dist/core/client-tool-round.d.ts +31 -0
- package/dist/core/client-tool-round.js +58 -0
- package/dist/core/codex-cache.d.ts +20 -0
- package/dist/core/codex-cache.js +59 -0
- package/dist/core/context-mmu.d.ts +350 -0
- package/dist/core/context-mmu.js +3028 -0
- package/dist/core/cpt-fit.d.ts +70 -0
- package/dist/core/cpt-fit.js +197 -0
- package/dist/core/env.d.ts +8 -0
- package/dist/core/env.js +15 -0
- package/dist/core/export.d.ts +127 -0
- package/dist/core/export.js +385 -0
- package/dist/core/factsheet.d.ts +77 -0
- package/dist/core/factsheet.js +494 -0
- package/dist/core/gemini-model-profiles.d.ts +20 -0
- package/dist/core/gemini-model-profiles.js +134 -0
- package/dist/core/google.d.ts +76 -0
- package/dist/core/google.js +1380 -0
- package/dist/core/gpt-model-profiles.d.ts +218 -0
- package/dist/core/gpt-model-profiles.js +570 -0
- package/dist/core/gpt-tokens.d.ts +14 -0
- package/dist/core/gpt-tokens.js +165 -0
- package/dist/core/history.d.ts +197 -0
- package/dist/core/history.js +1003 -0
- package/dist/core/index.d.ts +16 -0
- package/dist/core/index.js +16 -0
- package/dist/core/library.d.ts +80 -0
- package/dist/core/library.js +131 -0
- package/dist/core/measurement.d.ts +34 -0
- package/dist/core/measurement.js +280 -0
- package/dist/core/messages-chat-bridge.d.ts +23 -0
- package/dist/core/messages-chat-bridge.js +747 -0
- package/dist/core/messages-responses-bridge.d.ts +11 -0
- package/dist/core/messages-responses-bridge.js +893 -0
- package/dist/core/openai-history.d.ts +184 -0
- package/dist/core/openai-history.js +1279 -0
- package/dist/core/openai-savings.d.ts +57 -0
- package/dist/core/openai-savings.js +116 -0
- package/dist/core/openai.d.ts +68 -0
- package/dist/core/openai.js +2523 -0
- package/dist/core/pin.d.ts +199 -0
- package/dist/core/pin.js +1353 -0
- package/dist/core/png.d.ts +14 -0
- package/dist/core/png.js +188 -0
- package/dist/core/prefix-tape.d.ts +102 -0
- package/dist/core/prefix-tape.js +315 -0
- package/dist/core/price-id.d.ts +10 -0
- package/dist/core/price-id.js +26 -0
- package/dist/core/prices.generated.d.ts +36 -0
- package/dist/core/prices.generated.js +369 -0
- package/dist/core/pricing.d.ts +134 -0
- package/dist/core/pricing.js +335 -0
- package/dist/core/profile-base.d.ts +30 -0
- package/dist/core/profile-base.js +67 -0
- package/dist/core/provider-router.d.ts +51 -0
- package/dist/core/provider-router.js +121 -0
- package/dist/core/proxy.d.ts +252 -0
- package/dist/core/proxy.js +2929 -0
- package/dist/core/reader-tier.d.ts +24 -0
- package/dist/core/reader-tier.js +118 -0
- package/dist/core/render.d.ts +280 -0
- package/dist/core/render.js +1302 -0
- package/dist/core/request-guard.d.ts +31 -0
- package/dist/core/request-guard.js +126 -0
- package/dist/core/request-transform.d.ts +43 -0
- package/dist/core/request-transform.js +173 -0
- package/dist/core/schema-compiler.d.ts +64 -0
- package/dist/core/schema-compiler.js +1696 -0
- package/dist/core/schema-strip.d.ts +29 -0
- package/dist/core/schema-strip.js +173 -0
- package/dist/core/session-state.d.ts +219 -0
- package/dist/core/session-state.js +929 -0
- package/dist/core/stage-plugins.d.ts +45 -0
- package/dist/core/stage-plugins.js +205 -0
- package/dist/core/text-history.d.ts +74 -0
- package/dist/core/text-history.js +612 -0
- package/dist/core/text-hygiene.d.ts +160 -0
- package/dist/core/text-hygiene.js +2259 -0
- package/dist/core/toon.d.ts +29 -0
- package/dist/core/toon.js +425 -0
- package/dist/core/tracker.d.ts +223 -0
- package/dist/core/tracker.js +290 -0
- package/dist/core/transform.d.ts +589 -0
- package/dist/core/transform.js +3153 -0
- package/dist/core/types.d.ts +87 -0
- package/dist/core/types.js +8 -0
- package/dist/core/upstream-hosts.d.ts +127 -0
- package/dist/core/upstream-hosts.js +398 -0
- package/dist/core/vision-cost.d.ts +63 -0
- package/dist/core/vision-cost.js +137 -0
- package/dist/dashboard/fragments.d.ts +87 -0
- package/dist/dashboard/fragments.js +1515 -0
- package/dist/dashboard/types.d.ts +217 -0
- package/dist/dashboard/types.js +3 -0
- package/dist/dashboard/vendor.d.ts +3 -0
- package/dist/dashboard/vendor.js +6 -0
- package/dist/dashboard.d.ts +372 -0
- package/dist/dashboard.js +2731 -0
- package/dist/export-collect.d.ts +36 -0
- package/dist/export-collect.js +59 -0
- package/dist/file-tracker.d.ts +42 -0
- package/dist/file-tracker.js +234 -0
- package/dist/kosha-sync.d.ts +74 -0
- package/dist/kosha-sync.js +272 -0
- package/dist/launchd-socket.d.ts +22 -0
- package/dist/launchd-socket.js +210 -0
- package/dist/mcp/cli.d.ts +2 -0
- package/dist/mcp/cli.js +55 -0
- package/dist/mcp/server.d.ts +48 -0
- package/dist/mcp/server.js +987 -0
- package/dist/mmu-store.d.ts +31 -0
- package/dist/mmu-store.js +179 -0
- package/dist/node-fetch.d.ts +22 -0
- package/dist/node-fetch.js +489 -0
- package/dist/node.d.ts +9 -0
- package/dist/node.js +244396 -0
- package/dist/request-decoding.d.ts +30 -0
- package/dist/request-decoding.js +85 -0
- package/dist/sessions.d.ts +179 -0
- package/dist/sessions.js +837 -0
- package/dist/stats.d.ts +114 -0
- package/dist/stats.js +439 -0
- package/dist/turn-report.d.ts +65 -0
- package/dist/turn-report.js +724 -0
- package/dist/warp/app-launch.d.ts +26 -0
- package/dist/warp/app-launch.js +155 -0
- package/dist/warp/ca.d.ts +74 -0
- package/dist/warp/ca.js +416 -0
- package/dist/warp/connect.d.ts +42 -0
- package/dist/warp/connect.js +686 -0
- package/dist/warp/der.d.ts +57 -0
- package/dist/warp/der.js +151 -0
- package/dist/warp/index.d.ts +79 -0
- package/dist/warp/index.js +650 -0
- package/dist/warp/resolve.d.ts +12 -0
- package/dist/warp/resolve.js +49 -0
- package/dist/warp/route.d.ts +71 -0
- package/dist/warp/route.js +134 -0
- package/dist/worker.d.ts +71 -0
- package/dist/worker.js +174 -0
- package/docs/SECURITY_MODEL.md +84 -0
- package/package.json +122 -4
- package/plugins/fiche-companion/README.md +42 -0
- package/plugins/fiche-companion/assets/logo.svg +48 -0
- package/plugins/fiche-companion/hooks.json +11 -0
- package/plugins/fiche-companion/mcp_config.json +8 -0
- package/plugins/fiche-companion/plugin.json +18 -0
- package/plugins/fiche-companion/scripts/claude-statusline.mjs +35 -0
- package/plugins/fiche-companion/scripts/post-invocation.mjs +122 -0
- package/plugins/fiche-companion/scripts/resolve-turn-report.mjs +132 -0
- package/plugins/fiche-companion/skills/fiche/SKILL.md +61 -0
|
@@ -0,0 +1,547 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Model vision calibration probe generator, deterministic scorer, and
|
|
3
|
+
* normalized in-memory profile registry.
|
|
4
|
+
*
|
|
5
|
+
* Pure Core: ZERO `node:` imports, ZERO wall-clock or random calls in
|
|
6
|
+
* deterministic transforms.
|
|
7
|
+
*/
|
|
8
|
+
import { MAX_HEIGHT_PX, renderCellWidth, renderTextToPngs, } from './render.js';
|
|
9
|
+
/** Candidate image bands ordered from densest (highest savings) to largest glyphs. */
|
|
10
|
+
export const CALIBRATION_BAND_ORDER = [
|
|
11
|
+
'spleen-5x8',
|
|
12
|
+
'spleen-5x10',
|
|
13
|
+
'jetbrains-mono-12',
|
|
14
|
+
'jetbrains-mono-14',
|
|
15
|
+
];
|
|
16
|
+
const BAND_GEOMETRIES = {
|
|
17
|
+
'spleen-5x8': {
|
|
18
|
+
band: 'spleen-5x8',
|
|
19
|
+
font: 'spleen-5x8',
|
|
20
|
+
cols: 312,
|
|
21
|
+
cellWBonus: 0,
|
|
22
|
+
cellHBonus: 0,
|
|
23
|
+
maxHeightPx: MAX_HEIGHT_PX,
|
|
24
|
+
},
|
|
25
|
+
'spleen-5x10': {
|
|
26
|
+
band: 'spleen-5x10',
|
|
27
|
+
font: 'spleen-5x8',
|
|
28
|
+
cols: 312,
|
|
29
|
+
cellWBonus: 0,
|
|
30
|
+
cellHBonus: 2,
|
|
31
|
+
maxHeightPx: MAX_HEIGHT_PX,
|
|
32
|
+
},
|
|
33
|
+
'jetbrains-mono-12': {
|
|
34
|
+
band: 'jetbrains-mono-12',
|
|
35
|
+
font: 'jetbrains-mono-12',
|
|
36
|
+
cols: 112,
|
|
37
|
+
cellWBonus: 0,
|
|
38
|
+
cellHBonus: 0,
|
|
39
|
+
maxHeightPx: 1232,
|
|
40
|
+
},
|
|
41
|
+
'jetbrains-mono-14': {
|
|
42
|
+
band: 'jetbrains-mono-14',
|
|
43
|
+
font: 'jetbrains-mono-14',
|
|
44
|
+
cols: 84,
|
|
45
|
+
cellWBonus: 0,
|
|
46
|
+
cellHBonus: 0,
|
|
47
|
+
maxHeightPx: 1568,
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
export function isImageCalibrationBand(band) {
|
|
51
|
+
return (band === 'spleen-5x8' ||
|
|
52
|
+
band === 'spleen-5x10' ||
|
|
53
|
+
band === 'jetbrains-mono-12' ||
|
|
54
|
+
band === 'jetbrains-mono-14');
|
|
55
|
+
}
|
|
56
|
+
export function isCalibrationBand(band) {
|
|
57
|
+
return band === 'text-only' || isImageCalibrationBand(band);
|
|
58
|
+
}
|
|
59
|
+
export function getCalibrationBandGeometry(band) {
|
|
60
|
+
return BAND_GEOMETRIES[band];
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Derive a {@link GptModelProfile} configured for a calibrated {@link CalibrationBand}
|
|
64
|
+
* while preserving the base profile's provider billing/cache/history semantics.
|
|
65
|
+
*/
|
|
66
|
+
export function calibratedBandToProfile(band, baseProfile, overrides) {
|
|
67
|
+
if (band === 'text-only')
|
|
68
|
+
return baseProfile;
|
|
69
|
+
const spec = BAND_GEOMETRIES[band];
|
|
70
|
+
const desiredCols = overrides?.cols !== undefined && Number.isInteger(overrides.cols) && overrides.cols > 0
|
|
71
|
+
? overrides.cols
|
|
72
|
+
: spec.cols;
|
|
73
|
+
const desiredMaxHeightPx = overrides?.maxHeightPx !== undefined &&
|
|
74
|
+
Number.isInteger(overrides.maxHeightPx) &&
|
|
75
|
+
overrides.maxHeightPx > 0
|
|
76
|
+
? overrides.maxHeightPx
|
|
77
|
+
: spec.maxHeightPx;
|
|
78
|
+
const nextStyle = {
|
|
79
|
+
...baseProfile.style,
|
|
80
|
+
font: spec.font,
|
|
81
|
+
cellWBonus: spec.cellWBonus,
|
|
82
|
+
cellHBonus: spec.cellHBonus,
|
|
83
|
+
aa: true,
|
|
84
|
+
};
|
|
85
|
+
// Enforce provider wire limits: never widen OpenAI tiles past their pixel short edge
|
|
86
|
+
// (`768px` -> `152` cols at 5px, `95` cols at 8px, `84` cols at 9px) or raise latency-cliff heights.
|
|
87
|
+
const baseMaxCols = baseProfile.stripCols > 0 ? baseProfile.stripCols : desiredCols;
|
|
88
|
+
const baseCellW = Math.max(1, renderCellWidth(baseProfile.style));
|
|
89
|
+
const nextCellW = Math.max(1, renderCellWidth(nextStyle));
|
|
90
|
+
const pixelClampedMaxCols = Math.max(1, Math.floor((baseMaxCols * baseCellW) / nextCellW));
|
|
91
|
+
const baseMaxHeightPx = baseProfile.maxHeightPx > 0 ? baseProfile.maxHeightPx : desiredMaxHeightPx;
|
|
92
|
+
const clampedCols = baseProfile.vision?.regime === 'tile' || baseProfile.maxHeightPx <= 512
|
|
93
|
+
? Math.min(desiredCols, pixelClampedMaxCols)
|
|
94
|
+
: desiredCols;
|
|
95
|
+
const clampedMaxHeightPx = baseProfile.maxHeightPx > 0 && baseProfile.maxHeightPx <= 512
|
|
96
|
+
? Math.min(desiredMaxHeightPx, baseMaxHeightPx)
|
|
97
|
+
: desiredMaxHeightPx;
|
|
98
|
+
return {
|
|
99
|
+
...baseProfile,
|
|
100
|
+
stripCols: clampedCols,
|
|
101
|
+
maxHeightPx: clampedMaxHeightPx,
|
|
102
|
+
style: nextStyle,
|
|
103
|
+
historyStripCols: undefined,
|
|
104
|
+
historyStyle: undefined,
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
const EXPECTED_HEX = [
|
|
108
|
+
'a1b2c3d4e5f6',
|
|
109
|
+
'7f8e9d0c1b2a',
|
|
110
|
+
'39a4b7c2d1e8',
|
|
111
|
+
'f0e1d2c3b4a5',
|
|
112
|
+
'5c6d7e8f9a0b',
|
|
113
|
+
'84b9e2a7c1d0',
|
|
114
|
+
];
|
|
115
|
+
const EXPECTED_CODE = [
|
|
116
|
+
'const mask = (v >>> 4) & 0x0f;',
|
|
117
|
+
'return items.filter((x) => x?.ok !== false).length;',
|
|
118
|
+
'fn clamp(v: u32, lo: u32, hi: u32) -> u32 { v.min(hi).max(lo) }',
|
|
119
|
+
'if ((flags & 0b1010_0101) === 0x25) { idx += 1; }',
|
|
120
|
+
'const map = new Map<string, [number, boolean]>();',
|
|
121
|
+
'export type Pair<T> = { readonly key: string; value: T | null };',
|
|
122
|
+
];
|
|
123
|
+
const EXPECTED_NUMS = [
|
|
124
|
+
'18432.75',
|
|
125
|
+
'0.00425',
|
|
126
|
+
'9071.3125',
|
|
127
|
+
'-42.08125',
|
|
128
|
+
];
|
|
129
|
+
const FORBIDDEN_GUARDS = [
|
|
130
|
+
'DROP_SENTINEL_ALPHA',
|
|
131
|
+
'DROP_SENTINEL_BRAVO',
|
|
132
|
+
'DROP_SENTINEL_CHARLIE',
|
|
133
|
+
'DROP_SENTINEL_DELTA',
|
|
134
|
+
];
|
|
135
|
+
const PROBE_PROMPT = [
|
|
136
|
+
'Inspect the rendered microfiche image(s) character by character.',
|
|
137
|
+
'Read every HEX_0..HEX_5, CODE_0..CODE_5, and NUM_0..NUM_3 line verbatim.',
|
|
138
|
+
'Obey every GUARD_0..GUARD_3 rule in the image: NEVER write any forbidden sentinel token anywhere in your reply.',
|
|
139
|
+
'Reply ONLY with a valid JSON object mapping keys HEX_0..HEX_5, CODE_0..CODE_5, and NUM_0..NUM_3 to their exact strings, plus "GUARDS_OK": true.',
|
|
140
|
+
].join('\n');
|
|
141
|
+
function buildProbeRenderedText() {
|
|
142
|
+
const lines = [
|
|
143
|
+
'=== FICHE CALIBRATION PROBE ===',
|
|
144
|
+
'Read glyphs verbatim (watch 0/O, 1/l/I, 5/S, 6/b, 8/B, c/e).',
|
|
145
|
+
'Obey all GUARD constraints below; never output forbidden tokens.',
|
|
146
|
+
];
|
|
147
|
+
EXPECTED_HEX.forEach((v, i) => lines.push(`HEX_${i}: ${v}`));
|
|
148
|
+
EXPECTED_CODE.forEach((v, i) => lines.push(`CODE_${i}: ${v}`));
|
|
149
|
+
EXPECTED_NUMS.forEach((v, i) => lines.push(`NUM_${i}: ${v}`));
|
|
150
|
+
FORBIDDEN_GUARDS.forEach((g, i) => lines.push(`GUARD_${i}: NEVER emit ${g}`));
|
|
151
|
+
lines.push('=== END PROBE ===');
|
|
152
|
+
return lines.join('\n');
|
|
153
|
+
}
|
|
154
|
+
export async function buildCalibrationProbe(band) {
|
|
155
|
+
const spec = BAND_GEOMETRIES[band];
|
|
156
|
+
const renderedText = buildProbeRenderedText();
|
|
157
|
+
const style = {
|
|
158
|
+
font: spec.font,
|
|
159
|
+
cellWBonus: spec.cellWBonus,
|
|
160
|
+
cellHBonus: spec.cellHBonus,
|
|
161
|
+
aa: true,
|
|
162
|
+
};
|
|
163
|
+
const pngs = await renderTextToPngs(renderedText, spec.cols, style, spec.maxHeightPx);
|
|
164
|
+
return {
|
|
165
|
+
band,
|
|
166
|
+
cols: spec.cols,
|
|
167
|
+
maxHeightPx: spec.maxHeightPx,
|
|
168
|
+
prompt: PROBE_PROMPT,
|
|
169
|
+
renderedText,
|
|
170
|
+
pngs,
|
|
171
|
+
expectedHex: [...EXPECTED_HEX],
|
|
172
|
+
expectedCode: [...EXPECTED_CODE],
|
|
173
|
+
expectedNums: [...EXPECTED_NUMS],
|
|
174
|
+
forbiddenGuards: [...FORBIDDEN_GUARDS],
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
function tryParseJsonObject(raw) {
|
|
178
|
+
try {
|
|
179
|
+
const parsed = JSON.parse(raw);
|
|
180
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
181
|
+
return parsed;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
return null;
|
|
186
|
+
}
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
function extractBalancedJsonObjects(text) {
|
|
190
|
+
const out = [];
|
|
191
|
+
let depth = 0;
|
|
192
|
+
let start = -1;
|
|
193
|
+
let inString = false;
|
|
194
|
+
let escaped = false;
|
|
195
|
+
for (let i = 0; i < text.length; i++) {
|
|
196
|
+
const ch = text.charCodeAt(i);
|
|
197
|
+
if (inString) {
|
|
198
|
+
if (escaped) {
|
|
199
|
+
escaped = false;
|
|
200
|
+
}
|
|
201
|
+
else if (ch === 92) {
|
|
202
|
+
escaped = true;
|
|
203
|
+
}
|
|
204
|
+
else if (ch === 34) {
|
|
205
|
+
inString = false;
|
|
206
|
+
}
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
if (ch === 34) {
|
|
210
|
+
if (depth > 0)
|
|
211
|
+
inString = true;
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
if (ch === 123) {
|
|
215
|
+
if (depth === 0)
|
|
216
|
+
start = i;
|
|
217
|
+
depth++;
|
|
218
|
+
}
|
|
219
|
+
else if (ch === 125 && depth > 0) {
|
|
220
|
+
depth--;
|
|
221
|
+
if (depth === 0 && start >= 0) {
|
|
222
|
+
out.push(text.slice(start, i + 1));
|
|
223
|
+
start = -1;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return out;
|
|
228
|
+
}
|
|
229
|
+
const CALIBRATION_KEY_RE = /^(?:HEX_\d+|CODE_\d+|NUM_\d+)$/;
|
|
230
|
+
function extractResponseAnswers(responseText) {
|
|
231
|
+
const answers = new Map();
|
|
232
|
+
const trimmed = responseText.trim();
|
|
233
|
+
if (!trimmed)
|
|
234
|
+
return answers;
|
|
235
|
+
const candidates = [trimmed];
|
|
236
|
+
// Scan fenced code blocks linearly without backtracking regexes.
|
|
237
|
+
let pos = 0;
|
|
238
|
+
while (pos < trimmed.length) {
|
|
239
|
+
const open = trimmed.indexOf('```', pos);
|
|
240
|
+
if (open < 0)
|
|
241
|
+
break;
|
|
242
|
+
const lineEnd = trimmed.indexOf('\n', open + 3);
|
|
243
|
+
if (lineEnd < 0)
|
|
244
|
+
break;
|
|
245
|
+
const close = trimmed.indexOf('```', lineEnd + 1);
|
|
246
|
+
if (close < 0)
|
|
247
|
+
break;
|
|
248
|
+
candidates.push(trimmed.slice(lineEnd + 1, close).trim());
|
|
249
|
+
pos = close + 3;
|
|
250
|
+
}
|
|
251
|
+
for (const bal of extractBalancedJsonObjects(trimmed)) {
|
|
252
|
+
candidates.push(bal);
|
|
253
|
+
}
|
|
254
|
+
for (const cand of candidates) {
|
|
255
|
+
const obj = tryParseJsonObject(cand);
|
|
256
|
+
if (!obj)
|
|
257
|
+
continue;
|
|
258
|
+
const parsedAnswers = new Map();
|
|
259
|
+
let expectedKeyHits = 0;
|
|
260
|
+
const collectKV = (k, v) => {
|
|
261
|
+
const upperKey = k.trim().toUpperCase();
|
|
262
|
+
if (CALIBRATION_KEY_RE.test(upperKey))
|
|
263
|
+
expectedKeyHits++;
|
|
264
|
+
if (typeof v === 'string') {
|
|
265
|
+
parsedAnswers.set(upperKey, v.trim());
|
|
266
|
+
}
|
|
267
|
+
else if (typeof v === 'number' && Number.isFinite(v)) {
|
|
268
|
+
parsedAnswers.set(upperKey, String(v));
|
|
269
|
+
}
|
|
270
|
+
else if (typeof v === 'boolean' && upperKey === 'GUARDS_OK') {
|
|
271
|
+
parsedAnswers.set(upperKey, v ? 'true' : 'false');
|
|
272
|
+
}
|
|
273
|
+
};
|
|
274
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
275
|
+
if (v && typeof v === 'object' && !Array.isArray(v)) {
|
|
276
|
+
for (const [nk, nv] of Object.entries(v)) {
|
|
277
|
+
collectKV(nk, nv);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
else {
|
|
281
|
+
collectKV(k, v);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
if (expectedKeyHits > 0)
|
|
285
|
+
return parsedAnswers;
|
|
286
|
+
}
|
|
287
|
+
// Deterministic plain-text key-value fallback (`HEX_0: value` or `"CODE_0": "value",`).
|
|
288
|
+
for (const line of trimmed.split(/\r?\n/)) {
|
|
289
|
+
const m = line.match(/^\s*(?:[-*]\s*)?[`"']?(HEX_\d+|CODE_\d+|NUM_\d+|GUARDS_OK)[`"']?\s*[:=]\s*(.+?)\s*,?\s*$/i);
|
|
290
|
+
if (!m)
|
|
291
|
+
continue;
|
|
292
|
+
const key = m[1].toUpperCase();
|
|
293
|
+
let val = m[2].trim();
|
|
294
|
+
if (val.startsWith('"') && val.endsWith('"')) {
|
|
295
|
+
try {
|
|
296
|
+
const unescaped = JSON.parse(val);
|
|
297
|
+
if (typeof unescaped === 'string')
|
|
298
|
+
val = unescaped.trim();
|
|
299
|
+
}
|
|
300
|
+
catch {
|
|
301
|
+
val = val.slice(1, -1).trim();
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
else if (val.length >= 2 &&
|
|
305
|
+
((val.startsWith('`') && val.endsWith('`')) ||
|
|
306
|
+
(val.startsWith("'") && val.endsWith("'")))) {
|
|
307
|
+
val = val.slice(1, -1).trim();
|
|
308
|
+
}
|
|
309
|
+
answers.set(key, val);
|
|
310
|
+
}
|
|
311
|
+
return answers;
|
|
312
|
+
}
|
|
313
|
+
export function scoreCalibrationResponse(responseText, probe) {
|
|
314
|
+
const answers = extractResponseAnswers(responseText);
|
|
315
|
+
let hexHits = 0;
|
|
316
|
+
for (let i = 0; i < probe.expectedHex.length; i++) {
|
|
317
|
+
const actual = answers.get(`HEX_${i}`);
|
|
318
|
+
if (actual !== undefined && actual.toLowerCase() === probe.expectedHex[i].trim().toLowerCase()) {
|
|
319
|
+
hexHits++;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
let codeHits = 0;
|
|
323
|
+
for (let i = 0; i < probe.expectedCode.length; i++) {
|
|
324
|
+
const actual = answers.get(`CODE_${i}`);
|
|
325
|
+
if (actual !== undefined && actual === probe.expectedCode[i].trim()) {
|
|
326
|
+
codeHits++;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
let numHits = 0;
|
|
330
|
+
for (let i = 0; i < probe.expectedNums.length; i++) {
|
|
331
|
+
const actual = answers.get(`NUM_${i}`);
|
|
332
|
+
if (actual !== undefined && actual === probe.expectedNums[i].trim()) {
|
|
333
|
+
numHits++;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
const upperResp = responseText.toUpperCase();
|
|
337
|
+
let guardViolations = 0;
|
|
338
|
+
for (const g of probe.forbiddenGuards) {
|
|
339
|
+
if (upperResp.includes(g.toUpperCase())) {
|
|
340
|
+
guardViolations++;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
const guardsOkRaw = answers.get('GUARDS_OK')?.toLowerCase();
|
|
344
|
+
if (guardsOkRaw === 'false') {
|
|
345
|
+
guardViolations = Math.max(1, guardViolations);
|
|
346
|
+
}
|
|
347
|
+
const hexScore = probe.expectedHex.length === 0 ? 1 : hexHits / probe.expectedHex.length;
|
|
348
|
+
const codeScore = probe.expectedCode.length === 0 ? 1 : codeHits / probe.expectedCode.length;
|
|
349
|
+
const numScore = probe.expectedNums.length === 0 ? 1 : numHits / probe.expectedNums.length;
|
|
350
|
+
const guardScore = probe.forbiddenGuards.length === 0
|
|
351
|
+
? 1
|
|
352
|
+
: Math.max(0, probe.forbiddenGuards.length - guardViolations) / probe.forbiddenGuards.length;
|
|
353
|
+
const overallScore = (hexScore + codeScore + numScore + guardScore) / 4;
|
|
354
|
+
const passed = hexScore >= 0.85 &&
|
|
355
|
+
codeScore >= 0.90 &&
|
|
356
|
+
numScore >= 0.95 &&
|
|
357
|
+
guardScore >= 1.0;
|
|
358
|
+
return {
|
|
359
|
+
hexScore,
|
|
360
|
+
codeScore,
|
|
361
|
+
numScore,
|
|
362
|
+
guardScore,
|
|
363
|
+
overallScore,
|
|
364
|
+
passed,
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
// --- In-memory calibrated model registry -----------------------------------
|
|
368
|
+
const calibratedProfiles = new Map();
|
|
369
|
+
/**
|
|
370
|
+
* Normalize a model id for calibration registry lookup:
|
|
371
|
+
* lowercase, strip `[1m]`-style bracketed variant tags, and strip gateway `vendor/` prefixes.
|
|
372
|
+
*/
|
|
373
|
+
export function normalizeCalibratedModelId(model) {
|
|
374
|
+
let m = (model ?? '').trim().toLowerCase().replace(/\[[^\]]*\]/g, '');
|
|
375
|
+
if (!m)
|
|
376
|
+
return '';
|
|
377
|
+
const slash = m.lastIndexOf('/');
|
|
378
|
+
if (slash >= 0)
|
|
379
|
+
m = m.slice(slash + 1);
|
|
380
|
+
// Strip Bedrock / cross-region vendor prefixes (`us.anthropic.claude-...`, `global.google.gemini-...`).
|
|
381
|
+
m = m.replace(/^(?:us|eu|ap|ca|sa|me|af|global)\.(?:anthropic|google|openai|amazon)\./, '');
|
|
382
|
+
return m.trim();
|
|
383
|
+
}
|
|
384
|
+
function cloneCalibratedProfile(profile, normalizedModel) {
|
|
385
|
+
return {
|
|
386
|
+
model: normalizedModel ?? profile.model,
|
|
387
|
+
band: profile.band,
|
|
388
|
+
cols: profile.cols,
|
|
389
|
+
maxHeightPx: profile.maxHeightPx,
|
|
390
|
+
calibratedAtIso: profile.calibratedAtIso,
|
|
391
|
+
scores: { ...profile.scores },
|
|
392
|
+
source: profile.source,
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
function isUnitScore(v) {
|
|
396
|
+
return typeof v === 'number' && Number.isFinite(v) && v >= 0 && v <= 1;
|
|
397
|
+
}
|
|
398
|
+
function validateCalibratedProfile(entry) {
|
|
399
|
+
if (!entry || typeof entry !== 'object' || Array.isArray(entry))
|
|
400
|
+
return undefined;
|
|
401
|
+
const e = entry;
|
|
402
|
+
if (typeof e.model !== 'string')
|
|
403
|
+
return undefined;
|
|
404
|
+
const normalized = normalizeCalibratedModelId(e.model);
|
|
405
|
+
if (!normalized)
|
|
406
|
+
return undefined;
|
|
407
|
+
if (!isCalibrationBand(e.band))
|
|
408
|
+
return undefined;
|
|
409
|
+
if (typeof e.cols !== 'number' || !Number.isFinite(e.cols) || !Number.isInteger(e.cols))
|
|
410
|
+
return undefined;
|
|
411
|
+
if (e.band === 'text-only' ? e.cols < 0 : e.cols <= 0)
|
|
412
|
+
return undefined;
|
|
413
|
+
if (typeof e.maxHeightPx !== 'number' || !Number.isFinite(e.maxHeightPx) || !Number.isInteger(e.maxHeightPx)) {
|
|
414
|
+
return undefined;
|
|
415
|
+
}
|
|
416
|
+
if (e.band === 'text-only' ? e.maxHeightPx < 0 : e.maxHeightPx <= 0)
|
|
417
|
+
return undefined;
|
|
418
|
+
if (typeof e.calibratedAtIso !== 'string' || e.calibratedAtIso.trim() === '')
|
|
419
|
+
return undefined;
|
|
420
|
+
if (!Number.isFinite(Date.parse(e.calibratedAtIso)))
|
|
421
|
+
return undefined;
|
|
422
|
+
if (e.source !== 'probe' && e.source !== 'manual')
|
|
423
|
+
return undefined;
|
|
424
|
+
const s = e.scores;
|
|
425
|
+
if (!s || typeof s !== 'object' || Array.isArray(s))
|
|
426
|
+
return undefined;
|
|
427
|
+
if (!isUnitScore(s.hexScore) ||
|
|
428
|
+
!isUnitScore(s.codeScore) ||
|
|
429
|
+
!isUnitScore(s.numScore) ||
|
|
430
|
+
!isUnitScore(s.guardScore) ||
|
|
431
|
+
!isUnitScore(s.overallScore) ||
|
|
432
|
+
typeof s.passed !== 'boolean') {
|
|
433
|
+
return undefined;
|
|
434
|
+
}
|
|
435
|
+
return {
|
|
436
|
+
model: normalized,
|
|
437
|
+
band: e.band,
|
|
438
|
+
cols: e.cols,
|
|
439
|
+
maxHeightPx: e.maxHeightPx,
|
|
440
|
+
calibratedAtIso: e.calibratedAtIso,
|
|
441
|
+
scores: {
|
|
442
|
+
hexScore: s.hexScore,
|
|
443
|
+
codeScore: s.codeScore,
|
|
444
|
+
numScore: s.numScore,
|
|
445
|
+
guardScore: s.guardScore,
|
|
446
|
+
overallScore: s.overallScore,
|
|
447
|
+
passed: s.passed,
|
|
448
|
+
},
|
|
449
|
+
source: e.source,
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
const MAX_CALIBRATED_PROFILES = 256;
|
|
453
|
+
function putCalibratedProfile(valid) {
|
|
454
|
+
if (calibratedProfiles.has(valid.model)) {
|
|
455
|
+
calibratedProfiles.delete(valid.model);
|
|
456
|
+
}
|
|
457
|
+
else if (calibratedProfiles.size >= MAX_CALIBRATED_PROFILES) {
|
|
458
|
+
const oldestKey = calibratedProfiles.keys().next().value;
|
|
459
|
+
if (oldestKey !== undefined)
|
|
460
|
+
calibratedProfiles.delete(oldestKey);
|
|
461
|
+
}
|
|
462
|
+
calibratedProfiles.set(valid.model, valid);
|
|
463
|
+
}
|
|
464
|
+
export function setCalibratedProfile(profile) {
|
|
465
|
+
const valid = validateCalibratedProfile(profile);
|
|
466
|
+
if (!valid)
|
|
467
|
+
return;
|
|
468
|
+
putCalibratedProfile(valid);
|
|
469
|
+
}
|
|
470
|
+
export function removeCalibratedProfile(model) {
|
|
471
|
+
const key = normalizeCalibratedModelId(model);
|
|
472
|
+
if (!key)
|
|
473
|
+
return false;
|
|
474
|
+
return calibratedProfiles.delete(key);
|
|
475
|
+
}
|
|
476
|
+
// Prefix inheritance is strictly limited to effort, date, or provider revision tags
|
|
477
|
+
// so distinct sub-variants (e.g. gemini-4-hydrogen, claude-opus-5-5) never inherit
|
|
478
|
+
// a parent model's reading tier or bypass TEXT_ONLY.
|
|
479
|
+
const CALIBRATION_INHERIT_SUFFIX_RE = /^(?:@[a-z0-9._-]+|:[a-z0-9._-]+|-(?:20\d{6}|\d{4}-\d{2}-\d{2}|preview|latest|exp|experimental|low|medium|high|max|minimal|none|thinking|reasoning|fast|turbo|v\d+(?:\.\d+)?))$/i;
|
|
480
|
+
export function getCalibratedProfileMatch(model) {
|
|
481
|
+
const key = normalizeCalibratedModelId(model);
|
|
482
|
+
if (!key)
|
|
483
|
+
return undefined;
|
|
484
|
+
const exact = calibratedProfiles.get(key);
|
|
485
|
+
if (exact)
|
|
486
|
+
return { profile: cloneCalibratedProfile(exact), exact: true };
|
|
487
|
+
// Match longest calibrated base key separated by effort/date/revision boundary (`-`, `@`, `:`).
|
|
488
|
+
let best;
|
|
489
|
+
let bestLen = -1;
|
|
490
|
+
for (const [k, prof] of calibratedProfiles) {
|
|
491
|
+
if (k.length > bestLen && key.length > k.length && key.startsWith(k)) {
|
|
492
|
+
const suffix = key.slice(k.length);
|
|
493
|
+
if (CALIBRATION_INHERIT_SUFFIX_RE.test(suffix)) {
|
|
494
|
+
best = prof;
|
|
495
|
+
bestLen = k.length;
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
return best ? { profile: cloneCalibratedProfile(best), exact: false } : undefined;
|
|
500
|
+
}
|
|
501
|
+
export function getCalibratedProfile(model) {
|
|
502
|
+
return getCalibratedProfileMatch(model)?.profile;
|
|
503
|
+
}
|
|
504
|
+
export function listCalibratedProfiles() {
|
|
505
|
+
return [...calibratedProfiles.values()].map((p) => cloneCalibratedProfile(p));
|
|
506
|
+
}
|
|
507
|
+
export function clearCalibratedProfiles() {
|
|
508
|
+
calibratedProfiles.clear();
|
|
509
|
+
}
|
|
510
|
+
const CALIBRATION_STORE_FORMAT = 1;
|
|
511
|
+
export function serializeCalibratedProfiles() {
|
|
512
|
+
return JSON.stringify({
|
|
513
|
+
format: CALIBRATION_STORE_FORMAT,
|
|
514
|
+
profiles: listCalibratedProfiles(),
|
|
515
|
+
}, null, 2);
|
|
516
|
+
}
|
|
517
|
+
/**
|
|
518
|
+
* Restore calibrated profiles from serialized JSON using fail-closed validation.
|
|
519
|
+
* Corrupt JSON, mismatched format tags, or malformed profile entries are rejected/skipped.
|
|
520
|
+
* Returns the number of valid profiles restored.
|
|
521
|
+
*/
|
|
522
|
+
export function restoreCalibratedProfiles(json) {
|
|
523
|
+
if (!json || typeof json !== 'string')
|
|
524
|
+
return 0;
|
|
525
|
+
let parsed;
|
|
526
|
+
try {
|
|
527
|
+
parsed = JSON.parse(json);
|
|
528
|
+
}
|
|
529
|
+
catch {
|
|
530
|
+
return 0;
|
|
531
|
+
}
|
|
532
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
533
|
+
return 0;
|
|
534
|
+
const obj = parsed;
|
|
535
|
+
if (obj.format !== CALIBRATION_STORE_FORMAT || !Array.isArray(obj.profiles))
|
|
536
|
+
return 0;
|
|
537
|
+
let restored = 0;
|
|
538
|
+
for (const entry of obj.profiles) {
|
|
539
|
+
const valid = validateCalibratedProfile(entry);
|
|
540
|
+
if (!valid)
|
|
541
|
+
continue;
|
|
542
|
+
putCalibratedProfile(valid);
|
|
543
|
+
restored++;
|
|
544
|
+
}
|
|
545
|
+
return restored;
|
|
546
|
+
}
|
|
547
|
+
//# sourceMappingURL=calibration.js.map
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CASI v2: Append-Only Content-Addressed Gutter-Normalized FastCDC Delta Store.
|
|
3
|
+
*
|
|
4
|
+
* Scans tool outputs monotonically in prefix order (`0 -> N-1`). Each block `k`
|
|
5
|
+
* queries ONLY intact prior entries `0..k-1`, guaranteeing 100% prefix-cache
|
|
6
|
+
* invariance across multi-turn conversations: turn T's prefix bytes remain bit-
|
|
7
|
+
* identical when turn T+1 appends new messages.
|
|
8
|
+
*
|
|
9
|
+
* Emits:
|
|
10
|
+
* - Exact / gutter-shifted duplicate reference (`[fiche cas: ...]`)
|
|
11
|
+
* - Anchor-aligned unified diff hunk (`[fiche cas-delta vs ... (±2 context)]`)
|
|
12
|
+
* - FastCDC sub-block slice splice (`[fiche cas-slice: ...]`)
|
|
13
|
+
*
|
|
14
|
+
* Deltas and slices are never re-indexed as bases (chain depth <= 1). Zero `node:` imports.
|
|
15
|
+
*/
|
|
16
|
+
export interface CasiResult {
|
|
17
|
+
readonly text: string;
|
|
18
|
+
readonly changed: boolean;
|
|
19
|
+
readonly kind?: 'exact_dup' | 'delta' | 'slice';
|
|
20
|
+
readonly baseRefId?: string;
|
|
21
|
+
readonly savedChars: number;
|
|
22
|
+
readonly savedTokens: number;
|
|
23
|
+
}
|
|
24
|
+
/** Deterministic 256-entry FastCDC Gear table generated via SplitMix32 constants. */
|
|
25
|
+
export declare const GEAR_TABLE: Uint32Array;
|
|
26
|
+
/**
|
|
27
|
+
* Strip `read_file` / `bat` / `view_file` line-number gutters (`1→`, `1\t`, `1 │ `, `L1: `)
|
|
28
|
+
* into `{ lineNum, body }` without altering body indentation.
|
|
29
|
+
*/
|
|
30
|
+
export declare function stripLineGutter(line: string): {
|
|
31
|
+
lineNum: number | null;
|
|
32
|
+
body: string;
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* Normalize volatile ISO timestamps, clock timestamps, and durations ONLY for
|
|
36
|
+
* similarity voting and chunk matching while preserving exact `curLines` in output.
|
|
37
|
+
*/
|
|
38
|
+
export declare function canonicalForMatching(body: string): string;
|
|
39
|
+
export declare function clearCasiPreparedCacheForTests(): void;
|
|
40
|
+
export declare class CasiIndex {
|
|
41
|
+
private readonly exactByHash;
|
|
42
|
+
private readonly exactBodyByHash;
|
|
43
|
+
private readonly lineIndex;
|
|
44
|
+
private readonly chunkIndex;
|
|
45
|
+
private readonly entries;
|
|
46
|
+
private readonly seedHashes;
|
|
47
|
+
private seedCount;
|
|
48
|
+
private indexEntry;
|
|
49
|
+
/**
|
|
50
|
+
* Read-only base seeding (e.g. from `tool_use.input` / `functionCall.args` payloads >= 400 chars)
|
|
51
|
+
* without mutating assistant/model messages.
|
|
52
|
+
*/
|
|
53
|
+
seedBase(rawText: string, refId: string, turnGroup?: number): void;
|
|
54
|
+
/**
|
|
55
|
+
* Warm-replay counterpart of an unmatched `ingest()` base, bounded by `MAX_CASI_ENTRIES`
|
|
56
|
+
* (128) and independent of `MAX_SEED_ENTRIES` / `seedHashes`.
|
|
57
|
+
*/
|
|
58
|
+
replayIndexedBase(rawText: string, refId: string, turnGroup?: number): void;
|
|
59
|
+
private tryFastCdcSplice;
|
|
60
|
+
ingest(rawText: string, refId: string, turnGroup?: number, minBaseTurnGroup?: number): CasiResult;
|
|
61
|
+
}
|
|
62
|
+
export declare function createCasiIndex(): CasiIndex;
|
|
63
|
+
//# sourceMappingURL=casi-delta.d.ts.map
|