@maind-dev/mcp-bridge 0.6.0 → 0.8.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 (40) hide show
  1. package/build/index.js +764 -157
  2. package/build/meta.json +1 -1
  3. package/package.json +2 -1
  4. package/build/auth.js +0 -179
  5. package/build/auth.js.map +0 -1
  6. package/build/client-detect.js +0 -109
  7. package/build/client-detect.js.map +0 -1
  8. package/build/device-id.js +0 -149
  9. package/build/device-id.js.map +0 -1
  10. package/build/forward.js +0 -433
  11. package/build/forward.js.map +0 -1
  12. package/build/index.js.map +0 -1
  13. package/build/install/atomic-write.js +0 -115
  14. package/build/install/atomic-write.js.map +0 -1
  15. package/build/install/browser-pair.js +0 -139
  16. package/build/install/browser-pair.js.map +0 -1
  17. package/build/install/client-targets.js +0 -135
  18. package/build/install/client-targets.js.map +0 -1
  19. package/build/install/flags.js +0 -139
  20. package/build/install/flags.js.map +0 -1
  21. package/build/install/hook-merge.js +0 -195
  22. package/build/install/hook-merge.js.map +0 -1
  23. package/build/install/index.js +0 -187
  24. package/build/install/index.js.map +0 -1
  25. package/build/install/json-merge.js +0 -160
  26. package/build/install/json-merge.js.map +0 -1
  27. package/build/install/preamble.js +0 -119
  28. package/build/install/preamble.js.map +0 -1
  29. package/build/install/project-root.js +0 -120
  30. package/build/install/project-root.js.map +0 -1
  31. package/build/install/report.js +0 -89
  32. package/build/install/report.js.map +0 -1
  33. package/build/install/telemetry.js +0 -83
  34. package/build/install/telemetry.js.map +0 -1
  35. package/build/install/toml-merge.js +0 -148
  36. package/build/install/toml-merge.js.map +0 -1
  37. package/build/project-key.js +0 -73
  38. package/build/project-key.js.map +0 -1
  39. package/build/version.js +0 -7
  40. package/build/version.js.map +0 -1
