@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.
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 +288 -2
  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 +122 -4
  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,987 @@
1
+ /**
2
+ * MCP server for fiche (stdio and stateless Streamable HTTP).
3
+ * One tool surface for every client. Tools are local, deterministic, and do
4
+ * not send the payload anywhere.
5
+ */
6
+ import { createServer } from 'node:http';
7
+ import * as fs from 'node:fs';
8
+ import * as os from 'node:os';
9
+ import * as path from 'node:path';
10
+ import { getAllowedModelBases, getConfiguredModelBases, isFicheSupportedModel } from '../core/applicability.js';
11
+ import { readBrandEnv } from '../core/env.js';
12
+ import { isMisresolvedModelId } from '../core/gpt-model-profiles.js';
13
+ import { shouldImageModel } from '../core/reader-tier.js';
14
+ import { isTextHygieneActive, resolveTextHygieneMode } from '../core/text-hygiene.js';
15
+ import { resolveOpticalHistoryPolicy } from '../core/transform.js';
16
+ import { transformAnyRequest, countBillable } from '../core/request-transform.js';
17
+ import { supportsExplicitPromptCacheBreakpoint } from '../core/codex-cache.js';
18
+ import { getGlobalMmuStore } from '../core/context-mmu.js';
19
+ import { defaultEventsFilePath, readTurnReport } from '../turn-report.js';
20
+ export const MCP_PROTOCOL = '2025-03-26';
21
+ export const SERVER_NAME = 'fiche-mcp';
22
+ export const SERVER_VERSION = typeof __FICHE_VERSION__ !== 'undefined' ? __FICHE_VERSION__ : '0.19.0';
23
+ /** Hard cap for one MCP message. Larger frames are rejected, not buffered. */
24
+ export const MCP_MAX_BYTES = 8 * 1024 * 1024;
25
+ const READ_ONLY = {
26
+ readOnlyHint: true,
27
+ destructiveHint: false,
28
+ idempotentHint: true,
29
+ openWorldHint: false,
30
+ };
31
+ const stats = {
32
+ startedAt: new Date().toISOString(),
33
+ calls: 0,
34
+ checkCalls: 0,
35
+ transformCalls: 0,
36
+ tokensSaved: 0,
37
+ };
38
+ const COST_NOTE = ' Calling this does not remove text already in the conversation. The argument and this result are both billed. The proxy is what saves tokens on live traffic.';
39
+ function tool(name, description, properties, required, annotations = READ_ONLY) {
40
+ return {
41
+ name,
42
+ description,
43
+ inputSchema: {
44
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
45
+ type: 'object',
46
+ properties,
47
+ required,
48
+ additionalProperties: false,
49
+ },
50
+ annotations,
51
+ };
52
+ }
53
+ export const MCP_TOOLS = [
54
+ tool('check_model', 'What fiche does for a model: whether it is in compression scope, and whether it gets images (strong page readers such as Gemini, Fable 5, Sol 5.6/6.1/6.2) or uses the 4-layer text compiler and passes clean text through (weak or unmeasured readers such as Claude 5.5, Grok, DeepSeek, Kimi, Astra). Queries live daemon /api/models when running.', {
55
+ model: { type: 'string', description: 'Model id, for example claude-fable-5 or gpt-6-astra.' },
56
+ forceImages: { type: 'boolean', description: 'Optional override to test forced imaging on an allowlisted model.' },
57
+ textHygiene: { type: 'string', enum: ['auto', 'on', 'off'], description: 'Optional text hygiene mode override.' },
58
+ }, ['model']),
59
+ tool('transform_request', 'Run fiche on an LLM request JSON object: bulky context becomes images for strong page readers (Gemini, Fable 5, Sol 5.6/6.1/6.2); text-tier models run the 4-layer deterministic text compiler (TSCG+TOON+CASI+ACDC) with zero image rendering and pass clean payloads through unchanged. Set upstream to https://chatgpt.com or any /backend-api/codex/ path to force-strip prompt_cache_breakpoint.' + COST_NOTE, {
60
+ request: { type: 'object', description: 'Provider request JSON (Anthropic messages, OpenAI responses, chat completions, or Gemini).' },
61
+ model: { type: 'string', description: 'Model id. Overrides request.model when set.' },
62
+ wire: { type: 'string', enum: ['auto', 'anthropic', 'responses', 'chat', 'google'], description: 'Request shape. auto detects.' },
63
+ upstream: { type: 'string', description: 'Upstream base URL. chatgpt.com disables explicit cache breakpoints.' },
64
+ pathname: { type: 'string', description: 'Request path, for example /backend-api/codex/responses.' },
65
+ forceImages: { type: 'boolean', description: 'Image even on a weak reader. Does not re-enable Codex breakpoints.' },
66
+ textHygiene: { type: 'string', enum: ['auto', 'on', 'off'], description: 'Text hygiene mode (auto, on, or off).' },
67
+ }, ['request']),
68
+ tool('health', 'Server identity, version, and the Codex breakpoint policy. Returns no secrets and no request data.', {}, []),
69
+ tool('stats', 'In-memory counters for this MCP process: calls and tokens saved. No payloads. This call increments the counters.', {}, [], { ...READ_ONLY, idempotentHint: false }),
70
+ tool('page_in', 'Retrieve verbatim lines from Fiche Context-MMU virtual memory by pageId (e.g. pg_...) or symbol/text query, optionally sliced by startLine/endLine/maxLines. Queries the local MMU store first, then falls back to the running proxy daemon on loopback.', {
71
+ pageId: { type: 'string', description: 'MMU page ID to dereference, for example pg_a1b2c3d4e5f6.' },
72
+ query: { type: 'string', description: 'Symbol name, file basename, or text query to find or focus an MMU page (<= 512 chars).' },
73
+ sessionKey: { type: 'string', description: 'Optional session key to scope page lookup to one session.' },
74
+ startLine: { type: 'number', description: '1-based start line within the matched page.' },
75
+ endLine: { type: 'number', description: '1-based end line within the matched page.' },
76
+ maxLines: { type: 'number', description: 'Maximum lines to return (default 120, max 500).' },
77
+ }, []),
78
+ tool('mmu_stats', 'Inspect Fiche Context-MMU virtual memory counters and resident page metadata (no raw page bodies). Queries the local MMU store first, then falls back to the running proxy daemon on loopback.', {
79
+ sessionKey: { type: 'string', description: 'Optional session key filter for resident MMU pages.' },
80
+ }, []),
81
+ ];
82
+ function textResult(payload, isError = false) {
83
+ return {
84
+ content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }],
85
+ structuredContent: payload,
86
+ isError,
87
+ };
88
+ }
89
+ function asRecord(value) {
90
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : null;
91
+ }
92
+ function resolveDaemonPort() {
93
+ const envPort = Number(process.env.PORT ?? 47821);
94
+ return Number.isSafeInteger(envPort) && envPort > 0 && envPort <= 65535 ? envPort : 47821;
95
+ }
96
+ function parsePositiveIntArg(value, field) {
97
+ if (value === undefined)
98
+ return { ok: true, value: undefined };
99
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1) {
100
+ return { ok: false, error: `${field} must be a positive integer` };
101
+ }
102
+ return { ok: true, value };
103
+ }
104
+ function matchesModelBases(model, bases) {
105
+ const base = model.replace(/\[[^\]]*\]/g, '').toLowerCase();
106
+ if (!base || isMisresolvedModelId(base))
107
+ return false;
108
+ const slash = base.lastIndexOf('/');
109
+ const unqualified = slash >= 0 ? base.slice(slash + 1) : null;
110
+ return bases.some((b) => {
111
+ const target = b.toLowerCase();
112
+ const hit = (id) => id === target || id.startsWith(`${target}-`) || id.startsWith(`${target}.`);
113
+ return hit(base) || (unqualified !== null && hit(unqualified));
114
+ });
115
+ }
116
+ function readConfigModelBases() {
117
+ const explicit = readBrandEnv('CONFIG');
118
+ if (process.env.VITEST && explicit === undefined)
119
+ return null;
120
+ const defaultFile = path.join(os.homedir(), '.config', 'fiche', 'config.json');
121
+ const legacyFile = path.join(os.homedir(), '.config', 'inkling', 'config.json');
122
+ const file = explicit ?? (fs.existsSync(defaultFile) || !fs.existsSync(legacyFile) ? defaultFile : legacyFile);
123
+ if (!fs.existsSync(file))
124
+ return null;
125
+ try {
126
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
127
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
128
+ return null;
129
+ if (Array.isArray(parsed.models)) {
130
+ return parsed.models.map((v) => String(v).trim()).filter(Boolean);
131
+ }
132
+ if (typeof parsed.models === 'string') {
133
+ const trimmed = parsed.models.trim();
134
+ if (!trimmed || /^(0|false|no|off|none)$/i.test(trimmed))
135
+ return [];
136
+ return trimmed.split(',').map((s) => s.trim()).filter(Boolean);
137
+ }
138
+ }
139
+ catch {
140
+ /* ignore invalid config */
141
+ }
142
+ return null;
143
+ }
144
+ function combineMmuStats(localStats, daemonStats) {
145
+ if (!daemonStats)
146
+ return { ...localStats };
147
+ const combined = { ...daemonStats };
148
+ for (const [k, v] of Object.entries(localStats)) {
149
+ const dv = combined[k];
150
+ if (typeof v === 'number' && typeof dv === 'number') {
151
+ combined[k] = dv + v;
152
+ }
153
+ else if (dv === undefined) {
154
+ combined[k] = v;
155
+ }
156
+ }
157
+ return combined;
158
+ }
159
+ async function callTool(name, args) {
160
+ stats.calls += 1;
161
+ if (name === 'health') {
162
+ const port = resolveDaemonPort();
163
+ let proxy = {
164
+ running: false,
165
+ port,
166
+ hint: 'Start proxy daemon with `fiche` or `fiche service start`',
167
+ };
168
+ try {
169
+ const res = await fetch(`http://127.0.0.1:${port}/api/health`, {
170
+ signal: AbortSignal.timeout(250),
171
+ });
172
+ if (res.ok) {
173
+ const data = (await res.json());
174
+ proxy = { running: true, ...data };
175
+ }
176
+ else {
177
+ await res.body?.cancel().catch(() => undefined);
178
+ }
179
+ }
180
+ catch {
181
+ // Proxy daemon unreachable — fast fail-open status
182
+ }
183
+ return textResult({
184
+ name: SERVER_NAME,
185
+ version: SERVER_VERSION,
186
+ protocol: MCP_PROTOCOL,
187
+ codex: 'prompt_cache_breakpoint is omitted for chatgpt.com and /backend-api/codex/responses',
188
+ proxy,
189
+ });
190
+ }
191
+ if (name === 'stats') {
192
+ const report = readTurnReport(defaultEventsFilePath());
193
+ return textResult({
194
+ ...stats,
195
+ proxy: report.lastTurn
196
+ ? {
197
+ lastTurn: report.lastTurn,
198
+ session: report.session,
199
+ }
200
+ : null,
201
+ });
202
+ }
203
+ if (name === 'page_in') {
204
+ if (args.pageId !== undefined && (typeof args.pageId !== 'string' || !args.pageId.trim())) {
205
+ return textResult({ error: 'pageId must be a non-empty string' }, true);
206
+ }
207
+ if (args.query !== undefined && (typeof args.query !== 'string' || !args.query.trim())) {
208
+ return textResult({ error: 'query must be a non-empty string' }, true);
209
+ }
210
+ if (args.sessionKey !== undefined && (typeof args.sessionKey !== 'string' || !args.sessionKey.trim())) {
211
+ return textResult({ error: 'sessionKey must be a non-empty string' }, true);
212
+ }
213
+ const pageId = typeof args.pageId === 'string' ? args.pageId.trim() : undefined;
214
+ const query = typeof args.query === 'string' ? args.query.trim() : undefined;
215
+ const sessionKey = typeof args.sessionKey === 'string' ? args.sessionKey.trim() : undefined;
216
+ if (query && query.length > 512) {
217
+ return textResult({ error: 'query must be <= 512 chars' }, true);
218
+ }
219
+ if (!pageId && !query) {
220
+ return textResult({ error: 'pageId or query must be provided' }, true);
221
+ }
222
+ const startParsed = parsePositiveIntArg(args.startLine, 'startLine');
223
+ if (!startParsed.ok)
224
+ return textResult({ error: startParsed.error }, true);
225
+ const endParsed = parsePositiveIntArg(args.endLine, 'endLine');
226
+ if (!endParsed.ok)
227
+ return textResult({ error: endParsed.error }, true);
228
+ const maxParsed = parsePositiveIntArg(args.maxLines, 'maxLines');
229
+ if (!maxParsed.ok)
230
+ return textResult({ error: maxParsed.error }, true);
231
+ const maxLines = maxParsed.value !== undefined ? Math.min(500, maxParsed.value) : 120;
232
+ const store = getGlobalMmuStore();
233
+ if (pageId) {
234
+ const hit = store.derefPage(pageId, {
235
+ sessionKey,
236
+ startLine: startParsed.value,
237
+ endLine: endParsed.value,
238
+ query,
239
+ maxLines,
240
+ });
241
+ if (hit) {
242
+ return textResult({
243
+ source: 'local',
244
+ pageId: hit.page.id,
245
+ refId: hit.page.refId,
246
+ sessionKey: hit.page.sessionKey,
247
+ filePath: hit.page.filePath,
248
+ lineCount: hit.page.lineCount,
249
+ startLine: hit.startLine,
250
+ endLine: hit.endLine,
251
+ text: hit.text,
252
+ symbols: hit.page.symbols,
253
+ });
254
+ }
255
+ }
256
+ else {
257
+ const matches = store.searchPages(query, sessionKey);
258
+ if (matches.length > 0) {
259
+ const top = matches[0];
260
+ const hit = store.derefPage(top.page.id, {
261
+ sessionKey: top.page.sessionKey,
262
+ startLine: startParsed.value,
263
+ endLine: endParsed.value,
264
+ query,
265
+ maxLines,
266
+ });
267
+ return textResult({
268
+ source: 'local',
269
+ pageId: top.page.id,
270
+ refId: top.page.refId,
271
+ sessionKey: top.page.sessionKey,
272
+ filePath: top.page.filePath,
273
+ lineCount: top.page.lineCount,
274
+ startLine: hit?.startLine ?? 1,
275
+ endLine: hit?.endLine ?? 0,
276
+ text: hit?.text ?? '',
277
+ symbols: top.page.symbols,
278
+ matches: matches.slice(0, 5).map((m) => ({
279
+ pageId: m.page.id,
280
+ refId: m.page.refId,
281
+ filePath: m.page.filePath,
282
+ score: m.score,
283
+ matchedLine: m.matchedLine,
284
+ })),
285
+ });
286
+ }
287
+ }
288
+ const port = resolveDaemonPort();
289
+ const qs = new URLSearchParams();
290
+ if (pageId)
291
+ qs.set('pageId', pageId);
292
+ if (query)
293
+ qs.set('query', query);
294
+ if (sessionKey)
295
+ qs.set('sessionKey', sessionKey);
296
+ if (startParsed.value !== undefined)
297
+ qs.set('startLine', String(startParsed.value));
298
+ if (endParsed.value !== undefined)
299
+ qs.set('endLine', String(endParsed.value));
300
+ qs.set('maxLines', String(maxLines));
301
+ try {
302
+ const res = await fetch(`http://127.0.0.1:${port}/api/mmu/page?${qs.toString()}`, {
303
+ signal: AbortSignal.timeout(250),
304
+ });
305
+ const data = (await res.json().catch(() => null));
306
+ if (!res.ok || !data) {
307
+ const msg = typeof data?.error === 'string' ? data.error : `MMU page lookup failed (HTTP ${res.status})`;
308
+ return textResult({ error: msg, source: 'daemon', port }, true);
309
+ }
310
+ return textResult({ source: 'daemon', ...data });
311
+ }
312
+ catch {
313
+ return textResult({
314
+ error: 'MMU page not found locally and fiche proxy daemon is unreachable',
315
+ port,
316
+ hint: 'Start proxy daemon with `fiche` or `fiche service start`',
317
+ }, true);
318
+ }
319
+ }
320
+ if (name === 'mmu_stats') {
321
+ if (args.sessionKey !== undefined && (typeof args.sessionKey !== 'string' || !args.sessionKey.trim())) {
322
+ return textResult({ error: 'sessionKey must be a non-empty string' }, true);
323
+ }
324
+ const sessionKey = typeof args.sessionKey === 'string' ? args.sessionKey.trim() : undefined;
325
+ const store = getGlobalMmuStore();
326
+ const allPages = store.listPages();
327
+ const storeStats = store.getStats();
328
+ const hasLocalState = allPages.length > 0 ||
329
+ storeStats.pagesStored > 0 ||
330
+ storeStats.tailHydrations > 0 ||
331
+ storeStats.markovFolds > 0 ||
332
+ storeStats.skillsStubbed > 0 ||
333
+ storeStats.densityPrunedBlocks > 0;
334
+ const localPages = sessionKey ? store.listPages(sessionKey) : allPages;
335
+ const safeLocalPages = localPages.slice(0, 50).map((p) => {
336
+ if (sessionKey)
337
+ return p;
338
+ const { factTokens: _omitted, ...rest } = p;
339
+ return rest;
340
+ });
341
+ const localPayload = {
342
+ stats: storeStats,
343
+ pageCount: localPages.length,
344
+ pages: safeLocalPages,
345
+ };
346
+ const port = resolveDaemonPort();
347
+ const qs = sessionKey ? `?sessionKey=${encodeURIComponent(sessionKey)}` : '';
348
+ try {
349
+ const res = await fetch(`http://127.0.0.1:${port}/api/mmu/stats${qs}`, {
350
+ signal: AbortSignal.timeout(250),
351
+ });
352
+ const data = (await res.json().catch(() => null));
353
+ if (!res.ok || !data) {
354
+ if (hasLocalState) {
355
+ return textResult({
356
+ source: 'local',
357
+ daemonRunning: false,
358
+ port,
359
+ ...localPayload,
360
+ local: localPayload,
361
+ daemon: null,
362
+ });
363
+ }
364
+ const msg = typeof data?.error === 'string' ? data.error : `MMU stats lookup failed (HTTP ${res.status})`;
365
+ return textResult({ error: msg, source: 'daemon', port }, true);
366
+ }
367
+ if (!hasLocalState) {
368
+ return textResult({
369
+ source: 'daemon',
370
+ daemonRunning: true,
371
+ port,
372
+ ...data,
373
+ local: localPayload,
374
+ daemon: data,
375
+ });
376
+ }
377
+ const daemonStats = asRecord(data.stats);
378
+ const daemonPageCount = typeof data.pageCount === 'number' ? data.pageCount : 0;
379
+ const daemonPages = Array.isArray(data.pages) ? data.pages : [];
380
+ const seenPageIds = new Set();
381
+ const mergedPages = [];
382
+ for (const p of [...daemonPages, ...safeLocalPages]) {
383
+ const rec = asRecord(p);
384
+ const pid = typeof rec?.id === 'string' ? rec.id : undefined;
385
+ if (pid) {
386
+ if (seenPageIds.has(pid))
387
+ continue;
388
+ seenPageIds.add(pid);
389
+ }
390
+ mergedPages.push(p);
391
+ if (mergedPages.length >= 50)
392
+ break;
393
+ }
394
+ return textResult({
395
+ source: 'combined',
396
+ daemonRunning: true,
397
+ port,
398
+ stats: combineMmuStats(storeStats, daemonStats),
399
+ pageCount: daemonPageCount + localPages.length,
400
+ pages: mergedPages,
401
+ local: localPayload,
402
+ daemon: data,
403
+ });
404
+ }
405
+ catch {
406
+ // Daemon offline — return local state
407
+ }
408
+ return textResult({
409
+ source: 'local',
410
+ daemonRunning: false,
411
+ port,
412
+ ...localPayload,
413
+ local: localPayload,
414
+ daemon: null,
415
+ });
416
+ }
417
+ if (name === 'check_model') {
418
+ const model = args.model;
419
+ if (typeof model !== 'string' || !model.trim())
420
+ return textResult({ error: 'model must be a non-empty string' }, true);
421
+ stats.checkCalls += 1;
422
+ const forceImages = args.forceImages === true ? true : args.forceImages === false ? false : undefined;
423
+ const hygieneArg = args.textHygiene === 'auto' || args.textHygiene === 'on' || args.textHygiene === 'off'
424
+ ? args.textHygiene
425
+ : undefined;
426
+ let inScope = isFicheSupportedModel(model);
427
+ let scopeSource = 'default';
428
+ let compressionEnabled;
429
+ let daemonEngineMode;
430
+ const port = resolveDaemonPort();
431
+ const shouldQueryDaemon = !process.env.VITEST || process.env.PORT !== undefined;
432
+ let gotDaemon = false;
433
+ if (shouldQueryDaemon) {
434
+ try {
435
+ const res = await fetch(`http://127.0.0.1:${port}/api/models`, {
436
+ signal: AbortSignal.timeout(250),
437
+ });
438
+ if (res.ok) {
439
+ const data = (await res.json().catch(() => null));
440
+ const rawBases = Array.isArray(data?.allowed_models)
441
+ ? data.allowed_models
442
+ : Array.isArray(data?.models)
443
+ ? data.models
444
+ : null;
445
+ if (rawBases && rawBases.every((m) => typeof m === 'string')) {
446
+ inScope = matchesModelBases(model, rawBases);
447
+ scopeSource = 'daemon';
448
+ gotDaemon = true;
449
+ if (typeof data?.compression_enabled === 'boolean') {
450
+ compressionEnabled = data.compression_enabled;
451
+ }
452
+ if (Array.isArray(data?.catalog)) {
453
+ const norm = model.trim().toLowerCase();
454
+ const catHit = data.catalog.find((c) => typeof c?.id === 'string' && c.id.toLowerCase() === norm);
455
+ if (catHit &&
456
+ (catHit.engine_mode === 'optical' || catHit.engine_mode === 'hybrid' || catHit.engine_mode === 'text')) {
457
+ daemonEngineMode = catHit.engine_mode;
458
+ }
459
+ }
460
+ }
461
+ }
462
+ else {
463
+ await res.body?.cancel().catch(() => undefined);
464
+ }
465
+ }
466
+ catch {
467
+ // Daemon unreachable — fall back to runtime / env / config.json
468
+ }
469
+ }
470
+ if (!gotDaemon) {
471
+ const allowed = getAllowedModelBases();
472
+ const configured = getConfiguredModelBases();
473
+ const hasRuntimeOverride = allowed.length !== configured.length || allowed.some((v, idx) => v !== configured[idx]);
474
+ if (hasRuntimeOverride) {
475
+ inScope = isFicheSupportedModel(model);
476
+ scopeSource = 'runtime';
477
+ }
478
+ else if (readBrandEnv('MODELS') !== undefined) {
479
+ inScope = isFicheSupportedModel(model);
480
+ scopeSource = 'env';
481
+ }
482
+ else {
483
+ const cfgBases = readConfigModelBases();
484
+ if (cfgBases !== null) {
485
+ inScope = matchesModelBases(model, cfgBases);
486
+ scopeSource = 'config';
487
+ }
488
+ else {
489
+ inScope = isFicheSupportedModel(model);
490
+ scopeSource = 'default';
491
+ }
492
+ }
493
+ }
494
+ const tier = shouldImageModel(model, inScope, forceImages) ? 'image' : 'text';
495
+ const hygieneMode = resolveTextHygieneMode(hygieneArg);
496
+ const hygieneActive = isTextHygieneActive(hygieneArg);
497
+ const engineMode = forceImages === undefined && hygieneArg === undefined && daemonEngineMode
498
+ ? daemonEngineMode
499
+ : tier === 'image'
500
+ ? (resolveOpticalHistoryPolicy({ model, textHygieneActive: hygieneActive }) === 'hybrid'
501
+ ? 'hybrid'
502
+ : 'optical')
503
+ : 'text';
504
+ return textResult({
505
+ model,
506
+ inScope,
507
+ readerTier: tier,
508
+ engineMode,
509
+ textEngine: tier === 'image' ? 'image+TOON+hygiene' : 'TSCG+TOON+CASI+ACDC',
510
+ scopeSource,
511
+ ...(compressionEnabled !== undefined ? { compressionEnabled } : {}),
512
+ action: !inScope
513
+ ? hygieneMode === 'on'
514
+ ? 'passthrough as text: outside FICHE_MODELS, 4-layer text hygiene forced on'
515
+ : 'passthrough: model is outside FICHE_MODELS'
516
+ : tier === 'image'
517
+ ? engineMode === 'hybrid'
518
+ ? 'hybrid: Turn-1 optical slab + Text-MMU history'
519
+ : 'images for bulky stale context; live turns stay text'
520
+ : 'passthrough as text: image rendering disabled; uses 4-layer text engine (TSCG+TOON+CASI+ACDC)',
521
+ });
522
+ }
523
+ if (name === 'transform_request') {
524
+ const request = asRecord(args.request);
525
+ if (!request)
526
+ return textResult({ error: 'request must be an object' }, true);
527
+ stats.transformCalls += 1;
528
+ const model = typeof args.model === 'string'
529
+ ? args.model
530
+ : typeof request.model === 'string' ? request.model : undefined;
531
+ const wire = (typeof args.wire === 'string' ? args.wire : 'auto');
532
+ const upstream = typeof args.upstream === 'string' ? args.upstream : undefined;
533
+ const pathname = typeof args.pathname === 'string' ? args.pathname : undefined;
534
+ const textHygiene = args.textHygiene === 'auto' || args.textHygiene === 'on' || args.textHygiene === 'off'
535
+ ? args.textHygiene
536
+ : undefined;
537
+ const looksGoogleAuto = wire === 'auto' &&
538
+ !Array.isArray(request.input) &&
539
+ typeof request.instructions !== 'string' &&
540
+ !Array.isArray(request.messages) &&
541
+ (request.systemInstruction !== undefined || request.contents !== undefined);
542
+ const isGooglePayload = wire === 'google' || looksGoogleAuto;
543
+ const outboundPayload = isGooglePayload
544
+ ? request
545
+ : { ...request, ...(model ? { model } : {}) };
546
+ const body = new TextEncoder().encode(JSON.stringify(outboundPayload));
547
+ if (body.byteLength > MCP_MAX_BYTES) {
548
+ return textResult({ error: `request exceeds ${MCP_MAX_BYTES} bytes` }, true);
549
+ }
550
+ try {
551
+ const result = await transformAnyRequest(body, {
552
+ model,
553
+ wire,
554
+ forceImages: args.forceImages === true ? true : args.forceImages === false ? false : undefined,
555
+ ...(textHygiene !== undefined ? { textHygiene } : {}),
556
+ route: { upstream, pathname },
557
+ explicitPromptCacheBreakpoints: supportsExplicitPromptCacheBreakpoint({ upstream, pathname }),
558
+ });
559
+ stats.tokensSaved += result.report.savedVsOriginal;
560
+ let transformed;
561
+ try {
562
+ transformed = JSON.parse(new TextDecoder().decode(result.body));
563
+ }
564
+ catch {
565
+ transformed = null;
566
+ }
567
+ return textResult({
568
+ request: transformed,
569
+ report: result.report,
570
+ });
571
+ }
572
+ catch (err) {
573
+ return textResult({ error: err instanceof Error ? err.message : 'transform failed' }, true);
574
+ }
575
+ }
576
+ return textResult({ error: `unknown tool ${name}` }, true);
577
+ }
578
+ export async function handleMcpMessage(message) {
579
+ const rpc = asRecord(message);
580
+ if (rpc && rpc.jsonrpc === '2.0' && rpc.method === undefined && asRecord(rpc.error)) {
581
+ return rpc;
582
+ }
583
+ if (!rpc || rpc.jsonrpc !== '2.0' || typeof rpc.method !== 'string') {
584
+ return { jsonrpc: '2.0', id: rpc?.id ?? null, error: { code: -32600, message: 'invalid jsonrpc request' } };
585
+ }
586
+ const id = rpc.id ?? null;
587
+ const notify = rpc.id === undefined;
588
+ if (rpc.method === 'notifications/initialized' || rpc.method === 'notifications/cancelled') {
589
+ // A client that sends these with an id still expects a reply.
590
+ if (rpc.id === undefined)
591
+ return null;
592
+ return { jsonrpc: '2.0', id: rpc.id, result: {} };
593
+ }
594
+ if (rpc.method === 'initialize') {
595
+ const requested = typeof rpc.params?.protocolVersion === 'string' ? rpc.params.protocolVersion : MCP_PROTOCOL;
596
+ const protocolVersion = requested === '2024-11-05' || requested === '2025-03-26' || requested === '2025-06-18'
597
+ ? requested
598
+ : MCP_PROTOCOL;
599
+ return {
600
+ jsonrpc: '2.0',
601
+ id,
602
+ result: {
603
+ protocolVersion,
604
+ capabilities: { tools: { listChanged: false } },
605
+ serverInfo: { name: SERVER_NAME, version: SERVER_VERSION },
606
+ instructions: 'fiche renders bulky stale context as images for strong page readers (Gemini, Fable 5, Sol) and runs the 4-layer deterministic text compiler (TSCG+TOON+CASI+ACDC) on text-tier models while passing clean payloads through. This server does not store prompts.',
607
+ },
608
+ };
609
+ }
610
+ if (rpc.method === 'ping')
611
+ return { jsonrpc: '2.0', id, result: {} };
612
+ if (rpc.method === 'tools/list')
613
+ return { jsonrpc: '2.0', id, result: { tools: MCP_TOOLS } };
614
+ if (rpc.method === 'tools/call') {
615
+ const params = rpc.params ?? {};
616
+ const name = typeof params.name === 'string' ? params.name : '';
617
+ const args = asRecord(params.arguments) ?? {};
618
+ const result = await callTool(name, args);
619
+ return { jsonrpc: '2.0', id, result };
620
+ }
621
+ if (notify)
622
+ return null;
623
+ return { jsonrpc: '2.0', id, error: { code: -32601, message: `method not found: ${rpc.method}` } };
624
+ }
625
+ const LSP_HEADER_PREFIX_RE = /^(?:content-length|content-type)\s*:/i;
626
+ const LSP_MAX_HEADER_BYTES = 16 * 1024;
627
+ const mcpDrainStates = new WeakMap();
628
+ /** Newline-delimited JSON, plus LSP Content-Length frames if a client sends them. */
629
+ export function pushMcpChunk(buffer, chunk, onMessage) {
630
+ let drain = mcpDrainStates.get(onMessage);
631
+ if (!drain) {
632
+ drain = { dropLspBytes: 0, dropLine: false };
633
+ mcpDrainStates.set(onMessage, drain);
634
+ }
635
+ let rest;
636
+ if (drain.dropLspBytes > 0) {
637
+ const chunkBuf = Buffer.from(chunk, 'utf8');
638
+ if (chunkBuf.length < drain.dropLspBytes) {
639
+ drain.dropLspBytes -= chunkBuf.length;
640
+ return '';
641
+ }
642
+ rest = chunkBuf.subarray(drain.dropLspBytes).toString('utf8');
643
+ drain.dropLspBytes = 0;
644
+ }
645
+ else if (drain.dropLine) {
646
+ const nl = chunk.indexOf('\n');
647
+ if (nl < 0)
648
+ return '';
649
+ drain.dropLine = false;
650
+ rest = chunk.slice(nl + 1);
651
+ }
652
+ else {
653
+ rest = buffer + chunk;
654
+ }
655
+ while (rest.length > 0) {
656
+ // Only a leading header is framing. A JSON payload that mentions
657
+ // "Content-Length:" must not flip the session into LSP mode.
658
+ if (LSP_HEADER_PREFIX_RE.test(rest)) {
659
+ const crlfEnd = rest.indexOf('\r\n\r\n');
660
+ const lfEnd = rest.indexOf('\n\n');
661
+ const useCrlf = crlfEnd >= 0 && (lfEnd < 0 || crlfEnd <= lfEnd);
662
+ const alt = useCrlf ? crlfEnd : lfEnd;
663
+ if (alt < 0) {
664
+ if (Buffer.byteLength(rest, 'utf8') > LSP_MAX_HEADER_BYTES) {
665
+ onMessage({
666
+ jsonrpc: '2.0',
667
+ id: null,
668
+ error: { code: -32600, message: `frame exceeds ${MCP_MAX_BYTES} bytes` },
669
+ }, true);
670
+ drain.dropLine = true;
671
+ return '';
672
+ }
673
+ break;
674
+ }
675
+ const sep = useCrlf ? 4 : 2;
676
+ const header = rest.slice(0, alt);
677
+ const match = /^content-length\s*:\s*(\d+)/im.exec(header);
678
+ if (!match) {
679
+ rest = rest.slice(alt + sep);
680
+ continue;
681
+ }
682
+ const length = Number(match[1]);
683
+ const bodyStart = alt + sep;
684
+ const bytes = Buffer.from(rest.slice(bodyStart), 'utf8');
685
+ if (!Number.isFinite(length) || length < 0 || length > MCP_MAX_BYTES) {
686
+ onMessage({
687
+ jsonrpc: '2.0',
688
+ id: null,
689
+ error: { code: -32600, message: `frame exceeds ${MCP_MAX_BYTES} bytes` },
690
+ }, true);
691
+ if (Number.isFinite(length) && length > 0) {
692
+ if (bytes.length >= length) {
693
+ rest = bytes.subarray(length).toString('utf8');
694
+ continue;
695
+ }
696
+ drain.dropLspBytes = length - bytes.length;
697
+ }
698
+ return '';
699
+ }
700
+ // Content-Length counts UTF-8 bytes, not UTF-16 code units.
701
+ if (bytes.length < length)
702
+ break;
703
+ const json = bytes.subarray(0, length).toString('utf8');
704
+ rest = bytes.subarray(length).toString('utf8');
705
+ try {
706
+ onMessage(JSON.parse(json), true);
707
+ }
708
+ catch {
709
+ onMessage({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'parse error' } }, true);
710
+ }
711
+ continue;
712
+ }
713
+ const nl = rest.indexOf('\n');
714
+ if (nl < 0) {
715
+ if (Buffer.byteLength(rest, 'utf8') > MCP_MAX_BYTES) {
716
+ onMessage({
717
+ jsonrpc: '2.0',
718
+ id: null,
719
+ error: { code: -32600, message: `message exceeds ${MCP_MAX_BYTES} bytes` },
720
+ }, false);
721
+ drain.dropLine = true;
722
+ return '';
723
+ }
724
+ break;
725
+ }
726
+ const rawLine = rest.slice(0, nl);
727
+ rest = rest.slice(nl + 1);
728
+ if (Buffer.byteLength(rawLine, 'utf8') > MCP_MAX_BYTES) {
729
+ onMessage({
730
+ jsonrpc: '2.0',
731
+ id: null,
732
+ error: { code: -32600, message: `message exceeds ${MCP_MAX_BYTES} bytes` },
733
+ }, false);
734
+ continue;
735
+ }
736
+ const line = rawLine.replace(/\r$/, '').trim();
737
+ if (!line)
738
+ continue;
739
+ try {
740
+ onMessage(JSON.parse(line), false);
741
+ }
742
+ catch {
743
+ onMessage({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'parse error' } }, false);
744
+ }
745
+ }
746
+ return rest;
747
+ }
748
+ export function encodeMcpMessage(message, framed) {
749
+ const json = JSON.stringify(message);
750
+ if (!framed)
751
+ return `${json}\n`;
752
+ return `Content-Length: ${Buffer.byteLength(json, 'utf8')}\r\n\r\n${json}`;
753
+ }
754
+ export async function runStdioServer() {
755
+ let buffer = '';
756
+ let framed = false;
757
+ let stdoutBroken = false;
758
+ const activeRequests = new Set();
759
+ const onStdoutError = (err) => {
760
+ if (err?.code === 'EPIPE' || err?.code === 'ERR_STREAM_DESTROYED') {
761
+ stdoutBroken = true;
762
+ }
763
+ };
764
+ process.stdout.on('error', onStdoutError);
765
+ const write = (message) => {
766
+ if (stdoutBroken || process.stdout.destroyed || !process.stdout.writable)
767
+ return;
768
+ try {
769
+ process.stdout.write(encodeMcpMessage(message, framed));
770
+ }
771
+ catch (err) {
772
+ const code = err?.code;
773
+ if (code === 'EPIPE' || code === 'ERR_STREAM_DESTROYED')
774
+ stdoutBroken = true;
775
+ else
776
+ throw err;
777
+ }
778
+ };
779
+ const dispatch = (message, messageFramed) => {
780
+ if (messageFramed)
781
+ framed = true;
782
+ const p = handleMcpMessage(message)
783
+ .then((response) => {
784
+ if (response)
785
+ write(response);
786
+ })
787
+ .catch((err) => {
788
+ const messageText = err instanceof Error ? err.message : 'internal error';
789
+ write({ jsonrpc: '2.0', id: null, error: { code: -32603, message: messageText } });
790
+ })
791
+ .finally(() => {
792
+ activeRequests.delete(p);
793
+ });
794
+ activeRequests.add(p);
795
+ };
796
+ process.stdin.setEncoding('utf8');
797
+ const onData = (chunk) => {
798
+ buffer = pushMcpChunk(buffer, chunk, dispatch);
799
+ };
800
+ process.stdin.on('data', onData);
801
+ try {
802
+ await new Promise((resolve) => {
803
+ const finish = () => {
804
+ if (buffer.trim().length > 0 && !LSP_HEADER_PREFIX_RE.test(buffer)) {
805
+ buffer = pushMcpChunk(buffer, '\n', dispatch);
806
+ }
807
+ resolve();
808
+ };
809
+ process.stdin.once('end', finish);
810
+ process.stdin.once('close', finish);
811
+ });
812
+ while (activeRequests.size > 0) {
813
+ await Promise.allSettled([...activeRequests]);
814
+ }
815
+ }
816
+ finally {
817
+ process.stdin.off('data', onData);
818
+ process.stdout.off('error', onStdoutError);
819
+ }
820
+ }
821
+ function loopbackHost(hostname) {
822
+ const host = hostname.toLowerCase().replace(/^\[|\]$/g, '');
823
+ return host === 'localhost' || host === '127.0.0.1' || host === '::1';
824
+ }
825
+ function originAllowed(origin) {
826
+ if (origin === undefined)
827
+ return true;
828
+ if (!origin.trim())
829
+ return false;
830
+ try {
831
+ return loopbackHost(new URL(origin).hostname);
832
+ }
833
+ catch {
834
+ return false;
835
+ }
836
+ }
837
+ /** DNS rebinding sends Host: attacker.example while connecting to 127.0.0.1. */
838
+ export function hostHeaderAllowed(hostHeader) {
839
+ if (!hostHeader)
840
+ return false;
841
+ let hostname = hostHeader.trim();
842
+ if (hostname.startsWith('[')) {
843
+ const end = hostname.indexOf(']');
844
+ hostname = end >= 0 ? hostname.slice(1, end) : hostname;
845
+ }
846
+ else {
847
+ hostname = hostname.replace(/:\d+$/, '');
848
+ }
849
+ return loopbackHost(hostname);
850
+ }
851
+ export function startHttpServer(port, options = {}) {
852
+ const onRequest = (req, res) => {
853
+ const origin = req.headers.origin;
854
+ const host = typeof req.headers.host === 'string' ? req.headers.host : undefined;
855
+ if ((typeof origin === 'string' && !originAllowed(origin)) || !hostHeaderAllowed(host)) {
856
+ res.writeHead(403, { 'content-type': 'application/json' });
857
+ res.end(JSON.stringify({ error: 'loopback only' }));
858
+ return;
859
+ }
860
+ if (req.method === 'GET' || req.method === 'DELETE') {
861
+ res.writeHead(405, { allow: 'POST', 'content-type': 'application/json' });
862
+ res.end(JSON.stringify({ error: 'stateless streamable HTTP accepts POST /mcp only' }));
863
+ return;
864
+ }
865
+ if (req.method !== 'POST' || (req.url ?? '').split('?')[0] !== '/mcp') {
866
+ res.writeHead(404, { 'content-type': 'application/json' });
867
+ res.end(JSON.stringify({ error: 'POST /mcp' }));
868
+ return;
869
+ }
870
+ const chunks = [];
871
+ let received = 0;
872
+ let rejected = false;
873
+ req.on('data', (chunk) => {
874
+ if (rejected)
875
+ return;
876
+ received += chunk.length;
877
+ if (received > MCP_MAX_BYTES) {
878
+ rejected = true;
879
+ // Signal `Connection: close` so keep-alive clients (e.g. Node 24 globalAgent)
880
+ // never pool/reuse this socket, and drain without abruptly triggering EPIPE.
881
+ res.writeHead(413, { 'content-type': 'application/json', connection: 'close' });
882
+ res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32600, message: 'body too large' } }));
883
+ req.resume();
884
+ return;
885
+ }
886
+ chunks.push(chunk);
887
+ });
888
+ req.on('error', () => {
889
+ if (!res.writableEnded)
890
+ res.destroy();
891
+ });
892
+ req.on('end', () => {
893
+ if (rejected)
894
+ return;
895
+ void (async () => {
896
+ try {
897
+ let message;
898
+ try {
899
+ message = JSON.parse(Buffer.concat(chunks).toString('utf8'));
900
+ }
901
+ catch {
902
+ res.writeHead(400, { 'content-type': 'application/json' });
903
+ res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'parse error' } }));
904
+ return;
905
+ }
906
+ const response = await handleMcpMessage(message);
907
+ if (!response) {
908
+ res.writeHead(202);
909
+ res.end();
910
+ return;
911
+ }
912
+ res.writeHead(200, { 'content-type': 'application/json' });
913
+ res.end(JSON.stringify(response));
914
+ }
915
+ catch (err) {
916
+ if (res.writableEnded)
917
+ return;
918
+ const messageText = err instanceof Error ? err.message : 'internal error';
919
+ res.writeHead(500, { 'content-type': 'application/json' });
920
+ res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32603, message: messageText } }));
921
+ }
922
+ })();
923
+ });
924
+ };
925
+ // Listen on ::1 too, so a client that resolves localhost to IPv6 connects.
926
+ const server = createServer(onRequest);
927
+ const v6 = createServer(onRequest);
928
+ const closeServer = (target) => new Promise((done, fail) => {
929
+ if (!target.listening) {
930
+ done();
931
+ return;
932
+ }
933
+ target.close((err) => err ? fail(err) : done());
934
+ });
935
+ const retriesLeft = options.retriesLeft ?? (port === 0 ? 3 : 0);
936
+ return new Promise((resolve, reject) => {
937
+ server.once('error', reject);
938
+ server.listen(port, '127.0.0.1', () => {
939
+ const address = server.address();
940
+ const bound = address && typeof address === 'object' ? address.port : port;
941
+ let settled = false;
942
+ const finish = (ipv6Listening) => {
943
+ if (settled)
944
+ return;
945
+ settled = true;
946
+ resolve({
947
+ port: bound,
948
+ ipv6Listening,
949
+ close: async () => {
950
+ await closeServer(server);
951
+ await closeServer(v6);
952
+ },
953
+ });
954
+ };
955
+ if (options.ipv4Only) {
956
+ finish(false);
957
+ return;
958
+ }
959
+ v6.once('error', (err) => {
960
+ if (settled)
961
+ return;
962
+ if (err.code === 'EAFNOSUPPORT' || err.code === 'EADDRNOTAVAIL') {
963
+ finish(false);
964
+ return;
965
+ }
966
+ if (port === 0 && err.code === 'EADDRINUSE' && retriesLeft > 0) {
967
+ settled = true;
968
+ void closeServer(server).then(() => startHttpServer(0, { ...options, retriesLeft: retriesLeft - 1 }).then(resolve, reject), reject);
969
+ return;
970
+ }
971
+ settled = true;
972
+ void closeServer(server).finally(() => {
973
+ reject(new Error(`failed to bind ::1:${bound} (${err.code ?? err.message}); pass --ipv4 to bind 127.0.0.1 only`));
974
+ });
975
+ });
976
+ v6.listen(bound, '::1', () => finish(true));
977
+ });
978
+ });
979
+ }
980
+ export function resetMcpStatsForTests() {
981
+ stats.calls = 0;
982
+ stats.checkCalls = 0;
983
+ stats.transformCalls = 0;
984
+ stats.tokensSaved = 0;
985
+ }
986
+ export { countBillable };
987
+ //# sourceMappingURL=server.js.map