@sriinnu/fiche 0.18.0-bootstrap.0 → 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.
Files changed (196) hide show
  1. package/CHANGELOG.md +134 -0
  2. package/LICENSE +22 -0
  3. package/NOTICE +13 -0
  4. package/PRIVACY.md +41 -0
  5. package/README.md +289 -0
  6. package/SECURITY.md +53 -0
  7. package/assets/JETBRAINS_MONO_LICENSE.txt +89 -0
  8. package/assets/SPLEEN_LICENSE.txt +24 -0
  9. package/assets/UNIFONT_LICENSE.txt +476 -0
  10. package/assets/fiche-logo-dark.svg +61 -0
  11. package/assets/fiche-logo-light.svg +61 -0
  12. package/assets/fiche-logo.svg +71 -0
  13. package/assets/fiche-mark.svg +48 -0
  14. package/bin/cli.js +7 -0
  15. package/bin/mcp.js +8 -0
  16. package/dist/calibrate.d.ts +30 -0
  17. package/dist/calibrate.js +588 -0
  18. package/dist/core/anthropic-vision.d.ts +28 -0
  19. package/dist/core/anthropic-vision.js +34 -0
  20. package/dist/core/applicability.d.ts +63 -0
  21. package/dist/core/applicability.js +151 -0
  22. package/dist/core/atlas-gray-jbmono10.d.ts +26 -0
  23. package/dist/core/atlas-gray-jbmono10.js +64 -0
  24. package/dist/core/atlas-gray-jbmono12.d.ts +26 -0
  25. package/dist/core/atlas-gray-jbmono12.js +64 -0
  26. package/dist/core/atlas-gray-jbmono14.d.ts +26 -0
  27. package/dist/core/atlas-gray-jbmono14.js +64 -0
  28. package/dist/core/atlas-gray.d.ts +26 -0
  29. package/dist/core/atlas-gray.js +64 -0
  30. package/dist/core/atlas-jbmono10.d.ts +34 -0
  31. package/dist/core/atlas-jbmono10.js +71 -0
  32. package/dist/core/atlas-jbmono12.d.ts +34 -0
  33. package/dist/core/atlas-jbmono12.js +71 -0
  34. package/dist/core/atlas-jbmono14.d.ts +34 -0
  35. package/dist/core/atlas-jbmono14.js +71 -0
  36. package/dist/core/atlas.d.ts +34 -0
  37. package/dist/core/atlas.js +71 -0
  38. package/dist/core/baseline.d.ts +121 -0
  39. package/dist/core/baseline.js +200 -0
  40. package/dist/core/calibration.d.ts +86 -0
  41. package/dist/core/calibration.js +547 -0
  42. package/dist/core/casi-delta.d.ts +63 -0
  43. package/dist/core/casi-delta.js +1271 -0
  44. package/dist/core/claude-model-profiles.d.ts +53 -0
  45. package/dist/core/claude-model-profiles.js +160 -0
  46. package/dist/core/client-tool-round.d.ts +31 -0
  47. package/dist/core/client-tool-round.js +58 -0
  48. package/dist/core/codex-cache.d.ts +20 -0
  49. package/dist/core/codex-cache.js +59 -0
  50. package/dist/core/context-mmu.d.ts +350 -0
  51. package/dist/core/context-mmu.js +3028 -0
  52. package/dist/core/cpt-fit.d.ts +70 -0
  53. package/dist/core/cpt-fit.js +197 -0
  54. package/dist/core/env.d.ts +8 -0
  55. package/dist/core/env.js +15 -0
  56. package/dist/core/export.d.ts +127 -0
  57. package/dist/core/export.js +385 -0
  58. package/dist/core/factsheet.d.ts +77 -0
  59. package/dist/core/factsheet.js +494 -0
  60. package/dist/core/gemini-model-profiles.d.ts +20 -0
  61. package/dist/core/gemini-model-profiles.js +134 -0
  62. package/dist/core/google.d.ts +76 -0
  63. package/dist/core/google.js +1380 -0
  64. package/dist/core/gpt-model-profiles.d.ts +218 -0
  65. package/dist/core/gpt-model-profiles.js +570 -0
  66. package/dist/core/gpt-tokens.d.ts +14 -0
  67. package/dist/core/gpt-tokens.js +165 -0
  68. package/dist/core/history.d.ts +197 -0
  69. package/dist/core/history.js +1003 -0
  70. package/dist/core/index.d.ts +16 -0
  71. package/dist/core/index.js +16 -0
  72. package/dist/core/library.d.ts +80 -0
  73. package/dist/core/library.js +131 -0
  74. package/dist/core/measurement.d.ts +34 -0
  75. package/dist/core/measurement.js +280 -0
  76. package/dist/core/messages-chat-bridge.d.ts +23 -0
  77. package/dist/core/messages-chat-bridge.js +747 -0
  78. package/dist/core/messages-responses-bridge.d.ts +11 -0
  79. package/dist/core/messages-responses-bridge.js +893 -0
  80. package/dist/core/openai-history.d.ts +184 -0
  81. package/dist/core/openai-history.js +1279 -0
  82. package/dist/core/openai-savings.d.ts +57 -0
  83. package/dist/core/openai-savings.js +116 -0
  84. package/dist/core/openai.d.ts +68 -0
  85. package/dist/core/openai.js +2523 -0
  86. package/dist/core/pin.d.ts +199 -0
  87. package/dist/core/pin.js +1353 -0
  88. package/dist/core/png.d.ts +14 -0
  89. package/dist/core/png.js +188 -0
  90. package/dist/core/prefix-tape.d.ts +102 -0
  91. package/dist/core/prefix-tape.js +315 -0
  92. package/dist/core/price-id.d.ts +10 -0
  93. package/dist/core/price-id.js +26 -0
  94. package/dist/core/prices.generated.d.ts +36 -0
  95. package/dist/core/prices.generated.js +369 -0
  96. package/dist/core/pricing.d.ts +134 -0
  97. package/dist/core/pricing.js +335 -0
  98. package/dist/core/profile-base.d.ts +30 -0
  99. package/dist/core/profile-base.js +67 -0
  100. package/dist/core/provider-router.d.ts +51 -0
  101. package/dist/core/provider-router.js +121 -0
  102. package/dist/core/proxy.d.ts +252 -0
  103. package/dist/core/proxy.js +2929 -0
  104. package/dist/core/reader-tier.d.ts +24 -0
  105. package/dist/core/reader-tier.js +118 -0
  106. package/dist/core/render.d.ts +280 -0
  107. package/dist/core/render.js +1302 -0
  108. package/dist/core/request-guard.d.ts +31 -0
  109. package/dist/core/request-guard.js +126 -0
  110. package/dist/core/request-transform.d.ts +43 -0
  111. package/dist/core/request-transform.js +173 -0
  112. package/dist/core/schema-compiler.d.ts +64 -0
  113. package/dist/core/schema-compiler.js +1696 -0
  114. package/dist/core/schema-strip.d.ts +29 -0
  115. package/dist/core/schema-strip.js +173 -0
  116. package/dist/core/session-state.d.ts +219 -0
  117. package/dist/core/session-state.js +929 -0
  118. package/dist/core/stage-plugins.d.ts +45 -0
  119. package/dist/core/stage-plugins.js +205 -0
  120. package/dist/core/text-history.d.ts +74 -0
  121. package/dist/core/text-history.js +612 -0
  122. package/dist/core/text-hygiene.d.ts +160 -0
  123. package/dist/core/text-hygiene.js +2259 -0
  124. package/dist/core/toon.d.ts +29 -0
  125. package/dist/core/toon.js +425 -0
  126. package/dist/core/tracker.d.ts +223 -0
  127. package/dist/core/tracker.js +290 -0
  128. package/dist/core/transform.d.ts +589 -0
  129. package/dist/core/transform.js +3153 -0
  130. package/dist/core/types.d.ts +87 -0
  131. package/dist/core/types.js +8 -0
  132. package/dist/core/upstream-hosts.d.ts +127 -0
  133. package/dist/core/upstream-hosts.js +398 -0
  134. package/dist/core/vision-cost.d.ts +63 -0
  135. package/dist/core/vision-cost.js +137 -0
  136. package/dist/dashboard/fragments.d.ts +87 -0
  137. package/dist/dashboard/fragments.js +1515 -0
  138. package/dist/dashboard/types.d.ts +217 -0
  139. package/dist/dashboard/types.js +3 -0
  140. package/dist/dashboard/vendor.d.ts +3 -0
  141. package/dist/dashboard/vendor.js +6 -0
  142. package/dist/dashboard.d.ts +372 -0
  143. package/dist/dashboard.js +2731 -0
  144. package/dist/export-collect.d.ts +36 -0
  145. package/dist/export-collect.js +59 -0
  146. package/dist/file-tracker.d.ts +42 -0
  147. package/dist/file-tracker.js +234 -0
  148. package/dist/kosha-sync.d.ts +74 -0
  149. package/dist/kosha-sync.js +272 -0
  150. package/dist/launchd-socket.d.ts +22 -0
  151. package/dist/launchd-socket.js +210 -0
  152. package/dist/mcp/cli.d.ts +2 -0
  153. package/dist/mcp/cli.js +55 -0
  154. package/dist/mcp/server.d.ts +48 -0
  155. package/dist/mcp/server.js +987 -0
  156. package/dist/mmu-store.d.ts +31 -0
  157. package/dist/mmu-store.js +179 -0
  158. package/dist/node-fetch.d.ts +22 -0
  159. package/dist/node-fetch.js +489 -0
  160. package/dist/node.d.ts +9 -0
  161. package/dist/node.js +244396 -0
  162. package/dist/request-decoding.d.ts +30 -0
  163. package/dist/request-decoding.js +85 -0
  164. package/dist/sessions.d.ts +179 -0
  165. package/dist/sessions.js +837 -0
  166. package/dist/stats.d.ts +114 -0
  167. package/dist/stats.js +439 -0
  168. package/dist/turn-report.d.ts +65 -0
  169. package/dist/turn-report.js +724 -0
  170. package/dist/warp/app-launch.d.ts +26 -0
  171. package/dist/warp/app-launch.js +155 -0
  172. package/dist/warp/ca.d.ts +74 -0
  173. package/dist/warp/ca.js +416 -0
  174. package/dist/warp/connect.d.ts +42 -0
  175. package/dist/warp/connect.js +686 -0
  176. package/dist/warp/der.d.ts +57 -0
  177. package/dist/warp/der.js +151 -0
  178. package/dist/warp/index.d.ts +79 -0
  179. package/dist/warp/index.js +650 -0
  180. package/dist/warp/resolve.d.ts +12 -0
  181. package/dist/warp/resolve.js +49 -0
  182. package/dist/warp/route.d.ts +71 -0
  183. package/dist/warp/route.js +134 -0
  184. package/dist/worker.d.ts +71 -0
  185. package/dist/worker.js +174 -0
  186. package/docs/SECURITY_MODEL.md +84 -0
  187. package/package.json +115 -3
  188. package/plugins/fiche-companion/README.md +42 -0
  189. package/plugins/fiche-companion/assets/logo.svg +48 -0
  190. package/plugins/fiche-companion/hooks.json +11 -0
  191. package/plugins/fiche-companion/mcp_config.json +8 -0
  192. package/plugins/fiche-companion/plugin.json +18 -0
  193. package/plugins/fiche-companion/scripts/claude-statusline.mjs +35 -0
  194. package/plugins/fiche-companion/scripts/post-invocation.mjs +122 -0
  195. package/plugins/fiche-companion/scripts/resolve-turn-report.mjs +132 -0
  196. package/plugins/fiche-companion/skills/fiche/SKILL.md +61 -0