package/build/index.js CHANGED
@@ -1,4 +1,514 @@
1
1
  #!/usr/bin/env node
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __esm = (fn, res) => function __init() {
5
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
+ };
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+
12
+ // src/device-id.ts
13
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync } from "node:fs";
14
+ import { homedir, hostname, platform, release } from "node:os";
15
+ import { randomUUID } from "node:crypto";
16
+ import { join } from "node:path";
17
+ function configDir() {
18
+ const home = homedir();
19
+ const env = process.env;
20
+ if (platform() === "darwin") {
21
+ return join(home, "Library", "Application Support", "maind");
22
+ }
23
+ if (platform() === "win32") {
24
+ const appdata = env.APPDATA && env.APPDATA.length > 0 ? env.APPDATA : join(home, "AppData", "Roaming");
25
+ return join(appdata, "maind");
26
+ }
27
+ const xdg = env.XDG_CONFIG_HOME && env.XDG_CONFIG_HOME.length > 0 ? env.XDG_CONFIG_HOME : join(home, ".config");
28
+ return join(xdg, "maind");
29
+ }
30
+ function ensureDir(path6) {
31
+ if (existsSync(path6)) return;
32
+ mkdirSync(path6, { recursive: true, mode: 448 });
33
+ }
34
+ function ensureDeviceId() {
35
+ const dir = configDir();
36
+ ensureDir(dir);
37
+ const file = join(dir, DEVICE_ID_FILE);
38
+ if (existsSync(file)) {
39
+ const stored = readFileSync(file, "utf8").trim();
40
+ if (isUuid(stored)) return stored;
41
+ }
42
+ const id = randomUUID();
43
+ writeFileSync(file, id + "\n", { encoding: "utf8", mode: 384 });
44
+ try {
45
+ chmodSync(file, 384);
46
+ } catch {
47
+ }
48
+ return id;
49
+ }
50
+ function isUuid(s) {
51
+ return UUID_RE.test(s);
52
+ }
53
+ function apiKeyPath() {
54
+ return join(configDir(), API_KEY_FILE);
55
+ }
56
+ function writeApiKey(key) {
57
+ const dir = configDir();
58
+ ensureDir(dir);
59
+ const file = apiKeyPath();
60
+ writeFileSync(file, key + "\n", { encoding: "utf8", mode: 384 });
61
+ try {
62
+ chmodSync(file, 384);
63
+ } catch {
64
+ }
65
+ }
66
+ function readApiKey() {
67
+ const file = apiKeyPath();
68
+ if (!existsSync(file)) return null;
69
+ const raw = readFileSync(file, "utf8").trim();
70
+ return raw.length > 0 ? raw : null;
71
+ }
72
+ function clearApiKey() {
73
+ const file = apiKeyPath();
74
+ if (!existsSync(file)) return;
75
+ writeFileSync(file, "", { encoding: "utf8", mode: 384 });
76
+ }
77
+ function clientMeta(version) {
78
+ return {
79
+ os: `${platform()} ${release()}`,
80
+ ide: "mcp-bridge",
81
+ ext_version: version,
82
+ device_id: ensureDeviceId()
83
+ };
84
+ }
85
+ var DEVICE_ID_FILE, API_KEY_FILE, UUID_RE;
86
+ var init_device_id = __esm({
87
+ "src/device-id.ts"() {
88
+ "use strict";
89
+ DEVICE_ID_FILE = "device-id";
90
+ API_KEY_FILE = "api-key";
91
+ UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
92
+ }
93
+ });
94
+
95
+ // src/version.ts
96
+ var BRIDGE_VERSION;
97
+ var init_version = __esm({
98
+ "src/version.ts"() {
99
+ "use strict";
100
+ BRIDGE_VERSION = "0.8.0";
101
+ }
102
+ });
103
+
104
+ // ../../packages/claude-code-telemetry/dist/types.js
105
+ var init_types = __esm({
106
+ "../../packages/claude-code-telemetry/dist/types.js"() {
107
+ "use strict";
108
+ }
109
+ });
110
+
111
+ // ../../packages/claude-code-telemetry/dist/transcript.js
112
+ var init_transcript = __esm({
113
+ "../../packages/claude-code-telemetry/dist/transcript.js"() {
114
+ "use strict";
115
+ }
116
+ });
117
+
118
+ // ../../packages/claude-code-telemetry/dist/decisions.js
119
+ var init_decisions = __esm({
120
+ "../../packages/claude-code-telemetry/dist/decisions.js"() {
121
+ "use strict";
122
+ }
123
+ });
124
+
125
+ // ../../packages/claude-code-telemetry/dist/effort.js
126
+ function detectEffortLevel(messageText) {
127
+ if (!messageText)
128
+ return null;
129
+ let last = null;
130
+ for (const match of messageText.matchAll(DIRECTIVE_RE)) {
131
+ const lvl = match[1].toLowerCase();
132
+ if (LEVELS.has(lvl))
133
+ last = lvl;
134
+ }
135
+ return last;
136
+ }
137
+ var LEVELS, DIRECTIVE_RE;
138
+ var init_effort = __esm({
139
+ "../../packages/claude-code-telemetry/dist/effort.js"() {
140
+ "use strict";
141
+ LEVELS = /* @__PURE__ */ new Set([
142
+ "low",
143
+ "medium",
144
+ "high",
145
+ "xhigh",
146
+ "max"
147
+ ]);
148
+ DIRECTIVE_RE = /(?:^|\s)\/(low|medium|high|xhigh|max)(?=\s|$|[!?.,;:])/gi;
149
+ }
150
+ });
151
+
152
+ // ../../packages/claude-code-telemetry/dist/session-analysis.js
153
+ import { createReadStream, existsSync as existsSync2 } from "node:fs";
154
+ import { createInterface as createInterface4 } from "node:readline";
155
+ function num2(v) {
156
+ return typeof v === "number" && Number.isFinite(v) ? v : 0;
157
+ }
158
+ function asBlocks(content) {
159
+ if (typeof content === "string")
160
+ return [{ type: "text", text: content }];
161
+ if (!Array.isArray(content))
162
+ return [];
163
+ return content.filter((b) => b !== null && typeof b === "object");
164
+ }
165
+ function textOf(blocks) {
166
+ const parts = [];
167
+ for (const b of blocks) {
168
+ if (b.type === "text" && typeof b.text === "string")
169
+ parts.push(b.text);
170
+ }
171
+ return parts.join("\n");
172
+ }
173
+ function isRepeat(prev, cur) {
174
+ const toks = (s) => new Set(s.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, " ").split(/\s+/).filter((w) => w.length > 2));
175
+ const a = toks(prev);
176
+ const b = toks(cur);
177
+ if (a.size < 3 || b.size < 3)
178
+ return false;
179
+ const [small, big] = a.size <= b.size ? [a, b] : [b, a];
180
+ let shared = 0;
181
+ for (const w of small)
182
+ if (big.has(w))
183
+ shared++;
184
+ return shared / small.size >= 0.8;
185
+ }
186
+ function classifyGenuine(text, prevText, priorWork) {
187
+ if (REWORK_RE.test(text))
188
+ return { polarity: -1, magnitude: MAG.rework, kind: "rework" };
189
+ if (priorWork && CORRECTION_RE.test(text))
190
+ return { polarity: -1, magnitude: MAG.correction, kind: "correction" };
191
+ if (ACCEPTANCE_RE.test(text))
192
+ return { polarity: 1, magnitude: MAG.acceptance, kind: "acceptance" };
193
+ if (prevText !== null && isRepeat(prevText, text))
194
+ return { polarity: -1, magnitude: MAG.repeat, kind: "repeat" };
195
+ return { polarity: 0, magnitude: 0, kind: "neutral" };
196
+ }
197
+ function emptyAnalysis(sessionId) {
198
+ return {
199
+ session_id: sessionId,
200
+ user_turns: 0,
201
+ assistant_turns: 0,
202
+ tool_calls: 0,
203
+ agent_questions: 0,
204
+ input_tokens: 0,
205
+ output_tokens: 0,
206
+ cache_read_tokens: 0,
207
+ cache_creation_tokens: 0,
208
+ user_chars: 0,
209
+ user_token_estimate: 0,
210
+ human_share: 0,
211
+ reactions_pos: 0,
212
+ reactions_neg: 0,
213
+ net_sentiment: 0,
214
+ corrections: 0,
215
+ reworks: 0,
216
+ interrupts: 0,
217
+ tool_denials: 0,
218
+ repeated_instructions: 0,
219
+ acceptances: 0,
220
+ momentum_series: [],
221
+ momentum_final: 0,
222
+ momentum_auc: 0,
223
+ ended_positive: false,
224
+ recovery_events: 0,
225
+ effort_at_end: null,
226
+ lines_seen: 0
227
+ };
228
+ }
229
+ async function analyzeSession(path6) {
230
+ const a = emptyAnalysis("");
231
+ if (!path6 || !existsSync2(path6))
232
+ return a;
233
+ const reactions = [];
234
+ let effort = null;
235
+ let priorAssistantWorked = false;
236
+ let prevUserText = null;
237
+ await new Promise((resolve2) => {
238
+ const stream = createReadStream(path6, { encoding: "utf-8" });
239
+ const rl = createInterface4({ input: stream });
240
+ const processLine = (line) => {
241
+ const trimmed = line.trim();
242
+ if (!trimmed)
243
+ return;
244
+ let parsed;
245
+ try {
246
+ parsed = JSON.parse(trimmed);
247
+ } catch {
248
+ return;
249
+ }
250
+ a.lines_seen++;
251
+ if (!a.session_id) {
252
+ const sid = parsed.sessionId ?? parsed.session_id;
253
+ if (typeof sid === "string" && sid)
254
+ a.session_id = sid;
255
+ }
256
+ const role = parsed.message?.role;
257
+ const isSide = parsed.isSidechain === true;
258
+ const usage = parsed.message?.usage;
259
+ if (role === "assistant" && usage) {
260
+ a.input_tokens += num2(usage.input_tokens);
261
+ a.output_tokens += num2(usage.output_tokens);
262
+ a.cache_read_tokens += num2(usage.cache_read_input_tokens);
263
+ a.cache_creation_tokens += num2(usage.cache_creation_input_tokens);
264
+ }
265
+ if (isSide)
266
+ return;
267
+ if (role === "assistant") {
268
+ a.assistant_turns++;
269
+ const blocks2 = asBlocks(parsed.message?.content);
270
+ let worked = false;
271
+ for (const b of blocks2) {
272
+ if (b.type === "tool_use") {
273
+ a.tool_calls++;
274
+ worked = true;
275
+ if (b.name === "AskUserQuestion")
276
+ a.agent_questions++;
277
+ }
278
+ }
279
+ priorAssistantWorked = worked;
280
+ return;
281
+ }
282
+ if (role !== "user")
283
+ return;
284
+ const blocks = asBlocks(parsed.message?.content);
285
+ const text = textOf(blocks);
286
+ if (text.includes(INTERRUPT_MARKER)) {
287
+ a.interrupts++;
288
+ reactions.push({ polarity: -1, magnitude: MAG.interrupt, kind: "interrupt" });
289
+ return;
290
+ }
291
+ const denied = blocks.some((b) => b.type === "tool_result" && b.is_error === true && typeof b.content === "string" && b.content.includes(DENIAL_MARKER));
292
+ if (denied) {
293
+ a.tool_denials++;
294
+ reactions.push({ polarity: -1, magnitude: MAG.denial, kind: "denial" });
295
+ return;
296
+ }
297
+ if (blocks.some((b) => b.type === "tool_result"))
298
+ return;
299
+ if (!text.trim())
300
+ return;
301
+ a.user_turns++;
302
+ a.user_chars += text.length;
303
+ const directive = detectEffortLevel(text);
304
+ if (directive)
305
+ effort = directive;
306
+ const r = classifyGenuine(text, prevUserText, priorAssistantWorked);
307
+ prevUserText = text;
308
+ if (r.kind === "correction")
309
+ a.corrections++;
310
+ else if (r.kind === "rework")
311
+ a.reworks++;
312
+ else if (r.kind === "repeat")
313
+ a.repeated_instructions++;
314
+ else if (r.kind === "acceptance")
315
+ a.acceptances++;
316
+ if (r.polarity !== 0)
317
+ reactions.push(r);
318
+ priorAssistantWorked = false;
319
+ };
320
+ rl.on("line", (line) => {
321
+ try {
322
+ processLine(line);
323
+ } catch {
324
+ }
325
+ });
326
+ rl.on("close", () => resolve2());
327
+ rl.on("error", () => resolve2());
328
+ stream.on("error", () => resolve2());
329
+ });
330
+ a.effort_at_end = effort;
331
+ a.user_token_estimate = Math.round(a.user_chars / 4);
332
+ const denom = a.user_token_estimate + a.output_tokens;
333
+ a.human_share = denom > 0 ? Number((a.user_token_estimate / denom).toFixed(4)) : 0;
334
+ let momentum = 0;
335
+ let auc = 0;
336
+ const series = [];
337
+ reactions.forEach((r, i) => {
338
+ if (r.polarity > 0)
339
+ a.reactions_pos++;
340
+ else if (r.polarity < 0)
341
+ a.reactions_neg++;
342
+ momentum = momentum * MOMENTUM_DECAY + r.polarity * r.magnitude;
343
+ const value = Number(momentum.toFixed(3));
344
+ series.push({
345
+ t: i,
346
+ value,
347
+ ...r.kind !== "neutral" ? { kind: r.kind } : {}
348
+ });
349
+ auc += value;
350
+ if (i > 0 && reactions[i - 1].polarity < 0 && r.polarity > 0)
351
+ a.recovery_events++;
352
+ });
353
+ a.net_sentiment = a.reactions_pos - a.reactions_neg;
354
+ a.momentum_series = series;
355
+ a.momentum_final = series.length ? series[series.length - 1].value : 0;
356
+ a.momentum_auc = Number(auc.toFixed(3));
357
+ a.ended_positive = a.momentum_final > 0;
358
+ return a;
359
+ }
360
+ var REWORK_RE, CORRECTION_RE, ACCEPTANCE_RE, INTERRUPT_MARKER, DENIAL_MARKER, MOMENTUM_DECAY, MAG;
361
+ var init_session_analysis = __esm({
362
+ "../../packages/claude-code-telemetry/dist/session-analysis.js"() {
363
+ "use strict";
364
+ init_effort();
365
+ REWORK_RE = /(\brückgängig\b|zurücknehmen|\bnochmal(s)?\b|noch mal|\brevert\b|\bundo\b|\bredo\b|stattdessen|\binstead\b|mach(e)? das (nochmal|neu)|try again)/i;
366
+ CORRECTION_RE = /(\bnein\b|\bfalsch\b|stimmt nicht|das ist nicht|so nicht|\bnicht so\b|warum hast du|wieso hast du|\bno\b|\bnope\b|\bwrong\b|\bincorrect\b|that'?s not|that is not|\bdon'?t\b|\bdoesn'?t\b|shouldn'?t)/i;
367
+ ACCEPTANCE_RE = /(\bdanke\b|\bperfekt\b|\bsuper\b|\bpasst\b|\bgenau\b|sieht gut|\bcommit\b|\bship\b|\bmerge\b|\bpush\b|looks good|\blgtm\b|\bthanks\b|thank you|\bperfect\b|\bgreat\b|\bexactly\b|\bnice\b|well done|👍|✅|🎉)/i;
368
+ INTERRUPT_MARKER = "[Request interrupted by user";
369
+ DENIAL_MARKER = "The user doesn't want to proceed with this tool use";
370
+ MOMENTUM_DECAY = 0.7;
371
+ MAG = {
372
+ denial: 1.5,
373
+ interrupt: 1.25,
374
+ rework: 1.5,
375
+ correction: 1,
376
+ acceptance: 1,
377
+ repeat: 0.75
378
+ };
379
+ }
380
+ });
381
+
382
+ // ../../packages/claude-code-telemetry/dist/parse.js
383
+ var init_parse = __esm({
384
+ "../../packages/claude-code-telemetry/dist/parse.js"() {
385
+ "use strict";
386
+ init_effort();
387
+ init_types();
388
+ }
389
+ });
390
+
391
+ // ../../packages/claude-code-telemetry/dist/windows.js
392
+ var FIVE_HOURS_MS, WEEK_MS;
393
+ var init_windows = __esm({
394
+ "../../packages/claude-code-telemetry/dist/windows.js"() {
395
+ "use strict";
396
+ FIVE_HOURS_MS = 5 * 60 * 60 * 1e3;
397
+ WEEK_MS = 7 * 24 * 60 * 60 * 1e3;
398
+ }
399
+ });
400
+
401
+ // ../../packages/claude-code-telemetry/dist/projects.js
402
+ import { homedir as homedir3 } from "node:os";
403
+ import { join as join10 } from "node:path";
404
+ var HOME, DEFAULT_PROJECTS_DIR;
405
+ var init_projects = __esm({
406
+ "../../packages/claude-code-telemetry/dist/projects.js"() {
407
+ "use strict";
408
+ HOME = homedir3();
409
+ DEFAULT_PROJECTS_DIR = join10(HOME, ".claude", "projects");
410
+ }
411
+ });
412
+
413
+ // ../../packages/claude-code-telemetry/dist/index.js
414
+ var init_dist = __esm({
415
+ "../../packages/claude-code-telemetry/dist/index.js"() {
416
+ "use strict";
417
+ init_types();
418
+ init_transcript();
419
+ init_decisions();
420
+ init_session_analysis();
421
+ init_parse();
422
+ init_effort();
423
+ init_windows();
424
+ init_projects();
425
+ }
426
+ });
427
+
428
+ // src/session-end/index.ts
429
+ var session_end_exports = {};
430
+ __export(session_end_exports, {
431
+ runOnSessionEnd: () => runOnSessionEnd
432
+ });
433
+ async function readHookInput() {
434
+ if (process.stdin.isTTY) return {};
435
+ const chunks = [];
436
+ return await new Promise((resolve2) => {
437
+ let settled = false;
438
+ const timer = setTimeout(() => {
439
+ if (!settled) {
440
+ settled = true;
441
+ resolve2({});
442
+ }
443
+ }, 200);
444
+ process.stdin.on("data", (c) => chunks.push(c));
445
+ process.stdin.on("end", () => {
446
+ if (settled) return;
447
+ settled = true;
448
+ clearTimeout(timer);
449
+ try {
450
+ const text = Buffer.concat(chunks).toString("utf-8").trim();
451
+ resolve2(text ? JSON.parse(text) : {});
452
+ } catch {
453
+ resolve2({});
454
+ }
455
+ });
456
+ process.stdin.on("error", () => {
457
+ if (settled) return;
458
+ settled = true;
459
+ clearTimeout(timer);
460
+ resolve2({});
461
+ });
462
+ });
463
+ }
464
+ async function postWithTimeout(apiKey, deviceId, analytics, timeoutMs) {
465
+ const post = fetch(INGEST_ENDPOINT, {
466
+ method: "POST",
467
+ headers: {
468
+ "content-type": "application/json",
469
+ authorization: `Bearer ${apiKey}`,
470
+ "x-maind-device-id": deviceId,
471
+ "x-maind-bridge-version": BRIDGE_VERSION
472
+ },
473
+ body: JSON.stringify({ session_analytics: analytics })
474
+ }).then(() => void 0).catch(() => void 0);
475
+ const timeout = new Promise((resolve2) => setTimeout(resolve2, timeoutMs));
476
+ await Promise.race([post, timeout]);
477
+ }
478
+ async function runOnSessionEnd() {
479
+ const apiKey = readApiKey();
480
+ if (!apiKey) return 0;
481
+ const input = await readHookInput();
482
+ const transcriptPath = typeof input.transcript_path === "string" ? input.transcript_path : "";
483
+ if (!transcriptPath) return 0;
484
+ try {
485
+ const analytics = await analyzeSession(transcriptPath);
486
+ if (typeof input.session_id === "string" && input.session_id) {
487
+ analytics.session_id = input.session_id;
488
+ }
489
+ if (!analytics.session_id) return 0;
490
+ await postWithTimeout(apiKey, ensureDeviceId(), analytics, 1500);
491
+ } catch (err) {
492
+ process.stderr.write(
493
+ `[maind-mcp-bridge] session-analytics failed: ${err instanceof Error ? err.message : String(err)}
494
+ `
495
+ );
496
+ }
497
+ return 0;
498
+ }
499
+ var INGEST_ENDPOINT;
500
+ var init_session_end = __esm({
501
+ "src/session-end/index.ts"() {
502
+ "use strict";
503
+ init_dist();
504
+ init_device_id();
505
+ init_version();
506
+ INGEST_ENDPOINT = process.env.MAIND_ENDPOINT ?? "https://vsddmiosisvfrairepxv.supabase.co/functions/v1/mcp-client-metrics-ingest";
507
+ }
508
+ });
509
+
510
+ // src/index.ts
511
+ import { randomUUID as randomUUID2 } from "node:crypto";
2
512
 
