@maind-dev/mcp-bridge 0.14.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 +709 -111
- 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)
|
|
@@ -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,8 +949,11 @@ 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
|
|
|
@@ -1454,9 +1904,9 @@ function printInstallHelp() {
|
|
|
1454
1904
|
"",
|
|
1455
1905
|
"Common flags:",
|
|
1456
1906
|
" --project-root <path> Override project-root detection (default: walk up from cwd)",
|
|
1457
|
-
" --full Non-interactive full setup (includes ~/.claude/settings.json
|
|
1907
|
+
" --full Non-interactive full setup (includes the ~/.claude/settings.json hooks)",
|
|
1458
1908
|
" --no-preamble Skip the 5 preamble files (MCP-config + pairing only)",
|
|
1459
|
-
" --no-hook Never write the
|
|
1909
|
+
" --no-hook Never write the Claude Code hooks (overrides --full for hooks)",
|
|
1460
1910
|
" --non-interactive Skip every TTY prompt (used by CI / Dashboard-One-Click)",
|
|
1461
1911
|
" --token <jwt> Use a pre-issued one-click token instead of browser pairing",
|
|
1462
1912
|
" --client <family> Install only for one client family (claude-code, cursor, ...)",
|
|
@@ -1658,12 +2108,79 @@ Which one should receive the MCP config and preamble files? [1-${candidates.leng
|
|
|
1658
2108
|
}
|
|
1659
2109
|
|
|
1660
2110
|
// src/install/client-targets.ts
|
|
1661
|
-
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
|
|
1662
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
|
+
});
|
|
1663
2176
|
return {
|
|
1664
|
-
command:
|
|
1665
|
-
args:
|
|
2177
|
+
command: launch.command,
|
|
2178
|
+
args: launch.args,
|
|
1666
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,
|
|
1667
2184
|
MAIND_CLIENT_FAMILY: opts.clientFamily,
|
|
1668
2185
|
MAIND_MCP_URL: opts.mcpUrl
|
|
1669
2186
|
}
|
|
@@ -1672,7 +2189,7 @@ function buildMaindServerEntry(opts) {
|
|
|
1672
2189
|
function claudeDesktopConfigPath(ctx) {
|
|
1673
2190
|
switch (ctx.platform) {
|
|
1674
2191
|
case "darwin":
|
|
1675
|
-
return
|
|
2192
|
+
return path3.join(
|
|
1676
2193
|
ctx.homeDir,
|
|
1677
2194
|
"Library",
|
|
1678
2195
|
"Application Support",
|
|
@@ -1680,12 +2197,12 @@ function claudeDesktopConfigPath(ctx) {
|
|
|
1680
2197
|
"claude_desktop_config.json"
|
|
1681
2198
|
);
|
|
1682
2199
|
case "win32": {
|
|
1683
|
-
const appData = ctx.appData ??
|
|
1684
|
-
return
|
|
2200
|
+
const appData = ctx.appData ?? path3.join(ctx.homeDir, "AppData", "Roaming");
|
|
2201
|
+
return path3.join(appData, "Claude", "claude_desktop_config.json");
|
|
1685
2202
|
}
|
|
1686
2203
|
default: {
|
|
1687
|
-
const xdg = ctx.xdgConfigHome ??
|
|
1688
|
-
return
|
|
2204
|
+
const xdg = ctx.xdgConfigHome ?? path3.join(ctx.homeDir, ".config");
|
|
2205
|
+
return path3.join(xdg, "Claude", "claude_desktop_config.json");
|
|
1689
2206
|
}
|
|
1690
2207
|
}
|
|
1691
2208
|
}
|
|
@@ -1696,7 +2213,7 @@ function getClientTargets(ctx) {
|
|
|
1696
2213
|
label: "Claude Code (project-scoped .mcp.json)",
|
|
1697
2214
|
clientFamilyEnv: "claude-code",
|
|
1698
2215
|
scope: "project",
|
|
1699
|
-
path:
|
|
2216
|
+
path: path3.join(ctx.projectRoot, ".mcp.json"),
|
|
1700
2217
|
kind: "json"
|
|
1701
2218
|
},
|
|
1702
2219
|
{
|
|
@@ -1704,7 +2221,7 @@ function getClientTargets(ctx) {
|
|
|
1704
2221
|
label: "Claude Code (user-scoped ~/.claude.json)",
|
|
1705
2222
|
clientFamilyEnv: "claude-code",
|
|
1706
2223
|
scope: "user",
|
|
1707
|
-
path:
|
|
2224
|
+
path: path3.join(ctx.homeDir, ".claude.json"),
|
|
1708
2225
|
kind: "json"
|
|
1709
2226
|
},
|
|
1710
2227
|
{
|
|
@@ -1720,7 +2237,7 @@ function getClientTargets(ctx) {
|
|
|
1720
2237
|
label: "Cursor (~/.cursor/mcp.json)",
|
|
1721
2238
|
clientFamilyEnv: "cursor",
|
|
1722
2239
|
scope: "user",
|
|
1723
|
-
path:
|
|
2240
|
+
path: path3.join(ctx.homeDir, ".cursor", "mcp.json"),
|
|
1724
2241
|
kind: "json"
|
|
1725
2242
|
},
|
|
1726
2243
|
{
|
|
@@ -1728,7 +2245,7 @@ function getClientTargets(ctx) {
|
|
|
1728
2245
|
label: "Windsurf (~/.codeium/windsurf/mcp_config.json)",
|
|
1729
2246
|
clientFamilyEnv: "windsurf",
|
|
1730
2247
|
scope: "user",
|
|
1731
|
-
path:
|
|
2248
|
+
path: path3.join(ctx.homeDir, ".codeium", "windsurf", "mcp_config.json"),
|
|
1732
2249
|
kind: "json"
|
|
1733
2250
|
},
|
|
1734
2251
|
{
|
|
@@ -1736,7 +2253,7 @@ function getClientTargets(ctx) {
|
|
|
1736
2253
|
label: "Codex CLI (~/.codex/config.toml)",
|
|
1737
2254
|
clientFamilyEnv: "codex",
|
|
1738
2255
|
scope: "user",
|
|
1739
|
-
path:
|
|
2256
|
+
path: path3.join(ctx.homeDir, ".codex", "config.toml"),
|
|
1740
2257
|
kind: "toml"
|
|
1741
2258
|
}
|
|
1742
2259
|
];
|
|
@@ -1763,7 +2280,7 @@ function nonEmpty(v) {
|
|
|
1763
2280
|
|
|
1764
2281
|
// src/install/atomic-write.ts
|
|
1765
2282
|
import * as fs2 from "node:fs/promises";
|
|
1766
|
-
import * as
|
|
2283
|
+
import * as path4 from "node:path";
|
|
1767
2284
|
async function readFileSafe(filepath) {
|
|
1768
2285
|
try {
|
|
1769
2286
|
return await fs2.readFile(filepath, "utf8");
|
|
@@ -1776,9 +2293,9 @@ async function ensureDir2(dir) {
|
|
|
1776
2293
|
await fs2.mkdir(dir, { recursive: true });
|
|
1777
2294
|
}
|
|
1778
2295
|
async function atomicWriteFile(filepath, content, mode) {
|
|
1779
|
-
const dir =
|
|
2296
|
+
const dir = path4.dirname(filepath);
|
|
1780
2297
|
await ensureDir2(dir);
|
|
1781
|
-
const tmp =
|
|
2298
|
+
const tmp = path4.join(
|
|
1782
2299
|
dir,
|
|
1783
2300
|
`.maind-install-${process.pid}-${Date.now()}.tmp`
|
|
1784
2301
|
);
|
|
@@ -2067,7 +2584,7 @@ function failed2(target, phase, err) {
|
|
|
2067
2584
|
}
|
|
2068
2585
|
|
|
2069
2586
|
// src/install/preamble.ts
|
|
2070
|
-
import * as
|
|
2587
|
+
import * as path5 from "node:path";
|
|
2071
2588
|
|
|
2072
2589
|
// ../../packages/integration-snippets/build/index.js
|
|
2073
2590
|
var STACK_PLACEHOLDER_TOKEN = "__STACK__";
|
|
@@ -2774,32 +3291,32 @@ function buildPreambleTargets(ctx) {
|
|
|
2774
3291
|
return [
|
|
2775
3292
|
{
|
|
2776
3293
|
key: "preamble:CLAUDE.md",
|
|
2777
|
-
path:
|
|
3294
|
+
path: path5.join(ctx.projectRoot, "CLAUDE.md"),
|
|
2778
3295
|
mayNeedParentDir: false
|
|
2779
3296
|
},
|
|
2780
3297
|
{
|
|
2781
3298
|
key: "preamble:AGENTS.md",
|
|
2782
|
-
path:
|
|
3299
|
+
path: path5.join(ctx.projectRoot, "AGENTS.md"),
|
|
2783
3300
|
mayNeedParentDir: false
|
|
2784
3301
|
},
|
|
2785
3302
|
{
|
|
2786
3303
|
key: "preamble:.github/copilot-instructions.md",
|
|
2787
|
-
path:
|
|
3304
|
+
path: path5.join(ctx.projectRoot, ".github", "copilot-instructions.md"),
|
|
2788
3305
|
mayNeedParentDir: true
|
|
2789
3306
|
},
|
|
2790
3307
|
{
|
|
2791
3308
|
key: "preamble:.cursorrules",
|
|
2792
|
-
path:
|
|
3309
|
+
path: path5.join(ctx.projectRoot, ".cursorrules"),
|
|
2793
3310
|
mayNeedParentDir: false
|
|
2794
3311
|
},
|
|
2795
3312
|
{
|
|
2796
3313
|
key: "preamble:.windsurfrules",
|
|
2797
|
-
path:
|
|
3314
|
+
path: path5.join(ctx.projectRoot, ".windsurfrules"),
|
|
2798
3315
|
mayNeedParentDir: false
|
|
2799
3316
|
},
|
|
2800
3317
|
{
|
|
2801
3318
|
key: "preamble:~/.claude/maind-session-start-reminder.md",
|
|
2802
|
-
path:
|
|
3319
|
+
path: path5.join(ctx.homeDir, ".claude", "maind-session-start-reminder.md"),
|
|
2803
3320
|
mayNeedParentDir: true
|
|
2804
3321
|
}
|
|
2805
3322
|
];
|
|
@@ -2815,7 +3332,7 @@ async function writePreambleFiles(ctx, dryRun = false) {
|
|
|
2815
3332
|
async function writeOnePreambleFile(target, dryRun) {
|
|
2816
3333
|
try {
|
|
2817
3334
|
if (target.mayNeedParentDir && !dryRun) {
|
|
2818
|
-
await ensureDir2(
|
|
3335
|
+
await ensureDir2(path5.dirname(target.path));
|
|
2819
3336
|
}
|
|
2820
3337
|
const alreadyPresent = await hasLinePrefix(target.path, PREAMBLE_HEADER_PREFIX);
|
|
2821
3338
|
if (alreadyPresent) {
|
|
@@ -2862,11 +3379,11 @@ function ensureTrailingBlankLine(content) {
|
|
|
2862
3379
|
}
|
|
2863
3380
|
|
|
2864
3381
|
// src/install/hook-merge.ts
|
|
2865
|
-
import * as
|
|
3382
|
+
import * as path6 from "node:path";
|
|
2866
3383
|
import * as readline2 from "node:readline";
|
|
2867
3384
|
var REMINDER_FILE_REL = ".claude/maind-session-start-reminder.md";
|
|
2868
3385
|
async function mergeClaudeHook(opts, spec) {
|
|
2869
|
-
const settingsPath =
|
|
3386
|
+
const settingsPath = path6.join(opts.homeDir, ".claude", "settings.json");
|
|
2870
3387
|
const targetKey = spec.targetKey;
|
|
2871
3388
|
if (opts.skip) {
|
|
2872
3389
|
return { target: targetKey, action: "skip", status: "skipped", detail: "--no-hook" };
|
|
@@ -2898,8 +3415,9 @@ async function mergeClaudeHook(opts, spec) {
|
|
|
2898
3415
|
return { target: targetKey, action: "merge", status: "failed", detail: `parse: ${errMessage(err)}` };
|
|
2899
3416
|
}
|
|
2900
3417
|
}
|
|
2901
|
-
|
|
2902
|
-
|
|
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) };
|
|
2903
3421
|
}
|
|
2904
3422
|
if (!opts.full) {
|
|
2905
3423
|
if (!opts.isInteractive) {
|
|
@@ -2962,33 +3480,77 @@ ${spec.consentDescription}
|
|
|
2962
3480
|
};
|
|
2963
3481
|
}
|
|
2964
3482
|
async function mergeSessionStartHook(opts) {
|
|
2965
|
-
const reminderPath =
|
|
3483
|
+
const reminderPath = path6.join(opts.homeDir, REMINDER_FILE_REL);
|
|
2966
3484
|
return mergeClaudeHook(opts, {
|
|
2967
3485
|
event: "SessionStart",
|
|
2968
3486
|
command: `cat ${reminderPath}`,
|
|
2969
3487
|
timeout: 5,
|
|
2970
3488
|
matchPattern: /maind-session-start-reminder\.md/,
|
|
2971
3489
|
targetKey: "hook:~/.claude/settings.json",
|
|
2972
|
-
|
|
3490
|
+
skipDetail: () => "SessionStart hook already references the reminder file",
|
|
2973
3491
|
consentDescription: `It 'cat's ${REMINDER_FILE_REL} into every new Claude Code session.`
|
|
2974
3492
|
});
|
|
2975
3493
|
}
|
|
2976
|
-
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);
|
|
2977
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, {
|
|
2978
3523
|
event: "Stop",
|
|
2979
|
-
|
|
3524
|
+
subcommand: "on-session-end",
|
|
2980
3525
|
timeout: 10,
|
|
2981
|
-
// Match any on-session-end command so we never double-wire (also covers a
|
|
2982
|
-
// hand-wired node-path hook the user may already have).
|
|
2983
|
-
matchPattern: /on-session-end/,
|
|
2984
3526
|
targetKey: "hook(stop):~/.claude/settings.json",
|
|
2985
|
-
|
|
2986
|
-
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."
|
|
3539
|
+
});
|
|
3540
|
+
}
|
|
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."
|
|
2987
3549
|
});
|
|
2988
3550
|
}
|
|
2989
|
-
function
|
|
3551
|
+
function findExistingHookCommand(settings, event, pattern) {
|
|
2990
3552
|
const groups = settings.hooks?.[event];
|
|
2991
|
-
if (!Array.isArray(groups)) return
|
|
3553
|
+
if (!Array.isArray(groups)) return null;
|
|
2992
3554
|
for (const group of groups) {
|
|
2993
3555
|
if (!isObject3(group)) continue;
|
|
2994
3556
|
const hooks = group.hooks;
|
|
@@ -2996,10 +3558,10 @@ function existingHookReferences(settings, event, pattern) {
|
|
|
2996
3558
|
for (const hook of hooks) {
|
|
2997
3559
|
if (!isObject3(hook)) continue;
|
|
2998
3560
|
const cmd = hook.command;
|
|
2999
|
-
if (typeof cmd === "string" && pattern.test(cmd)) return
|
|
3561
|
+
if (typeof cmd === "string" && pattern.test(cmd)) return cmd;
|
|
3000
3562
|
}
|
|
3001
3563
|
}
|
|
3002
|
-
return
|
|
3564
|
+
return null;
|
|
3003
3565
|
}
|
|
3004
3566
|
async function promptYesNo(out, prompt) {
|
|
3005
3567
|
out.write(prompt);
|
|
@@ -3328,6 +3890,8 @@ Skipping remaining steps.
|
|
|
3328
3890
|
out: process.stdout
|
|
3329
3891
|
};
|
|
3330
3892
|
report.add(await mergeSessionStartHook(hookOpts));
|
|
3893
|
+
report.add(await mergeSessionStartMetricsHook(hookOpts));
|
|
3894
|
+
report.add(await mergeToolUseHook(hookOpts));
|
|
3331
3895
|
report.add(await mergeStopHook(hookOpts));
|
|
3332
3896
|
if (!flags.dryRun) {
|
|
3333
3897
|
await postInstallTelemetry({
|
|
@@ -3937,12 +4501,12 @@ function toPosix(p) {
|
|
|
3937
4501
|
function classify(paths) {
|
|
3938
4502
|
const out = [];
|
|
3939
4503
|
for (const raw of paths) {
|
|
3940
|
-
const
|
|
3941
|
-
if (!
|
|
4504
|
+
const path7 = toPosix(raw).trim();
|
|
4505
|
+
if (!path7 || isSkippablePath(path7))
|
|
3942
4506
|
continue;
|
|
3943
|
-
const language = languageForPath(
|
|
4507
|
+
const language = languageForPath(path7);
|
|
3944
4508
|
if (language)
|
|
3945
|
-
out.push({ path:
|
|
4509
|
+
out.push({ path: path7, language });
|
|
3946
4510
|
}
|
|
3947
4511
|
return out;
|
|
3948
4512
|
}
|
|
@@ -4264,18 +4828,18 @@ function readFileHistory(repoRoot, paths, opts = {}) {
|
|
|
4264
4828
|
const cleanPaths = paths.map((p) => p.trim()).filter((p) => p.length > 0 && !p.startsWith(":"));
|
|
4265
4829
|
const scoped = cleanPaths.slice(0, MAX_HISTORY_PATHS);
|
|
4266
4830
|
const history = [];
|
|
4267
|
-
for (const
|
|
4831
|
+
for (const path7 of scoped) {
|
|
4268
4832
|
const raw = runGit(repoRoot, [
|
|
4269
4833
|
"log",
|
|
4270
4834
|
"-n",
|
|
4271
4835
|
String(window),
|
|
4272
4836
|
LOG_FORMAT,
|
|
4273
4837
|
"--",
|
|
4274
|
-
|
|
4838
|
+
path7
|
|
4275
4839
|
]);
|
|
4276
4840
|
const commits = raw === null ? [] : splitRecords(raw).map(parseHistoryRecord).filter((c) => c !== null);
|
|
4277
4841
|
history.push({
|
|
4278
|
-
path:
|
|
4842
|
+
path: path7,
|
|
4279
4843
|
lastCommits: commits.slice(0, limit),
|
|
4280
4844
|
ownership: includeOwnership ? { topAuthors: aggregateOwnership(commits), commitsInWindow: commits.length } : null
|
|
4281
4845
|
});
|
|
@@ -4715,11 +5279,11 @@ var RISK_RULES = [
|
|
|
4715
5279
|
// ../../packages/code-index/build/review/risk-scan.js
|
|
4716
5280
|
function scanRiskFlags(input) {
|
|
4717
5281
|
const flags = /* @__PURE__ */ new Set();
|
|
4718
|
-
for (const [
|
|
5282
|
+
for (const [path7, status] of input.paths) {
|
|
4719
5283
|
for (const rule of RISK_RULES) {
|
|
4720
5284
|
if (flags.has(rule.flag))
|
|
4721
5285
|
continue;
|
|
4722
|
-
if (!rule.path.test(
|
|
5286
|
+
if (!rule.path.test(path7))
|
|
4723
5287
|
continue;
|
|
4724
5288
|
if (rule.onlyWhenAdded && status !== "added")
|
|
4725
5289
|
continue;
|
|
@@ -4727,19 +5291,19 @@ function scanRiskFlags(input) {
|
|
|
4727
5291
|
flags.add(rule.flag);
|
|
4728
5292
|
continue;
|
|
4729
5293
|
}
|
|
4730
|
-
const text = contentForPath(
|
|
5294
|
+
const text = contentForPath(path7, input);
|
|
4731
5295
|
if (text !== null && rule.content.test(text))
|
|
4732
5296
|
flags.add(rule.flag);
|
|
4733
5297
|
}
|
|
4734
5298
|
}
|
|
4735
5299
|
return [...flags].sort();
|
|
4736
5300
|
}
|
|
4737
|
-
function contentForPath(
|
|
4738
|
-
const hunks = input.hunks.get(
|
|
5301
|
+
function contentForPath(path7, input) {
|
|
5302
|
+
const hunks = input.hunks.get(path7);
|
|
4739
5303
|
if (hunks && !hunks.wholeFile && !hunks.degraded) {
|
|
4740
5304
|
return hunks.addedLines.join("\n");
|
|
4741
5305
|
}
|
|
4742
|
-
return input.readUntracked(
|
|
5306
|
+
return input.readUntracked(path7);
|
|
4743
5307
|
}
|
|
4744
5308
|
|
|
4745
5309
|
// ../../packages/code-index/build/store/schema.js
|
|
@@ -5306,8 +5870,8 @@ var NodeSqliteStore = class {
|
|
|
5306
5870
|
indexedAt: r.indexed_at
|
|
5307
5871
|
}));
|
|
5308
5872
|
}
|
|
5309
|
-
async getFile(
|
|
5310
|
-
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);
|
|
5311
5875
|
if (!r)
|
|
5312
5876
|
return null;
|
|
5313
5877
|
return {
|
|
@@ -5335,10 +5899,10 @@ var NodeSqliteStore = class {
|
|
|
5335
5899
|
});
|
|
5336
5900
|
tx();
|
|
5337
5901
|
}
|
|
5338
|
-
async deleteFile(
|
|
5902
|
+
async deleteFile(path7) {
|
|
5339
5903
|
const tx = this.db.transaction(() => {
|
|
5340
|
-
this.deleteFileGraph(
|
|
5341
|
-
this.db.prepare("DELETE FROM files WHERE path = ?").run(
|
|
5904
|
+
this.deleteFileGraph(path7);
|
|
5905
|
+
this.db.prepare("DELETE FROM files WHERE path = ?").run(path7);
|
|
5342
5906
|
});
|
|
5343
5907
|
tx();
|
|
5344
5908
|
}
|
|
@@ -5366,8 +5930,8 @@ var NodeSqliteStore = class {
|
|
|
5366
5930
|
const r = this.db.prepare("SELECT * FROM nodes WHERE node_key = ?").get(nodeKey);
|
|
5367
5931
|
return r ? toNodeRow(r) : null;
|
|
5368
5932
|
}
|
|
5369
|
-
async getNodesByFile(
|
|
5370
|
-
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);
|
|
5371
5935
|
return rows.map(toNodeRow);
|
|
5372
5936
|
}
|
|
5373
5937
|
async getNodesByKinds(kinds) {
|
|
@@ -5483,8 +6047,8 @@ var NodeSqliteStore = class {
|
|
|
5483
6047
|
}));
|
|
5484
6048
|
}
|
|
5485
6049
|
// ── internal helpers ──
|
|
5486
|
-
deleteFileGraph(
|
|
5487
|
-
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);
|
|
5488
6052
|
const delEdge = this.db.prepare("DELETE FROM edges WHERE src_key = ?");
|
|
5489
6053
|
const delFts = this.db.prepare("DELETE FROM nodes_fts WHERE node_key = ?");
|
|
5490
6054
|
for (let i = 0; i < keys.length; i += CHUNK) {
|
|
@@ -5493,7 +6057,7 @@ var NodeSqliteStore = class {
|
|
|
5493
6057
|
delFts.run(k);
|
|
5494
6058
|
}
|
|
5495
6059
|
}
|
|
5496
|
-
this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(
|
|
6060
|
+
this.db.prepare("DELETE FROM nodes WHERE file_path = ?").run(path7);
|
|
5497
6061
|
}
|
|
5498
6062
|
_insNode = null;
|
|
5499
6063
|
insertNodeStmt() {
|
|
@@ -6364,6 +6928,16 @@ function normalizeMachineLabel(raw) {
|
|
|
6364
6928
|
|
|
6365
6929
|
// src/index.ts
|
|
6366
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
|
+
}
|
|
6367
6941
|
var SAVINGS_FLUSH_INTERVAL_MS = 6e4;
|
|
6368
6942
|
async function ensureApiKey() {
|
|
6369
6943
|
const fromEnv = (process.env.MAIND_API_KEY ?? "").trim();
|
|
@@ -6407,6 +6981,17 @@ async function main() {
|
|
|
6407
6981
|
const { runOnSessionEnd: runOnSessionEnd2 } = await Promise.resolve().then(() => (init_session_end(), session_end_exports));
|
|
6408
6982
|
process.exit(await runOnSessionEnd2());
|
|
6409
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
|
+
}
|
|
6410
6995
|
if (process.argv.includes("--version") || process.argv.includes("-v")) {
|
|
6411
6996
|
process.stdout.write(BRIDGE_VERSION + "\n");
|
|
6412
6997
|
process.exit(0);
|
|
@@ -6503,7 +7088,7 @@ function printHelp() {
|
|
|
6503
7088
|
"",
|
|
6504
7089
|
"Usage:",
|
|
6505
7090
|
" npx -y @maind-dev/mcp-bridge # run as MCP server (stdio)",
|
|
6506
|
-
" 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)",
|
|
6507
7092
|
" npx -y @maind-dev/mcp-bridge --reauth # discard local key and re-run device flow",
|
|
6508
7093
|
" npx -y @maind-dev/mcp-bridge --version",
|
|
6509
7094
|
" npx -y @maind-dev/mcp-bridge --help",
|
|
@@ -6511,6 +7096,19 @@ function printHelp() {
|
|
|
6511
7096
|
"Run `install --help` for full setup flags:",
|
|
6512
7097
|
" npx -y @maind-dev/mcp-bridge install --help",
|
|
6513
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
|
+
"",
|
|
6514
7112
|
"Environment overrides (rarely needed):",
|
|
6515
7113
|
" MAIND_MCP_URL Streamable-HTTP endpoint (default https://mcp.maind.dev/mcp)",
|
|
6516
7114
|
" MAIND_CLIENT_FAMILY Forward real client family (claude-code|codex|copilot|cursor|windsurf|...)",
|