@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,272 @@
1
+ /**
2
+ * Syncs Fiche's `models` allowlist from a local Kosha model registry snapshot
3
+ * (`~/.kosha/registry.json`, `$KOSHA_REGISTRY`, `--file <path>`, or
4
+ * `kosha registry export` CLI fallback).
5
+ *
6
+ * Node-only module: never imported from `src/core/`.
7
+ */
8
+ import { spawnSync } from 'node:child_process';
9
+ import * as fs from 'node:fs';
10
+ import * as os from 'node:os';
11
+ import * as path from 'node:path';
12
+ /**
13
+ * Map Kosha provider identifiers (including `-cn` and billing/coding sub-feeds)
14
+ * to Fiche's canonical `ProviderId` values.
15
+ */
16
+ export const KOSHA_PROVIDER_TO_FICHE = {
17
+ anthropic: 'anthropic',
18
+ openai: 'openai',
19
+ google: 'google',
20
+ deepseek: 'deepseek',
21
+ kimi: 'kimi',
22
+ moonshot: 'kimi',
23
+ 'moonshot-cn': 'kimi',
24
+ glm: 'glm',
25
+ zai: 'glm',
26
+ 'zai-coding-plan': 'glm',
27
+ minimax: 'minimax',
28
+ 'minimax-cn': 'minimax',
29
+ qwen: 'qwen',
30
+ alibaba: 'qwen',
31
+ 'alibaba-cn': 'qwen',
32
+ 'alibaba-token-plan': 'qwen',
33
+ openrouter: 'openrouter',
34
+ xai: 'xai',
35
+ groq: 'groq',
36
+ together: 'together',
37
+ fireworks: 'fireworks',
38
+ cerebras: 'cerebras',
39
+ mistral: 'mistral',
40
+ perplexity: 'perplexity',
41
+ cohere: 'cohere',
42
+ sambanova: 'sambanova',
43
+ github: 'github',
44
+ azure: 'azure',
45
+ vercel: 'vercel',
46
+ };
47
+ const SKIP_EXACT_PLACEHOLDERS = new Set([
48
+ 'auto',
49
+ 'search',
50
+ 'container',
51
+ 'aqa',
52
+ 'chat-latest',
53
+ 'chat',
54
+ 'default',
55
+ 'latest',
56
+ 'free',
57
+ 'firerouter',
58
+ 'gpt',
59
+ 'claude',
60
+ ]);
61
+ const NON_LLM_MODALITY_RE = /(?:^|[-_.])(embed|embedding|rerank|moderation|safeguard|prompt-guard|whisper|tts|audio|speech|voice|asr|ocr|transcribe|realtime|image|flux|sora|veo|lyria|imagen|video)(?:$|[-_.])/;
62
+ const TRAILING_DATE_RE = /(?:-\d{4}-\d{2}-\d{2}|-\d{2}-\d{4}|-\d{8}|-\d{6}|-\d{4})+$/g;
63
+ const TRAILING_VARIANT_RE = /-(?:latest|preview|beta|ga|exp|fast|highspeed|non-reasoning|reasoning|thinking|instruct|chat|fp8|bf16|turbo)$/g;
64
+ /**
65
+ * Normalize a raw Kosha model ID into a clean, deduplicatable model-base entry
66
+ * suitable for `FICHE_MODELS` / `~/.config/fiche/config.json` `models`.
67
+ * Returns `null` for aliases (`~...`), router endpoints (`/routers/`),
68
+ * placeholders (`auto`, `chat-latest`, `free`, `firerouter`, overly-broad `gpt`/`claude`),
69
+ * non-LLM modalities (embeddings, audio, voice, asr, ocr, image, video, moderation),
70
+ * or malformed IDs.
71
+ */
72
+ export function normalizeKoshaModelBase(rawId) {
73
+ let s = String(rawId || '').trim().toLowerCase();
74
+ if (!s || s.startsWith('~') || s.includes('/routers/'))
75
+ return null;
76
+ // Strip bracketed context tags (e.g. `[1m]`)
77
+ s = s.replace(/\[[^\]]*\]/g, '');
78
+ // Strip provider/account namespace segments (`google/gemini-...`, `accounts/fireworks/models/...`)
79
+ const slash = s.lastIndexOf('/');
80
+ if (slash >= 0)
81
+ s = s.slice(slash + 1);
82
+ // Strip colon routing/variant suffixes (`:free`, `:exacto`, `:peft:...`, `:0813`)
83
+ // and Vertex `@version` / `@date` suffixes (`claude-opus-5-5@20261001`).
84
+ const colon = s.indexOf(':');
85
+ if (colon >= 0)
86
+ s = s.slice(0, colon);
87
+ const at = s.indexOf('@');
88
+ if (at >= 0)
89
+ s = s.slice(0, at);
90
+ s = s.trim();
91
+ if (!s || SKIP_EXACT_PLACEHOLDERS.has(s))
92
+ return null;
93
+ let prev;
94
+ do {
95
+ prev = s;
96
+ s = s.replace(TRAILING_DATE_RE, '');
97
+ s = s.replace(TRAILING_VARIANT_RE, '');
98
+ s = s.replace(TRAILING_DATE_RE, '');
99
+ } while (s !== prev);
100
+ if (!s ||
101
+ (s.length < 3 && !/^o[1-9]$/.test(s)) ||
102
+ SKIP_EXACT_PLACEHOLDERS.has(s) ||
103
+ NON_LLM_MODALITY_RE.test(s)) {
104
+ return null;
105
+ }
106
+ if (!/^[a-z0-9][a-z0-9._-]*$/.test(s))
107
+ return null;
108
+ // Collapse every Gemini variant to the family base `gemini` (matches DEFAULT_MODEL_BASES).
109
+ if (s === 'gemini' || s.startsWith('gemini-'))
110
+ return 'gemini';
111
+ return s;
112
+ }
113
+ function iterSnapshotModels(snapshot) {
114
+ const out = [];
115
+ const push = (m, fallbackProvider) => {
116
+ const modelRaw = String(m.modelId ?? m.id ?? '').trim();
117
+ const providerRaw = String(m.providerId ?? m.provider ?? fallbackProvider ?? '').trim();
118
+ if (!modelRaw || !providerRaw)
119
+ return;
120
+ out.push({
121
+ providerRaw,
122
+ modelRaw,
123
+ mode: String(m.mode ?? 'chat').toLowerCase(),
124
+ status: String(m.status ?? '').toLowerCase(),
125
+ });
126
+ };
127
+ if (Array.isArray(snapshot.models)) {
128
+ for (const m of snapshot.models) {
129
+ if (m && typeof m === 'object')
130
+ push(m);
131
+ }
132
+ }
133
+ if (Array.isArray(snapshot.providers)) {
134
+ for (const p of snapshot.providers) {
135
+ if (!p || typeof p !== 'object' || !Array.isArray(p.models))
136
+ continue;
137
+ const fallbackProvider = String(p.providerId ?? p.id ?? '').trim();
138
+ for (const m of p.models) {
139
+ if (m && typeof m === 'object')
140
+ push(m, fallbackProvider);
141
+ }
142
+ }
143
+ }
144
+ return out;
145
+ }
146
+ function modelBaseCovers(prefix, candidate) {
147
+ const p = prefix.toLowerCase();
148
+ const c = candidate.toLowerCase();
149
+ return c === p || c.startsWith(`${p}-`);
150
+ }
151
+ /**
152
+ * Extract normalized, deduplicated, prefix-collapsed chat model bases for the
153
+ * selected Fiche providers from a Kosha registry snapshot.
154
+ */
155
+ export function extractKoshaModelBases(snapshot, opts) {
156
+ const allowedProviders = new Set(opts.providers);
157
+ const rawBases = new Set();
158
+ const providersMatched = new Set();
159
+ const entries = iterSnapshotModels(snapshot);
160
+ let matchedModels = 0;
161
+ for (const item of entries) {
162
+ if (item.mode !== 'chat')
163
+ continue;
164
+ if (item.status === 'retired' || item.status === 'deprecated')
165
+ continue;
166
+ const mapped = KOSHA_PROVIDER_TO_FICHE[item.providerRaw.toLowerCase()];
167
+ if (!mapped || !allowedProviders.has(mapped))
168
+ continue;
169
+ const base = normalizeKoshaModelBase(item.modelRaw);
170
+ if (!base)
171
+ continue;
172
+ matchedModels += 1;
173
+ providersMatched.add(mapped);
174
+ rawBases.add(base);
175
+ }
176
+ // Collapse prefix-redundant children (e.g. keep `claude-fable-5`, drop `claude-fable-5-1`).
177
+ const shortestFirst = [...rawBases].sort((a, b) => a.length - b.length || a.localeCompare(b));
178
+ const kept = [];
179
+ for (const candidate of shortestFirst) {
180
+ if (kept.some((prefix) => modelBaseCovers(prefix, candidate)))
181
+ continue;
182
+ kept.push(candidate);
183
+ }
184
+ kept.sort((a, b) => a.localeCompare(b));
185
+ return {
186
+ bases: kept,
187
+ scannedModels: entries.length,
188
+ matchedModels,
189
+ providersMatched: [...providersMatched].sort((a, b) => a.localeCompare(b)),
190
+ };
191
+ }
192
+ /**
193
+ * Merge newly discovered Kosha model bases with Fiche's current `models` list.
194
+ * Preserves existing bases and skips any discovered base already covered by an
195
+ * existing shorter prefix (`deepseek` already matches `deepseek-coder`), unless
196
+ * `replace` is true.
197
+ */
198
+ export function mergeModelBases(existing, discovered, replace) {
199
+ const existingClean = [...new Set(existing.map((s) => s.trim()).filter(Boolean))];
200
+ if (replace) {
201
+ const replaced = [...new Set(discovered.map((s) => s.trim()).filter(Boolean))];
202
+ const added = replaced.filter((cand) => !existingClean.some((e) => modelBaseCovers(e, cand)));
203
+ return { merged: replaced, added };
204
+ }
205
+ const merged = [...existingClean];
206
+ const added = [];
207
+ for (const cand of discovered) {
208
+ const clean = cand.trim();
209
+ if (!clean)
210
+ continue;
211
+ if (merged.some((cur) => modelBaseCovers(cur, clean)))
212
+ continue;
213
+ merged.push(clean);
214
+ added.push(clean);
215
+ }
216
+ return { merged, added };
217
+ }
218
+ /**
219
+ * Load a Kosha registry snapshot from `--file`, `$KOSHA_REGISTRY`,
220
+ * `~/.kosha/registry.json`, or `kosha registry export`.
221
+ */
222
+ export function loadKoshaSnapshot(explicitFile) {
223
+ if (explicitFile) {
224
+ const resolved = path.resolve(explicitFile);
225
+ let raw;
226
+ try {
227
+ raw = fs.readFileSync(resolved, 'utf8');
228
+ }
229
+ catch (e) {
230
+ throw new Error(`Could not read Kosha registry file ${resolved}: ${e.message}`);
231
+ }
232
+ return { snapshot: parseRegistryObject(raw, resolved), source: resolved };
233
+ }
234
+ const candidates = [];
235
+ const envPath = process.env.KOSHA_REGISTRY?.trim();
236
+ if (envPath)
237
+ candidates.push(path.resolve(envPath));
238
+ candidates.push(path.join(os.homedir(), '.kosha', 'registry.json'));
239
+ for (const filePath of candidates) {
240
+ if (!fs.existsSync(filePath))
241
+ continue;
242
+ const raw = fs.readFileSync(filePath, 'utf8');
243
+ return { snapshot: parseRegistryObject(raw, filePath), source: filePath };
244
+ }
245
+ const proc = spawnSync('kosha', ['registry', 'export'], {
246
+ encoding: 'utf8',
247
+ maxBuffer: 64 * 1024 * 1024,
248
+ timeout: 15_000,
249
+ });
250
+ if (proc.error || proc.status !== 0 || !proc.stdout?.trim()) {
251
+ const detail = proc.error?.message || proc.stderr?.trim() || `exit ${proc.status ?? 'unknown'}`;
252
+ throw new Error(`Could not load Kosha registry (~/.kosha/registry.json not found and \`kosha registry export\` failed: ${detail}). Run \`kosha update\` or pass \`--file <path>\`.`);
253
+ }
254
+ return {
255
+ snapshot: parseRegistryObject(proc.stdout, 'kosha registry export'),
256
+ source: 'kosha registry export',
257
+ };
258
+ }
259
+ function parseRegistryObject(raw, label) {
260
+ let parsed;
261
+ try {
262
+ parsed = JSON.parse(raw);
263
+ }
264
+ catch (e) {
265
+ throw new Error(`Invalid Kosha registry JSON from ${label}: ${e.message}`);
266
+ }
267
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
268
+ throw new Error(`Invalid Kosha registry root from ${label}: expected JSON object`);
269
+ }
270
+ return parsed;
271
+ }
272
+ //# sourceMappingURL=kosha-sync.js.map
@@ -0,0 +1,22 @@
1
+ /** First file descriptor assigned by systemd / launchd-exec socket activation. */
2
+ export declare const SD_LISTEN_FDS_START = 3;
3
+ export declare const LAUNCHD_SOCKET_EXEC_C = "#include <errno.h>\n#include <fcntl.h>\n#include <launch.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n\nint main(int argc, char *argv[]) {\n if (argc < 2) {\n fprintf(stderr, \"fiche-launchd-exec: expected target binary argument\\n\");\n return 64;\n }\n\n int *fds = NULL;\n size_t cnt = 0;\n int rc = launch_activate_socket(\"Listeners\", &fds, &cnt);\n if (rc == 0 && cnt > 0 && fds != NULL) {\n int primary = fds[0];\n if (primary != 3) {\n if (dup2(primary, 3) < 0) {\n perror(\"fiche-launchd-exec: dup2\");\n for (size_t i = 0; i < cnt; i++) {\n if (fds[i] >= 0) close(fds[i]);\n }\n free(fds);\n return 1;\n }\n }\n for (size_t i = 0; i < cnt; i++) {\n if (fds[i] >= 0 && fds[i] != 3) {\n close(fds[i]);\n }\n }\n free(fds);\n\n int flags = fcntl(3, F_GETFD);\n if (flags < 0 || fcntl(3, F_SETFD, flags & ~FD_CLOEXEC) < 0) {\n perror(\"fiche-launchd-exec: fcntl\");\n return 1;\n }\n\n char pidbuf[32];\n snprintf(pidbuf, sizeof(pidbuf), \"%ld\", (long)getpid());\n if (setenv(\"LISTEN_FDS\", \"1\", 1) != 0 || setenv(\"LISTEN_PID\", pidbuf, 1) != 0) {\n perror(\"fiche-launchd-exec: setenv\");\n return 1;\n }\n } else {\n if (fds != NULL) {\n for (size_t i = 0; i < cnt; i++) {\n if (fds[i] >= 0) close(fds[i]);\n }\n free(fds);\n }\n unsetenv(\"LISTEN_FDS\");\n unsetenv(\"LISTEN_PID\");\n if (rc != 0 && rc != ENOENT && rc != ESRCH) {\n fprintf(stderr, \"fiche-launchd-exec: launch_activate_socket: %s\\n\", strerror(rc));\n }\n }\n\n execv(argv[1], &argv[1]);\n perror(\"fiche-launchd-exec: execv\");\n return 127;\n}\n";
4
+ /**
5
+ * Parse systemd / fiche-launchd-exec socket activation environment variables.
6
+ * Returns the primary listening fd (always 3) only when LISTEN_PID matches
7
+ * `pid` and LISTEN_FDS >= 1.
8
+ */
9
+ export declare function resolveInheritedListenFd(env?: NodeJS.ProcessEnv, pid?: number): number | null;
10
+ export interface LaunchdShimResult {
11
+ supported: boolean;
12
+ shimPath: string | null;
13
+ rebuilt: boolean;
14
+ reason?: string;
15
+ }
16
+ /**
17
+ * Compile (if missing or stale) the tiny macOS <launch.h> exec trampoline that
18
+ * acquires launchd's listening socket via launch_activate_socket("Listeners")
19
+ * and execv()s Node with LISTEN_FDS=1 / LISTEN_PID=<pid>.
20
+ */
21
+ export declare function ensureLaunchdSocketShim(ficheDir: string, dryRun?: boolean): LaunchdShimResult;
22
+ //# sourceMappingURL=launchd-socket.d.ts.map
@@ -0,0 +1,210 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { createHash, randomBytes } from 'node:crypto';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ /** First file descriptor assigned by systemd / launchd-exec socket activation. */
6
+ export const SD_LISTEN_FDS_START = 3;
7
+ export const LAUNCHD_SOCKET_EXEC_C = `#include <errno.h>
8
+ #include <fcntl.h>
9
+ #include <launch.h>
10
+ #include <stdio.h>
11
+ #include <stdlib.h>
12
+ #include <string.h>
13
+ #include <unistd.h>
14
+
15
+ int main(int argc, char *argv[]) {
16
+ if (argc < 2) {
17
+ fprintf(stderr, "fiche-launchd-exec: expected target binary argument\\n");
18
+ return 64;
19
+ }
20
+
21
+ int *fds = NULL;
22
+ size_t cnt = 0;
23
+ int rc = launch_activate_socket("Listeners", &fds, &cnt);
24
+ if (rc == 0 && cnt > 0 && fds != NULL) {
25
+ int primary = fds[0];
26
+ if (primary != ${SD_LISTEN_FDS_START}) {
27
+ if (dup2(primary, ${SD_LISTEN_FDS_START}) < 0) {
28
+ perror("fiche-launchd-exec: dup2");
29
+ for (size_t i = 0; i < cnt; i++) {
30
+ if (fds[i] >= 0) close(fds[i]);
31
+ }
32
+ free(fds);
33
+ return 1;
34
+ }
35
+ }
36
+ for (size_t i = 0; i < cnt; i++) {
37
+ if (fds[i] >= 0 && fds[i] != ${SD_LISTEN_FDS_START}) {
38
+ close(fds[i]);
39
+ }
40
+ }
41
+ free(fds);
42
+
43
+ int flags = fcntl(${SD_LISTEN_FDS_START}, F_GETFD);
44
+ if (flags < 0 || fcntl(${SD_LISTEN_FDS_START}, F_SETFD, flags & ~FD_CLOEXEC) < 0) {
45
+ perror("fiche-launchd-exec: fcntl");
46
+ return 1;
47
+ }
48
+
49
+ char pidbuf[32];
50
+ snprintf(pidbuf, sizeof(pidbuf), "%ld", (long)getpid());
51
+ if (setenv("LISTEN_FDS", "1", 1) != 0 || setenv("LISTEN_PID", pidbuf, 1) != 0) {
52
+ perror("fiche-launchd-exec: setenv");
53
+ return 1;
54
+ }
55
+ } else {
56
+ if (fds != NULL) {
57
+ for (size_t i = 0; i < cnt; i++) {
58
+ if (fds[i] >= 0) close(fds[i]);
59
+ }
60
+ free(fds);
61
+ }
62
+ unsetenv("LISTEN_FDS");
63
+ unsetenv("LISTEN_PID");
64
+ if (rc != 0 && rc != ENOENT && rc != ESRCH) {
65
+ fprintf(stderr, "fiche-launchd-exec: launch_activate_socket: %s\\n", strerror(rc));
66
+ }
67
+ }
68
+
69
+ execv(argv[1], &argv[1]);
70
+ perror("fiche-launchd-exec: execv");
71
+ return 127;
72
+ }
73
+ `;
74
+ /**
75
+ * Parse systemd / fiche-launchd-exec socket activation environment variables.
76
+ * Returns the primary listening fd (always 3) only when LISTEN_PID matches
77
+ * `pid` and LISTEN_FDS >= 1.
78
+ */
79
+ export function resolveInheritedListenFd(env = process.env, pid = process.pid) {
80
+ const rawPid = env.LISTEN_PID?.trim() ?? '';
81
+ const rawFds = env.LISTEN_FDS?.trim() ?? '';
82
+ if (!/^\d+$/.test(rawPid) || !/^\d+$/.test(rawFds)) {
83
+ return null;
84
+ }
85
+ const listenPid = Number(rawPid);
86
+ const listenFds = Number(rawFds);
87
+ if (!Number.isSafeInteger(listenPid) || listenPid !== pid) {
88
+ return null;
89
+ }
90
+ if (!Number.isSafeInteger(listenFds) || listenFds < 1) {
91
+ return null;
92
+ }
93
+ return SD_LISTEN_FDS_START;
94
+ }
95
+ const MACOS_CC = '/usr/bin/cc';
96
+ function sha256Hex(data) {
97
+ return createHash('sha256').update(data).digest('hex');
98
+ }
99
+ function isOwnedRegularFile(filePath) {
100
+ try {
101
+ const st = fs.lstatSync(filePath);
102
+ if (!st.isFile())
103
+ return false;
104
+ if (typeof process.getuid === 'function' && st.uid !== process.getuid())
105
+ return false;
106
+ return true;
107
+ }
108
+ catch {
109
+ return false;
110
+ }
111
+ }
112
+ function parseStampHashes(raw) {
113
+ try {
114
+ const parsed = JSON.parse(raw);
115
+ if (typeof parsed?.sourceSha256 === 'string' &&
116
+ /^[0-9a-f]{64}$/i.test(parsed.sourceSha256) &&
117
+ typeof parsed?.binarySha256 === 'string' &&
118
+ /^[0-9a-f]{64}$/i.test(parsed.binarySha256)) {
119
+ return { sourceSha256: parsed.sourceSha256.toLowerCase(), binarySha256: parsed.binarySha256.toLowerCase() };
120
+ }
121
+ }
122
+ catch {
123
+ // Legacy or malformed stamp — force clean rebuild.
124
+ }
125
+ return null;
126
+ }
127
+ function safeUnlink(filePath) {
128
+ try {
129
+ fs.unlinkSync(filePath);
130
+ }
131
+ catch {
132
+ // ignore cleanup failures
133
+ }
134
+ }
135
+ /**
136
+ * Compile (if missing or stale) the tiny macOS <launch.h> exec trampoline that
137
+ * acquires launchd's listening socket via launch_activate_socket("Listeners")
138
+ * and execv()s Node with LISTEN_FDS=1 / LISTEN_PID=<pid>.
139
+ */
140
+ export function ensureLaunchdSocketShim(ficheDir, dryRun = false) {
141
+ if (process.platform !== 'darwin') {
142
+ return { supported: false, shimPath: null, rebuilt: false, reason: 'non-darwin' };
143
+ }
144
+ const ccExists = fs.existsSync(MACOS_CC);
145
+ const binDir = path.join(ficheDir, 'bin');
146
+ const shimPath = path.join(binDir, 'fiche-launchd-exec');
147
+ const stampPath = path.join(binDir, 'fiche-launchd-exec.sha256');
148
+ const expectedSourceHash = sha256Hex(LAUNCHD_SOCKET_EXEC_C);
149
+ let cachedValid = false;
150
+ if (isOwnedRegularFile(shimPath) && isOwnedRegularFile(stampPath)) {
151
+ try {
152
+ const stamp = parseStampHashes(fs.readFileSync(stampPath, 'utf8'));
153
+ if (stamp && stamp.sourceSha256 === expectedSourceHash) {
154
+ const binBytes = fs.readFileSync(shimPath);
155
+ cachedValid = sha256Hex(binBytes) === stamp.binarySha256;
156
+ }
157
+ }
158
+ catch {
159
+ cachedValid = false;
160
+ }
161
+ }
162
+ if (cachedValid) {
163
+ return { supported: true, shimPath, rebuilt: false };
164
+ }
165
+ if (!ccExists) {
166
+ return {
167
+ supported: false,
168
+ shimPath: null,
169
+ rebuilt: false,
170
+ reason: `missing ${MACOS_CC}`,
171
+ };
172
+ }
173
+ if (dryRun) {
174
+ return { supported: true, shimPath, rebuilt: true };
175
+ }
176
+ const dirExisted = fs.existsSync(binDir);
177
+ fs.mkdirSync(binDir, { recursive: true, mode: 0o700 });
178
+ if (!dirExisted)
179
+ fs.chmodSync(binDir, 0o700);
180
+ const suffix = `${process.pid}.${Date.now()}.${randomBytes(8).toString('hex')}`;
181
+ const srcTmp = path.join(binDir, `fiche-launchd-exec.${suffix}.c`);
182
+ const binTmp = path.join(binDir, `fiche-launchd-exec.${suffix}.bin`);
183
+ const stampTmp = path.join(binDir, `fiche-launchd-exec.${suffix}.sha256`);
184
+ try {
185
+ fs.writeFileSync(srcTmp, LAUNCHD_SOCKET_EXEC_C, { flag: 'wx', mode: 0o600 });
186
+ execFileSync(MACOS_CC, ['-O2', '-Wall', '-Wextra', '-Werror', '-x', 'c', srcTmp, '-o', binTmp], { stdio: 'pipe' });
187
+ fs.chmodSync(binTmp, 0o700);
188
+ const binBytes = fs.readFileSync(binTmp);
189
+ const binaryHash = sha256Hex(binBytes);
190
+ fs.renameSync(binTmp, shimPath);
191
+ fs.writeFileSync(stampTmp, `${JSON.stringify({ sourceSha256: expectedSourceHash, binarySha256: binaryHash })}\n`, { flag: 'wx', mode: 0o600 });
192
+ fs.renameSync(stampTmp, stampPath);
193
+ return { supported: true, shimPath, rebuilt: true };
194
+ }
195
+ catch (err) {
196
+ safeUnlink(binTmp);
197
+ safeUnlink(stampTmp);
198
+ const detail = err instanceof Error ? err.message : String(err);
199
+ return {
200
+ supported: false,
201
+ shimPath: null,
202
+ rebuilt: false,
203
+ reason: `compile failed: ${detail}`,
204
+ };
205
+ }
206
+ finally {
207
+ safeUnlink(srcTmp);
208
+ }
209
+ }
210
+ //# sourceMappingURL=launchd-socket.js.map
@@ -0,0 +1,2 @@
1
+ export declare function runMcpCommand(argv: string[]): Promise<void>;
2
+ //# sourceMappingURL=cli.d.ts.map
@@ -0,0 +1,55 @@
1
+ import { runStdioServer, startHttpServer, SERVER_NAME, SERVER_VERSION } from './server.js';
2
+ function parseHttpPort(argv) {
3
+ const eqArg = argv.find((a) => a.startsWith('--http='));
4
+ if (eqArg !== undefined) {
5
+ const raw = eqArg.slice('--http='.length).trim();
6
+ const port = /^\d+$/.test(raw) ? Number(raw) : NaN;
7
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
8
+ process.stderr.write('[fiche-mcp] --http needs an integer port in 1..65535\n');
9
+ process.exit(1);
10
+ }
11
+ return { enabled: true, port };
12
+ }
13
+ const idx = argv.indexOf('--http');
14
+ if (idx >= 0) {
15
+ const next = argv[idx + 1];
16
+ const raw = next !== undefined && !next.startsWith('-') ? next.trim() : '47823';
17
+ const port = /^\d+$/.test(raw) ? Number(raw) : NaN;
18
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
19
+ process.stderr.write('[fiche-mcp] --http needs an integer port in 1..65535\n');
20
+ process.exit(1);
21
+ }
22
+ return { enabled: true, port };
23
+ }
24
+ return { enabled: false, port: 47823 };
25
+ }
26
+ export async function runMcpCommand(argv) {
27
+ if (argv.includes('--help') || argv.includes('-h')) {
28
+ process.stderr.write(`${SERVER_NAME} ${SERVER_VERSION}\n` +
29
+ ' fiche-mcp stdio (also: fiche mcp)\n' +
30
+ ' fiche-mcp --http [47823] Streamable HTTP on 127.0.0.1 + ::1\n' +
31
+ ' fiche-mcp --http=47823 --ipv4 Streamable HTTP on 127.0.0.1 only\n');
32
+ return;
33
+ }
34
+ const httpOpt = parseHttpPort(argv);
35
+ if (httpOpt.enabled) {
36
+ const ipv4Only = argv.includes('--ipv4');
37
+ const server = await startHttpServer(httpOpt.port, { ipv4Only });
38
+ const hostsLabel = server.ipv6Listening ? '127.0.0.1 + ::1' : '127.0.0.1';
39
+ process.stderr.write(`[fiche-mcp] streamable HTTP on http://127.0.0.1:${server.port}/mcp (${hostsLabel})\n`);
40
+ await new Promise((resolve) => {
41
+ let closing = false;
42
+ const stop = () => {
43
+ if (closing)
44
+ return;
45
+ closing = true;
46
+ void server.close().finally(resolve);
47
+ };
48
+ process.once('SIGINT', stop);
49
+ process.once('SIGTERM', stop);
50
+ });
51
+ return;
52
+ }
53
+ await runStdioServer();
54
+ }
55
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1,48 @@
1
+ import { countBillable } from '../core/request-transform.js';
2
+ export declare const MCP_PROTOCOL = "2025-03-26";
3
+ export declare const SERVER_NAME = "fiche-mcp";
4
+ export declare const SERVER_VERSION: string;
5
+ /** Hard cap for one MCP message. Larger frames are rejected, not buffered. */
6
+ export declare const MCP_MAX_BYTES: number;
7
+ export interface McpStats {
8
+ startedAt: string;
9
+ calls: number;
10
+ checkCalls: number;
11
+ transformCalls: number;
12
+ tokensSaved: number;
13
+ }
14
+ export declare const MCP_TOOLS: {
15
+ name: string;
16
+ description: string;
17
+ inputSchema: {
18
+ $schema: string;
19
+ type: string;
20
+ properties: Record<string, unknown>;
21
+ required: string[];
22
+ additionalProperties: boolean;
23
+ };
24
+ annotations: {
25
+ readOnlyHint: boolean;
26
+ destructiveHint: boolean;
27
+ idempotentHint: boolean;
28
+ openWorldHint: boolean;
29
+ };
30
+ }[];
31
+ export declare function handleMcpMessage(message: unknown): Promise<unknown | null>;
32
+ /** Newline-delimited JSON, plus LSP Content-Length frames if a client sends them. */
33
+ export declare function pushMcpChunk(buffer: string, chunk: string, onMessage: (message: unknown, framed: boolean) => void): string;
34
+ export declare function encodeMcpMessage(message: unknown, framed: boolean): string;
35
+ export declare function runStdioServer(): Promise<void>;
36
+ /** DNS rebinding sends Host: attacker.example while connecting to 127.0.0.1. */
37
+ export declare function hostHeaderAllowed(hostHeader: string | undefined): boolean;
38
+ export declare function startHttpServer(port: number, options?: {
39
+ ipv4Only?: boolean;
40
+ retriesLeft?: number;
41
+ }): Promise<{
42
+ port: number;
43
+ ipv6Listening: boolean;
44
+ close: () => Promise<void>;
45
+ }>;
46
+ export declare function resetMcpStatsForTests(): void;
47
+ export { countBillable };
48
+ //# sourceMappingURL=server.d.ts.map