@@ -0,0 +1,588 @@
1
+ /**
2
+ * CLI + atomic file persistence for `fiche calibrate`.
3
+ *
4
+ * Probes vision models across candidate microfiche rendering bands from densest
5
+ * (`spleen-5x8`) to largest (`jetbrains-mono-14`), records the densest passing
6
+ * band (or `text-only` fallback), and persists `~/.config/fiche/calibrated-models.json`
7
+ * atomically with mode `0600`.
8
+ */
9
+ import crypto from 'node:crypto';
10
+ import fs from 'node:fs';
11
+ import os from 'node:os';
12
+ import path from 'node:path';
13
+ import { CALIBRATION_BAND_ORDER, buildCalibrationProbe, getCalibratedProfile, isImageCalibrationBand, listCalibratedProfiles, normalizeCalibratedModelId, removeCalibratedProfile, restoreCalibratedProfiles, scoreCalibrationResponse, serializeCalibratedProfiles, setCalibratedProfile, } from './core/calibration.js';
14
+ import { isGeminiModel, resolveGeminiProfile } from './core/gemini-model-profiles.js';
15
+ import { resolveGptProfile } from './core/gpt-model-profiles.js';
16
+ import { visionTokens } from './core/vision-cost.js';
17
+ export function defaultCalibratedProfilesPath(env = process.env) {
18
+ const override = env.FICHE_CALIBRATED_MODELS?.trim() || env.INKLING_CALIBRATED_MODELS?.trim();
19
+ if (override)
20
+ return override;
21
+ return path.join(os.homedir(), '.config', 'fiche', 'calibrated-models.json');
22
+ }
23
+ const MAX_CALIBRATION_FILE_BYTES = 1024 * 1024;
24
+ let warnedCalibrationDirMode = false;
25
+ export function loadCalibratedProfilesFile(filePath = defaultCalibratedProfilesPath()) {
26
+ let fd;
27
+ try {
28
+ const st = fs.lstatSync(filePath);
29
+ if (!st.isFile() || st.size > MAX_CALIBRATION_FILE_BYTES)
30
+ return 0;
31
+ fd = fs.openSync(filePath, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
32
+ const raw = fs.readFileSync(fd, 'utf8');
33
+ return restoreCalibratedProfiles(raw);
34
+ }
35
+ catch (err) {
36
+ if (err.code === 'ENOENT')
37
+ return 0;
38
+ return 0;
39
+ }
40
+ finally {
41
+ if (fd !== undefined) {
42
+ try {
43
+ fs.closeSync(fd);
44
+ }
45
+ catch {
46
+ /* ignore close failure */
47
+ }
48
+ }
49
+ }
50
+ }
51
+ export function saveCalibratedProfilesFile(filePath = defaultCalibratedProfilesPath()) {
52
+ const dir = path.dirname(filePath);
53
+ const parentExists = fs.existsSync(dir);
54
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
55
+ if (!parentExists) {
56
+ fs.chmodSync(dir, 0o700);
57
+ }
58
+ else if (!warnedCalibrationDirMode) {
59
+ const dirMode = fs.statSync(dir).mode;
60
+ if ((dirMode & 0o077) !== 0) {
61
+ warnedCalibrationDirMode = true;
62
+ console.warn(`[fiche] warning: calibration directory ${dir} has permissive mode ${(dirMode & 0o777).toString(8)}; chmod 700 recommended`);
63
+ }
64
+ }
65
+ const nonce = crypto.randomBytes(6).toString('hex');
66
+ const tmp = `${filePath}.${process.pid}.${nonce}.tmp`;
67
+ const payload = `${serializeCalibratedProfiles()}\n`;
68
+ const flags = fs.constants.O_WRONLY |
69
+ fs.constants.O_CREAT |
70
+ fs.constants.O_EXCL |
71
+ (fs.constants.O_NOFOLLOW ?? 0);
72
+ let fd;
73
+ try {
74
+ fd = fs.openSync(tmp, flags, 0o600);
75
+ fs.writeFileSync(fd, payload, 'utf8');
76
+ fs.fchmodSync(fd, 0o600);
77
+ fs.closeSync(fd);
78
+ fd = undefined;
79
+ fs.renameSync(tmp, filePath);
80
+ }
81
+ catch (err) {
82
+ if (fd !== undefined) {
83
+ try {
84
+ fs.closeSync(fd);
85
+ }
86
+ catch {
87
+ /* ignore close failure */
88
+ }
89
+ }
90
+ try {
91
+ fs.unlinkSync(tmp);
92
+ }
93
+ catch {
94
+ /* ignore cleanup failure */
95
+ }
96
+ throw err;
97
+ }
98
+ }
99
+ function uint8ToBase64(bytes) {
100
+ return Buffer.from(bytes).toString('base64');
101
+ }
102
+ function resolveProvider(model, explicit) {
103
+ if (explicit !== 'auto')
104
+ return explicit;
105
+ const lower = model.toLowerCase();
106
+ if (lower.includes('gemini') || lower.startsWith('google/'))
107
+ return 'google';
108
+ if (lower.includes('claude') || lower.includes('anthropic'))
109
+ return 'anthropic';
110
+ return 'openai';
111
+ }
112
+ function resolveApiKey(provider, env) {
113
+ switch (provider) {
114
+ case 'google':
115
+ return {
116
+ key: env.GEMINI_API_KEY?.trim() || env.GOOGLE_API_KEY?.trim() || undefined,
117
+ authKind: 'api-key',
118
+ envNames: ['GEMINI_API_KEY', 'GOOGLE_API_KEY'],
119
+ };
120
+ case 'anthropic': {
121
+ const apiKey = env.ANTHROPIC_API_KEY?.trim();
122
+ if (apiKey) {
123
+ return { key: apiKey, authKind: 'api-key', envNames: ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN'] };
124
+ }
125
+ const authToken = env.ANTHROPIC_AUTH_TOKEN?.trim();
126
+ return {
127
+ key: authToken || undefined,
128
+ authKind: 'oauth-bearer',
129
+ envNames: ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN'],
130
+ };
131
+ }
132
+ case 'openai':
133
+ return {
134
+ key: env.OPENAI_API_KEY?.trim() || undefined,
135
+ authKind: 'oauth-bearer',
136
+ envNames: ['OPENAI_API_KEY'],
137
+ };
138
+ }
139
+ }
140
+ function stripProviderPrefix(model, _provider) {
141
+ let trimmed = model.trim().replace(/\[[^\]]*\]/g, '');
142
+ const slash = trimmed.lastIndexOf('/');
143
+ if (slash >= 0)
144
+ trimmed = trimmed.slice(slash + 1);
145
+ return trimmed.trim();
146
+ }
147
+ const CALIBRATION_FETCH_TIMEOUT_MS = 30_000;
148
+ async function sendProbeToProvider(provider, model, apiKey, authKind, probe, fetchImpl) {
149
+ const apiModel = stripProviderPrefix(model, provider);
150
+ if (provider === 'google') {
151
+ const url = `https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(apiModel)}:generateContent`;
152
+ const body = {
153
+ contents: [
154
+ {
155
+ role: 'user',
156
+ parts: [
157
+ ...probe.pngs.map((img) => ({
158
+ inlineData: { mimeType: 'image/png', data: uint8ToBase64(img.png) },
159
+ })),
160
+ { text: probe.prompt },
161
+ ],
162
+ },
163
+ ],
164
+ generationConfig: { temperature: 0 },
165
+ };
166
+ const res = await fetchImpl(url, {
167
+ method: 'POST',
168
+ redirect: 'manual',
169
+ signal: AbortSignal.timeout(CALIBRATION_FETCH_TIMEOUT_MS),
170
+ headers: {
171
+ 'content-type': 'application/json',
172
+ 'x-goog-api-key': apiKey,
173
+ },
174
+ body: JSON.stringify(body),
175
+ });
176
+ const text = await res.text();
177
+ if (!res.ok) {
178
+ throw new Error(`Google API ${res.status}: ${text.slice(0, 240)}`);
179
+ }
180
+ const json = JSON.parse(text);
181
+ return (json.candidates?.[0]?.content?.parts ?? [])
182
+ .map((p) => (typeof p.text === 'string' ? p.text : ''))
183
+ .join('\n');
184
+ }
185
+ if (provider === 'anthropic') {
186
+ const body = {
187
+ model: apiModel,
188
+ max_tokens: 1024,
189
+ temperature: 0,
190
+ messages: [
191
+ {
192
+ role: 'user',
193
+ content: [
194
+ ...probe.pngs.map((img) => ({
195
+ type: 'image',
196
+ source: {
197
+ type: 'base64',
198
+ media_type: 'image/png',
199
+ data: uint8ToBase64(img.png),
200
+ },
201
+ })),
202
+ { type: 'text', text: probe.prompt },
203
+ ],
204
+ },
205
+ ],
206
+ };
207
+ const authHeaders = authKind === 'oauth-bearer'
208
+ ? { authorization: `Bearer ${apiKey}` }
209
+ : { 'x-api-key': apiKey };
210
+ const res = await fetchImpl('https://api.anthropic.com/v1/messages', {
211
+ method: 'POST',
212
+ redirect: 'manual',
213
+ signal: AbortSignal.timeout(CALIBRATION_FETCH_TIMEOUT_MS),
214
+ headers: {
215
+ 'content-type': 'application/json',
216
+ ...authHeaders,
217
+ 'anthropic-version': '2023-06-01',
218
+ },
219
+ body: JSON.stringify(body),
220
+ });
221
+ const text = await res.text();
222
+ if (!res.ok) {
223
+ throw new Error(`Anthropic API ${res.status}: ${text.slice(0, 240)}`);
224
+ }
225
+ const json = JSON.parse(text);
226
+ return (json.content ?? [])
227
+ .filter((b) => b.type === 'text' && typeof b.text === 'string')
228
+ .map((b) => b.text)
229
+ .join('\n');
230
+ }
231
+ // OpenAI Chat Completions
232
+ const gptProfile = resolveGptProfile(model);
233
+ const imageDetail = gptProfile.imageDetail ?? 'high';
234
+ const body = {
235
+ model: apiModel,
236
+ max_tokens: 1024,
237
+ temperature: 0,
238
+ messages: [
239
+ {
240
+ role: 'user',
241
+ content: [
242
+ ...probe.pngs.map((img) => ({
243
+ type: 'image_url',
244
+ image_url: {
245
+ url: `data:image/png;base64,${uint8ToBase64(img.png)}`,
246
+ detail: imageDetail,
247
+ },
248
+ })),
249
+ { type: 'text', text: probe.prompt },
250
+ ],
251
+ },
252
+ ],
253
+ };
254
+ const res = await fetchImpl('https://api.openai.com/v1/chat/completions', {
255
+ method: 'POST',
256
+ redirect: 'manual',
257
+ signal: AbortSignal.timeout(CALIBRATION_FETCH_TIMEOUT_MS),
258
+ headers: {
259
+ 'content-type': 'application/json',
260
+ authorization: `Bearer ${apiKey}`,
261
+ },
262
+ body: JSON.stringify(body),
263
+ });
264
+ const text = await res.text();
265
+ if (!res.ok) {
266
+ throw new Error(`OpenAI API ${res.status}: ${text.slice(0, 240)}`);
267
+ }
268
+ const json = JSON.parse(text);
269
+ const content = json.choices?.[0]?.message?.content;
270
+ if (typeof content === 'string')
271
+ return content;
272
+ if (Array.isArray(content)) {
273
+ return content
274
+ .map((part) => (typeof part.text === 'string' ? part.text : ''))
275
+ .join('\n');
276
+ }
277
+ return '';
278
+ }
279
+ function estimateProbeTokens(model, probe) {
280
+ const profile = isGeminiModel(model)
281
+ ? resolveGeminiProfile(model)
282
+ : resolveGptProfile(model);
283
+ let total = 0;
284
+ for (const img of probe.pngs) {
285
+ total += visionTokens(profile, img.width, img.height);
286
+ }
287
+ return total;
288
+ }
289
+ function buildPerfectFixtureJson(probe) {
290
+ const payload = {};
291
+ probe.expectedHex.forEach((v, i) => { payload[`HEX_${i}`] = v; });
292
+ probe.expectedCode.forEach((v, i) => { payload[`CODE_${i}`] = v; });
293
+ probe.expectedNums.forEach((v, i) => { payload[`NUM_${i}`] = v; });
294
+ payload.GUARDS_OK = true;
295
+ return JSON.stringify(payload);
296
+ }
297
+ function parseCliArgs(rawArgv) {
298
+ const argv = rawArgv[0] === 'calibrate' ? rawArgv.slice(1) : rawArgv;
299
+ const out = {
300
+ help: false,
301
+ list: false,
302
+ dryRun: false,
303
+ json: false,
304
+ provider: 'auto',
305
+ band: 'auto',
306
+ };
307
+ for (let i = 0; i < argv.length; i++) {
308
+ const a = argv[i];
309
+ if (a === '--help' || a === '-h') {
310
+ out.help = true;
311
+ }
312
+ else if (a === '--list') {
313
+ out.list = true;
314
+ }
315
+ else if (a === '--dry-run') {
316
+ out.dryRun = true;
317
+ }
318
+ else if (a === '--json') {
319
+ out.json = true;
320
+ }
321
+ else if (a === '--clear' || a.startsWith('--clear=')) {
322
+ const val = a.startsWith('--clear=') ? a.slice('--clear='.length) : argv[++i];
323
+ if (!val || val.startsWith('-')) {
324
+ out.error = 'Missing model argument for --clear';
325
+ return out;
326
+ }
327
+ out.clearModel = val;
328
+ }
329
+ else if (a === '--provider' || a.startsWith('--provider=')) {
330
+ const val = (a.startsWith('--provider=') ? a.slice('--provider='.length) : argv[++i])?.toLowerCase();
331
+ if (val !== 'auto' && val !== 'google' && val !== 'anthropic' && val !== 'openai') {
332
+ out.error = `Invalid --provider: ${val ?? '(missing)'} (expected: auto|google|anthropic|openai)`;
333
+ return out;
334
+ }
335
+ out.provider = val;
336
+ }
337
+ else if (a === '--band' || a.startsWith('--band=')) {
338
+ const val = (a.startsWith('--band=') ? a.slice('--band='.length) : argv[++i])?.toLowerCase();
339
+ if (val !== 'auto' && !isImageCalibrationBand(val)) {
340
+ out.error = `Invalid --band: ${val ?? '(missing)'} (expected: auto|spleen-5x8|spleen-5x10|jetbrains-mono-12|jetbrains-mono-14)`;
341
+ return out;
342
+ }
343
+ out.band = val;
344
+ }
345
+ else if (a.startsWith('-')) {
346
+ out.error = `Unknown option: ${a}`;
347
+ return out;
348
+ }
349
+ else if (!out.model) {
350
+ out.model = a;
351
+ }
352
+ else {
353
+ out.error = `Unexpected extra positional argument: ${a}`;
354
+ return out;
355
+ }
356
+ }
357
+ return out;
358
+ }
359
+ const USAGE_TEXT = [
360
+ 'Usage: fiche calibrate <model> [options]',
361
+ ' fiche calibrate --list [--json]',
362
+ ' fiche calibrate --clear <model> [--json]',
363
+ '',
364
+ 'Options:',
365
+ ' --provider <auto|google|anthropic|openai> Upstream API format (default: auto)',
366
+ ' --band <auto|spleen-5x8|spleen-5x10|jetbrains-mono-12|jetbrains-mono-14>',
367
+ ' Band(s) to probe (default: auto)',
368
+ ' --dry-run Build probes & self-verify offline (no API call)',
369
+ ' --list Show calibrated models from disk',
370
+ ' --clear <model> Remove a calibrated model entry',
371
+ ' --json Emit machine-readable JSON',
372
+ ].join('\n');
373
+ function formatScorePct(v) {
374
+ return `${Math.round(v * 100)}%`;
375
+ }
376
+ export async function runCalibrationCli(argv, deps = {}) {
377
+ const env = deps.env ?? process.env;
378
+ const filePath = deps.filePath ?? defaultCalibratedProfilesPath(env);
379
+ const stdout = deps.stdout ?? ((line) => console.log(line));
380
+ const stderr = deps.stderr ?? ((line) => console.error(line));
381
+ const fetchImpl = deps.fetchImpl ?? fetch;
382
+ const now = deps.now ?? (() => new Date());
383
+ const parsed = parseCliArgs(argv);
384
+ if (parsed.error) {
385
+ stderr(`[fiche calibrate] ${parsed.error}`);
386
+ return 2;
387
+ }
388
+ if (parsed.help) {
389
+ stdout(USAGE_TEXT);
390
+ return 0;
391
+ }
392
+ if (parsed.list) {
393
+ loadCalibratedProfilesFile(filePath);
394
+ const profiles = listCalibratedProfiles();
395
+ if (parsed.json) {
396
+ stdout(JSON.stringify({ file: filePath, profiles }, null, 2));
397
+ return 0;
398
+ }
399
+ if (profiles.length === 0) {
400
+ stdout(`No calibrated models stored (${filePath}).`);
401
+ return 0;
402
+ }
403
+ stdout(`Calibrated models (${profiles.length}, ${filePath}):`);
404
+ for (const p of profiles) {
405
+ stdout(` - ${p.model} band=${p.band} cols=${p.cols} maxH=${p.maxHeightPx}` +
406
+ ` overall=${formatScorePct(p.scores.overallScore)} passed=${p.scores.passed} (${p.source}, ${p.calibratedAtIso})`);
407
+ }
408
+ return 0;
409
+ }
410
+ if (parsed.clearModel !== undefined) {
411
+ loadCalibratedProfilesFile(filePath);
412
+ const normalized = normalizeCalibratedModelId(parsed.clearModel);
413
+ const removed = removeCalibratedProfile(parsed.clearModel);
414
+ if (removed) {
415
+ try {
416
+ saveCalibratedProfilesFile(filePath);
417
+ }
418
+ catch (err) {
419
+ const msg = err instanceof Error ? err.message : String(err);
420
+ if (parsed.json) {
421
+ stdout(JSON.stringify({ ok: false, error: msg, model: normalized, file: filePath }, null, 2));
422
+ }
423
+ else {
424
+ stderr(`[fiche calibrate] failed to save ${filePath}: ${msg}`);
425
+ }
426
+ return 1;
427
+ }
428
+ }
429
+ if (parsed.json) {
430
+ stdout(JSON.stringify({ ok: true, model: normalized, removed, file: filePath }, null, 2));
431
+ return 0;
432
+ }
433
+ stdout(removed
434
+ ? `[fiche calibrate] removed ${normalized} from ${filePath}`
435
+ : `[fiche calibrate] ${normalized || parsed.clearModel} was not calibrated`);
436
+ return 0;
437
+ }
438
+ if (!parsed.model) {
439
+ stderr('[fiche calibrate] missing <model> (or pass --list / --clear <model>)');
440
+ return 2;
441
+ }
442
+ const normalizedModel = normalizeCalibratedModelId(parsed.model);
443
+ if (!normalizedModel) {
444
+ stderr('[fiche calibrate] invalid model identifier');
445
+ return 2;
446
+ }
447
+ const provider = resolveProvider(parsed.model, parsed.provider);
448
+ const bandsToTest = parsed.band === 'auto' ? CALIBRATION_BAND_ORDER : [parsed.band];
449
+ if (parsed.dryRun) {
450
+ loadCalibratedProfilesFile(filePath);
451
+ const bandReports = [];
452
+ for (const band of bandsToTest) {
453
+ const probe = await buildCalibrationProbe(band);
454
+ const perfect = scoreCalibrationResponse(buildPerfectFixtureJson(probe), probe);
455
+ const guardFailText = JSON.stringify({
456
+ ...JSON.parse(buildPerfectFixtureJson(probe)),
457
+ LEAK: probe.forbiddenGuards[0],
458
+ });
459
+ const guardFail = scoreCalibrationResponse(guardFailText, probe);
460
+ const selfVerified = perfect.passed && perfect.overallScore === 1 && !guardFail.passed && guardFail.guardScore < 1;
461
+ bandReports.push({
462
+ band,
463
+ cols: probe.cols,
464
+ maxHeightPx: probe.maxHeightPx,
465
+ pages: probe.pngs.length,
466
+ dimensions: probe.pngs.map((img) => ({
467
+ width: img.width,
468
+ height: img.height,
469
+ bytes: img.png.byteLength,
470
+ droppedChars: img.droppedChars,
471
+ })),
472
+ estimatedImageTokens: estimateProbeTokens(parsed.model, probe),
473
+ selfVerified,
474
+ });
475
+ }
476
+ if (parsed.json) {
477
+ stdout(JSON.stringify({
478
+ dryRun: true,
479
+ model: normalizedModel,
480
+ provider,
481
+ bands: bandReports,
482
+ existing: getCalibratedProfile(parsed.model) ?? null,
483
+ }, null, 2));
484
+ return 0;
485
+ }
486
+ stdout(`[fiche calibrate --dry-run] model=${normalizedModel} provider=${provider}`);
487
+ for (const b of bandReports) {
488
+ const dims = b.dimensions.map((d) => `${d.width}x${d.height} (${d.bytes} B, dropped=${d.droppedChars})`).join(', ');
489
+ stdout(` • ${b.band.padEnd(18)} cols=${b.cols} maxH=${b.maxHeightPx} pages=${b.pages} ` +
490
+ `dims=[${dims}] estTokens=${b.estimatedImageTokens} selfCheck=${b.selfVerified ? 'ok' : 'FAIL'}`);
491
+ }
492
+ return 0;
493
+ }
494
+ const { key: apiKey, authKind = 'api-key', envNames } = resolveApiKey(provider, env);
495
+ if (!apiKey) {
496
+ const msg = `Missing API key for provider "${provider}" (checked: ${envNames.join(', ')})`;
497
+ if (parsed.json) {
498
+ stdout(JSON.stringify({ ok: false, error: msg, provider, model: normalizedModel }, null, 2));
499
+ }
500
+ else {
501
+ stderr(`[fiche calibrate] ${msg}`);
502
+ }
503
+ return 1;
504
+ }
505
+ const attempts = [];
506
+ let winner;
507
+ try {
508
+ for (const band of bandsToTest) {
509
+ const probe = await buildCalibrationProbe(band);
510
+ const reply = await sendProbeToProvider(provider, parsed.model, apiKey, authKind, probe, fetchImpl);
511
+ const scores = scoreCalibrationResponse(reply, probe);
512
+ const attempt = {
513
+ band,
514
+ cols: probe.cols,
515
+ maxHeightPx: probe.maxHeightPx,
516
+ scores,
517
+ };
518
+ attempts.push(attempt);
519
+ if (scores.passed) {
520
+ winner = attempt;
521
+ break;
522
+ }
523
+ }
524
+ }
525
+ catch (err) {
526
+ const msg = err instanceof Error ? err.message : String(err);
527
+ if (parsed.json) {
528
+ stdout(JSON.stringify({ ok: false, error: msg, provider, model: normalizedModel, attempts }, null, 2));
529
+ }
530
+ else {
531
+ stderr(`[fiche calibrate] probe failed: ${msg}`);
532
+ }
533
+ return 1;
534
+ }
535
+ const bestFail = attempts.reduce((best, cur) => (!best || cur.scores.overallScore > best.scores.overallScore ? cur : best), undefined);
536
+ const finalBand = winner ? winner.band : 'text-only';
537
+ const finalScores = winner
538
+ ? winner.scores
539
+ : {
540
+ ...(bestFail?.scores ?? {
541
+ hexScore: 0,
542
+ codeScore: 0,
543
+ numScore: 0,
544
+ guardScore: 0,
545
+ overallScore: 0,
546
+ passed: false,
547
+ }),
548
+ passed: false,
549
+ };
550
+ const profile = {
551
+ model: normalizedModel,
552
+ band: finalBand,
553
+ cols: winner ? winner.cols : 0,
554
+ maxHeightPx: winner ? winner.maxHeightPx : 0,
555
+ calibratedAtIso: now().toISOString(),
556
+ scores: finalScores,
557
+ source: 'probe',
558
+ };
559
+ // Reload right before persisting to reduce read-modify-write races across concurrent runs.
560
+ loadCalibratedProfilesFile(filePath);
561
+ setCalibratedProfile(profile);
562
+ try {
563
+ saveCalibratedProfilesFile(filePath);
564
+ }
565
+ catch (err) {
566
+ const msg = err instanceof Error ? err.message : String(err);
567
+ if (parsed.json) {
568
+ stdout(JSON.stringify({ ok: false, error: msg, provider, model: normalizedModel, file: filePath }, null, 2));
569
+ }
570
+ else {
571
+ stderr(`[fiche calibrate] failed to save ${filePath}: ${msg}`);
572
+ }
573
+ return 1;
574
+ }
575
+ if (parsed.json) {
576
+ stdout(JSON.stringify({ ok: true, provider, model: normalizedModel, file: filePath, profile, attempts }, null, 2));
577
+ return 0;
578
+ }
579
+ stdout(`[fiche calibrate] model=${normalizedModel} provider=${provider} -> ${profile.band} (${profile.scores.passed ? 'PASSED' : 'TEXT-ONLY FALLBACK'})`);
580
+ for (const a of attempts) {
581
+ stdout(` • ${a.band.padEnd(18)} hex=${formatScorePct(a.scores.hexScore)} code=${formatScorePct(a.scores.codeScore)} ` +
582
+ `num=${formatScorePct(a.scores.numScore)} guard=${formatScorePct(a.scores.guardScore)} ` +
583
+ `overall=${formatScorePct(a.scores.overallScore)} ${a.scores.passed ? 'PASS' : 'FAIL'}`);
584
+ }
585
+ stdout(`[fiche calibrate] saved to ${filePath}`);
586
+ return 0;
587
+ }
588
+ //# sourceMappingURL=calibrate.js.map
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Anthropic image / vision INPUT-TOKEN cost model, by model id.
3
+ *
4
+ * Anthropic bills images by 28×28-pixel PATCHES, not by a pixel ratio: an image
5
+ * costs `⌈width/28⌉ × ⌈height/28⌉` visual tokens, computed AFTER the image is
6
+ * downscaled to fit the model tier's long-edge and visual-token limits.
7
+ * (The older `(width×height)/750` figure was a ~4–5% continuous approximation of
8
+ * this same 28²=784 px²/patch grid; it is no longer the documented formula.)
9
+ * https://platform.claude.com/docs/en/build-with-claude/vision
10
+ * https://platform.claude.com/docs/en/build-with-claude/vision-coordinates
11
+ *
12
+ * The math itself is the `patch28` regime in src/core/vision-cost.ts, which is
13
+ * the single interpreter for EVERY provider's image pricing and is a dependency
14
+ * leaf. This module is the Anthropic-facing, model-id-aware wrapper around it:
15
+ * it maps an id to its resolution tier via the model profile. Gate conservatism
16
+ * (safety margin) lives at the gate, not here, so these numbers stay honest
17
+ * about what Anthropic actually charges.
18
+ */
19
+ export { ANTHROPIC_PATCH_PX, patchTokens, patchTokensForTier, type AnthropicVisionProfile, } from './vision-cost.js';
20
+ /** Resolve a model's vision tier. Which model sits on which tier is a property
21
+ * of the model profile (`visionTier` in gpt-model-profiles.ts), not a list
22
+ * maintained here: profile resolution already handles id aliases, `[variant]`
23
+ * tags, and INKLING_GPT_PROFILES overrides. This module owns only the geometry
24
+ * each tier implies. Non-Claude and blank ids have no tier and get standard. */
25
+ export declare function anthropicVisionProfile(model: string | null | undefined): import("./vision-cost.js").AnthropicVisionProfile;
26
+ /** Anthropic visual-token cost of a `width×height` image for `model`'s tier. */
27
+ export declare function anthropicVisionTokens(model: string | null | undefined, width: number, height: number): number;
28
+ //# sourceMappingURL=anthropic-vision.d.ts.map
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Anthropic image / vision INPUT-TOKEN cost model, by model id.
3
+ *
4
+ * Anthropic bills images by 28×28-pixel PATCHES, not by a pixel ratio: an image
5
+ * costs `⌈width/28⌉ × ⌈height/28⌉` visual tokens, computed AFTER the image is
6
+ * downscaled to fit the model tier's long-edge and visual-token limits.
7
+ * (The older `(width×height)/750` figure was a ~4–5% continuous approximation of
8
+ * this same 28²=784 px²/patch grid; it is no longer the documented formula.)
9
+ * https://platform.claude.com/docs/en/build-with-claude/vision
10
+ * https://platform.claude.com/docs/en/build-with-claude/vision-coordinates
11
+ *
12
+ * The math itself is the `patch28` regime in src/core/vision-cost.ts, which is
13
+ * the single interpreter for EVERY provider's image pricing and is a dependency
14
+ * leaf. This module is the Anthropic-facing, model-id-aware wrapper around it:
15
+ * it maps an id to its resolution tier via the model profile. Gate conservatism
16
+ * (safety margin) lives at the gate, not here, so these numbers stay honest
17
+ * about what Anthropic actually charges.
18
+ */
19
+ import { resolveGptProfile } from './gpt-model-profiles.js';
20
+ import { ANTHROPIC_TIERS, patchTokensForTier } from './vision-cost.js';
21
+ export { ANTHROPIC_PATCH_PX, patchTokens, patchTokensForTier, } from './vision-cost.js';
22
+ /** Resolve a model's vision tier. Which model sits on which tier is a property
23
+ * of the model profile (`visionTier` in gpt-model-profiles.ts), not a list
24
+ * maintained here: profile resolution already handles id aliases, `[variant]`
25
+ * tags, and INKLING_GPT_PROFILES overrides. This module owns only the geometry
26
+ * each tier implies. Non-Claude and blank ids have no tier and get standard. */
27
+ export function anthropicVisionProfile(model) {
28
+ return ANTHROPIC_TIERS[resolveGptProfile(model).visionTier ?? 'standard'];
29
+ }
30
+ /** Anthropic visual-token cost of a `width×height` image for `model`'s tier. */
31
+ export function anthropicVisionTokens(model, width, height) {
32
+ return patchTokensForTier(anthropicVisionProfile(model).tier, width, height);
33
+ }
34
+ //# sourceMappingURL=anthropic-vision.js.map