3
513
  // src/forward.ts
4
514
  import { createInterface } from "node:readline";
@@ -461,84 +971,11 @@ function extractHint(lowerBody) {
461
971
  return "auth_failed";
462
972
  }
463
973
 
464
- // src/device-id.ts
465
- import { existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync } from "node:fs";
466
- import { homedir, hostname, platform, release } from "node:os";
467
- import { randomUUID } from "node:crypto";
468
- import { join } from "node:path";
469
- function configDir() {
470
- const home = homedir();
471
- const env = process.env;
472
- if (platform() === "darwin") {
473
- return join(home, "Library", "Application Support", "maind");
474
- }
475
- if (platform() === "win32") {
476
- const appdata = env.APPDATA && env.APPDATA.length > 0 ? env.APPDATA : join(home, "AppData", "Roaming");
477
- return join(appdata, "maind");
478
- }
479
- const xdg = env.XDG_CONFIG_HOME && env.XDG_CONFIG_HOME.length > 0 ? env.XDG_CONFIG_HOME : join(home, ".config");
480
- return join(xdg, "maind");
481
- }
482
- function ensureDir(path6) {
483
- if (existsSync(path6)) return;
484
- mkdirSync(path6, { recursive: true, mode: 448 });
485
- }
486
- var DEVICE_ID_FILE = "device-id";
487
- var API_KEY_FILE = "api-key";
488
- function ensureDeviceId() {
489
- const dir = configDir();
490
- ensureDir(dir);
491
- const file = join(dir, DEVICE_ID_FILE);
492
- if (existsSync(file)) {
493
- const stored = readFileSync(file, "utf8").trim();
494
- if (isUuid(stored)) return stored;
495
- }
496
- const id = randomUUID();
497
- writeFileSync(file, id + "\n", { encoding: "utf8", mode: 384 });
498
- try {
499
- chmodSync(file, 384);
500
- } catch {
501
- }
502
- return id;
503
- }
504
- var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
505
- function isUuid(s) {
506
- return UUID_RE.test(s);
507
- }
508
- function apiKeyPath() {
509
- return join(configDir(), API_KEY_FILE);
510
- }
511
- function writeApiKey(key) {
512
- const dir = configDir();
513
- ensureDir(dir);
514
- const file = apiKeyPath();
515
- writeFileSync(file, key + "\n", { encoding: "utf8", mode: 384 });
516
- try {
517
- chmodSync(file, 384);
518
- } catch {
519
- }
520
- }
521
- function readApiKey() {
522
- const file = apiKeyPath();
523
- if (!existsSync(file)) return null;
524
- const raw = readFileSync(file, "utf8").trim();
525
- return raw.length > 0 ? raw : null;
526
- }
527
- function clearApiKey() {
528
- const file = apiKeyPath();
529
- if (!existsSync(file)) return;
530
- writeFileSync(file, "", { encoding: "utf8", mode: 384 });
531
- }
532
- function clientMeta(version) {
533
- return {
534
- os: `${platform()} ${release()}`,
535
- ide: "mcp-bridge",
536
- ext_version: version,
537
- device_id: ensureDeviceId()
538
- };
539
- }
974
+ // src/index.ts
975
+ init_device_id();
540
976
 
