@maind-dev/mcp-bridge 0.13.0 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -0
- package/build/index.js +986 -118
- package/build/meta.json +1 -1
- package/package.json +1 -1
package/build/index.js
CHANGED
|
@@ -27,9 +27,9 @@ function configDir() {
|
|
|
27
27
|
const xdg = env.XDG_CONFIG_HOME && env.XDG_CONFIG_HOME.length > 0 ? env.XDG_CONFIG_HOME : join2(home, ".config");
|
|
28
28
|
return join2(xdg, "maind");
|
|
29
29
|
}
|
|
30
|
-
function ensureDir(
|
|
31
|
-
if (existsSync(
|
|
32
|
-
mkdirSync2(
|
|
30
|
+
function ensureDir(path7) {
|
|
31
|
+
if (existsSync(path7)) return;
|
|
32
|
+
mkdirSync2(path7, { recursive: true, mode: 448 });
|
|
33
33
|
}
|
|
34
34
|
function ensureDeviceId() {
|
|
35
35
|
const dir = configDir();
|
|
@@ -97,7 +97,7 @@ var BRIDGE_VERSION;
|
|
|
97
97
|
var init_version = __esm({
|
|
98
98
|
"src/version.ts"() {
|
|
99
99
|
"use strict";
|
|
100
|
-
BRIDGE_VERSION = "0.
|
|
100
|
+
BRIDGE_VERSION = "0.16.0";
|
|
101
101
|
}
|
|
102
102
|
});
|
|
103
103
|
|
|
@@ -109,6 +109,54 @@ var init_types = __esm({
|
|
|
109
109
|
});
|
|
110
110
|
|
|
111
111
|
// ../../packages/claude-code-telemetry/dist/transcript.js
|
|
112
|
+
import { createReadStream, existsSync as existsSync4 } from "node:fs";
|
|
113
|
+
import { stat } from "node:fs/promises";
|
|
114
|
+
import { createInterface as createInterface4 } from "node:readline";
|
|
115
|
+
async function summariseTranscript(path7) {
|
|
116
|
+
if (!path7 || !existsSync4(path7))
|
|
117
|
+
return null;
|
|
118
|
+
let stats;
|
|
119
|
+
try {
|
|
120
|
+
stats = await stat(path7);
|
|
121
|
+
} catch {
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
let input = 0;
|
|
125
|
+
let output = 0;
|
|
126
|
+
let lines = 0;
|
|
127
|
+
return await new Promise((resolve2) => {
|
|
128
|
+
const stream = createReadStream(path7, { encoding: "utf-8" });
|
|
129
|
+
const rl = createInterface4({ input: stream });
|
|
130
|
+
rl.on("line", (line) => {
|
|
131
|
+
const trimmed = line.trim();
|
|
132
|
+
if (!trimmed)
|
|
133
|
+
return;
|
|
134
|
+
lines++;
|
|
135
|
+
try {
|
|
136
|
+
const parsed = JSON.parse(trimmed);
|
|
137
|
+
const usage = parsed.message?.usage;
|
|
138
|
+
if (!usage)
|
|
139
|
+
return;
|
|
140
|
+
if (typeof usage.input_tokens === "number")
|
|
141
|
+
input += usage.input_tokens;
|
|
142
|
+
if (typeof usage.output_tokens === "number")
|
|
143
|
+
output += usage.output_tokens;
|
|
144
|
+
} catch {
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
rl.on("close", () => {
|
|
148
|
+
resolve2({
|
|
149
|
+
input_tokens: input,
|
|
150
|
+
output_tokens: output,
|
|
151
|
+
total_tokens: input + output,
|
|
152
|
+
lines_seen: lines,
|
|
153
|
+
last_modified_ms: stats.mtimeMs
|
|
154
|
+
});
|
|
155
|
+
});
|
|
156
|
+
rl.on("error", () => resolve2(null));
|
|
157
|
+
stream.on("error", () => resolve2(null));
|
|
158
|
+
});
|
|
159
|
+
}
|
|
112
160
|
var init_transcript = __esm({
|
|
113
161
|
"../../packages/claude-code-telemetry/dist/transcript.js"() {
|
|
114
162
|
"use strict";
|
|
@@ -150,8 +198,8 @@ var init_effort = __esm({
|
|
|
150
198
|
});
|
|
151
199
|
|
|
152
200
|
// ../../packages/claude-code-telemetry/dist/session-analysis.js
|
|
153
|
-
import { createReadStream, existsSync as
|
|
154
|
-
import { createInterface as
|
|
201
|
+
import { createReadStream as createReadStream2, existsSync as existsSync5 } from "node:fs";
|
|
202
|
+
import { createInterface as createInterface5 } from "node:readline";
|
|
155
203
|
function num2(v) {
|
|
156
204
|
return typeof v === "number" && Number.isFinite(v) ? v : 0;
|
|
157
205
|
}
|
|
@@ -226,17 +274,17 @@ function emptyAnalysis(sessionId) {
|
|
|
226
274
|
lines_seen: 0
|
|
227
275
|
};
|
|
228
276
|
}
|
|
229
|
-
async function analyzeSession(
|
|
277
|
+
async function analyzeSession(path7) {
|
|
230
278
|
const a = emptyAnalysis("");
|
|
231
|
-
if (!
|
|
279
|
+
if (!path7 || !existsSync5(path7))
|
|
232
280
|
return a;
|
|
233
281
|
const reactions = [];
|
|
234
282
|
let effort = null;
|
|
235
283
|
let priorAssistantWorked = false;
|
|
236
284
|
let prevUserText = null;
|
|
237
285
|
await new Promise((resolve2) => {
|
|
238
|
-
const stream =
|
|
239
|
-
const rl =
|
|
286
|
+
const stream = createReadStream2(path7, { encoding: "utf-8" });
|
|
287
|
+
const rl = createInterface5({ input: stream });
|
|
240
288
|
const processLine = (line) => {
|
|
241
289
|
const trimmed = line.trim();
|
|
242
290
|
if (!trimmed)
|
|
@@ -400,13 +448,13 @@ var init_windows = __esm({
|
|
|
400
448
|
|
|
401
449
|
// ../../packages/claude-code-telemetry/dist/projects.js
|
|
402
450
|
import { homedir as homedir3 } from "node:os";
|
|
403
|
-
import { join as
|
|
451
|
+
import { join as join12 } from "node:path";
|
|
404
452
|
var HOME, DEFAULT_PROJECTS_DIR;
|
|
405
453
|
var init_projects = __esm({
|
|
406
454
|
"../../packages/claude-code-telemetry/dist/projects.js"() {
|
|
407
455
|
"use strict";
|
|
408
456
|
HOME = homedir3();
|
|
409
|
-
DEFAULT_PROJECTS_DIR =
|
|
457
|
+
DEFAULT_PROJECTS_DIR = join12(HOME, ".claude", "projects");
|
|
410
458
|
}
|
|
411
459
|
});
|
|
412
460
|
|
|
@@ -425,42 +473,439 @@ var init_dist = __esm({
|
|
|
425
473
|
}
|
|
426
474
|
});
|
|
427
475
|
|
|
428
|
-
// src/
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
476
|
+
// src/hooks/api.ts
|
|
477
|
+
function ingestHeaders(apiKey) {
|
|
478
|
+
return {
|
|
479
|
+
"content-type": "application/json",
|
|
480
|
+
authorization: `Bearer ${apiKey}`,
|
|
481
|
+
"x-maind-device-id": ensureDeviceId()
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
async function postMetrics(endpoint, apiKey, metrics) {
|
|
485
|
+
if (metrics.length === 0) return { ok: true, inserted: 0 };
|
|
486
|
+
try {
|
|
487
|
+
const res = await fetch(endpoint, {
|
|
488
|
+
method: "POST",
|
|
489
|
+
headers: ingestHeaders(apiKey),
|
|
490
|
+
body: JSON.stringify({ metrics })
|
|
491
|
+
});
|
|
492
|
+
if (!res.ok) {
|
|
493
|
+
const text = await res.text().catch(() => "");
|
|
494
|
+
return {
|
|
495
|
+
ok: false,
|
|
496
|
+
inserted: 0,
|
|
497
|
+
status: res.status,
|
|
498
|
+
error: text.slice(0, 500)
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
const json = await res.json().catch(() => null);
|
|
502
|
+
return {
|
|
503
|
+
ok: true,
|
|
504
|
+
inserted: json?.inserted_metrics ?? metrics.length,
|
|
505
|
+
status: res.status
|
|
506
|
+
};
|
|
507
|
+
} catch (err) {
|
|
508
|
+
return {
|
|
509
|
+
ok: false,
|
|
510
|
+
inserted: 0,
|
|
511
|
+
error: err instanceof Error ? err.message : String(err)
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
var DEFAULT_INGEST_ENDPOINT;
|
|
516
|
+
var init_api = __esm({
|
|
517
|
+
"src/hooks/api.ts"() {
|
|
518
|
+
"use strict";
|
|
519
|
+
init_device_id();
|
|
520
|
+
DEFAULT_INGEST_ENDPOINT = process.env.MAIND_ENDPOINT ?? "https://vsddmiosisvfrairepxv.supabase.co/functions/v1/mcp-client-metrics-ingest";
|
|
521
|
+
}
|
|
432
522
|
});
|
|
523
|
+
|
|
524
|
+
// src/hooks/hook-input.ts
|
|
433
525
|
async function readHookInput() {
|
|
434
526
|
if (process.stdin.isTTY) return {};
|
|
435
527
|
const chunks = [];
|
|
436
528
|
return await new Promise((resolve2) => {
|
|
437
529
|
let settled = false;
|
|
438
|
-
const
|
|
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", () => {
|
|
530
|
+
const settle = (value) => {
|
|
446
531
|
if (settled) return;
|
|
447
532
|
settled = true;
|
|
448
533
|
clearTimeout(timer);
|
|
534
|
+
resolve2(value);
|
|
535
|
+
};
|
|
536
|
+
const timer = setTimeout(() => settle({}), STDIN_TIMEOUT_MS);
|
|
537
|
+
process.stdin.on("data", (c) => chunks.push(c));
|
|
538
|
+
process.stdin.on("end", () => {
|
|
449
539
|
try {
|
|
450
540
|
const text = Buffer.concat(chunks).toString("utf-8").trim();
|
|
451
|
-
|
|
541
|
+
settle(text ? JSON.parse(text) : {});
|
|
452
542
|
} catch {
|
|
453
|
-
|
|
543
|
+
settle({});
|
|
454
544
|
}
|
|
455
545
|
});
|
|
456
|
-
process.stdin.on("error", () => {
|
|
457
|
-
if (settled) return;
|
|
458
|
-
settled = true;
|
|
459
|
-
clearTimeout(timer);
|
|
460
|
-
resolve2({});
|
|
461
|
-
});
|
|
546
|
+
process.stdin.on("error", () => settle({}));
|
|
462
547
|
});
|
|
463
548
|
}
|
|
549
|
+
function transcriptPathOf(input) {
|
|
550
|
+
return typeof input.transcript_path === "string" ? input.transcript_path : "";
|
|
551
|
+
}
|
|
552
|
+
var STDIN_TIMEOUT_MS;
|
|
553
|
+
var init_hook_input = __esm({
|
|
554
|
+
"src/hooks/hook-input.ts"() {
|
|
555
|
+
"use strict";
|
|
556
|
+
STDIN_TIMEOUT_MS = 200;
|
|
557
|
+
}
|
|
558
|
+
});
|
|
559
|
+
|
|
560
|
+
// src/hooks/state.ts
|
|
561
|
+
import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2, rename as rename2 } from "node:fs/promises";
|
|
562
|
+
import { existsSync as existsSync6 } from "node:fs";
|
|
563
|
+
import { homedir as homedir4 } from "node:os";
|
|
564
|
+
import { join as join13 } from "node:path";
|
|
565
|
+
function emptyState() {
|
|
566
|
+
return { config: null, sessions: {}, pending_metrics: [] };
|
|
567
|
+
}
|
|
568
|
+
async function loadState() {
|
|
569
|
+
if (!existsSync6(STATE_FILE)) return emptyState();
|
|
570
|
+
try {
|
|
571
|
+
const raw = await readFile2(STATE_FILE, "utf-8");
|
|
572
|
+
const parsed = JSON.parse(raw);
|
|
573
|
+
return {
|
|
574
|
+
config: parsed.config ?? null,
|
|
575
|
+
sessions: parsed.sessions ?? {},
|
|
576
|
+
pending_metrics: Array.isArray(parsed.pending_metrics) ? parsed.pending_metrics : [],
|
|
577
|
+
thresholds: parsed.thresholds,
|
|
578
|
+
thresholds_synced_at: parsed.thresholds_synced_at
|
|
579
|
+
};
|
|
580
|
+
} catch (err) {
|
|
581
|
+
process.stderr.write(
|
|
582
|
+
`[maind-mcp-bridge] state.json corrupt, resetting: ${err instanceof Error ? err.message : String(err)}
|
|
583
|
+
`
|
|
584
|
+
);
|
|
585
|
+
return emptyState();
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
async function saveState(state) {
|
|
589
|
+
if (!existsSync6(STATE_DIR)) {
|
|
590
|
+
await mkdir2(STATE_DIR, { recursive: true, mode: 448 });
|
|
591
|
+
}
|
|
592
|
+
const tmp = `${STATE_FILE}.tmp`;
|
|
593
|
+
await writeFile2(tmp, JSON.stringify(state, null, 2), { mode: 384 });
|
|
594
|
+
await rename2(tmp, STATE_FILE);
|
|
595
|
+
}
|
|
596
|
+
function resolveThresholds(state) {
|
|
597
|
+
return state.thresholds ?? state.config?.thresholds ?? DEFAULT_THRESHOLDS;
|
|
598
|
+
}
|
|
599
|
+
var STATE_DIR, STATE_FILE, DEFAULT_THRESHOLDS;
|
|
600
|
+
var init_state = __esm({
|
|
601
|
+
"src/hooks/state.ts"() {
|
|
602
|
+
"use strict";
|
|
603
|
+
STATE_DIR = join13(homedir4(), ".maind");
|
|
604
|
+
STATE_FILE = join13(STATE_DIR, "state.json");
|
|
605
|
+
DEFAULT_THRESHOLDS = {
|
|
606
|
+
warn_at_pct: 60,
|
|
607
|
+
handoff_at_pct: 85,
|
|
608
|
+
model_token_limit: 2e5
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
});
|
|
612
|
+
|
|
613
|
+
// src/hooks/index.ts
|
|
614
|
+
var hooks_exports = {};
|
|
615
|
+
__export(hooks_exports, {
|
|
616
|
+
effectiveConfig: () => effectiveConfig,
|
|
617
|
+
runFlush: () => runFlush,
|
|
618
|
+
runHookStatus: () => runHookStatus,
|
|
619
|
+
runOnSessionStart: () => runOnSessionStart,
|
|
620
|
+
runOnToolUse: () => runOnToolUse,
|
|
621
|
+
runSessionEndMetrics: () => runSessionEndMetrics,
|
|
622
|
+
runSyncConfig: () => runSyncConfig
|
|
623
|
+
});
|
|
624
|
+
import { writeFile as writeFile3 } from "node:fs/promises";
|
|
625
|
+
import { join as join14 } from "node:path";
|
|
626
|
+
function effectiveConfig(state) {
|
|
627
|
+
if (state.config) return state.config;
|
|
628
|
+
const key = readApiKey();
|
|
629
|
+
if (key === null) return null;
|
|
630
|
+
return { api_key: key, endpoint: DEFAULT_INGEST_ENDPOINT };
|
|
631
|
+
}
|
|
632
|
+
function getOrCreateSession(state, sessionId) {
|
|
633
|
+
let session = state.sessions[sessionId];
|
|
634
|
+
if (!session) {
|
|
635
|
+
session = {
|
|
636
|
+
session_id: sessionId,
|
|
637
|
+
started_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
638
|
+
tool_call_count: 0,
|
|
639
|
+
lessons_consulted: 0
|
|
640
|
+
};
|
|
641
|
+
state.sessions[sessionId] = session;
|
|
642
|
+
}
|
|
643
|
+
return session;
|
|
644
|
+
}
|
|
645
|
+
async function runOnSessionStart() {
|
|
646
|
+
const state = await loadState();
|
|
647
|
+
if (effectiveConfig(state) === null) return 0;
|
|
648
|
+
const input = await readHookInput();
|
|
649
|
+
const sessionId = sessionIdOf(input);
|
|
650
|
+
if (sessionId === null) return 0;
|
|
651
|
+
getOrCreateSession(state, sessionId);
|
|
652
|
+
await saveState(state);
|
|
653
|
+
return 0;
|
|
654
|
+
}
|
|
655
|
+
async function runOnToolUse() {
|
|
656
|
+
const state = await loadState();
|
|
657
|
+
if (effectiveConfig(state) === null) return 0;
|
|
658
|
+
const input = await readHookInput();
|
|
659
|
+
const sessionId = sessionIdOf(input) ?? "unknown";
|
|
660
|
+
const session = getOrCreateSession(state, sessionId);
|
|
661
|
+
session.tool_call_count += 1;
|
|
662
|
+
const tool = (input.tool_name ?? "").toString();
|
|
663
|
+
if (tool.includes("search_lessons") || tool.includes("get_session_briefing") || tool.includes("get_lesson")) {
|
|
664
|
+
session.lessons_consulted += 1;
|
|
665
|
+
}
|
|
666
|
+
const transcriptPath = input.transcript_path;
|
|
667
|
+
if (typeof transcriptPath === "string" && transcriptPath && !session.transcript_path) {
|
|
668
|
+
session.transcript_path = transcriptPath;
|
|
669
|
+
}
|
|
670
|
+
if (session.transcript_path) {
|
|
671
|
+
const summary = await summariseTranscript(session.transcript_path);
|
|
672
|
+
if (summary) {
|
|
673
|
+
session.token_count = summary.total_tokens;
|
|
674
|
+
await maybeEmitAdvisory(state, session);
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
await saveState(state);
|
|
678
|
+
return 0;
|
|
679
|
+
}
|
|
680
|
+
async function maybeEmitAdvisory(state, session) {
|
|
681
|
+
const t = resolveThresholds(state);
|
|
682
|
+
const tokens = session.token_count ?? 0;
|
|
683
|
+
if (t.model_token_limit <= 0) return;
|
|
684
|
+
const ratio = tokens / t.model_token_limit;
|
|
685
|
+
let status = "ok";
|
|
686
|
+
if (ratio >= t.handoff_at_pct / 100) status = "handoff_recommended";
|
|
687
|
+
else if (ratio >= t.warn_at_pct / 100) status = "warn";
|
|
688
|
+
if (session.last_advisory_status === status) return;
|
|
689
|
+
session.last_advisory_status = status;
|
|
690
|
+
if (status === "ok") return;
|
|
691
|
+
const pct = Math.round(ratio * 100);
|
|
692
|
+
const payload = {
|
|
693
|
+
session_id: session.session_id,
|
|
694
|
+
status,
|
|
695
|
+
tokens,
|
|
696
|
+
ratio: Number(ratio.toFixed(3)),
|
|
697
|
+
pct,
|
|
698
|
+
thresholds: t,
|
|
699
|
+
suggested_next: status === "handoff_recommended" ? "use_generate_handoff_brief" : "wrap_up_current_subtask",
|
|
700
|
+
emitted_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
701
|
+
};
|
|
702
|
+
try {
|
|
703
|
+
await writeFile3(
|
|
704
|
+
join14(STATE_DIR, `handoff_advisory_${session.session_id}.json`),
|
|
705
|
+
JSON.stringify(payload, null, 2)
|
|
706
|
+
);
|
|
707
|
+
} catch (err) {
|
|
708
|
+
process.stderr.write(
|
|
709
|
+
`[maind-mcp-bridge] failed to write advisory marker: ${err instanceof Error ? err.message : String(err)}
|
|
710
|
+
`
|
|
711
|
+
);
|
|
712
|
+
}
|
|
713
|
+
if (status === "warn") {
|
|
714
|
+
process.stderr.write(
|
|
715
|
+
`[maind] \u26A0 Token usage at ~${pct}% (warn threshold ${t.warn_at_pct}%). Consider wrapping the current sub-task before opening new threads.
|
|
716
|
+
`
|
|
717
|
+
);
|
|
718
|
+
} else {
|
|
719
|
+
process.stderr.write(
|
|
720
|
+
`[maind] \u26D4 Token usage at ~${pct}% (handoff threshold ${t.handoff_at_pct}%). Strongly consider compiling a HANDOFF brief and starting a fresh session \u2014 call recommend_handoff or generate_handoff_brief.
|
|
721
|
+
`
|
|
722
|
+
);
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
async function runSessionEndMetrics(sessionId) {
|
|
726
|
+
try {
|
|
727
|
+
const state = await loadState();
|
|
728
|
+
const config = effectiveConfig(state);
|
|
729
|
+
if (config === null) return;
|
|
730
|
+
const id = sessionId ?? Object.keys(state.sessions)[0];
|
|
731
|
+
const session = id ? state.sessions[id] : void 0;
|
|
732
|
+
if (session) {
|
|
733
|
+
const durationMs = Date.now() - new Date(session.started_at).getTime();
|
|
734
|
+
state.pending_metrics.push(
|
|
735
|
+
{
|
|
736
|
+
session_id: id,
|
|
737
|
+
metric_key: "session_duration_ms",
|
|
738
|
+
metric_value: Math.max(0, durationMs)
|
|
739
|
+
},
|
|
740
|
+
{
|
|
741
|
+
session_id: id,
|
|
742
|
+
metric_key: "tool_call_count",
|
|
743
|
+
metric_value: session.tool_call_count
|
|
744
|
+
},
|
|
745
|
+
{
|
|
746
|
+
session_id: id,
|
|
747
|
+
metric_key: "lessons_consulted",
|
|
748
|
+
metric_value: session.lessons_consulted
|
|
749
|
+
}
|
|
750
|
+
);
|
|
751
|
+
delete state.sessions[id];
|
|
752
|
+
await saveState(state);
|
|
753
|
+
}
|
|
754
|
+
await flushPending(config, STOP_FLUSH_TIMEOUT_MS);
|
|
755
|
+
} catch (err) {
|
|
756
|
+
process.stderr.write(
|
|
757
|
+
`[maind-mcp-bridge] session metrics failed: ${err instanceof Error ? err.message : String(err)}
|
|
758
|
+
`
|
|
759
|
+
);
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
async function runFlush() {
|
|
763
|
+
const state = await loadState();
|
|
764
|
+
const config = effectiveConfig(state);
|
|
765
|
+
if (config === null) {
|
|
766
|
+
process.stderr.write(
|
|
767
|
+
"[maind-mcp-bridge] not paired \u2014 run `maind-mcp-bridge install` first.\n"
|
|
768
|
+
);
|
|
769
|
+
return 1;
|
|
770
|
+
}
|
|
771
|
+
const result = await flushPending(config, MANUAL_FLUSH_TIMEOUT_MS);
|
|
772
|
+
process.stdout.write(JSON.stringify(result, null, 2) + "\n");
|
|
773
|
+
return result.ok ? 0 : 1;
|
|
774
|
+
}
|
|
775
|
+
async function flushPending(config, timeoutMs) {
|
|
776
|
+
const state = await loadState();
|
|
777
|
+
if (state.pending_metrics.length === 0) {
|
|
778
|
+
return { ok: true, flushed: 0, remaining: 0 };
|
|
779
|
+
}
|
|
780
|
+
const batch = state.pending_metrics.slice(0, 100);
|
|
781
|
+
const post = postMetrics(config.endpoint, config.api_key, batch);
|
|
782
|
+
const timeout = new Promise(
|
|
783
|
+
(resolve2) => setTimeout(() => resolve2({ ok: false, inserted: 0, error: "timeout" }), timeoutMs)
|
|
784
|
+
);
|
|
785
|
+
const result = await Promise.race([post, timeout]);
|
|
786
|
+
if (result.ok) {
|
|
787
|
+
const fresh = await loadState();
|
|
788
|
+
fresh.pending_metrics = fresh.pending_metrics.slice(batch.length);
|
|
789
|
+
await saveState(fresh);
|
|
790
|
+
return { ok: true, flushed: batch.length, remaining: fresh.pending_metrics.length };
|
|
791
|
+
}
|
|
792
|
+
return {
|
|
793
|
+
ok: false,
|
|
794
|
+
flushed: 0,
|
|
795
|
+
remaining: state.pending_metrics.length,
|
|
796
|
+
error: result.error
|
|
797
|
+
};
|
|
798
|
+
}
|
|
799
|
+
async function runHookStatus() {
|
|
800
|
+
const state = await loadState();
|
|
801
|
+
const config = effectiveConfig(state);
|
|
802
|
+
process.stdout.write(
|
|
803
|
+
JSON.stringify(
|
|
804
|
+
{
|
|
805
|
+
paired: config !== null,
|
|
806
|
+
source: state.config ? "maind-hook init (legacy)" : "bridge credential",
|
|
807
|
+
endpoint: config?.endpoint ?? null,
|
|
808
|
+
api_key_prefix: config ? config.api_key.slice(0, 12) + "\u2026" : null,
|
|
809
|
+
open_sessions: Object.keys(state.sessions).length,
|
|
810
|
+
pending_metrics: state.pending_metrics.length,
|
|
811
|
+
thresholds: resolveThresholds(state),
|
|
812
|
+
thresholds_synced_at: state.thresholds_synced_at ?? state.config?.thresholds_synced_at ?? null
|
|
813
|
+
},
|
|
814
|
+
null,
|
|
815
|
+
2
|
|
816
|
+
) + "\n"
|
|
817
|
+
);
|
|
818
|
+
return 0;
|
|
819
|
+
}
|
|
820
|
+
async function runSyncConfig() {
|
|
821
|
+
const state = await loadState();
|
|
822
|
+
const config = effectiveConfig(state);
|
|
823
|
+
if (config === null) {
|
|
824
|
+
process.stderr.write(
|
|
825
|
+
"[maind-mcp-bridge] not paired \u2014 run `maind-mcp-bridge install` first.\n"
|
|
826
|
+
);
|
|
827
|
+
return 1;
|
|
828
|
+
}
|
|
829
|
+
const endpoint = config.thresholds_endpoint ?? DEFAULT_THRESHOLDS_ENDPOINT;
|
|
830
|
+
let res;
|
|
831
|
+
try {
|
|
832
|
+
res = await fetch(endpoint, {
|
|
833
|
+
method: "POST",
|
|
834
|
+
headers: {
|
|
835
|
+
"content-type": "application/json",
|
|
836
|
+
authorization: `Bearer ${config.api_key}`
|
|
837
|
+
}
|
|
838
|
+
});
|
|
839
|
+
} catch (err) {
|
|
840
|
+
process.stderr.write(
|
|
841
|
+
`[maind-mcp-bridge] sync-config network error: ${err instanceof Error ? err.message : String(err)}
|
|
842
|
+
`
|
|
843
|
+
);
|
|
844
|
+
return 1;
|
|
845
|
+
}
|
|
846
|
+
if (!res.ok) {
|
|
847
|
+
process.stderr.write(
|
|
848
|
+
`[maind-mcp-bridge] sync-config HTTP ${res.status} ${res.statusText}
|
|
849
|
+
`
|
|
850
|
+
);
|
|
851
|
+
const body2 = await res.text().catch(() => "");
|
|
852
|
+
if (body2) process.stderr.write(body2.slice(0, 500) + "\n");
|
|
853
|
+
return 1;
|
|
854
|
+
}
|
|
855
|
+
let body;
|
|
856
|
+
try {
|
|
857
|
+
body = await res.json();
|
|
858
|
+
} catch {
|
|
859
|
+
process.stderr.write("[maind-mcp-bridge] sync-config: invalid JSON response\n");
|
|
860
|
+
return 1;
|
|
861
|
+
}
|
|
862
|
+
const t = body;
|
|
863
|
+
if (typeof t.warn_at_pct !== "number" || typeof t.handoff_at_pct !== "number" || typeof t.model_token_limit !== "number") {
|
|
864
|
+
process.stderr.write(
|
|
865
|
+
"[maind-mcp-bridge] sync-config: response missing expected fields\n"
|
|
866
|
+
);
|
|
867
|
+
return 1;
|
|
868
|
+
}
|
|
869
|
+
state.thresholds = {
|
|
870
|
+
warn_at_pct: t.warn_at_pct,
|
|
871
|
+
handoff_at_pct: t.handoff_at_pct,
|
|
872
|
+
model_token_limit: t.model_token_limit
|
|
873
|
+
};
|
|
874
|
+
state.thresholds_synced_at = (/* @__PURE__ */ new Date()).toISOString();
|
|
875
|
+
await saveState(state);
|
|
876
|
+
process.stdout.write(
|
|
877
|
+
JSON.stringify(
|
|
878
|
+
{ ok: true, thresholds: state.thresholds, synced_at: state.thresholds_synced_at },
|
|
879
|
+
null,
|
|
880
|
+
2
|
|
881
|
+
) + "\n"
|
|
882
|
+
);
|
|
883
|
+
return 0;
|
|
884
|
+
}
|
|
885
|
+
function sessionIdOf(input) {
|
|
886
|
+
const id = typeof input.session_id === "string" ? input.session_id.trim() : "";
|
|
887
|
+
return id.length > 0 ? id : null;
|
|
888
|
+
}
|
|
889
|
+
var DEFAULT_THRESHOLDS_ENDPOINT, STOP_FLUSH_TIMEOUT_MS, MANUAL_FLUSH_TIMEOUT_MS;
|
|
890
|
+
var init_hooks = __esm({
|
|
891
|
+
"src/hooks/index.ts"() {
|
|
892
|
+
"use strict";
|
|
893
|
+
init_dist();
|
|
894
|
+
init_device_id();
|
|
895
|
+
init_api();
|
|
896
|
+
init_hook_input();
|
|
897
|
+
init_state();
|
|
898
|
+
DEFAULT_THRESHOLDS_ENDPOINT = process.env.MAIND_THRESHOLDS_ENDPOINT ?? "https://vsddmiosisvfrairepxv.supabase.co/functions/v1/get-context-thresholds";
|
|
899
|
+
STOP_FLUSH_TIMEOUT_MS = 1500;
|
|
900
|
+
MANUAL_FLUSH_TIMEOUT_MS = 1e4;
|
|
901
|
+
}
|
|
902
|
+
});
|
|
903
|
+
|
|
904
|
+
// src/session-end/index.ts
|
|
905
|
+
var session_end_exports = {};
|
|
906
|
+
__export(session_end_exports, {
|
|
907
|
+
runOnSessionEnd: () => runOnSessionEnd
|
|
908
|
+
});
|
|
464
909
|
async function postWithTimeout(apiKey, deviceId, analytics, timeoutMs) {
|
|
465
910
|
const post = fetch(INGEST_ENDPOINT, {
|
|
466
911
|
method: "POST",
|
|
@@ -479,21 +924,23 @@ async function runOnSessionEnd() {
|
|
|
479
924
|
const apiKey = readApiKey();
|
|
480
925
|
if (!apiKey) return 0;
|
|
481
926
|
const input = await readHookInput();
|
|
482
|
-
const
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
analytics.session_id =
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
927
|
+
const sessionId = typeof input.session_id === "string" && input.session_id ? input.session_id : null;
|
|
928
|
+
const transcriptPath = transcriptPathOf(input);
|
|
929
|
+
if (transcriptPath) {
|
|
930
|
+
try {
|
|
931
|
+
const analytics = await analyzeSession(transcriptPath);
|
|
932
|
+
if (sessionId) analytics.session_id = sessionId;
|
|
933
|
+
if (analytics.session_id) {
|
|
934
|
+
await postWithTimeout(apiKey, ensureDeviceId(), analytics, 1500);
|
|
935
|
+
}
|
|
936
|
+
} catch (err) {
|
|
937
|
+
process.stderr.write(
|
|
938
|
+
`[maind-mcp-bridge] session-analytics failed: ${err instanceof Error ? err.message : String(err)}
|
|
494
939
|
`
|
|
495
|
-
|
|
940
|
+
);
|
|
941
|
+
}
|
|
496
942
|
}
|
|
943
|
+
await runSessionEndMetrics(sessionId);
|
|
497
944
|
return 0;
|
|
498
945
|
}
|
|
499
946
|
var INGEST_ENDPOINT;
|
|
@@ -502,13 +949,16 @@ var init_session_end = __esm({
|
|
|
502
949
|
"use strict";
|
|
503
950
|
init_dist();
|
|
504
951
|
init_device_id();
|
|
952
|
+
init_api();
|
|
953
|
+
init_hook_input();
|
|
954
|
+
init_hooks();
|
|
505
955
|
init_version();
|
|
506
|
-
INGEST_ENDPOINT =
|
|
956
|
+
INGEST_ENDPOINT = DEFAULT_INGEST_ENDPOINT;
|
|
507
957
|
}
|
|
508
958
|
});
|
|
509
959
|
|
|
510
960
|
// src/index.ts
|
|
511
|
-
import { randomUUID as
|
|
961
|
+
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
512
962
|
|
|
513
963
|
// src/forward.ts
|
|
514
964
|
import { createInterface } from "node:readline";
|
|
@@ -701,6 +1151,11 @@ var Forwarder = class {
|
|
|
701
1151
|
projectKey;
|
|
702
1152
|
/** Local codebase-index tool router, or null when the feature is disabled. */
|
|
703
1153
|
localRouter;
|
|
1154
|
+
/** Auto-presence announcer (ADR-242), or null when disabled. */
|
|
1155
|
+
presence;
|
|
1156
|
+
/** Monotonic counter for presence-frame JSON-RPC ids (string-namespaced so
|
|
1157
|
+
* they can never collide with the local client's numeric ids). */
|
|
1158
|
+
presenceFrameId = 0;
|
|
704
1159
|
/** Set by the first response that carries an Mcp-Session-Id header. */
|
|
705
1160
|
sessionId = null;
|
|
706
1161
|
/**
|
|
@@ -737,6 +1192,7 @@ var Forwarder = class {
|
|
|
737
1192
|
const rawKey = (cfg.projectKey ?? null)?.trim().toLowerCase() ?? null;
|
|
738
1193
|
this.projectKey = rawKey && /^[a-f0-9]{64}$/.test(rawKey) ? rawKey : null;
|
|
739
1194
|
this.localRouter = cfg.localRouter ?? null;
|
|
1195
|
+
this.presence = cfg.presence ?? null;
|
|
740
1196
|
this.mcpUrl = cfg.mcpUrl ?? process.env.MAIND_MCP_URL ?? DEFAULT_MCP_URL;
|
|
741
1197
|
}
|
|
742
1198
|
/**
|
|
@@ -771,6 +1227,9 @@ var Forwarder = class {
|
|
|
771
1227
|
this.initFrame = frame;
|
|
772
1228
|
}
|
|
773
1229
|
const parsed = parseRpc(frame);
|
|
1230
|
+
if (parsed?.method === "tools/call") {
|
|
1231
|
+
this.presence?.onActivity();
|
|
1232
|
+
}
|
|
774
1233
|
if (this.localRouter && this.localRouter.handlesToolCall(parsed?.method, parsed?.params)) {
|
|
775
1234
|
const out = await this.localRouter.handleToolCall(parsed?.id ?? null, parsed?.params);
|
|
776
1235
|
process.stdout.write(out + "\n");
|
|
@@ -836,6 +1295,7 @@ var Forwarder = class {
|
|
|
836
1295
|
if (isInitializeRequest(frame)) {
|
|
837
1296
|
const body = contentType.startsWith("text/event-stream") ? await collectSseText(response) : await response.text();
|
|
838
1297
|
this.cacheInitializeResult(body);
|
|
1298
|
+
this.presence?.onSessionReady();
|
|
839
1299
|
if (body.trim().length > 0) {
|
|
840
1300
|
process.stdout.write(body + "\n");
|
|
841
1301
|
}
|
|
@@ -869,6 +1329,37 @@ var Forwarder = class {
|
|
|
869
1329
|
const id = tryExtractId(frame);
|
|
870
1330
|
emitJsonRpcError(id, -32001, `bridge auth error: ${body.slice(0, 200)}`);
|
|
871
1331
|
}
|
|
1332
|
+
/**
|
|
1333
|
+
* Auto-presence transport (ADR-242): post a self-generated `tools/call` on
|
|
1334
|
+
* the forwarder's EXISTING MCP session. The response is drained and NEVER
|
|
1335
|
+
* written to stdout — the local client must not see frames it didn't send.
|
|
1336
|
+
* String-namespaced ids keep the frame disjoint from the client's numeric
|
|
1337
|
+
* JSON-RPC ids. Riding the shared session (instead of opening a second one)
|
|
1338
|
+
* keeps the server's session accounting honest AND carries the detected
|
|
1339
|
+
* client-family headers, so the announce row shows the real client.
|
|
1340
|
+
* Throws on any failure — the announcer turns that into backoff, fail-open.
|
|
1341
|
+
*/
|
|
1342
|
+
async postPresenceToolCall(name, args) {
|
|
1343
|
+
if (this.sessionId === null) {
|
|
1344
|
+
throw new Error("presence: no MCP session established yet");
|
|
1345
|
+
}
|
|
1346
|
+
this.presenceFrameId += 1;
|
|
1347
|
+
const frame = JSON.stringify({
|
|
1348
|
+
jsonrpc: "2.0",
|
|
1349
|
+
id: `maind-presence-${this.presenceFrameId}`,
|
|
1350
|
+
method: "tools/call",
|
|
1351
|
+
params: { name, arguments: args }
|
|
1352
|
+
});
|
|
1353
|
+
const response = await fetch(this.mcpUrl, {
|
|
1354
|
+
method: "POST",
|
|
1355
|
+
headers: this.buildHeaders(true),
|
|
1356
|
+
body: frame
|
|
1357
|
+
});
|
|
1358
|
+
await response.text().catch(() => "");
|
|
1359
|
+
if (!response.ok) {
|
|
1360
|
+
throw new Error(`presence: upstream HTTP ${response.status}`);
|
|
1361
|
+
}
|
|
1362
|
+
}
|
|
872
1363
|
/**
|
|
873
1364
|
* Build the outbound header set. `includeSession` attaches the current
|
|
874
1365
|
* Mcp-Session-Id (when set) — pass false for the recovery initialize, which
|
|
@@ -1413,9 +1904,9 @@ function printInstallHelp() {
|
|
|
1413
1904
|
"",
|
|
1414
1905
|
"Common flags:",
|
|
1415
1906
|
" --project-root <path> Override project-root detection (default: walk up from cwd)",
|
|
1416
|
-
" --full Non-interactive full setup (includes ~/.claude/settings.json
|
|
1907
|
+
" --full Non-interactive full setup (includes the ~/.claude/settings.json hooks)",
|
|
1417
1908
|
" --no-preamble Skip the 5 preamble files (MCP-config + pairing only)",
|
|
1418
|
-
" --no-hook Never write the
|
|
1909
|
+
" --no-hook Never write the Claude Code hooks (overrides --full for hooks)",
|
|
1419
1910
|
" --non-interactive Skip every TTY prompt (used by CI / Dashboard-One-Click)",
|
|
1420
1911
|
" --token <jwt> Use a pre-issued one-click token instead of browser pairing",
|
|
1421
1912
|
" --client <family> Install only for one client family (claude-code, cursor, ...)",
|
|
@@ -1617,12 +2108,79 @@ Which one should receive the MCP config and preamble files? [1-${candidates.leng
|
|
|
1617
2108
|
}
|
|
1618
2109
|
|
|
1619
2110
|
// src/install/client-targets.ts
|
|
1620
|
-
import * as
|
|
2111
|
+
import * as path3 from "node:path";
|
|
2112
|
+
|
|
2113
|
+
// src/install/bridge-entry.ts
|
|
2114
|
+
import path2 from "node:path";
|
|
2115
|
+
import { fileURLToPath } from "node:url";
|
|
2116
|
+
var NPX_PACKAGE = "@maind-dev/mcp-bridge";
|
|
2117
|
+
function isEphemeralEntry(entryPath, sep2 = path2.sep) {
|
|
2118
|
+
return entryPath.split(sep2).includes("_npx");
|
|
2119
|
+
}
|
|
2120
|
+
function resolveBridgeLaunch(opts) {
|
|
2121
|
+
const extra = opts.extraArgs ?? [];
|
|
2122
|
+
const npx = (reason) => ({
|
|
2123
|
+
command: "npx",
|
|
2124
|
+
args: ["-y", NPX_PACKAGE, ...extra],
|
|
2125
|
+
env: {},
|
|
2126
|
+
fallbackReason: reason
|
|
2127
|
+
});
|
|
2128
|
+
if (opts.entryPath === null) {
|
|
2129
|
+
return npx("bridge entry path could not be resolved");
|
|
2130
|
+
}
|
|
2131
|
+
if (isEphemeralEntry(opts.entryPath, opts.sep)) {
|
|
2132
|
+
return npx("bridge is running from the npx cache (install it globally to pin a path)");
|
|
2133
|
+
}
|
|
2134
|
+
if (!opts.nodePath) {
|
|
2135
|
+
return npx("node executable path unavailable");
|
|
2136
|
+
}
|
|
2137
|
+
return {
|
|
2138
|
+
command: opts.nodePath,
|
|
2139
|
+
args: [opts.entryPath, ...extra],
|
|
2140
|
+
env: opts.isElectron ? { ELECTRON_RUN_AS_NODE: "1" } : {},
|
|
2141
|
+
fallbackReason: null
|
|
2142
|
+
};
|
|
2143
|
+
}
|
|
2144
|
+
function currentBridgeEntry() {
|
|
2145
|
+
try {
|
|
2146
|
+
const here = fileURLToPath(import.meta.url);
|
|
2147
|
+
return here.endsWith(".js") ? here : null;
|
|
2148
|
+
} catch {
|
|
2149
|
+
return null;
|
|
2150
|
+
}
|
|
2151
|
+
}
|
|
2152
|
+
function launchToShellCommand(launch) {
|
|
2153
|
+
const assignments = Object.entries(launch.env).map(
|
|
2154
|
+
([k, v]) => `${k}=${shellQuote(v)}`
|
|
2155
|
+
);
|
|
2156
|
+
return [...assignments, launch.command, ...launch.args].map((part, i) => i < assignments.length ? part : shellQuote(part)).join(" ");
|
|
2157
|
+
}
|
|
2158
|
+
function isNpxForm(command) {
|
|
2159
|
+
return /(^|\s)npx(\s|$)/.test(command) && command.includes(NPX_PACKAGE);
|
|
2160
|
+
}
|
|
2161
|
+
function isLegacyHookForm(command) {
|
|
2162
|
+
return /(^|[\s/])maind-hook(\s|$)/.test(command);
|
|
2163
|
+
}
|
|
2164
|
+
function shellQuote(value) {
|
|
2165
|
+
if (/^[A-Za-z0-9_@%+=:,./-]+$/.test(value)) return value;
|
|
2166
|
+
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
2167
|
+
}
|
|
2168
|
+
|
|
2169
|
+
// src/install/client-targets.ts
|
|
1621
2170
|
function buildMaindServerEntry(opts) {
|
|
2171
|
+
const launch = opts.launch ?? resolveBridgeLaunch({
|
|
2172
|
+
entryPath: currentBridgeEntry(),
|
|
2173
|
+
nodePath: process.execPath,
|
|
2174
|
+
isElectron: process.versions.electron !== void 0
|
|
2175
|
+
});
|
|
1622
2176
|
return {
|
|
1623
|
-
command:
|
|
1624
|
-
args:
|
|
2177
|
+
command: launch.command,
|
|
2178
|
+
args: launch.args,
|
|
1625
2179
|
env: {
|
|
2180
|
+
// launch.env first: it carries interpreter requirements (ELECTRON_RUN_AS_NODE),
|
|
2181
|
+
// and the maind settings below must stay authoritative over anything a
|
|
2182
|
+
// future launch flavour might name the same way.
|
|
2183
|
+
...launch.env,
|
|
1626
2184
|
MAIND_CLIENT_FAMILY: opts.clientFamily,
|
|
1627
2185
|
MAIND_MCP_URL: opts.mcpUrl
|
|
1628
2186
|
}
|
|
@@ -1631,7 +2189,7 @@ function buildMaindServerEntry(opts) {
|
|
|
1631
2189
|
function claudeDesktopConfigPath(ctx) {
|
|
1632
2190
|
switch (ctx.platform) {
|
|
1633
2191
|
case "darwin":
|
|
1634
|
-
return
|
|
2192
|
+
return path3.join(
|
|
1635
2193
|
ctx.homeDir,
|
|
1636
2194
|
"Library",
|
|
1637
2195
|
"Application Support",
|
|
@@ -1639,12 +2197,12 @@ function claudeDesktopConfigPath(ctx) {
|
|
|
1639
2197
|
"claude_desktop_config.json"
|
|
1640
2198
|
);
|
|
1641
2199
|
case "win32": {
|
|
1642
|
-
const appData = ctx.appData ??
|
|
1643
|
-
return
|
|
2200
|
+
const appData = ctx.appData ?? path3.join(ctx.homeDir, "AppData", "Roaming");
|
|
2201
|
+
return path3.join(appData, "Claude", "claude_desktop_config.json");
|
|
1644
2202
|
}
|
|
1645
2203
|
default: {
|
|
1646
|
-
const xdg = ctx.xdgConfigHome ??
|
|
1647
|
-
return
|
|
2204
|
+
const xdg = ctx.xdgConfigHome ?? path3.join(ctx.homeDir, ".config");
|
|
2205
|
+
return path3.join(xdg, "Claude", "claude_desktop_config.json");
|
|
1648
2206
|
}
|
|
1649
2207
|
}
|
|
1650
2208
|
}
|
|
@@ -1655,7 +2213,7 @@ function getClientTargets(ctx) {
|
|
|
1655
2213
|
label: "Claude Code (project-scoped .mcp.json)",
|
|
1656
2214
|
clientFamilyEnv: "claude-code",
|
|
1657
2215
|
scope: "project",
|
|
1658
|
-
path:
|
|
2216
|
+
path: path3.join(ctx.projectRoot, ".mcp.json"),
|
|
1659
2217
|
kind: "json"
|
|
1660
2218
|
},
|
|
1661
2219
|
{
|
|
@@ -1663,7 +2221,7 @@ function getClientTargets(ctx) {
|
|
|
1663
2221
|
label: "Claude Code (user-scoped ~/.claude.json)",
|
|
1664
2222
|
clientFamilyEnv: "claude-code",
|
|
1665
2223
|
scope: "user",
|
|
1666
|
-
path:
|
|
2224
|
+
path: path3.join(ctx.homeDir, ".claude.json"),
|
|
1667
2225
|
kind: "json"
|
|
1668
2226
|
},
|
|
1669
2227
|
{
|
|
@@ -1679,7 +2237,7 @@ function getClientTargets(ctx) {
|
|
|
1679
2237
|
label: "Cursor (~/.cursor/mcp.json)",
|
|
1680
2238
|
clientFamilyEnv: "cursor",
|
|
1681
2239
|
scope: "user",
|
|
1682
|
-
path:
|
|
2240
|
+
path: path3.join(ctx.homeDir, ".cursor", "mcp.json"),
|
|
1683
2241
|
kind: "json"
|
|
1684
2242
|
},
|
|
1685
2243
|
{
|
|
@@ -1687,7 +2245,7 @@ function getClientTargets(ctx) {
|
|
|
1687
2245
|
label: "Windsurf (~/.codeium/windsurf/mcp_config.json)",
|
|
1688
2246
|
clientFamilyEnv: "windsurf",
|
|
1689
2247
|
scope: "user",
|
|
1690
|
-
path:
|
|
2248
|
+
path: path3.join(ctx.homeDir, ".codeium", "windsurf", "mcp_config.json"),
|
|
1691
2249
|
kind: "json"
|
|
1692
2250
|
},
|
|
1693
2251
|
{
|
|
@@ -1695,7 +2253,7 @@ function getClientTargets(ctx) {
|
|
|
1695
2253
|
label: "Codex CLI (~/.codex/config.toml)",
|
|
1696
2254
|
clientFamilyEnv: "codex",
|
|
1697
2255
|
scope: "user",
|
|
1698
|
-
path:
|
|
2256
|
+
path: path3.join(ctx.homeDir, ".codex", "config.toml"),
|
|
1699
2257
|
kind: "toml"
|
|
1700
2258
|
}
|
|
1701
2259
|
];
|
|
@@ -1722,7 +2280,7 @@ function nonEmpty(v) {
|
|
|
1722
2280
|
|
|
1723
2281
|
// src/install/atomic-write.ts
|
|
1724
2282
|
import * as fs2 from "node:fs/promises";
|
|
1725
|
-
import * as
|
|
2283
|
+
import * as path4 from "node:path";
|
|
1726
2284
|
async function readFileSafe(filepath) {
|
|
1727
2285
|
try {
|
|
1728
2286
|
return await fs2.readFile(filepath, "utf8");
|
|
@@ -1735,9 +2293,9 @@ async function ensureDir2(dir) {
|
|
|
1735
2293
|
await fs2.mkdir(dir, { recursive: true });
|
|
1736
2294
|
}
|
|
1737
2295
|
async function atomicWriteFile(filepath, content, mode) {
|
|
1738
|
-
const dir =
|
|
2296
|
+
const dir = path4.dirname(filepath);
|
|
1739
2297
|
await ensureDir2(dir);
|
|
1740
|
-
const tmp =
|
|
2298
|
+
const tmp = path4.join(
|
|
1741
2299
|
dir,
|
|
1742
2300
|
`.maind-install-${process.pid}-${Date.now()}.tmp`
|
|
1743
2301
|
);
|
|
@@ -2026,7 +2584,7 @@ function failed2(target, phase, err) {
|
|
|
2026
2584
|
}
|
|
2027
2585
|
|
|
2028
2586
|
// src/install/preamble.ts
|
|
2029
|
-
import * as
|
|
2587
|
+
import * as path5 from "node:path";
|
|
2030
2588
|
|
|
2031
2589
|
// ../../packages/integration-snippets/build/index.js
|
|
2032
2590
|
var STACK_PLACEHOLDER_TOKEN = "__STACK__";
|
|
@@ -2733,32 +3291,32 @@ function buildPreambleTargets(ctx) {
|
|
|
2733
3291
|
return [
|
|
2734
3292
|
{
|
|
2735
3293
|
key: "preamble:CLAUDE.md",
|
|
2736
|
-
path:
|
|
3294
|
+
path: path5.join(ctx.projectRoot, "CLAUDE.md"),
|
|
2737
3295
|
mayNeedParentDir: false
|
|
2738
3296
|
},
|
|
2739
3297
|
{
|
|
2740
3298
|
key: "preamble:AGENTS.md",
|
|
2741
|
-
path:
|
|
3299
|
+
path: path5.join(ctx.projectRoot, "AGENTS.md"),
|
|
2742
3300
|
mayNeedParentDir: false
|
|
2743
3301
|
},
|
|
2744
3302
|
{
|
|
2745
3303
|
key: "preamble:.github/copilot-instructions.md",
|
|
2746
|
-
path:
|
|
3304
|
+
path: path5.join(ctx.projectRoot, ".github", "copilot-instructions.md"),
|
|
2747
3305
|
mayNeedParentDir: true
|
|
2748
3306
|
},
|
|
2749
3307
|
{
|
|
2750
3308
|
key: "preamble:.cursorrules",
|
|
2751
|
-
path:
|
|
3309
|
+
path: path5.join(ctx.projectRoot, ".cursorrules"),
|
|
2752
3310
|
mayNeedParentDir: false
|
|
2753
3311
|
},
|
|
2754
3312
|
{
|
|
2755
3313
|
key: "preamble:.windsurfrules",
|
|
2756
|
-
path:
|
|
3314
|
+
path: path5.join(ctx.projectRoot, ".windsurfrules"),
|
|
2757
3315
|
mayNeedParentDir: false
|
|
2758
3316
|
},
|
|
2759
3317
|
{
|
|
2760
3318
|
key: "preamble:~/.claude/maind-session-start-reminder.md",
|
|
2761
|
-
path:
|
|
3319
|
+
path: path5.join(ctx.homeDir, ".claude", "maind-session-start-reminder.md"),
|
|
2762
3320
|
mayNeedParentDir: true
|
|
2763
3321
|
}
|
|
2764
3322
|
];
|
|
@@ -2774,7 +3332,7 @@ async function writePreambleFiles(ctx, dryRun = false) {
|
|
|
2774
3332
|
async function writeOnePreambleFile(target, dryRun) {
|
|
2775
3333
|
try {
|
|
2776
3334
|
if (target.mayNeedParentDir && !dryRun) {
|
|
2777
|
-
await ensureDir2(
|
|
3335
|
+
await ensureDir2(path5.dirname(target.path));
|
|
2778
3336
|
}
|
|
2779
3337
|
const alreadyPresent = await hasLinePrefix(target.path, PREAMBLE_HEADER_PREFIX);
|
|
2780
3338
|
if (alreadyPresent) {
|
|
@@ -2821,11 +3379,11 @@ function ensureTrailingBlankLine(content) {
|
|
|
2821
3379
|
}
|
|
2822
3380
|
|
|
2823
3381
|
// src/install/hook-merge.ts
|
|
2824
|
-
import * as
|
|
3382
|
+
import * as path6 from "node:path";
|
|
2825
3383
|
import * as readline2 from "node:readline";
|
|
2826
3384
|
var REMINDER_FILE_REL = ".claude/maind-session-start-reminder.md";
|
|
2827
3385
|
async function mergeClaudeHook(opts, spec) {
|
|
2828
|
-
const settingsPath =
|
|
3386
|
+
const settingsPath = path6.join(opts.homeDir, ".claude", "settings.json");
|
|
2829
3387
|
const targetKey = spec.targetKey;
|
|
2830
3388
|
if (opts.skip) {
|
|
2831
3389
|
return { target: targetKey, action: "skip", status: "skipped", detail: "--no-hook" };
|
|
@@ -2857,8 +3415,9 @@ async function mergeClaudeHook(opts, spec) {
|
|
|
2857
3415
|
return { target: targetKey, action: "merge", status: "failed", detail: `parse: ${errMessage(err)}` };
|
|
2858
3416
|
}
|
|
2859
3417
|
}
|
|
2860
|
-
|
|
2861
|
-
|
|
3418
|
+
const existing = findExistingHookCommand(settings, spec.event, spec.matchPattern);
|
|
3419
|
+
if (existing !== null) {
|
|
3420
|
+
return { target: targetKey, action: "skip", status: "skipped", detail: spec.skipDetail(existing) };
|
|
2862
3421
|
}
|
|
2863
3422
|
if (!opts.full) {
|
|
2864
3423
|
if (!opts.isInteractive) {
|
|
@@ -2921,33 +3480,77 @@ ${spec.consentDescription}
|
|
|
2921
3480
|
};
|
|
2922
3481
|
}
|
|
2923
3482
|
async function mergeSessionStartHook(opts) {
|
|
2924
|
-
const reminderPath =
|
|
3483
|
+
const reminderPath = path6.join(opts.homeDir, REMINDER_FILE_REL);
|
|
2925
3484
|
return mergeClaudeHook(opts, {
|
|
2926
3485
|
event: "SessionStart",
|
|
2927
3486
|
command: `cat ${reminderPath}`,
|
|
2928
3487
|
timeout: 5,
|
|
2929
3488
|
matchPattern: /maind-session-start-reminder\.md/,
|
|
2930
3489
|
targetKey: "hook:~/.claude/settings.json",
|
|
2931
|
-
|
|
3490
|
+
skipDetail: () => "SessionStart hook already references the reminder file",
|
|
2932
3491
|
consentDescription: `It 'cat's ${REMINDER_FILE_REL} into every new Claude Code session.`
|
|
2933
3492
|
});
|
|
2934
3493
|
}
|
|
2935
|
-
async function
|
|
3494
|
+
async function mergeSubcommandHook(opts, spec) {
|
|
3495
|
+
const launch = opts.launch ?? resolveBridgeLaunch({
|
|
3496
|
+
entryPath: currentBridgeEntry(),
|
|
3497
|
+
nodePath: process.execPath,
|
|
3498
|
+
extraArgs: [spec.subcommand],
|
|
3499
|
+
isElectron: process.versions.electron !== void 0
|
|
3500
|
+
});
|
|
3501
|
+
const command = launchToShellCommand(launch);
|
|
2936
3502
|
return mergeClaudeHook(opts, {
|
|
3503
|
+
event: spec.event,
|
|
3504
|
+
command,
|
|
3505
|
+
timeout: spec.timeout,
|
|
3506
|
+
matchPattern: new RegExp(spec.subcommand),
|
|
3507
|
+
targetKey: spec.targetKey,
|
|
3508
|
+
skipDetail: (existing) => {
|
|
3509
|
+
const wired = `${spec.label} already runs maind ${spec.subcommand}`;
|
|
3510
|
+
if (isLegacyHookForm(existing)) {
|
|
3511
|
+
return `${wired}, but via the retired \`maind-hook\` binary \u2014 the bridge now owns that subcommand and \`maind-hook\` is no longer published. Replace its command with: ${command}`;
|
|
3512
|
+
}
|
|
3513
|
+
if (isNpxForm(existing)) {
|
|
3514
|
+
return `${wired}, but via \`npx\` \u2014 which resolves through PATH and npm's per-Node-version globals. Replace its command with: ${command}`;
|
|
3515
|
+
}
|
|
3516
|
+
return wired;
|
|
3517
|
+
},
|
|
3518
|
+
consentDescription: spec.consentDescription
|
|
3519
|
+
});
|
|
3520
|
+
}
|
|
3521
|
+
async function mergeStopHook(opts) {
|
|
3522
|
+
return mergeSubcommandHook(opts, {
|
|
2937
3523
|
event: "Stop",
|
|
2938
|
-
|
|
3524
|
+
subcommand: "on-session-end",
|
|
2939
3525
|
timeout: 10,
|
|
2940
|
-
// Match any on-session-end command so we never double-wire (also covers a
|
|
2941
|
-
// hand-wired node-path hook the user may already have).
|
|
2942
|
-
matchPattern: /on-session-end/,
|
|
2943
3526
|
targetKey: "hook(stop):~/.claude/settings.json",
|
|
2944
|
-
|
|
2945
|
-
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."
|
|
3527
|
+
label: "Stop hook",
|
|
3528
|
+
consentDescription: "It runs 'maind-mcp-bridge on-session-end' \u2014 derives session communication analytics (momentum + reactions) from the transcript at session end, and flushes the session's Tier-3 counters. Gated by Tier-3 consent server-side."
|
|
3529
|
+
});
|
|
3530
|
+
}
|
|
3531
|
+
async function mergeSessionStartMetricsHook(opts) {
|
|
3532
|
+
return mergeSubcommandHook(opts, {
|
|
3533
|
+
event: "SessionStart",
|
|
3534
|
+
subcommand: "on-session-start",
|
|
3535
|
+
timeout: 5,
|
|
3536
|
+
targetKey: "hook(session-start):~/.claude/settings.json",
|
|
3537
|
+
label: "SessionStart hook",
|
|
3538
|
+
consentDescription: "It runs 'maind-mcp-bridge on-session-start' \u2014 opens a tracked session so duration and tool-call counts can be measured. Writes only to ~/.maind/state.json; nothing leaves the machine here."
|
|
2946
3539
|
});
|
|
2947
3540
|
}
|
|
2948
|
-
function
|
|
3541
|
+
async function mergeToolUseHook(opts) {
|
|
3542
|
+
return mergeSubcommandHook(opts, {
|
|
3543
|
+
event: "PreToolUse",
|
|
3544
|
+
subcommand: "on-tool-use",
|
|
3545
|
+
timeout: 5,
|
|
3546
|
+
targetKey: "hook(pre-tool-use):~/.claude/settings.json",
|
|
3547
|
+
label: "PreToolUse hook",
|
|
3548
|
+
consentDescription: "It runs 'maind-mcp-bridge on-tool-use' before every tool call \u2014 counts calls, and warns you on stderr when the session's token usage crosses your handoff thresholds (ADR-039). Only the tool NAME is read, never its arguments."
|
|
3549
|
+
});
|
|
3550
|
+
}
|
|
3551
|
+
function findExistingHookCommand(settings, event, pattern) {
|
|
2949
3552
|
const groups = settings.hooks?.[event];
|
|
2950
|
-
if (!Array.isArray(groups)) return
|
|
3553
|
+
if (!Array.isArray(groups)) return null;
|
|
2951
3554
|
for (const group of groups) {
|
|
2952
3555
|
if (!isObject3(group)) continue;
|
|
2953
3556
|
const hooks = group.hooks;
|
|
@@ -2955,10 +3558,10 @@ function existingHookReferences(settings, event, pattern) {
|
|
|
2955
3558
|
for (const hook of hooks) {
|
|
2956
3559
|
if (!isObject3(hook)) continue;
|
|
2957
3560
|
const cmd = hook.command;
|
|
2958
|
-
if (typeof cmd === "string" && pattern.test(cmd)) return
|
|
3561
|
+
if (typeof cmd === "string" && pattern.test(cmd)) return cmd;
|
|
2959
3562
|
}
|
|
2960
3563
|
}
|
|
2961
|
-
return
|
|
3564
|
+
return null;
|
|
2962
3565
|
}
|
|
2963
3566
|
async function promptYesNo(out, prompt) {
|
|
2964
3567
|
out.write(prompt);
|
|
@@ -3287,6 +3890,8 @@ Skipping remaining steps.
|
|
|
3287
3890
|
out: process.stdout
|
|
3288
3891
|
};
|
|
3289
3892
|
report.add(await mergeSessionStartHook(hookOpts));
|
|
3893
|
+
report.add(await mergeSessionStartMetricsHook(hookOpts));
|
|
3894
|
+
report.add(await mergeToolUseHook(hookOpts));
|
|
3290
3895
|
report.add(await mergeStopHook(hookOpts));
|
|
3291
3896
|
if (!flags.dryRun) {
|
|
3292
3897
|
await postInstallTelemetry({
|
|
@@ -3896,12 +4501,12 @@ function toPosix(p) {
|
|
|
3896
4501
|
function classify(paths) {
|
|
3897
4502
|
const out = [];
|
|
3898
4503
|
for (const raw of paths) {
|
|
3899
|
-
const
|
|
3900
|
-
if (!
|
|
4504
|
+
const path7 = toPosix(raw).trim();
|
|
4505
|
+
if (!path7 || isSkippablePath(path7))
|
|
3901
4506
|
continue;
|
|
3902
|
-
const language = languageForPath(
|
|
4507
|
+
const language = languageForPath(path7);
|
|
3903
4508
|
if (language)
|
|
3904
|
-
out.push({ path:
|
|
4509
|
+
out.push({ path: path7, language });
|
|
3905
4510
|
}
|
|
3906
4511
|
return out;
|
|
3907
4512
|
}
|
|
@@ -4223,18 +4828,18 @@ function readFileHistory(repoRoot, paths, opts = {}) {
|
|
|
4223
4828
|
const cleanPaths = paths.map((p) => p.trim()).filter((p) => p.length > 0 && !p.startsWith(":"));
|
|
4224
4829
|
const scoped = cleanPaths.slice(0, MAX_HISTORY_PATHS);
|
|
4225
4830
|
const history = [];
|
|
4226
|
-
for (const
|
|
4831
|
+
for (const path7 of scoped) {
|
|
4227
4832
|
const raw = runGit(repoRoot, [
|
|
4228
4833
|
"log",
|
|
4229
4834
|
"-n",
|
|
4230
4835
|
String(window),
|
|
4231
4836
|
LOG_FORMAT,
|
|
4232
4837
|
"--",
|
|
4233
|
-
|
|
4838
|
+
path7
|
|
4234
4839
|
]);
|
|
4235
4840
|
const commits = raw === null ? [] : splitRecords(raw).map(parseHistoryRecord).filter((c) => c !== null);
|
|
4236
4841
|
history.push({
|
|
4237
|
-
path:
|
|
4842
|
+
path: path7,
|
|
4238
4843
|
lastCommits: commits.slice(0, limit),
|
|
4239
4844
|
ownership: includeOwnership ? { topAuthors: aggregateOwnership(commits), commitsInWindow: commits.length } : null
|
|
4240
4845
|
});
|
|
@@ -4366,6 +4971,17 @@ function computeDivergence(facts) {
|
|
|
4366
4971
|
hint: "git push"
|
|
4367
4972
|
});
|
|
4368
4973
|
}
|
|
4974
|
+
if (facts.unmergedMigrations.length > 0) {
|
|
4975
|
+
const n = facts.unmergedMigrations.length;
|
|
4976
|
+
out.push({
|
|
4977
|
+
id: "branch.unmerged-migrations",
|
|
4978
|
+
status: "info",
|
|
4979
|
+
scope: "branch",
|
|
4980
|
+
title: "Migrations not yet on the base branch",
|
|
4981
|
+
detail: `${n} migration file(s) added on '${facts.branch}' are not on origin/${facts.defaultBranch} yet \u2014 a cloud DB push run from ${facts.defaultBranch} will NOT include them until this branch is merged.`,
|
|
4982
|
+
hint: `Merge to ${facts.defaultBranch} first (promote), then run 'supabase db push --linked' from ${facts.defaultBranch}.`
|
|
4983
|
+
});
|
|
4984
|
+
}
|
|
4369
4985
|
if (facts.isSharedMainTree && facts.otherWorktrees > 0 && facts.uncommitted > 0 && !onFeatureBranch) {
|
|
4370
4986
|
out.push({
|
|
4371
4987
|
id: "worktree.direct-on-shared-base",
|
|
@@ -4497,7 +5113,8 @@ async function gatherRepoHealthFacts(repoRoot, opts = {}) {
|
|
|
4497
5113
|
isSharedMainTree: false,
|
|
4498
5114
|
otherWorktrees: 0,
|
|
4499
5115
|
worktreeParity: null,
|
|
4500
|
-
release: null
|
|
5116
|
+
release: null,
|
|
5117
|
+
unmergedMigrations: []
|
|
4501
5118
|
};
|
|
4502
5119
|
}
|
|
4503
5120
|
const branchRaw = trimOrNull(runGit(repoRoot, ["rev-parse", "--abbrev-ref", "HEAD"]));
|
|
@@ -4548,6 +5165,18 @@ async function gatherRepoHealthFacts(repoRoot, opts = {}) {
|
|
|
4548
5165
|
};
|
|
4549
5166
|
}
|
|
4550
5167
|
const release2 = opts.includeRelease === false ? null : gatherReleaseFact(repoRoot, branch);
|
|
5168
|
+
let unmergedMigrations = [];
|
|
5169
|
+
if (defaultBranch) {
|
|
5170
|
+
const raw = runGit(repoRoot, [
|
|
5171
|
+
"diff",
|
|
5172
|
+
"--name-only",
|
|
5173
|
+
"--diff-filter=A",
|
|
5174
|
+
`origin/${defaultBranch}...HEAD`,
|
|
5175
|
+
"--",
|
|
5176
|
+
"*supabase/migrations/*.sql"
|
|
5177
|
+
]);
|
|
5178
|
+
unmergedMigrations = (raw ?? "").split("\n").map((l) => l.trim()).filter((l) => l.length > 0);
|
|
5179
|
+
}
|
|
4551
5180
|
return {
|
|
4552
5181
|
isRepo: true,
|
|
4553
5182
|
branch,
|
|
@@ -4563,7 +5192,8 @@ async function gatherRepoHealthFacts(repoRoot, opts = {}) {
|
|
|
4563
5192
|
isSharedMainTree,
|
|
4564
5193
|
otherWorktrees,
|
|
4565
5194
|
worktreeParity,
|
|
4566
|
-
release: release2
|
|
5195
|
+
release: release2,
|
|
5196
|
+
unmergedMigrations
|
|
4567
5197
|
};
|
|
4568
5198
|
}
|
|
4569
5199
|
function samePath(a, b) {
|
|
@@ -4649,11 +5279,11 @@ var RISK_RULES = [
|
|
|
4649
5279
|
// ../../packages/code-index/build/review/risk-scan.js
|
|
4650
5280
|
function scanRiskFlags(input) {
|
|
4651
5281
|
const flags = /* @__PURE__ */ new Set();
|
|
4652
|
-
for (const [
|
|
5282
|
+
for (const [path7, status] of input.paths) {
|
|
4653
5283
|
for (const rule of RISK_RULES) {
|
|
4654
5284
|
if (flags.has(rule.flag))
|
|
4655
5285
|
continue;
|
|
4656
|
-
if (!rule.path.test(
|
|
5286
|
+
if (!rule.path.test(path7))
|
|
4657
5287
|
continue;
|
|
4658
5288
|
if (rule.onlyWhenAdded && status !== "added")
|
|
4659
5289
|
continue;
|
|
@@ -4661,19 +5291,19 @@ function scanRiskFlags(input) {
|
|
|
4661
5291
|
flags.add(rule.flag);
|
|
4662
5292
|
continue;
|
|
4663
5293
|
}
|
|
4664
|
-
const text = contentForPath(
|
|
5294
|
+
const text = contentForPath(path7, input);
|
|
4665
5295
|
if (text !== null && rule.content.test(text))
|
|
4666
5296
|
flags.add(rule.flag);
|
|
4667
5297
|
}
|
|
4668
5298
|
}
|
|
4669
5299
|
return [...flags].sort();
|
|
4670
5300
|
}
|
|
4671
|
-
function contentForPath(
|
|
4672
|
-
const hunks = input.hunks.get(
|
|
5301
|
+
function contentForPath(path7, input) {
|
|
5302
|
+
const hunks = input.hunks.get(path7);
|
|
4673
5303
|
if (hunks && !hunks.wholeFile && !hunks.degraded) {
|
|
4674
5304
|
return hunks.addedLines.join("\n");
|
|
4675
5305
|
}
|
|
4676
|
-
return input.readUntracked(
|
|
5306
|
+
return input.readUntracked(path7);
|
|
4677
5307
|
}
|
|
4678
5308
|
|
|
4679
5309
|
// ../../packages/code-index/build/store/schema.js
|
|
@@ -5240,8 +5870,8 @@ var NodeSqliteStore = class {
|
|
|
5240
5870
|
indexedAt: r.indexed_at
|
|
5241
5871
|
}));
|
|
5242
5872
|
}
|
|
5243
|
-
async getFile(
|
|
5244
|
-
const r = this.db.prepare("SELECT * FROM files WHERE path = ?").get(
|
|
5873
|
+
async getFile(path7) {
|
|
5874
|
+
const r = this.db.prepare("SELECT * FROM files WHERE path = ?").get(path7);
|
|
5245
5875
|
if (!r)
|
|
5246
5876
|
return null;
|
|
5247
5877
|
return {
|
|
@@ -5269,10 +5899,10 @@ var NodeSqliteStore = class {
|
|
|
5269
5899
|
});
|
|
5270
5900
|
tx();
|
|
5271
5901
|
}
|
|
5272
|
-
async deleteFile(
|
|
5902
|
+
async deleteFile(path7) {
|
|
5273
5903
|
const tx = this.db.transaction(() => {
|
|
5274
|
-
this.deleteFileGraph(
|
|
5275
|
-
this.db.prepare("DELETE FROM files WHERE path = ?").run(
|
|
5904
|
+
this.deleteFileGraph(path7);
|
|
5905
|
+
this.db.prepare("DELETE FROM files WHERE path = ?").run(path7);
|
|
5276
5906
|
});
|
|
5277
5907
|
tx();
|
|
5278
5908
|
}
|
|
@@ -5300,8 +5930,8 @@ var NodeSqliteStore = class {
|
|
|
5300
5930
|
const r = this.db.prepare("SELECT * FROM nodes WHERE node_key = ?").get(nodeKey);
|
|
5301
5931
|
return r ? toNodeRow(r) : null;
|
|
5302
5932
|
}
|
|
5303
|
-
async getNodesByFile(
|
|
5304
|
-
const rows = this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(
|
|
5933
|
+
async getNodesByFile(path7) {
|
|
5934
|
+
const rows = this.db.prepare("SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line").all(path7);
|
|
5305
5935
|
return rows.map(toNodeRow);
|
|
5306
5936
|
}
|
|
5307
5937
|
async getNodesByKinds(kinds) {
|
|
@@ -5417,8 +6047,8 @@ var NodeSqliteStore = class {
|
|
|
5417
6047
|
}));
|
|
5418
6048
|
}
|
|
5419
6049
|
// ── internal helpers ──
|
|
5420
|
-
deleteFileGraph(
|
|
5421
|
-
const keys = this.db.prepare("SELECT node_key FROM nodes WHERE file_path = ?").all(
|
|
6050
|
+
deleteFileGraph(path7) {
|
|
6051
|
+
const keys = this.db.prepare("SELECT node_key FROM nodes WHERE file_path = ?").all(path7).map((r) => r.node_key);
|
|
5422
6052
|
const delEdge = this.db.prepare("DELETE FROM edges WHERE src_key = ?");
|
|
5423
6053
|
const delFts = this.db.prepare("DELETE FROM nodes_fts WHERE node_key = ?");
|
|
5424
6054
|
for (let i = 0; i < keys.length; i += CHUNK) {
|
|
@@ -5427,7 +6057,7 @@ var NodeSqliteStore = class {
|
|
|
5427
6057
|
delFts.run(k);
|
|
5428
6058
|
}
|
|
5429
6059
|
}
|
|
5430
|
-
this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(
|
|
6060
|
+
this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(path7);
|
|
5431
6061
|
}
|
|
5432
6062
|
_insNode = null;
|
|
5433
6063
|
insertNodeStmt() {
|
|
@@ -6120,8 +6750,194 @@ async function postSavingsMetric(input) {
|
|
|
6120
6750
|
}
|
|
6121
6751
|
}
|
|
6122
6752
|
|
|
6753
|
+
// src/presence.ts
|
|
6754
|
+
import { execFile } from "node:child_process";
|
|
6755
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
6756
|
+
|
|
6757
|
+
// src/bridge-config.ts
|
|
6758
|
+
init_device_id();
|
|
6759
|
+
import { existsSync as existsSync3, readFileSync as readFileSync6 } from "node:fs";
|
|
6760
|
+
import { join as join11 } from "node:path";
|
|
6761
|
+
function bridgeConfigPath() {
|
|
6762
|
+
return join11(configDir(), "config.json");
|
|
6763
|
+
}
|
|
6764
|
+
function readBridgeConfig() {
|
|
6765
|
+
try {
|
|
6766
|
+
const file = bridgeConfigPath();
|
|
6767
|
+
if (!existsSync3(file)) return null;
|
|
6768
|
+
const raw = JSON.parse(readFileSync6(file, "utf8"));
|
|
6769
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
6770
|
+
return null;
|
|
6771
|
+
}
|
|
6772
|
+
const o = raw;
|
|
6773
|
+
const config = {};
|
|
6774
|
+
if (typeof o.auto_announce === "boolean") {
|
|
6775
|
+
config.auto_announce = o.auto_announce;
|
|
6776
|
+
}
|
|
6777
|
+
if (typeof o.machine_label === "string") {
|
|
6778
|
+
config.machine_label = o.machine_label;
|
|
6779
|
+
}
|
|
6780
|
+
return config;
|
|
6781
|
+
} catch {
|
|
6782
|
+
return null;
|
|
6783
|
+
}
|
|
6784
|
+
}
|
|
6785
|
+
|
|
6786
|
+
// src/presence.ts
|
|
6787
|
+
var REFRESH_THROTTLE_MS = 45e3;
|
|
6788
|
+
var TTL_MINUTES = 120;
|
|
6789
|
+
var BACKOFF_BASE_MS = 3e4;
|
|
6790
|
+
var BACKOFF_CAP_MS = 15 * 6e4;
|
|
6791
|
+
var END_TIMEOUT_MS = 1500;
|
|
6792
|
+
var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
6793
|
+
function resolveClientSessionId(env) {
|
|
6794
|
+
const fromEnv = (env.MAIND_SESSION_ID ?? "").trim().toLowerCase();
|
|
6795
|
+
return UUID_RE2.test(fromEnv) ? fromEnv : randomUUID2();
|
|
6796
|
+
}
|
|
6797
|
+
function autoAnnounceDisabled(env, config) {
|
|
6798
|
+
const raw = (env.MAIND_AUTO_ANNOUNCE ?? "").trim().toLowerCase();
|
|
6799
|
+
if (raw === "off" || raw === "0" || raw === "false") return true;
|
|
6800
|
+
return config?.auto_announce === false;
|
|
6801
|
+
}
|
|
6802
|
+
var PresenceAnnouncer = class {
|
|
6803
|
+
projectKey;
|
|
6804
|
+
postToolCall;
|
|
6805
|
+
now;
|
|
6806
|
+
gitBranch;
|
|
6807
|
+
log;
|
|
6808
|
+
machineLabel;
|
|
6809
|
+
enabled;
|
|
6810
|
+
sessionId;
|
|
6811
|
+
lastAnnounceAt = 0;
|
|
6812
|
+
inFlight = false;
|
|
6813
|
+
consecutiveFailures = 0;
|
|
6814
|
+
nextAttemptAt = 0;
|
|
6815
|
+
ended = false;
|
|
6816
|
+
constructor(deps) {
|
|
6817
|
+
const env = deps.env ?? process.env;
|
|
6818
|
+
const config = (deps.readConfig ?? readBridgeConfig)();
|
|
6819
|
+
this.projectKey = deps.projectKey;
|
|
6820
|
+
this.postToolCall = deps.postToolCall;
|
|
6821
|
+
this.now = deps.now ?? Date.now;
|
|
6822
|
+
this.gitBranch = deps.gitBranch ?? defaultGitBranch;
|
|
6823
|
+
this.log = deps.log ?? ((msg) => process.stderr.write(msg + "\n"));
|
|
6824
|
+
this.machineLabel = normalizeMachineLabel(config?.machine_label);
|
|
6825
|
+
this.enabled = this.projectKey !== null && !autoAnnounceDisabled(env, config);
|
|
6826
|
+
this.sessionId = resolveClientSessionId(env);
|
|
6827
|
+
}
|
|
6828
|
+
get isEnabled() {
|
|
6829
|
+
return this.enabled;
|
|
6830
|
+
}
|
|
6831
|
+
/**
|
|
6832
|
+
* Called once the forwarder's MCP session is established (initialize
|
|
6833
|
+
* response captured). Fires the first announce — the session becomes visible
|
|
6834
|
+
* on /planning without any agent involvement (C1).
|
|
6835
|
+
*/
|
|
6836
|
+
onSessionReady() {
|
|
6837
|
+
if (!this.enabled || this.ended) return;
|
|
6838
|
+
if (this.lastAnnounceAt > 0) return;
|
|
6839
|
+
void this.announce("active");
|
|
6840
|
+
}
|
|
6841
|
+
/**
|
|
6842
|
+
* Called on every real tool-call passing through the bridge. Throttled
|
|
6843
|
+
* re-announce keeps the session fresh WHILE it is actually working; an idle
|
|
6844
|
+
* session stops refreshing and goes stale on the renderer — honest freshness.
|
|
6845
|
+
*/
|
|
6846
|
+
onActivity() {
|
|
6847
|
+
if (!this.enabled || this.ended) return;
|
|
6848
|
+
if (this.lastAnnounceAt === 0) return;
|
|
6849
|
+
if (this.now() - this.lastAnnounceAt < REFRESH_THROTTLE_MS) return;
|
|
6850
|
+
void this.announce("active");
|
|
6851
|
+
}
|
|
6852
|
+
/**
|
|
6853
|
+
* Best-effort `status:'ended'` on shutdown, bounded by END_TIMEOUT_MS so it
|
|
6854
|
+
* can never hold the process open. The server TTL is the fallback.
|
|
6855
|
+
*/
|
|
6856
|
+
async end() {
|
|
6857
|
+
if (!this.enabled || this.ended) return;
|
|
6858
|
+
this.ended = true;
|
|
6859
|
+
if (this.lastAnnounceAt === 0) return;
|
|
6860
|
+
const timeout = new Promise(
|
|
6861
|
+
(resolve2) => setTimeout(resolve2, END_TIMEOUT_MS).unref()
|
|
6862
|
+
);
|
|
6863
|
+
await Promise.race([this.send("ended"), timeout]);
|
|
6864
|
+
}
|
|
6865
|
+
async announce(status) {
|
|
6866
|
+
if (this.inFlight) return;
|
|
6867
|
+
if (this.now() < this.nextAttemptAt) return;
|
|
6868
|
+
this.inFlight = true;
|
|
6869
|
+
try {
|
|
6870
|
+
await this.send(status);
|
|
6871
|
+
if (this.consecutiveFailures > 0) {
|
|
6872
|
+
this.log("[maind-mcp-bridge] presence announce recovered.");
|
|
6873
|
+
}
|
|
6874
|
+
this.consecutiveFailures = 0;
|
|
6875
|
+
this.nextAttemptAt = 0;
|
|
6876
|
+
this.lastAnnounceAt = this.now();
|
|
6877
|
+
} catch (err) {
|
|
6878
|
+
this.consecutiveFailures += 1;
|
|
6879
|
+
const backoff = Math.min(
|
|
6880
|
+
BACKOFF_BASE_MS * 2 ** (this.consecutiveFailures - 1),
|
|
6881
|
+
BACKOFF_CAP_MS
|
|
6882
|
+
);
|
|
6883
|
+
this.nextAttemptAt = this.now() + backoff;
|
|
6884
|
+
if (this.consecutiveFailures === 1) {
|
|
6885
|
+
this.log(
|
|
6886
|
+
`[maind-mcp-bridge] presence announce failed (advisory, backing off): ${err instanceof Error ? err.message : String(err)}`
|
|
6887
|
+
);
|
|
6888
|
+
}
|
|
6889
|
+
} finally {
|
|
6890
|
+
this.inFlight = false;
|
|
6891
|
+
}
|
|
6892
|
+
}
|
|
6893
|
+
async send(status) {
|
|
6894
|
+
if (this.projectKey === null) return;
|
|
6895
|
+
const args = {
|
|
6896
|
+
project_key: this.projectKey,
|
|
6897
|
+
session_id: this.sessionId,
|
|
6898
|
+
status,
|
|
6899
|
+
ttl_minutes: TTL_MINUTES
|
|
6900
|
+
};
|
|
6901
|
+
if (status === "active") {
|
|
6902
|
+
const branch = await this.gitBranch();
|
|
6903
|
+
if (branch) args.branch = branch;
|
|
6904
|
+
if (this.machineLabel) args.machine_label = this.machineLabel;
|
|
6905
|
+
}
|
|
6906
|
+
await this.postToolCall("announce_session", args);
|
|
6907
|
+
}
|
|
6908
|
+
};
|
|
6909
|
+
async function defaultGitBranch() {
|
|
6910
|
+
return await new Promise((resolve2) => {
|
|
6911
|
+
execFile(
|
|
6912
|
+
"git",
|
|
6913
|
+
["rev-parse", "--abbrev-ref", "HEAD"],
|
|
6914
|
+
{ timeout: 2e3, encoding: "utf8" },
|
|
6915
|
+
(err, stdout) => {
|
|
6916
|
+
if (err) return resolve2(null);
|
|
6917
|
+
const branch = stdout.trim();
|
|
6918
|
+
resolve2(branch.length > 0 && branch !== "HEAD" ? branch : null);
|
|
6919
|
+
}
|
|
6920
|
+
);
|
|
6921
|
+
});
|
|
6922
|
+
}
|
|
6923
|
+
function normalizeMachineLabel(raw) {
|
|
6924
|
+
if (typeof raw !== "string") return null;
|
|
6925
|
+
const v = raw.trim().slice(0, 100);
|
|
6926
|
+
return v.length > 0 ? v : null;
|
|
6927
|
+
}
|
|
6928
|
+
|
|
6123
6929
|
// src/index.ts
|
|
6124
6930
|
var MAX_REAUTH_ATTEMPTS = 1;
|
|
6931
|
+
var HOOK_SUBCOMMANDS = [
|
|
6932
|
+
"on-session-start",
|
|
6933
|
+
"on-tool-use",
|
|
6934
|
+
"sync-config",
|
|
6935
|
+
"flush",
|
|
6936
|
+
"status"
|
|
6937
|
+
];
|
|
6938
|
+
function isHookSubcommand(value) {
|
|
6939
|
+
return HOOK_SUBCOMMANDS.includes(value);
|
|
6940
|
+
}
|
|
6125
6941
|
var SAVINGS_FLUSH_INTERVAL_MS = 6e4;
|
|
6126
6942
|
async function ensureApiKey() {
|
|
6127
6943
|
const fromEnv = (process.env.MAIND_API_KEY ?? "").trim();
|
|
@@ -6165,6 +6981,17 @@ async function main() {
|
|
|
6165
6981
|
const { runOnSessionEnd: runOnSessionEnd2 } = await Promise.resolve().then(() => (init_session_end(), session_end_exports));
|
|
6166
6982
|
process.exit(await runOnSessionEnd2());
|
|
6167
6983
|
}
|
|
6984
|
+
if (firstPositional !== void 0 && isHookSubcommand(firstPositional)) {
|
|
6985
|
+
const hooks = await Promise.resolve().then(() => (init_hooks(), hooks_exports));
|
|
6986
|
+
const run = {
|
|
6987
|
+
"on-session-start": hooks.runOnSessionStart,
|
|
6988
|
+
"on-tool-use": hooks.runOnToolUse,
|
|
6989
|
+
"sync-config": hooks.runSyncConfig,
|
|
6990
|
+
flush: hooks.runFlush,
|
|
6991
|
+
status: hooks.runHookStatus
|
|
6992
|
+
}[firstPositional];
|
|
6993
|
+
process.exit(await run());
|
|
6994
|
+
}
|
|
6168
6995
|
if (process.argv.includes("--version") || process.argv.includes("-v")) {
|
|
6169
6996
|
process.stdout.write(BRIDGE_VERSION + "\n");
|
|
6170
6997
|
process.exit(0);
|
|
@@ -6186,7 +7013,7 @@ async function main() {
|
|
|
6186
7013
|
const savingsEnabled = process.env.MAIND_DISABLE_CODEBASE_TOOLS !== "1" && process.env.MAIND_DISABLE_SAVINGS_METRICS !== "1";
|
|
6187
7014
|
const aggregator = savingsEnabled ? new SavingsAggregator() : null;
|
|
6188
7015
|
const localRouter = process.env.MAIND_DISABLE_CODEBASE_TOOLS === "1" ? null : new LocalToolRouter(void 0, aggregator);
|
|
6189
|
-
const savingsSessionId = `bridge-${
|
|
7016
|
+
const savingsSessionId = `bridge-${randomUUID3()}`;
|
|
6190
7017
|
const flushSavings = async () => {
|
|
6191
7018
|
if (!aggregator) return;
|
|
6192
7019
|
const delta = aggregator.takePending();
|
|
@@ -6203,6 +7030,23 @@ async function main() {
|
|
|
6203
7030
|
void flushSavings();
|
|
6204
7031
|
}, SAVINGS_FLUSH_INTERVAL_MS) : null;
|
|
6205
7032
|
flushTimer?.unref();
|
|
7033
|
+
let currentForwarder = null;
|
|
7034
|
+
const presence = new PresenceAnnouncer({
|
|
7035
|
+
projectKey,
|
|
7036
|
+
postToolCall: (name, args) => {
|
|
7037
|
+
if (currentForwarder === null) {
|
|
7038
|
+
return Promise.reject(new Error("presence: no active forwarder"));
|
|
7039
|
+
}
|
|
7040
|
+
return currentForwarder.postPresenceToolCall(name, args);
|
|
7041
|
+
}
|
|
7042
|
+
});
|
|
7043
|
+
if (presence.isEnabled) {
|
|
7044
|
+
const endAndExit = (code) => {
|
|
7045
|
+
void presence.end().finally(() => process.exit(code));
|
|
7046
|
+
};
|
|
7047
|
+
process.on("SIGTERM", () => endAndExit(143));
|
|
7048
|
+
process.on("SIGINT", () => endAndExit(130));
|
|
7049
|
+
}
|
|
6206
7050
|
let attempts = 0;
|
|
6207
7051
|
try {
|
|
6208
7052
|
while (true) {
|
|
@@ -6211,8 +7055,10 @@ async function main() {
|
|
|
6211
7055
|
deviceId,
|
|
6212
7056
|
bridgeVersion: BRIDGE_VERSION,
|
|
6213
7057
|
projectKey,
|
|
6214
|
-
localRouter
|
|
7058
|
+
localRouter,
|
|
7059
|
+
presence
|
|
6215
7060
|
});
|
|
7061
|
+
currentForwarder = forwarder;
|
|
6216
7062
|
try {
|
|
6217
7063
|
await forwarder.run();
|
|
6218
7064
|
return;
|
|
@@ -6231,6 +7077,7 @@ async function main() {
|
|
|
6231
7077
|
}
|
|
6232
7078
|
} finally {
|
|
6233
7079
|
if (flushTimer) clearInterval(flushTimer);
|
|
7080
|
+
await presence.end();
|
|
6234
7081
|
await flushSavings();
|
|
6235
7082
|
}
|
|
6236
7083
|
}
|
|
@@ -6241,7 +7088,7 @@ function printHelp() {
|
|
|
6241
7088
|
"",
|
|
6242
7089
|
"Usage:",
|
|
6243
7090
|
" npx -y @maind-dev/mcp-bridge # run as MCP server (stdio)",
|
|
6244
|
-
" npx -y @maind-dev/mcp-bridge install # one-shot setup (configs, preamble,
|
|
7091
|
+
" npx -y @maind-dev/mcp-bridge install # one-shot setup (configs, preamble, hooks)",
|
|
6245
7092
|
" npx -y @maind-dev/mcp-bridge --reauth # discard local key and re-run device flow",
|
|
6246
7093
|
" npx -y @maind-dev/mcp-bridge --version",
|
|
6247
7094
|
" npx -y @maind-dev/mcp-bridge --help",
|
|
@@ -6249,13 +7096,34 @@ function printHelp() {
|
|
|
6249
7096
|
"Run `install --help` for full setup flags:",
|
|
6250
7097
|
" npx -y @maind-dev/mcp-bridge install --help",
|
|
6251
7098
|
"",
|
|
7099
|
+
"Claude Code hook subcommands (wired by `install`; run them by hand only for",
|
|
7100
|
+
"diagnostics). They read the hook payload on stdin and use the bridge's own",
|
|
7101
|
+
"paired credential \u2014 no separate init:",
|
|
7102
|
+
" on-session-start open a tracked session (Tier-3 flat metrics)",
|
|
7103
|
+
" on-tool-use bump counters + evaluate the ADR-039 context advisory",
|
|
7104
|
+
" on-session-end session analytics + close/flush the tracked session",
|
|
7105
|
+
" sync-config pull your context thresholds from the server (ADR-039)",
|
|
7106
|
+
" flush post queued Tier-3 metrics now",
|
|
7107
|
+
" status show pairing, queued metrics and active thresholds",
|
|
7108
|
+
"",
|
|
7109
|
+
"Tier-3 collection is gated by consent server-side: https://app.maind.dev/consent",
|
|
7110
|
+
"Thresholds are configured at https://app.maind.dev/settings \u2014 run sync-config after.",
|
|
7111
|
+
"",
|
|
6252
7112
|
"Environment overrides (rarely needed):",
|
|
6253
7113
|
" MAIND_MCP_URL Streamable-HTTP endpoint (default https://mcp.maind.dev/mcp)",
|
|
6254
7114
|
" MAIND_CLIENT_FAMILY Forward real client family (claude-code|codex|copilot|cursor|windsurf|...)",
|
|
6255
7115
|
" MAIND_CLIENT_VERSION Optional client version marker (max 64 chars)",
|
|
6256
7116
|
" MAIND_FUNCTIONS_ORIGIN Supabase Edge Functions base URL for device-auth",
|
|
7117
|
+
" MAIND_AUTO_ANNOUNCE Set to 'off' to disable automatic presence announces (ADR-242)",
|
|
7118
|
+
" MAIND_SESSION_ID Shared session identity (UUID) \u2014 IDEs inject it so bridge+hook dedupe",
|
|
6257
7119
|
" XDG_CONFIG_HOME Override config-dir parent on Linux/BSD",
|
|
6258
7120
|
"",
|
|
7121
|
+
"Auto-presence (ADR-242): the bridge announces this session on the repo's",
|
|
7122
|
+
"shared working tree (project_key hash + branch only \u2014 no hostname, no paths),",
|
|
7123
|
+
"refreshes while tools are actually called, and ends the row on exit.",
|
|
7124
|
+
"Persistent opt-out / explicit machine_label via config.json in the maind",
|
|
7125
|
+
'config dir: { "auto_announce": false, "machine_label": "my-box" }',
|
|
7126
|
+
"",
|
|
6259
7127
|
"Place this in your .mcp.json (or equivalent):",
|
|
6260
7128
|
"",
|
|
6261
7129
|
" {",
|