541
977
  // src/auth.ts
978
+ init_device_id();
542
979
  import { spawn } from "node:child_process";
543
980
  import { platform as platform2 } from "node:os";
544
981
  var DEFAULT_FUNCTIONS_ORIGIN = "https://vsddmiosisvfrairepxv.supabase.co/functions/v1";
@@ -666,8 +1103,8 @@ async function openExternalBrowser(url) {
666
1103
  });
667
1104
  }
668
1105
 
669
- // src/version.ts
670
- var BRIDGE_VERSION = "0.6.0";
1106
+ // src/index.ts
1107
+ init_version();
671
1108
 
672
1109
  // src/project-key.ts
673
1110
  import { execFileSync } from "node:child_process";
@@ -714,6 +1151,7 @@ function computeProjectKey() {
714
1151
  }
715
1152
 
716
1153
  // src/install/index.ts
1154
+ init_version();
717
1155
  import * as os from "node:os";
718
1156
 
719
1157
  // src/install/flags.ts
@@ -2225,27 +2663,17 @@ function ensureTrailingBlankLine(content) {
2225
2663
  import * as path5 from "node:path";
2226
2664
  import * as readline2 from "node:readline";
2227
2665
  var REMINDER_FILE_REL = ".claude/maind-session-start-reminder.md";
2228
- async function mergeSessionStartHook(opts) {
2666
+ async function mergeClaudeHook(opts, spec) {
2229
2667
  const settingsPath = path5.join(opts.homeDir, ".claude", "settings.json");
2230
- const targetKey = "hook:~/.claude/settings.json";
2668
+ const targetKey = spec.targetKey;
2231
2669
  if (opts.skip) {
2232
- return {
2233
- target: targetKey,
2234
- action: "skip",
2235
- status: "skipped",
2236
- detail: "--no-hook"
2237
- };
2670
+ return { target: targetKey, action: "skip", status: "skipped", detail: "--no-hook" };
2238
2671
  }
2239
2672
  let raw;
2240
2673
  try {
2241
2674
  raw = await readFileSafe(settingsPath);
2242
2675
  } catch (err) {
2243
- return {
2244
- target: targetKey,
2245
- action: "merge",
2246
- status: "failed",
2247
- detail: `read: ${errMessage(err)}`
2248
- };
2676
+ return { target: targetKey, action: "merge", status: "failed", detail: `read: ${errMessage(err)}` };
2249
2677
  }
2250
2678
  let settings;
2251
2679
  let action = "create";
@@ -2265,22 +2693,11 @@ async function mergeSessionStartHook(opts) {
2265
2693
  }
2266
2694
  settings = parsed;
2267
2695
  } catch (err) {
2268
- return {
2269
- target: targetKey,
2270
- action: "merge",
2271
- status: "failed",
2272
- detail: `parse: ${errMessage(err)}`
2273
- };
2696
+ return { target: targetKey, action: "merge", status: "failed", detail: `parse: ${errMessage(err)}` };
2274
2697
  }
2275
2698
  }
2276
- const reminderRefRegex = /maind-session-start-reminder\.md/;
2277
- if (existingHookReferencesReminder(settings, reminderRefRegex)) {
2278
- return {
2279
- target: targetKey,
2280
- action: "skip",
2281
- status: "skipped",
2282
- detail: "SessionStart hook already references the reminder file"
2283
- };
2699
+ if (existingHookReferences(settings, spec.event, spec.matchPattern)) {
2700
+ return { target: targetKey, action: "skip", status: "skipped", detail: spec.skipDetailWhenPresent };
2284
2701
  }
2285
2702
  if (!opts.full) {
2286
2703
  if (!opts.isInteractive) {
@@ -2302,34 +2719,23 @@ async function mergeSessionStartHook(opts) {
2302
2719
  const consent = await promptYesNo(
2303
2720
  opts.out,
2304
2721
  `
2305
- Merge a SessionStart hook into ${settingsPath}?
2306
- It 'cat's ${REMINDER_FILE_REL} into every new Claude Code session.
2722
+ Merge a ${spec.event} hook into ${settingsPath}?
2723
+ ${spec.consentDescription}
2307
2724
  [Y/n]: `
2308
2725
  );
2309
2726
  if (!consent) {
2310
- return {
2311
- target: targetKey,
2312
- action: "skip",
2313
- status: "skipped",
2314
- detail: "user declined"
2315
- };
2727
+ return { target: targetKey, action: "skip", status: "skipped", detail: "user declined" };
2316
2728
  }
2317
2729
  }
2318
- const reminderPath = path5.join(opts.homeDir, REMINDER_FILE_REL);
2319
2730
  const newHookGroup = {
2320
- hooks: [
2321
- {
2322
- type: "command",
2323
- command: `cat ${reminderPath}`,
2324
- timeout: 5
2325
- }
2326
- ]
2731
+ hooks: [{ type: "command", command: spec.command, timeout: spec.timeout }]
2327
2732
  };
2733
+ const existingGroups = settings.hooks?.[spec.event] ?? [];
2328
2734
  const nextSettings = {
2329
2735
  ...settings,
2330
2736
  hooks: {
2331
2737
  ...settings.hooks ?? {},
2332
- SessionStart: [...settings.hooks?.SessionStart ?? [], newHookGroup]
2738
+ [spec.event]: [...existingGroups, newHookGroup]
2333
2739
  }
2334
2740
  };
2335
2741
  const nextRaw = JSON.stringify(nextSettings, null, 2) + "\n";
@@ -2344,12 +2750,7 @@ It 'cat's ${REMINDER_FILE_REL} into every new Claude Code session.
2344
2750
  try {
2345
2751
  await atomicWriteFile(settingsPath, nextRaw, 384);
2346
2752
  } catch (err) {
2347
- return {
2348
- target: targetKey,
2349
- action: "merge",
2350
- status: "failed",
2351
- detail: `write: ${errMessage(err)}`
2352
- };
2753
+ return { target: targetKey, action: "merge", status: "failed", detail: `write: ${errMessage(err)}` };
2353
2754
  }
2354
2755
  return {
2355
2756
  target: targetKey,
@@ -2358,10 +2759,35 @@ It 'cat's ${REMINDER_FILE_REL} into every new Claude Code session.
2358
2759
  detail: settingsPath
2359
2760
  };
2360
2761
  }
2361
- function existingHookReferencesReminder(settings, pattern) {
2362
- const sessionStart = settings.hooks?.SessionStart;
2363
- if (!Array.isArray(sessionStart)) return false;
2364
- for (const group of sessionStart) {
2762
+ async function mergeSessionStartHook(opts) {
2763
+ const reminderPath = path5.join(opts.homeDir, REMINDER_FILE_REL);
2764
+ return mergeClaudeHook(opts, {
2765
+ event: "SessionStart",
2766
+ command: `cat ${reminderPath}`,
2767
+ timeout: 5,
2768
+ matchPattern: /maind-session-start-reminder\.md/,
2769
+ targetKey: "hook:~/.claude/settings.json",
2770
+ skipDetailWhenPresent: "SessionStart hook already references the reminder file",
2771
+ consentDescription: `It 'cat's ${REMINDER_FILE_REL} into every new Claude Code session.`
2772
+ });
2773
+ }
2774
+ async function mergeStopHook(opts) {
2775
+ return mergeClaudeHook(opts, {
2776
+ event: "Stop",
2777
+ command: "npx -y @maind-dev/mcp-bridge on-session-end",
2778
+ timeout: 10,
2779
+ // Match any on-session-end command so we never double-wire (also covers a
2780
+ // hand-wired node-path hook the user may already have).
2781
+ matchPattern: /on-session-end/,
2782
+ targetKey: "hook(stop):~/.claude/settings.json",
2783
+ skipDetailWhenPresent: "Stop hook already runs maind on-session-end",
2784
+ consentDescription: "It runs 'maind-mcp-bridge on-session-end' \u2014 derives session communication analytics (momentum + reactions) from the transcript at session end. Gated by Tier-3 consent server-side."
2785
+ });
2786
+ }
2787
+ function existingHookReferences(settings, event, pattern) {
2788
+ const groups = settings.hooks?.[event];
2789
+ if (!Array.isArray(groups)) return false;
2790
+ for (const group of groups) {
2365
2791
  if (!isObject3(group)) continue;
2366
2792
  const hooks = group.hooks;
2367
2793
  if (!Array.isArray(hooks)) continue;
@@ -2395,6 +2821,7 @@ function errMessage(err) {
2395
2821
  }
2396
2822
 
2397
2823
  // src/install/browser-pair.ts
2824
+ init_device_id();
2398
2825
  async function pairOrUseToken(opts) {
2399
2826
  const targetKey = "browser-pair";
2400
2827
  if (opts.token !== null) {
@@ -2690,15 +3117,16 @@ Skipping remaining steps.
2690
3117
  detail: "--no-preamble"
2691
3118
  });
2692
3119
  }
2693
- const hookResult = await mergeSessionStartHook({
3120
+ const hookOpts = {
2694
3121
  homeDir,
2695
3122
  isInteractive,
2696
3123
  full: flags.full,
2697
3124
  skip: flags.noHook,
2698
3125
  dryRun: flags.dryRun,
2699
3126
  out: process.stdout
2700
- });
2701
- report.add(hookResult);
3127
+ };
3128
+ report.add(await mergeSessionStartHook(hookOpts));
3129
+ report.add(await mergeStopHook(hookOpts));
2702
3130
  if (!flags.dryRun) {
2703
3131
  await postInstallTelemetry({
2704
3132
  enabled: flags.telemetry || flags.full,
@@ -4113,6 +4541,79 @@ function defaultEngineFactory() {
4113
4541
  return createNodeCodeIndex({ repoRoot: resolveRepoRoot() });
4114
4542
  }
4115
4543
 
4544
+ // src/local-tools/savings.ts
4545
+ import { readFileSync as readFileSync3 } from "node:fs";
4546
+ import { join as join9 } from "node:path";
4547
+
4548
+ // src/local-tools/token-estimate.ts
4549
+ var CHARS_PER_TOKEN = 4;
4550
+ function estimateTokens(text) {
4551
+ if (!text) return 0;
4552
+ return Math.ceil(text.length / CHARS_PER_TOKEN);
4553
+ }
4554
+
4555
+ // src/local-tools/savings.ts
4556
+ var MAX_FILE_BYTES = 1e6;
4557
+ var SavingsAggregator = class {
4558
+ pendingTokens = 0;
4559
+ pendingCalls = 0;
4560
+ add(savedTokens) {
4561
+ if (!Number.isFinite(savedTokens) || savedTokens <= 0) return;
4562
+ this.pendingTokens += Math.floor(savedTokens);
4563
+ this.pendingCalls += 1;
4564
+ }
4565
+ hasPending() {
4566
+ return this.pendingTokens > 0;
4567
+ }
4568
+ /** Return the pending delta and reset the accumulator. */
4569
+ takePending() {
4570
+ const out = { tokens: this.pendingTokens, calls: this.pendingCalls };
4571
+ this.pendingTokens = 0;
4572
+ this.pendingCalls = 0;
4573
+ return out;
4574
+ }
4575
+ };
4576
+ function readFileCapped(absPath) {
4577
+ try {
4578
+ const content = readFileSync3(absPath, "utf8");
4579
+ return content.length > MAX_FILE_BYTES ? content.slice(0, MAX_FILE_BYTES) : content;
4580
+ } catch {
4581
+ return "";
4582
+ }
4583
+ }
4584
+ function distinctFilePaths(result) {
4585
+ if (!Array.isArray(result)) return [];
4586
+ const seen = /* @__PURE__ */ new Set();
4587
+ for (const hit of result) {
4588
+ const fp = hit?.filePath;
4589
+ if (typeof fp === "string" && fp.length > 0) seen.add(fp);
4590
+ }
4591
+ return [...seen];
4592
+ }
4593
+ function measureLocalToolSaved(name, result, serialized, repoRoot) {
4594
+ try {
4595
+ const resultTokens = estimateTokens(serialized);
4596
+ if (name === "codebase_search") {
4597
+ const files = distinctFilePaths(result);
4598
+ if (files.length === 0) return 0;
4599
+ let wholeTokens = 0;
4600
+ for (const fp of files) {
4601
+ wholeTokens += estimateTokens(readFileCapped(join9(repoRoot, fp)));
4602
+ }
4603
+ return Math.max(0, wholeTokens - resultTokens);
4604
+ }
4605
+ if (name === "codebase_snippet") {
4606
+ const fp = result?.filePath;
4607
+ if (typeof fp !== "string" || fp.length === 0) return 0;
4608
+ const wholeTokens = estimateTokens(readFileCapped(join9(repoRoot, fp)));
4609
+ return Math.max(0, wholeTokens - resultTokens);
4610
+ }
4611
+ return 0;
4612
+ } catch {
4613
+ return 0;
4614
+ }
4615
+ }
4616
+
4116
4617
  // src/local-tools/tools.ts
4117
4618
  import { createHash as createHash3 } from "node:crypto";
4118
4619
  function nodeKeyHash(nodeKey) {
@@ -4290,10 +4791,21 @@ async function dispatchLocalTool(engine, name, args) {
4290
4791
 
4291
4792
  // src/local-tools/router.ts
4292
4793
  var LocalToolRouter = class {
4293
- constructor(makeEngine = defaultEngineFactory) {
4794
+ /**
4795
+ * @param makeEngine factory for the local code-index engine (injectable in tests).
4796
+ * @param aggregator optional Weg-B savings accumulator. When present, each
4797
+ * measurable local tool call feeds it a delta; null disables
4798
+ * measurement entirely (feature off).
4799
+ * @param resolveRoot repo-root resolver for the whole-file counterfactual
4800
+ * (injectable in tests; defaults to the git top-level of cwd).
4801
+ */
4802
+ constructor(makeEngine = defaultEngineFactory, aggregator = null, resolveRoot = resolveRepoRoot) {
4294
4803
  this.makeEngine = makeEngine;
4804
+ this.aggregator = aggregator;
4805
+ this.resolveRoot = resolveRoot;
4295
4806
  }
4296
4807
  engine = null;
4808
+ repoRootCache = null;
4297
4809
  /** The tool descriptors to advertise in tools/list. */
4298
4810
  descriptors() {
4299
4811
  return LOCAL_TOOLS;
@@ -4315,11 +4827,13 @@ var LocalToolRouter = class {
4315
4827
  const args = p.arguments && typeof p.arguments === "object" ? p.arguments : {};
4316
4828
  try {
4317
4829
  const result = await dispatchLocalTool(this.getEngine(), name, args);
4830
+ const serialized = JSON.stringify(result, null, 2);
4831
+ this.recordSavings(name, result, serialized);
4318
4832
  return JSON.stringify({
4319
4833
  jsonrpc: "2.0",
4320
4834
  id,
4321
4835
  result: {
4322
- content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
4836
+ content: [{ type: "text", text: serialized }]
4323
4837
  }
4324
4838
  });
4325
4839
  } catch (err) {
@@ -4359,10 +4873,75 @@ var LocalToolRouter = class {
4359
4873
  if (!this.engine) this.engine = this.makeEngine();
4360
4874
  return this.engine;
4361
4875
  }
4876
+ /**
4877
+ * Feed the savings aggregator with the tokens saved by answering `name`
4878
+ * locally. No-op when measurement is disabled or the tool has no whole-file
4879
+ * counterfactual. Fully defensive — never throws into the tool path.
4880
+ */
4881
+ recordSavings(name, result, serialized) {
4882
+ if (!this.aggregator) return;
4883
+ if (name !== "codebase_search" && name !== "codebase_snippet") return;
4884
+ try {
4885
+ if (this.repoRootCache === null) this.repoRootCache = this.resolveRoot();
4886
+ const saved = measureLocalToolSaved(name, result, serialized, this.repoRootCache);
4887
+ this.aggregator.add(saved);
4888
+ } catch {
4889
+ }
4890
+ }
4362
4891
  };
4363
4892
 
4893
+ // src/functions-origin.ts
4894
+ var DEFAULT_FUNCTIONS_ORIGIN3 = "https://vsddmiosisvfrairepxv.supabase.co/functions/v1";
4895
+ function functionsOrigin2() {
4896
+ const v = (process.env.MAIND_FUNCTIONS_ORIGIN ?? "").trim().replace(/\/+$/, "");
4897
+ return v.length > 0 ? v : DEFAULT_FUNCTIONS_ORIGIN3;
4898
+ }
4899
+
4900
+ // src/metrics-post.ts
4901
+ var INGEST_PATH = "/mcp-client-metrics-ingest";
4902
+ var POST_TIMEOUT_MS = 4e3;
4903
+ var SAVINGS_METRIC_KEY = "codebase_search_tokens_saved";
4904
+ async function postSavingsMetric(input) {
4905
+ if (!Number.isFinite(input.tokensSaved) || input.tokensSaved <= 0) return false;
4906
+ const url = `${functionsOrigin2()}${INGEST_PATH}`;
4907
+ const controller = new AbortController();
4908
+ const timer = setTimeout(() => controller.abort(), POST_TIMEOUT_MS);
4909
+ try {
4910
+ const res = await fetch(url, {
4911
+ method: "POST",
4912
+ headers: {
4913
+ "content-type": "application/json",
4914
+ authorization: `Bearer ${input.apiKey}`,
4915
+ "x-maind-device-id": input.deviceId,
4916
+ "user-agent": `@maind-dev/mcp-bridge/${input.bridgeVersion}`
4917
+ },
4918
+ body: JSON.stringify({
4919
+ metrics: [
4920
+ {
4921
+ session_id: input.sessionId,
4922
+ metric_key: SAVINGS_METRIC_KEY,
4923
+ metric_value: Math.floor(input.tokensSaved)
4924
+ }
4925
+ ]
4926
+ }),
4927
+ signal: controller.signal
4928
+ });
4929
+ await res.text().catch(() => "");
4930
+ return res.ok;
4931
+ } catch (err) {
4932
+ process.stderr.write(
4933
+ `[maind-mcp-bridge] savings metric post failed (ignored): ${err instanceof Error ? err.message : String(err)}
4934
+ `
4935
+ );
4936
+ return false;
4937
+ } finally {
4938
+ clearTimeout(timer);
4939
+ }
4940
+ }
4941
+
4364
4942
  // src/index.ts
4365
4943
  var MAX_REAUTH_ATTEMPTS = 1;
4944
+ var SAVINGS_FLUSH_INTERVAL_MS = 6e4;
4366
4945
  async function ensureApiKey() {
4367
4946
  const fromEnv = (process.env.MAIND_API_KEY ?? "").trim();
4368
4947
  if (fromEnv.length > 0) {
@@ -4401,6 +4980,10 @@ async function main() {
4401
4980
  const code = await runInstall(installArgs);
4402
4981
  process.exit(code);
4403
4982
  }
4983
+ if (firstPositional === "on-session-end") {
4984
+ const { runOnSessionEnd: runOnSessionEnd2 } = await Promise.resolve().then(() => (init_session_end(), session_end_exports));
4985
+ process.exit(await runOnSessionEnd2());
4986
+ }
4404
4987
  if (process.argv.includes("--version") || process.argv.includes("-v")) {
4405
4988
  process.stdout.write(BRIDGE_VERSION + "\n");
4406
4989
  process.exit(0);
@@ -4419,31 +5002,55 @@ async function main() {
4419
5002
  const deviceId = ensureDeviceId();
4420
5003
  let apiKey = await ensureApiKey();
4421
5004
  const projectKey = computeProjectKey();
4422
- const localRouter = process.env.MAIND_DISABLE_CODEBASE_TOOLS === "1" ? null : new LocalToolRouter();
4423
- let attempts = 0;
4424
- while (true) {
4425
- const forwarder = new Forwarder({
5005
+ const savingsEnabled = process.env.MAIND_DISABLE_CODEBASE_TOOLS !== "1" && process.env.MAIND_DISABLE_SAVINGS_METRICS !== "1";
5006
+ const aggregator = savingsEnabled ? new SavingsAggregator() : null;
5007
+ const localRouter = process.env.MAIND_DISABLE_CODEBASE_TOOLS === "1" ? null : new LocalToolRouter(void 0, aggregator);
5008
+ const savingsSessionId = `bridge-${randomUUID2()}`;
5009
+ const flushSavings = async () => {
5010
+ if (!aggregator) return;
5011
+ const delta = aggregator.takePending();
5012
+ if (delta.tokens <= 0) return;
5013
+ await postSavingsMetric({
4426
5014
  apiKey,
4427
5015
  deviceId,
4428
- bridgeVersion: BRIDGE_VERSION,
4429
- projectKey,
4430
- localRouter
5016
+ sessionId: savingsSessionId,
5017
+ tokensSaved: delta.tokens,
5018
+ bridgeVersion: BRIDGE_VERSION
4431
5019
  });
4432
- try {
4433
- await forwarder.run();
4434
- return;
4435
- } catch (err) {
4436
- if (err instanceof BridgeReauthNeeded && attempts < MAX_REAUTH_ATTEMPTS) {
4437
- attempts += 1;
4438
- process.stderr.write(
4439
- `[maind-mcp-bridge] server reported ${err.message}; re-authorizing\u2026
5020
+ };
5021
+ const flushTimer = aggregator ? setInterval(() => {
5022
+ void flushSavings();
5023
+ }, SAVINGS_FLUSH_INTERVAL_MS) : null;
5024
+ flushTimer?.unref();
5025
+ let attempts = 0;
5026
+ try {
5027
+ while (true) {
5028
+ const forwarder = new Forwarder({
5029
+ apiKey,
5030
+ deviceId,
5031
+ bridgeVersion: BRIDGE_VERSION,
5032
+ projectKey,
5033
+ localRouter
5034
+ });
5035
+ try {
5036
+ await forwarder.run();
5037
+ return;
5038
+ } catch (err) {
5039
+ if (err instanceof BridgeReauthNeeded && attempts < MAX_REAUTH_ATTEMPTS) {
5040
+ attempts += 1;
5041
+ process.stderr.write(
5042
+ `[maind-mcp-bridge] server reported ${err.message}; re-authorizing\u2026
4440
5043
  `
4441
- );
4442
- apiKey = await reauth();
4443
- continue;
5044
+ );
5045
+ apiKey = await reauth();
5046
+ continue;
5047
+ }
5048
+ throw err;
4444
5049
  }
4445
- throw err;
4446
5050
  }
5051
+ } finally {
5052
+ if (flushTimer) clearInterval(flushTimer);
5053
+ await flushSavings();
4447
5054
  }
4448
5055
  }
4449
5056
  function printHelp() {