@maind-dev/mcp-bridge 0.25.0 → 0.26.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/build/index.js +536 -345
- package/build/meta.json +1 -1
- package/package.json +1 -1
package/build/index.js
CHANGED
|
@@ -84,7 +84,7 @@ ${original}`
|
|
|
84
84
|
return JSON.stringify({ jsonrpc: "2.0", id, result });
|
|
85
85
|
}
|
|
86
86
|
function fallbackMarker(cachedAt, now) {
|
|
87
|
-
return `NOTE (
|
|
87
|
+
return `NOTE (MAIND cache fallback): the MAIND MCP server was unreachable, so these project conventions were served from a local snapshot taken ${relativeAge(cachedAt, now)}. They may be stale, and MAIND tools are unavailable until the server is reachable again.`;
|
|
88
88
|
}
|
|
89
89
|
function relativeAge(cachedAt, now) {
|
|
90
90
|
const then = Date.parse(cachedAt);
|
|
@@ -202,7 +202,7 @@ var BRIDGE_VERSION;
|
|
|
202
202
|
var init_version = __esm({
|
|
203
203
|
"src/version.ts"() {
|
|
204
204
|
"use strict";
|
|
205
|
-
BRIDGE_VERSION = "0.
|
|
205
|
+
BRIDGE_VERSION = "0.26.0";
|
|
206
206
|
}
|
|
207
207
|
});
|
|
208
208
|
|
|
@@ -491,6 +491,43 @@ var init_hook_wiring = __esm({
|
|
|
491
491
|
}
|
|
492
492
|
});
|
|
493
493
|
|
|
494
|
+
// src/bridge-config.ts
|
|
495
|
+
import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
|
|
496
|
+
import { join as join8 } from "node:path";
|
|
497
|
+
function bridgeConfigPath() {
|
|
498
|
+
return join8(configDir(), "config.json");
|
|
499
|
+
}
|
|
500
|
+
function readBridgeConfig() {
|
|
501
|
+
try {
|
|
502
|
+
const file = bridgeConfigPath();
|
|
503
|
+
if (!existsSync3(file)) return null;
|
|
504
|
+
const raw = JSON.parse(readFileSync3(file, "utf8"));
|
|
505
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
506
|
+
return null;
|
|
507
|
+
}
|
|
508
|
+
const o = raw;
|
|
509
|
+
const config = {};
|
|
510
|
+
if (typeof o.auto_announce === "boolean") {
|
|
511
|
+
config.auto_announce = o.auto_announce;
|
|
512
|
+
}
|
|
513
|
+
if (typeof o.machine_label === "string") {
|
|
514
|
+
config.machine_label = o.machine_label;
|
|
515
|
+
}
|
|
516
|
+
if (typeof o.auto_working_paths === "boolean") {
|
|
517
|
+
config.auto_working_paths = o.auto_working_paths;
|
|
518
|
+
}
|
|
519
|
+
return config;
|
|
520
|
+
} catch {
|
|
521
|
+
return null;
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
var init_bridge_config = __esm({
|
|
525
|
+
"src/bridge-config.ts"() {
|
|
526
|
+
"use strict";
|
|
527
|
+
init_device_id();
|
|
528
|
+
}
|
|
529
|
+
});
|
|
530
|
+
|
|
494
531
|
// ../../packages/code-index/build/parse/keys.js
|
|
495
532
|
function moduleKey(filePath) {
|
|
496
533
|
return `${filePath}#<module>`;
|
|
@@ -1123,8 +1160,103 @@ var init_history = __esm({
|
|
|
1123
1160
|
}
|
|
1124
1161
|
});
|
|
1125
1162
|
|
|
1126
|
-
// ../../packages/code-index/build/repo-health/
|
|
1163
|
+
// ../../packages/code-index/build/repo-health/hooks.js
|
|
1127
1164
|
import { execFileSync as execFileSync4 } from "node:child_process";
|
|
1165
|
+
import { readdirSync as readdirSync2, statSync as statSync2 } from "node:fs";
|
|
1166
|
+
import { isAbsolute as isAbsolute2, join as join11, relative, resolve as resolve2 } from "node:path";
|
|
1167
|
+
function isRealHook(name) {
|
|
1168
|
+
return !name.endsWith(".sample") && !name.startsWith(".");
|
|
1169
|
+
}
|
|
1170
|
+
function gitConfig(root, key) {
|
|
1171
|
+
try {
|
|
1172
|
+
const out2 = execFileSync4("git", ["-C", root, "config", "--get", key], {
|
|
1173
|
+
encoding: "utf-8",
|
|
1174
|
+
timeout: 5e3,
|
|
1175
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
1176
|
+
}).trim();
|
|
1177
|
+
return out2.length > 0 ? out2 : null;
|
|
1178
|
+
} catch {
|
|
1179
|
+
return null;
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
function hasExecutableHook(dir) {
|
|
1183
|
+
let entries;
|
|
1184
|
+
try {
|
|
1185
|
+
entries = readdirSync2(dir);
|
|
1186
|
+
} catch {
|
|
1187
|
+
return null;
|
|
1188
|
+
}
|
|
1189
|
+
for (const name of entries.filter(isRealHook)) {
|
|
1190
|
+
try {
|
|
1191
|
+
const st = statSync2(join11(dir, name));
|
|
1192
|
+
if (st.isFile() && (st.mode & 73) !== 0)
|
|
1193
|
+
return true;
|
|
1194
|
+
} catch {
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
return false;
|
|
1198
|
+
}
|
|
1199
|
+
function isDir(p) {
|
|
1200
|
+
try {
|
|
1201
|
+
return statSync2(p).isDirectory();
|
|
1202
|
+
} catch {
|
|
1203
|
+
return false;
|
|
1204
|
+
}
|
|
1205
|
+
}
|
|
1206
|
+
function displayPath(root, absolute) {
|
|
1207
|
+
const rel = relative(root, absolute);
|
|
1208
|
+
return !rel || rel.startsWith("..") ? absolute : rel;
|
|
1209
|
+
}
|
|
1210
|
+
function resolveHookState(root) {
|
|
1211
|
+
const hookDirs = VERSIONED_HOOK_DIRS.filter((d) => isDir(join11(root, d)));
|
|
1212
|
+
const hooksPath = gitConfig(root, "core.hooksPath");
|
|
1213
|
+
const effectiveAbs = hooksPath ? isAbsolute2(hooksPath) ? hooksPath : resolve2(root, hooksPath) : join11(root, ".git", "hooks");
|
|
1214
|
+
const effectiveDir = displayPath(root, effectiveAbs);
|
|
1215
|
+
const found = hasExecutableHook(effectiveAbs);
|
|
1216
|
+
if (found === true) {
|
|
1217
|
+
return {
|
|
1218
|
+
verdict: "wired",
|
|
1219
|
+
reason: hooksPath ? "wired" : "default_path",
|
|
1220
|
+
hookDirs,
|
|
1221
|
+
hooksPath,
|
|
1222
|
+
effectiveDir
|
|
1223
|
+
};
|
|
1224
|
+
}
|
|
1225
|
+
const reason = hooksPath ? found === null ? "path_missing" : "path_empty" : hookDirs.length > 0 ? "path_unset" : "no_hooks";
|
|
1226
|
+
return {
|
|
1227
|
+
verdict: hookDirs.length > 0 ? "present_unwired" : "absent",
|
|
1228
|
+
reason,
|
|
1229
|
+
hookDirs,
|
|
1230
|
+
hooksPath,
|
|
1231
|
+
effectiveDir
|
|
1232
|
+
};
|
|
1233
|
+
}
|
|
1234
|
+
function describeHookState(state) {
|
|
1235
|
+
switch (state.reason) {
|
|
1236
|
+
case "wired":
|
|
1237
|
+
return `Git-Gates aktiv (core.hooksPath \u2192 ${state.effectiveDir}).`;
|
|
1238
|
+
case "default_path":
|
|
1239
|
+
return "Git-Gates aktiv (.git/hooks, nicht versioniert).";
|
|
1240
|
+
case "path_unset":
|
|
1241
|
+
return `${state.hookDirs.join(", ")} liegt im Repo, aber core.hooksPath ist ungesetzt \u2014 kein Gate feuert.`;
|
|
1242
|
+
case "path_missing":
|
|
1243
|
+
return `core.hooksPath zeigt auf ${state.effectiveDir}, das es nicht gibt \u2014 git f\xFChrt keinen Hook aus.`;
|
|
1244
|
+
case "path_empty":
|
|
1245
|
+
return `core.hooksPath zeigt auf ${state.effectiveDir}, dort liegt kein ausf\xFChrbarer Hook.`;
|
|
1246
|
+
case "no_hooks":
|
|
1247
|
+
return "Keine Git-Hooks im Repo.";
|
|
1248
|
+
}
|
|
1249
|
+
}
|
|
1250
|
+
var VERSIONED_HOOK_DIRS;
|
|
1251
|
+
var init_hooks = __esm({
|
|
1252
|
+
"../../packages/code-index/build/repo-health/hooks.js"() {
|
|
1253
|
+
"use strict";
|
|
1254
|
+
VERSIONED_HOOK_DIRS = [".githooks", ".husky"];
|
|
1255
|
+
}
|
|
1256
|
+
});
|
|
1257
|
+
|
|
1258
|
+
// ../../packages/code-index/build/repo-health/divergence.js
|
|
1259
|
+
import { execFileSync as execFileSync5 } from "node:child_process";
|
|
1128
1260
|
import { existsSync as existsSync4, readFileSync as readFileSync4 } from "node:fs";
|
|
1129
1261
|
import { posix as posix3 } from "node:path";
|
|
1130
1262
|
function computeDivergence(facts) {
|
|
@@ -1250,8 +1382,23 @@ function computeDivergence(facts) {
|
|
|
1250
1382
|
hint: "Check the CI provider's billing/spending status before debugging code."
|
|
1251
1383
|
});
|
|
1252
1384
|
}
|
|
1385
|
+
const hookFinding = computeHookFinding(facts.hooks);
|
|
1386
|
+
if (hookFinding)
|
|
1387
|
+
out2.push(hookFinding);
|
|
1253
1388
|
return sortFindings(out2);
|
|
1254
1389
|
}
|
|
1390
|
+
function computeHookFinding(hooks) {
|
|
1391
|
+
if (!hooks || hooks.verdict !== "present_unwired")
|
|
1392
|
+
return null;
|
|
1393
|
+
return {
|
|
1394
|
+
id: "setup.hooks-unwired",
|
|
1395
|
+
status: "warn",
|
|
1396
|
+
scope: "setup",
|
|
1397
|
+
title: "Git-Hooks liegen im Repo, feuern aber nicht",
|
|
1398
|
+
detail: describeHookState(hooks),
|
|
1399
|
+
hint: hooks.reason === "path_missing" ? `core.hooksPath zeigt ins Leere. Korrigieren: git config core.hooksPath ${hooks.hookDirs[0] ?? ".githooks"}` : `git config core.hooksPath ${hooks.hookDirs[0] ?? ".githooks"} \u2014 git klont das Verzeichnis mit, den Pfad nie.`
|
|
1400
|
+
};
|
|
1401
|
+
}
|
|
1255
1402
|
function sortFindings(f) {
|
|
1256
1403
|
return [...f].sort((a, b) => STATUS_ORDER[a.status] - STATUS_ORDER[b.status] || a.id.localeCompare(b.id));
|
|
1257
1404
|
}
|
|
@@ -1340,7 +1487,8 @@ async function gatherRepoHealthFacts(repoRoot, opts = {}) {
|
|
|
1340
1487
|
otherWorktrees: 0,
|
|
1341
1488
|
worktreeParity: null,
|
|
1342
1489
|
release: null,
|
|
1343
|
-
unmergedMigrations: []
|
|
1490
|
+
unmergedMigrations: [],
|
|
1491
|
+
hooks: null
|
|
1344
1492
|
};
|
|
1345
1493
|
}
|
|
1346
1494
|
const branchRaw = trimOrNull(runGit(repoRoot, ["rev-parse", "--abbrev-ref", "HEAD"]));
|
|
@@ -1419,7 +1567,8 @@ async function gatherRepoHealthFacts(repoRoot, opts = {}) {
|
|
|
1419
1567
|
otherWorktrees,
|
|
1420
1568
|
worktreeParity,
|
|
1421
1569
|
release: release2,
|
|
1422
|
-
unmergedMigrations
|
|
1570
|
+
unmergedMigrations,
|
|
1571
|
+
hooks: resolveHookState(repoRoot)
|
|
1423
1572
|
};
|
|
1424
1573
|
}
|
|
1425
1574
|
function samePath(a, b) {
|
|
@@ -1450,7 +1599,7 @@ function gatherReleaseFact(repoRoot, branch) {
|
|
|
1450
1599
|
}
|
|
1451
1600
|
function runGh(repoRoot, args) {
|
|
1452
1601
|
try {
|
|
1453
|
-
return
|
|
1602
|
+
return execFileSync5("gh", args, {
|
|
1454
1603
|
cwd: repoRoot,
|
|
1455
1604
|
encoding: "utf8",
|
|
1456
1605
|
stdio: ["ignore", "pipe", "ignore"],
|
|
@@ -1470,6 +1619,7 @@ var DEFAULT_WORKTREE_PROBE_PATHS, WORKTREE_REQUIREMENTS_RELPATH, STATUS_ORDER;
|
|
|
1470
1619
|
var init_divergence = __esm({
|
|
1471
1620
|
"../../packages/code-index/build/repo-health/divergence.js"() {
|
|
1472
1621
|
"use strict";
|
|
1622
|
+
init_hooks();
|
|
1473
1623
|
init_discover();
|
|
1474
1624
|
DEFAULT_WORKTREE_PROBE_PATHS = [
|
|
1475
1625
|
"supabase/config.toml",
|
|
@@ -1482,7 +1632,7 @@ var init_divergence = __esm({
|
|
|
1482
1632
|
});
|
|
1483
1633
|
|
|
1484
1634
|
// ../../packages/code-index/build/repo-health/number-collisions.js
|
|
1485
|
-
import { existsSync as existsSync5, readdirSync as
|
|
1635
|
+
import { existsSync as existsSync5, readdirSync as readdirSync3 } from "node:fs";
|
|
1486
1636
|
import { posix as posix4 } from "node:path";
|
|
1487
1637
|
function isCounterNamespace(numbers, opts = {}) {
|
|
1488
1638
|
const minFiles = opts.minFiles ?? DEFAULT_MIN_FILES;
|
|
@@ -1689,7 +1839,7 @@ async function gatherNumberCollisionFacts(repoRoot, opts = {}) {
|
|
|
1689
1839
|
if (!existsSync5(abs))
|
|
1690
1840
|
continue;
|
|
1691
1841
|
try {
|
|
1692
|
-
for (const file of
|
|
1842
|
+
for (const file of readdirSync3(abs))
|
|
1693
1843
|
record(`${dir}/${file}`, "self", "this worktree");
|
|
1694
1844
|
} catch {
|
|
1695
1845
|
skipped.push(`could not read ${dir}`);
|
|
@@ -1720,7 +1870,7 @@ async function gatherNumberCollisionFacts(repoRoot, opts = {}) {
|
|
|
1720
1870
|
if (!existsSync5(abs))
|
|
1721
1871
|
continue;
|
|
1722
1872
|
try {
|
|
1723
|
-
for (const file of
|
|
1873
|
+
for (const file of readdirSync3(abs)) {
|
|
1724
1874
|
record(`${dir}/${file}`, "worktree", `Worktree ${root}`);
|
|
1725
1875
|
}
|
|
1726
1876
|
} catch {
|
|
@@ -2443,6 +2593,7 @@ var init_build = __esm({
|
|
|
2443
2593
|
init_history();
|
|
2444
2594
|
init_risk_rules();
|
|
2445
2595
|
init_divergence();
|
|
2596
|
+
init_hooks();
|
|
2446
2597
|
init_number_collisions();
|
|
2447
2598
|
init_types();
|
|
2448
2599
|
init_types2();
|
|
@@ -2451,23 +2602,221 @@ var init_build = __esm({
|
|
|
2451
2602
|
}
|
|
2452
2603
|
});
|
|
2453
2604
|
|
|
2605
|
+
// src/presence.ts
|
|
2606
|
+
import { execFile } from "node:child_process";
|
|
2607
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
2608
|
+
function resolveClientSessionId(env) {
|
|
2609
|
+
const fromEnv = (env.MAIND_SESSION_ID ?? "").trim().toLowerCase();
|
|
2610
|
+
return UUID_RE2.test(fromEnv) ? fromEnv : randomUUID2();
|
|
2611
|
+
}
|
|
2612
|
+
function autoAnnounceDisabled(env, config) {
|
|
2613
|
+
const raw = (env.MAIND_AUTO_ANNOUNCE ?? "").trim().toLowerCase();
|
|
2614
|
+
if (raw === "off" || raw === "0" || raw === "false") return true;
|
|
2615
|
+
return config?.auto_announce === false;
|
|
2616
|
+
}
|
|
2617
|
+
function autoWorkingPathsEnabled(env, config) {
|
|
2618
|
+
const raw = (env.MAIND_AUTO_WORKING_PATHS ?? "").trim().toLowerCase();
|
|
2619
|
+
if (raw === "on" || raw === "1" || raw === "true") return true;
|
|
2620
|
+
if (raw === "off" || raw === "0" || raw === "false") return false;
|
|
2621
|
+
return config?.auto_working_paths === true;
|
|
2622
|
+
}
|
|
2623
|
+
async function defaultGitBranch() {
|
|
2624
|
+
return await new Promise((resolve3) => {
|
|
2625
|
+
execFile(
|
|
2626
|
+
"git",
|
|
2627
|
+
["rev-parse", "--abbrev-ref", "HEAD"],
|
|
2628
|
+
{ timeout: 2e3, encoding: "utf8" },
|
|
2629
|
+
(err, stdout) => {
|
|
2630
|
+
if (err) return resolve3(null);
|
|
2631
|
+
const branch = stdout.trim();
|
|
2632
|
+
resolve3(branch.length > 0 && branch !== "HEAD" ? branch : null);
|
|
2633
|
+
}
|
|
2634
|
+
);
|
|
2635
|
+
});
|
|
2636
|
+
}
|
|
2637
|
+
function normalizeMachineLabel(raw) {
|
|
2638
|
+
if (typeof raw !== "string") return null;
|
|
2639
|
+
const v = raw.trim().slice(0, 100);
|
|
2640
|
+
return v.length > 0 ? v : null;
|
|
2641
|
+
}
|
|
2642
|
+
var REFRESH_THROTTLE_MS, TTL_MINUTES, BACKOFF_BASE_MS, BACKOFF_CAP_MS, END_TIMEOUT_MS, UUID_RE2, PresenceAnnouncer;
|
|
2643
|
+
var init_presence = __esm({
|
|
2644
|
+
"src/presence.ts"() {
|
|
2645
|
+
"use strict";
|
|
2646
|
+
init_bridge_config();
|
|
2647
|
+
REFRESH_THROTTLE_MS = 45e3;
|
|
2648
|
+
TTL_MINUTES = 120;
|
|
2649
|
+
BACKOFF_BASE_MS = 3e4;
|
|
2650
|
+
BACKOFF_CAP_MS = 15 * 6e4;
|
|
2651
|
+
END_TIMEOUT_MS = 1500;
|
|
2652
|
+
UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
2653
|
+
PresenceAnnouncer = class {
|
|
2654
|
+
projectKey;
|
|
2655
|
+
postToolCall;
|
|
2656
|
+
now;
|
|
2657
|
+
gitBranch;
|
|
2658
|
+
log;
|
|
2659
|
+
machineLabel;
|
|
2660
|
+
enabled;
|
|
2661
|
+
// ADR-277: consented enrichment + snapshot sink (both optional, fail-open).
|
|
2662
|
+
workingPathsEnabled;
|
|
2663
|
+
deriveWorkingPaths;
|
|
2664
|
+
snapshot;
|
|
2665
|
+
lastBranch = null;
|
|
2666
|
+
sessionId;
|
|
2667
|
+
lastAnnounceAt = 0;
|
|
2668
|
+
inFlight = false;
|
|
2669
|
+
consecutiveFailures = 0;
|
|
2670
|
+
nextAttemptAt = 0;
|
|
2671
|
+
ended = false;
|
|
2672
|
+
constructor(deps) {
|
|
2673
|
+
const env = deps.env ?? process.env;
|
|
2674
|
+
const config = (deps.readConfig ?? readBridgeConfig)();
|
|
2675
|
+
this.projectKey = deps.projectKey;
|
|
2676
|
+
this.postToolCall = deps.postToolCall;
|
|
2677
|
+
this.now = deps.now ?? Date.now;
|
|
2678
|
+
this.gitBranch = deps.gitBranch ?? defaultGitBranch;
|
|
2679
|
+
this.log = deps.log ?? ((msg) => process.stderr.write(msg + "\n"));
|
|
2680
|
+
this.machineLabel = normalizeMachineLabel(config?.machine_label);
|
|
2681
|
+
this.enabled = this.projectKey !== null && !autoAnnounceDisabled(env, config);
|
|
2682
|
+
this.workingPathsEnabled = autoWorkingPathsEnabled(env, config);
|
|
2683
|
+
this.deriveWorkingPaths = deps.deriveWorkingPaths ?? null;
|
|
2684
|
+
this.snapshot = deps.snapshot ?? null;
|
|
2685
|
+
this.sessionId = resolveClientSessionId(env);
|
|
2686
|
+
}
|
|
2687
|
+
get isEnabled() {
|
|
2688
|
+
return this.enabled;
|
|
2689
|
+
}
|
|
2690
|
+
/**
|
|
2691
|
+
* Called once the forwarder's MCP session is established (initialize
|
|
2692
|
+
* response captured). Fires the first announce — the session becomes visible
|
|
2693
|
+
* on /planning without any agent involvement (C1).
|
|
2694
|
+
*/
|
|
2695
|
+
onSessionReady() {
|
|
2696
|
+
if (!this.enabled || this.ended) return;
|
|
2697
|
+
if (this.lastAnnounceAt > 0) return;
|
|
2698
|
+
void this.announce("active");
|
|
2699
|
+
}
|
|
2700
|
+
/**
|
|
2701
|
+
* Called on every real tool-call passing through the bridge. Throttled
|
|
2702
|
+
* re-announce keeps the session fresh WHILE it is actually working; an idle
|
|
2703
|
+
* session stops refreshing and goes stale on the renderer — honest freshness.
|
|
2704
|
+
*/
|
|
2705
|
+
onActivity() {
|
|
2706
|
+
if (!this.enabled || this.ended) return;
|
|
2707
|
+
if (this.lastAnnounceAt === 0) return;
|
|
2708
|
+
if (this.now() - this.lastAnnounceAt < REFRESH_THROTTLE_MS) return;
|
|
2709
|
+
void this.announce("active");
|
|
2710
|
+
}
|
|
2711
|
+
/**
|
|
2712
|
+
* Best-effort `status:'ended'` on shutdown, bounded by END_TIMEOUT_MS so it
|
|
2713
|
+
* can never hold the process open. The server TTL is the fallback.
|
|
2714
|
+
*/
|
|
2715
|
+
async end() {
|
|
2716
|
+
if (!this.enabled || this.ended) return;
|
|
2717
|
+
this.ended = true;
|
|
2718
|
+
if (this.lastAnnounceAt === 0) return;
|
|
2719
|
+
const timeout = new Promise(
|
|
2720
|
+
(resolve3) => setTimeout(resolve3, END_TIMEOUT_MS).unref()
|
|
2721
|
+
);
|
|
2722
|
+
await Promise.race([this.send("ended"), timeout]);
|
|
2723
|
+
}
|
|
2724
|
+
async announce(status) {
|
|
2725
|
+
if (this.inFlight) return;
|
|
2726
|
+
if (this.now() < this.nextAttemptAt) return;
|
|
2727
|
+
this.inFlight = true;
|
|
2728
|
+
try {
|
|
2729
|
+
await this.send(status);
|
|
2730
|
+
if (this.consecutiveFailures > 0) {
|
|
2731
|
+
this.log("[maind-mcp-bridge] presence announce recovered.");
|
|
2732
|
+
}
|
|
2733
|
+
this.consecutiveFailures = 0;
|
|
2734
|
+
this.nextAttemptAt = 0;
|
|
2735
|
+
this.lastAnnounceAt = this.now();
|
|
2736
|
+
} catch (err) {
|
|
2737
|
+
this.consecutiveFailures += 1;
|
|
2738
|
+
const backoff = Math.min(
|
|
2739
|
+
BACKOFF_BASE_MS * 2 ** (this.consecutiveFailures - 1),
|
|
2740
|
+
BACKOFF_CAP_MS
|
|
2741
|
+
);
|
|
2742
|
+
this.nextAttemptAt = this.now() + backoff;
|
|
2743
|
+
if (this.consecutiveFailures === 1) {
|
|
2744
|
+
this.log(
|
|
2745
|
+
`[maind-mcp-bridge] presence announce failed (advisory, backing off): ${err instanceof Error ? err.message : String(err)}`
|
|
2746
|
+
);
|
|
2747
|
+
}
|
|
2748
|
+
} finally {
|
|
2749
|
+
this.inFlight = false;
|
|
2750
|
+
}
|
|
2751
|
+
}
|
|
2752
|
+
async send(status) {
|
|
2753
|
+
if (this.projectKey === null) return;
|
|
2754
|
+
const args = {
|
|
2755
|
+
project_key: this.projectKey,
|
|
2756
|
+
session_id: this.sessionId,
|
|
2757
|
+
status,
|
|
2758
|
+
ttl_minutes: TTL_MINUTES,
|
|
2759
|
+
// Self-declaration (migration 20260801120000). The server CANNOT derive
|
|
2760
|
+
// this: our announce rides the very same forwarder — headers included —
|
|
2761
|
+
// as an `announce_session` the agent writes itself, so the two requests
|
|
2762
|
+
// are byte-identical apart from these args. Without the marker a
|
|
2763
|
+
// skeleton row is indistinguishable from a sloppy agent session, which
|
|
2764
|
+
// is how 16 of 23 rows came to say nothing AND not say why. Display hint
|
|
2765
|
+
// only; the server keeps 'agent' once an agent has enriched the row.
|
|
2766
|
+
// ADR-277: the server ALSO keys its consent enforcement on this
|
|
2767
|
+
// self-declaration — infra-supplied working_paths are consent-gated,
|
|
2768
|
+
// deliberate agent declarations are not.
|
|
2769
|
+
announce_source: "bridge"
|
|
2770
|
+
};
|
|
2771
|
+
if (status === "active") {
|
|
2772
|
+
const branch = await this.gitBranch();
|
|
2773
|
+
if (branch) args.branch = branch;
|
|
2774
|
+
this.lastBranch = branch;
|
|
2775
|
+
if (this.machineLabel) args.machine_label = this.machineLabel;
|
|
2776
|
+
if (this.workingPathsEnabled && this.deriveWorkingPaths) {
|
|
2777
|
+
try {
|
|
2778
|
+
const wp = await this.deriveWorkingPaths();
|
|
2779
|
+
if (wp && wp.length > 0) args.working_paths = wp;
|
|
2780
|
+
} catch {
|
|
2781
|
+
}
|
|
2782
|
+
}
|
|
2783
|
+
}
|
|
2784
|
+
const payload = await this.postToolCall("announce_session", args);
|
|
2785
|
+
if (this.snapshot) {
|
|
2786
|
+
try {
|
|
2787
|
+
if (status === "ended") {
|
|
2788
|
+
this.snapshot.endSession();
|
|
2789
|
+
} else if (payload !== null && payload !== void 0) {
|
|
2790
|
+
this.snapshot.write(payload, {
|
|
2791
|
+
sessionId: this.sessionId,
|
|
2792
|
+
branch: this.lastBranch
|
|
2793
|
+
});
|
|
2794
|
+
}
|
|
2795
|
+
} catch {
|
|
2796
|
+
}
|
|
2797
|
+
}
|
|
2798
|
+
}
|
|
2799
|
+
};
|
|
2800
|
+
}
|
|
2801
|
+
});
|
|
2802
|
+
|
|
2454
2803
|
// src/presence-snapshot.ts
|
|
2455
2804
|
import {
|
|
2456
2805
|
mkdirSync as mkdirSync4,
|
|
2457
|
-
readdirSync as
|
|
2806
|
+
readdirSync as readdirSync4,
|
|
2458
2807
|
readFileSync as readFileSync7,
|
|
2459
2808
|
renameSync as renameSync2,
|
|
2460
|
-
statSync as
|
|
2809
|
+
statSync as statSync3,
|
|
2461
2810
|
unlinkSync,
|
|
2462
2811
|
writeFileSync as writeFileSync3
|
|
2463
2812
|
} from "node:fs";
|
|
2464
2813
|
import { homedir as homedir3 } from "node:os";
|
|
2465
|
-
import { join as
|
|
2814
|
+
import { join as join13 } from "node:path";
|
|
2466
2815
|
function presenceSnapshotBaseDir() {
|
|
2467
|
-
return
|
|
2816
|
+
return join13(homedir3(), ".maind", "presence");
|
|
2468
2817
|
}
|
|
2469
2818
|
function projectDir(baseDir, projectKey) {
|
|
2470
|
-
return
|
|
2819
|
+
return join13(baseDir, projectKey);
|
|
2471
2820
|
}
|
|
2472
2821
|
function createSnapshotStore(opts) {
|
|
2473
2822
|
const baseDir = opts.baseDir ?? presenceSnapshotBaseDir();
|
|
@@ -2496,7 +2845,7 @@ function createSnapshotStore(opts) {
|
|
|
2496
2845
|
conflicts: Array.isArray(p.conflicts) ? p.conflicts : []
|
|
2497
2846
|
};
|
|
2498
2847
|
mkdirSync4(dir, { recursive: true, mode: 448 });
|
|
2499
|
-
ownFile =
|
|
2848
|
+
ownFile = join13(dir, `${meta.sessionId}.json`);
|
|
2500
2849
|
const tmp = `${ownFile}.tmp-${pid}`;
|
|
2501
2850
|
writeFileSync3(tmp, JSON.stringify(snapshot), { mode: 384 });
|
|
2502
2851
|
renameSync2(tmp, ownFile);
|
|
@@ -2514,12 +2863,12 @@ function createSnapshotStore(opts) {
|
|
|
2514
2863
|
}
|
|
2515
2864
|
function pruneStale(dir, nowMs, keep) {
|
|
2516
2865
|
try {
|
|
2517
|
-
for (const name of
|
|
2866
|
+
for (const name of readdirSync4(dir)) {
|
|
2518
2867
|
if (!name.endsWith(".json")) continue;
|
|
2519
|
-
const file =
|
|
2868
|
+
const file = join13(dir, name);
|
|
2520
2869
|
if (file === keep) continue;
|
|
2521
2870
|
try {
|
|
2522
|
-
const age = nowMs -
|
|
2871
|
+
const age = nowMs - statSync3(file).mtimeMs;
|
|
2523
2872
|
if (age > SNAPSHOT_TTL_MS) unlinkSync(file);
|
|
2524
2873
|
} catch {
|
|
2525
2874
|
}
|
|
@@ -2531,11 +2880,11 @@ function readSnapshots(projectKey, baseDir = presenceSnapshotBaseDir()) {
|
|
|
2531
2880
|
try {
|
|
2532
2881
|
const dir = projectDir(baseDir, projectKey);
|
|
2533
2882
|
const out2 = [];
|
|
2534
|
-
for (const name of
|
|
2883
|
+
for (const name of readdirSync4(dir)) {
|
|
2535
2884
|
if (!name.endsWith(".json")) continue;
|
|
2536
2885
|
try {
|
|
2537
2886
|
const raw = JSON.parse(
|
|
2538
|
-
readFileSync7(
|
|
2887
|
+
readFileSync7(join13(dir, name), "utf8")
|
|
2539
2888
|
);
|
|
2540
2889
|
const snap = parseSnapshot(raw);
|
|
2541
2890
|
if (snap) out2.push(snap);
|
|
@@ -2603,7 +2952,7 @@ async function summariseTranscript(path8) {
|
|
|
2603
2952
|
let input = 0;
|
|
2604
2953
|
let output = 0;
|
|
2605
2954
|
let lines2 = 0;
|
|
2606
|
-
return await new Promise((
|
|
2955
|
+
return await new Promise((resolve3) => {
|
|
2607
2956
|
const stream = createReadStream(path8, { encoding: "utf-8" });
|
|
2608
2957
|
const rl = createInterface5({ input: stream });
|
|
2609
2958
|
rl.on("line", (line) => {
|
|
@@ -2624,7 +2973,7 @@ async function summariseTranscript(path8) {
|
|
|
2624
2973
|
}
|
|
2625
2974
|
});
|
|
2626
2975
|
rl.on("close", () => {
|
|
2627
|
-
|
|
2976
|
+
resolve3({
|
|
2628
2977
|
input_tokens: input,
|
|
2629
2978
|
output_tokens: output,
|
|
2630
2979
|
total_tokens: input + output,
|
|
@@ -2632,8 +2981,8 @@ async function summariseTranscript(path8) {
|
|
|
2632
2981
|
last_modified_ms: stats.mtimeMs
|
|
2633
2982
|
});
|
|
2634
2983
|
});
|
|
2635
|
-
rl.on("error", () =>
|
|
2636
|
-
stream.on("error", () =>
|
|
2984
|
+
rl.on("error", () => resolve3(null));
|
|
2985
|
+
stream.on("error", () => resolve3(null));
|
|
2637
2986
|
});
|
|
2638
2987
|
}
|
|
2639
2988
|
var init_transcript = __esm({
|
|
@@ -2776,6 +3125,8 @@ function emptyAnalysis(sessionId) {
|
|
|
2776
3125
|
model_mix: [],
|
|
2777
3126
|
ai_title: null,
|
|
2778
3127
|
session_slug: null,
|
|
3128
|
+
maind_tool_calls: {},
|
|
3129
|
+
maind_connected: "unknown",
|
|
2779
3130
|
lines_seen: 0,
|
|
2780
3131
|
analyzer_version: ANALYZER_VERSION
|
|
2781
3132
|
};
|
|
@@ -2789,7 +3140,7 @@ async function analyzeSession(path8) {
|
|
|
2789
3140
|
let effort = null;
|
|
2790
3141
|
let priorAssistantWorked = false;
|
|
2791
3142
|
let prevUserText = null;
|
|
2792
|
-
await new Promise((
|
|
3143
|
+
await new Promise((resolve3) => {
|
|
2793
3144
|
const stream = createReadStream2(path8, { encoding: "utf-8" });
|
|
2794
3145
|
const rl = createInterface6({ input: stream });
|
|
2795
3146
|
const processLine = (line) => {
|
|
@@ -2826,6 +3177,18 @@ async function analyzeSession(path8) {
|
|
|
2826
3177
|
const rawTs = parsed.timestamp ? Date.parse(parsed.timestamp) : Number.NaN;
|
|
2827
3178
|
bumpModel(modelMix, parsed.message.model, isSide, num2(usage?.output_tokens), Number.isFinite(rawTs) ? rawTs : 0);
|
|
2828
3179
|
}
|
|
3180
|
+
if (role === "assistant") {
|
|
3181
|
+
for (const b of asBlocks(parsed.message?.content)) {
|
|
3182
|
+
if (b.type !== "tool_use" || typeof b.name !== "string")
|
|
3183
|
+
continue;
|
|
3184
|
+
if (!b.name.startsWith(MAIND_TOOL_PREFIX))
|
|
3185
|
+
continue;
|
|
3186
|
+
const tool = b.name.slice(MAIND_TOOL_PREFIX.length);
|
|
3187
|
+
if (!tool)
|
|
3188
|
+
continue;
|
|
3189
|
+
a.maind_tool_calls[tool] = (a.maind_tool_calls[tool] ?? 0) + 1;
|
|
3190
|
+
}
|
|
3191
|
+
}
|
|
2829
3192
|
if (isSide)
|
|
2830
3193
|
return;
|
|
2831
3194
|
if (role === "assistant") {
|
|
@@ -2887,9 +3250,9 @@ async function analyzeSession(path8) {
|
|
|
2887
3250
|
} catch {
|
|
2888
3251
|
}
|
|
2889
3252
|
});
|
|
2890
|
-
rl.on("close", () =>
|
|
2891
|
-
rl.on("error", () =>
|
|
2892
|
-
stream.on("error", () =>
|
|
3253
|
+
rl.on("close", () => resolve3());
|
|
3254
|
+
rl.on("error", () => resolve3());
|
|
3255
|
+
stream.on("error", () => resolve3());
|
|
2893
3256
|
});
|
|
2894
3257
|
a.effort_at_end = effort;
|
|
2895
3258
|
a.model_mix = [...modelMix.values()].sort((x, y) => x.first_ts - y.first_ts || x.model.localeCompare(y.model));
|
|
@@ -2920,14 +3283,17 @@ async function analyzeSession(path8) {
|
|
|
2920
3283
|
a.momentum_final = series.length ? series[series.length - 1].value : 0;
|
|
2921
3284
|
a.momentum_auc = Number(auc.toFixed(3));
|
|
2922
3285
|
a.ended_positive = a.momentum_final > 0;
|
|
3286
|
+
if (Object.keys(a.maind_tool_calls).length > 0)
|
|
3287
|
+
a.maind_connected = "connected";
|
|
2923
3288
|
return a;
|
|
2924
3289
|
}
|
|
2925
|
-
var ANALYZER_VERSION, REWORK_RE, CORRECTION_RE, ACCEPTANCE_RE, INTERRUPT_MARKER, DENIAL_MARKER, SYNTHETIC_MODEL, MOMENTUM_DECAY, MAG;
|
|
3290
|
+
var MAIND_TOOL_PREFIX, ANALYZER_VERSION, REWORK_RE, CORRECTION_RE, ACCEPTANCE_RE, INTERRUPT_MARKER, DENIAL_MARKER, SYNTHETIC_MODEL, MOMENTUM_DECAY, MAG;
|
|
2926
3291
|
var init_session_analysis = __esm({
|
|
2927
3292
|
"../../packages/claude-code-telemetry/dist/session-analysis.js"() {
|
|
2928
3293
|
"use strict";
|
|
2929
3294
|
init_effort();
|
|
2930
|
-
|
|
3295
|
+
MAIND_TOOL_PREFIX = "mcp__maind__";
|
|
3296
|
+
ANALYZER_VERSION = "2026-08-16";
|
|
2931
3297
|
REWORK_RE = /(\brückgängig\b|zurücknehmen|\bnochmal(s)?\b|noch mal|\brevert\b|\bundo\b|\bredo\b|stattdessen|\binstead\b|mach(e)? das (nochmal|neu)|try again)/i;
|
|
2932
3298
|
CORRECTION_RE = /(\bnein\b|\bfalsch\b|stimmt nicht|das ist nicht|so nicht|\bnicht so\b|warum hast du|wieso hast du|\bno\b|\bnope\b|\bwrong\b|\bincorrect\b|that'?s not|that is not|\bdon'?t\b|\bdoesn'?t\b|shouldn'?t)/i;
|
|
2933
3299
|
ACCEPTANCE_RE = /(\bdanke\b|\bperfekt\b|\bsuper\b|\bpasst\b|\bgenau\b|sieht gut|\bcommit\b|\bship\b|\bmerge\b|\bpush\b|looks good|\blgtm\b|\bthanks\b|thank you|\bperfect\b|\bgreat\b|\bexactly\b|\bnice\b|well done|👍|✅|🎉)/i;
|
|
@@ -3021,7 +3387,7 @@ async function analyzeSpan(path8) {
|
|
|
3021
3387
|
let prevMs = null;
|
|
3022
3388
|
let prevHolder = "human";
|
|
3023
3389
|
const pauses = [];
|
|
3024
|
-
await new Promise((
|
|
3390
|
+
await new Promise((resolve3) => {
|
|
3025
3391
|
const stream = createReadStream3(path8, { encoding: "utf-8" });
|
|
3026
3392
|
const rl = createInterface7({ input: stream });
|
|
3027
3393
|
const processLine = (line) => {
|
|
@@ -3079,9 +3445,9 @@ async function analyzeSpan(path8) {
|
|
|
3079
3445
|
} catch {
|
|
3080
3446
|
}
|
|
3081
3447
|
});
|
|
3082
|
-
rl.on("close", () =>
|
|
3083
|
-
rl.on("error", () =>
|
|
3084
|
-
stream.on("error", () =>
|
|
3448
|
+
rl.on("close", () => resolve3());
|
|
3449
|
+
rl.on("error", () => resolve3());
|
|
3450
|
+
stream.on("error", () => resolve3());
|
|
3085
3451
|
});
|
|
3086
3452
|
if (firstMs === null)
|
|
3087
3453
|
return s;
|
|
@@ -3126,13 +3492,13 @@ var init_windows = __esm({
|
|
|
3126
3492
|
|
|
3127
3493
|
// ../../packages/claude-code-telemetry/dist/projects.js
|
|
3128
3494
|
import { homedir as homedir4 } from "node:os";
|
|
3129
|
-
import { join as
|
|
3495
|
+
import { join as join14 } from "node:path";
|
|
3130
3496
|
var HOME, DEFAULT_PROJECTS_DIR;
|
|
3131
3497
|
var init_projects = __esm({
|
|
3132
3498
|
"../../packages/claude-code-telemetry/dist/projects.js"() {
|
|
3133
3499
|
"use strict";
|
|
3134
3500
|
HOME = homedir4();
|
|
3135
|
-
DEFAULT_PROJECTS_DIR =
|
|
3501
|
+
DEFAULT_PROJECTS_DIR = join14(HOME, ".claude", "projects");
|
|
3136
3502
|
}
|
|
3137
3503
|
});
|
|
3138
3504
|
|
|
@@ -3201,48 +3567,6 @@ var init_api = __esm({
|
|
|
3201
3567
|
}
|
|
3202
3568
|
});
|
|
3203
3569
|
|
|
3204
|
-
// src/hooks/hook-input.ts
|
|
3205
|
-
async function readHookInput() {
|
|
3206
|
-
if (process.stdin.isTTY) return {};
|
|
3207
|
-
const chunks = [];
|
|
3208
|
-
return await new Promise((resolve2) => {
|
|
3209
|
-
let settled = false;
|
|
3210
|
-
const settle = (value) => {
|
|
3211
|
-
if (settled) return;
|
|
3212
|
-
settled = true;
|
|
3213
|
-
clearTimeout(timer);
|
|
3214
|
-
resolve2(value);
|
|
3215
|
-
};
|
|
3216
|
-
const timer = setTimeout(() => settle({}), STDIN_TIMEOUT_MS);
|
|
3217
|
-
process.stdin.on("data", (c) => chunks.push(c));
|
|
3218
|
-
process.stdin.on("end", () => {
|
|
3219
|
-
try {
|
|
3220
|
-
const text = Buffer.concat(chunks).toString("utf-8").trim();
|
|
3221
|
-
settle(text ? JSON.parse(text) : {});
|
|
3222
|
-
} catch {
|
|
3223
|
-
settle({});
|
|
3224
|
-
}
|
|
3225
|
-
});
|
|
3226
|
-
process.stdin.on("error", () => settle({}));
|
|
3227
|
-
});
|
|
3228
|
-
}
|
|
3229
|
-
function transcriptPathOf(input) {
|
|
3230
|
-
return typeof input.transcript_path === "string" ? input.transcript_path : "";
|
|
3231
|
-
}
|
|
3232
|
-
function toolFilePathOf(input) {
|
|
3233
|
-
const args = input.tool_input;
|
|
3234
|
-
if (args === null || typeof args !== "object") return "";
|
|
3235
|
-
const p = args.file_path;
|
|
3236
|
-
return typeof p === "string" ? p : "";
|
|
3237
|
-
}
|
|
3238
|
-
var STDIN_TIMEOUT_MS;
|
|
3239
|
-
var init_hook_input = __esm({
|
|
3240
|
-
"src/hooks/hook-input.ts"() {
|
|
3241
|
-
"use strict";
|
|
3242
|
-
STDIN_TIMEOUT_MS = 200;
|
|
3243
|
-
}
|
|
3244
|
-
});
|
|
3245
|
-
|
|
3246
3570
|
// src/hooks/edit-guard.ts
|
|
3247
3571
|
function prefixConflict(a, b) {
|
|
3248
3572
|
if (a === b) return true;
|
|
@@ -3351,11 +3675,53 @@ var init_edit_guard = __esm({
|
|
|
3351
3675
|
}
|
|
3352
3676
|
});
|
|
3353
3677
|
|
|
3678
|
+
// src/hooks/hook-input.ts
|
|
3679
|
+
async function readHookInput() {
|
|
3680
|
+
if (process.stdin.isTTY) return {};
|
|
3681
|
+
const chunks = [];
|
|
3682
|
+
return await new Promise((resolve3) => {
|
|
3683
|
+
let settled = false;
|
|
3684
|
+
const settle = (value) => {
|
|
3685
|
+
if (settled) return;
|
|
3686
|
+
settled = true;
|
|
3687
|
+
clearTimeout(timer);
|
|
3688
|
+
resolve3(value);
|
|
3689
|
+
};
|
|
3690
|
+
const timer = setTimeout(() => settle({}), STDIN_TIMEOUT_MS);
|
|
3691
|
+
process.stdin.on("data", (c) => chunks.push(c));
|
|
3692
|
+
process.stdin.on("end", () => {
|
|
3693
|
+
try {
|
|
3694
|
+
const text = Buffer.concat(chunks).toString("utf-8").trim();
|
|
3695
|
+
settle(text ? JSON.parse(text) : {});
|
|
3696
|
+
} catch {
|
|
3697
|
+
settle({});
|
|
3698
|
+
}
|
|
3699
|
+
});
|
|
3700
|
+
process.stdin.on("error", () => settle({}));
|
|
3701
|
+
});
|
|
3702
|
+
}
|
|
3703
|
+
function transcriptPathOf(input) {
|
|
3704
|
+
return typeof input.transcript_path === "string" ? input.transcript_path : "";
|
|
3705
|
+
}
|
|
3706
|
+
function toolFilePathOf(input) {
|
|
3707
|
+
const args = input.tool_input;
|
|
3708
|
+
if (args === null || typeof args !== "object") return "";
|
|
3709
|
+
const p = args.file_path;
|
|
3710
|
+
return typeof p === "string" ? p : "";
|
|
3711
|
+
}
|
|
3712
|
+
var STDIN_TIMEOUT_MS;
|
|
3713
|
+
var init_hook_input = __esm({
|
|
3714
|
+
"src/hooks/hook-input.ts"() {
|
|
3715
|
+
"use strict";
|
|
3716
|
+
STDIN_TIMEOUT_MS = 200;
|
|
3717
|
+
}
|
|
3718
|
+
});
|
|
3719
|
+
|
|
3354
3720
|
// src/hooks/state.ts
|
|
3355
3721
|
import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2, rename as rename2 } from "node:fs/promises";
|
|
3356
3722
|
import { existsSync as existsSync9 } from "node:fs";
|
|
3357
3723
|
import { homedir as homedir5 } from "node:os";
|
|
3358
|
-
import { join as
|
|
3724
|
+
import { join as join15 } from "node:path";
|
|
3359
3725
|
function emptyState() {
|
|
3360
3726
|
return { config: null, sessions: {}, pending_metrics: [] };
|
|
3361
3727
|
}
|
|
@@ -3394,8 +3760,8 @@ var STATE_DIR, STATE_FILE, DEFAULT_THRESHOLDS;
|
|
|
3394
3760
|
var init_state = __esm({
|
|
3395
3761
|
"src/hooks/state.ts"() {
|
|
3396
3762
|
"use strict";
|
|
3397
|
-
STATE_DIR =
|
|
3398
|
-
STATE_FILE =
|
|
3763
|
+
STATE_DIR = join15(homedir5(), ".maind");
|
|
3764
|
+
STATE_FILE = join15(STATE_DIR, "state.json");
|
|
3399
3765
|
DEFAULT_THRESHOLDS = {
|
|
3400
3766
|
warn_at_pct: 60,
|
|
3401
3767
|
handoff_at_pct: 85,
|
|
@@ -3408,6 +3774,7 @@ var init_state = __esm({
|
|
|
3408
3774
|
var hooks_exports = {};
|
|
3409
3775
|
__export(hooks_exports, {
|
|
3410
3776
|
effectiveConfig: () => effectiveConfig,
|
|
3777
|
+
grandparentPid: () => grandparentPid,
|
|
3411
3778
|
runFlush: () => runFlush,
|
|
3412
3779
|
runHookStatus: () => runHookStatus,
|
|
3413
3780
|
runOnFileEdit: () => runOnFileEdit,
|
|
@@ -3417,11 +3784,11 @@ __export(hooks_exports, {
|
|
|
3417
3784
|
runSessionEndMetrics: () => runSessionEndMetrics,
|
|
3418
3785
|
runSyncConfig: () => runSyncConfig
|
|
3419
3786
|
});
|
|
3420
|
-
import { execFileSync as
|
|
3787
|
+
import { execFileSync as execFileSync7 } from "node:child_process";
|
|
3421
3788
|
import { existsSync as existsSync10, readFileSync as readFileSync8, realpathSync } from "node:fs";
|
|
3422
3789
|
import { writeFile as writeFile3 } from "node:fs/promises";
|
|
3423
3790
|
import { homedir as homedir6 } from "node:os";
|
|
3424
|
-
import { basename, dirname as dirname5, isAbsolute as
|
|
3791
|
+
import { basename, dirname as dirname5, isAbsolute as isAbsolute3, join as join16, relative as relative2 } from "node:path";
|
|
3425
3792
|
function effectiveConfig(state) {
|
|
3426
3793
|
if (state.config) return state.config;
|
|
3427
3794
|
const key = readApiKey();
|
|
@@ -3478,7 +3845,7 @@ async function runOnSessionStart() {
|
|
|
3478
3845
|
}
|
|
3479
3846
|
function readSettingsRaw() {
|
|
3480
3847
|
try {
|
|
3481
|
-
const p =
|
|
3848
|
+
const p = join16(homedir6(), ".claude", "settings.json");
|
|
3482
3849
|
return existsSync10(p) ? readFileSync8(p, "utf8") : null;
|
|
3483
3850
|
} catch {
|
|
3484
3851
|
return null;
|
|
@@ -3487,7 +3854,7 @@ function readSettingsRaw() {
|
|
|
3487
3854
|
function grandparentPid() {
|
|
3488
3855
|
try {
|
|
3489
3856
|
if (process.platform === "win32") return null;
|
|
3490
|
-
const out2 =
|
|
3857
|
+
const out2 = execFileSync7("ps", ["-o", "ppid=", "-p", String(process.ppid)], {
|
|
3491
3858
|
timeout: 1e3,
|
|
3492
3859
|
encoding: "utf8"
|
|
3493
3860
|
});
|
|
@@ -3528,7 +3895,7 @@ function realpathOfUnwritten(p) {
|
|
|
3528
3895
|
for (; ; ) {
|
|
3529
3896
|
try {
|
|
3530
3897
|
const real = realpathSync(head);
|
|
3531
|
-
return
|
|
3898
|
+
return join16(real, ...tail.reverse());
|
|
3532
3899
|
} catch {
|
|
3533
3900
|
const parent = dirname5(head);
|
|
3534
3901
|
if (parent === head) return p;
|
|
@@ -3562,11 +3929,11 @@ async function runOnFileWrite() {
|
|
|
3562
3929
|
const filePath = toolFilePathOf(input);
|
|
3563
3930
|
if (!filePath) return 0;
|
|
3564
3931
|
const cwd = typeof input.cwd === "string" && input.cwd.length > 0 ? input.cwd : process.cwd();
|
|
3565
|
-
const abs =
|
|
3932
|
+
const abs = isAbsolute3(filePath) ? filePath : join16(cwd, filePath);
|
|
3566
3933
|
if (existsSync10(abs)) return 0;
|
|
3567
3934
|
const repoRoot = resolveRepoRoot(cwd);
|
|
3568
|
-
const rel =
|
|
3569
|
-
if (rel.length === 0 || rel.startsWith("..") ||
|
|
3935
|
+
const rel = relative2(repoRoot, realpathOfUnwritten(abs));
|
|
3936
|
+
if (rel.length === 0 || rel.startsWith("..") || isAbsolute3(rel)) return 0;
|
|
3570
3937
|
const verdict = await checkNumberForPath(repoRoot, rel);
|
|
3571
3938
|
if (!verdict.taken || verdict.namespace === null) return 0;
|
|
3572
3939
|
process.stdout.write(denyPayload(denyReason(verdict, verdict.namespace)));
|
|
@@ -3591,7 +3958,7 @@ async function runOnFileEdit() {
|
|
|
3591
3958
|
const filePath = toolFilePathOf(input);
|
|
3592
3959
|
if (!filePath) return 0;
|
|
3593
3960
|
const cwd = typeof input.cwd === "string" && input.cwd.length > 0 ? input.cwd : process.cwd();
|
|
3594
|
-
const abs =
|
|
3961
|
+
const abs = isAbsolute3(filePath) ? filePath : join16(cwd, filePath);
|
|
3595
3962
|
const projectKey = computeProjectKey();
|
|
3596
3963
|
if (projectKey === null) return 0;
|
|
3597
3964
|
const snaps = readSnapshots(projectKey);
|
|
@@ -3603,8 +3970,8 @@ async function runOnFileEdit() {
|
|
|
3603
3970
|
if (own === null) return 0;
|
|
3604
3971
|
const repoRoot = resolveRepoRoot(cwd);
|
|
3605
3972
|
const real = existsSync10(abs) ? realpathSync(abs) : realpathOfUnwritten(abs);
|
|
3606
|
-
const rel =
|
|
3607
|
-
if (rel.length === 0 || rel.startsWith("..") ||
|
|
3973
|
+
const rel = relative2(repoRoot, real).replace(/\\/g, "/");
|
|
3974
|
+
if (rel.length === 0 || rel.startsWith("..") || isAbsolute3(rel)) return 0;
|
|
3608
3975
|
const advice = adviseOnPath(own.snap, rel, {
|
|
3609
3976
|
via: own.via,
|
|
3610
3977
|
currentBranch: own.via === "cwd" ? currentGitBranch(cwd) : null,
|
|
@@ -3619,7 +3986,7 @@ async function runOnFileEdit() {
|
|
|
3619
3986
|
}
|
|
3620
3987
|
function currentGitBranch(cwd) {
|
|
3621
3988
|
try {
|
|
3622
|
-
const out2 =
|
|
3989
|
+
const out2 = execFileSync7("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
|
|
3623
3990
|
cwd,
|
|
3624
3991
|
timeout: 1e3,
|
|
3625
3992
|
encoding: "utf8"
|
|
@@ -3654,7 +4021,7 @@ async function maybeEmitAdvisory(state, session) {
|
|
|
3654
4021
|
};
|
|
3655
4022
|
try {
|
|
3656
4023
|
await writeFile3(
|
|
3657
|
-
|
|
4024
|
+
join16(STATE_DIR, `handoff_advisory_${session.session_id}.json`),
|
|
3658
4025
|
JSON.stringify(payload, null, 2)
|
|
3659
4026
|
);
|
|
3660
4027
|
} catch (err) {
|
|
@@ -3733,7 +4100,7 @@ async function flushPending(config, timeoutMs) {
|
|
|
3733
4100
|
const batch = state.pending_metrics.slice(0, 100);
|
|
3734
4101
|
const post = postMetrics(config.endpoint, config.api_key, batch);
|
|
3735
4102
|
const timeout = new Promise(
|
|
3736
|
-
(
|
|
4103
|
+
(resolve3) => setTimeout(() => resolve3({ ok: false, inserted: 0, error: "timeout" }), timeoutMs)
|
|
3737
4104
|
);
|
|
3738
4105
|
const result = await Promise.race([post, timeout]);
|
|
3739
4106
|
if (result.ok) {
|
|
@@ -3793,7 +4160,7 @@ async function runHookStatus() {
|
|
|
3793
4160
|
return 0;
|
|
3794
4161
|
}
|
|
3795
4162
|
function readHookWiring() {
|
|
3796
|
-
const settingsPath =
|
|
4163
|
+
const settingsPath = join16(homedir6(), ".claude", "settings.json");
|
|
3797
4164
|
let raw = null;
|
|
3798
4165
|
try {
|
|
3799
4166
|
if (existsSync10(settingsPath)) raw = readFileSync8(settingsPath, "utf8");
|
|
@@ -3871,7 +4238,7 @@ function sessionIdOf(input) {
|
|
|
3871
4238
|
return id.length > 0 ? id : null;
|
|
3872
4239
|
}
|
|
3873
4240
|
var DEFAULT_THRESHOLDS_ENDPOINT, STOP_FLUSH_TIMEOUT_MS, MANUAL_FLUSH_TIMEOUT_MS, WIRING_REMEDY;
|
|
3874
|
-
var
|
|
4241
|
+
var init_hooks2 = __esm({
|
|
3875
4242
|
"src/hooks/index.ts"() {
|
|
3876
4243
|
"use strict";
|
|
3877
4244
|
init_dist();
|
|
@@ -3892,11 +4259,48 @@ var init_hooks = __esm({
|
|
|
3892
4259
|
}
|
|
3893
4260
|
});
|
|
3894
4261
|
|
|
4262
|
+
// src/session-end/connection.ts
|
|
4263
|
+
function resolveConnection(e) {
|
|
4264
|
+
if (e.ownSnapshotAgeMs !== null && e.ownSnapshotAgeMs <= SNAPSHOT_EVIDENCE_MAX_AGE_MS) {
|
|
4265
|
+
return "connected";
|
|
4266
|
+
}
|
|
4267
|
+
if (e.sawMaindCall) return "connected";
|
|
4268
|
+
if (e.presenceUsable) return "not_connected";
|
|
4269
|
+
return "unknown";
|
|
4270
|
+
}
|
|
4271
|
+
var SNAPSHOT_EVIDENCE_MAX_AGE_MS;
|
|
4272
|
+
var init_connection = __esm({
|
|
4273
|
+
"src/session-end/connection.ts"() {
|
|
4274
|
+
"use strict";
|
|
4275
|
+
SNAPSHOT_EVIDENCE_MAX_AGE_MS = 30 * 6e4;
|
|
4276
|
+
}
|
|
4277
|
+
});
|
|
4278
|
+
|
|
3895
4279
|
// src/session-end/index.ts
|
|
3896
4280
|
var session_end_exports = {};
|
|
3897
4281
|
__export(session_end_exports, {
|
|
3898
4282
|
runOnSessionEnd: () => runOnSessionEnd
|
|
3899
4283
|
});
|
|
4284
|
+
function connectionVerdict(sawMaindCall, nowMs) {
|
|
4285
|
+
try {
|
|
4286
|
+
const projectKey = computeProjectKey();
|
|
4287
|
+
const presenceUsable = projectKey !== null && !autoAnnounceDisabled(process.env, readBridgeConfig());
|
|
4288
|
+
let ownSnapshotAgeMs = null;
|
|
4289
|
+
if (projectKey !== null) {
|
|
4290
|
+
const own = selectOwnSnapshot(readSnapshots(projectKey), {
|
|
4291
|
+
grandparentPid: grandparentPid(),
|
|
4292
|
+
cwd: process.cwd()
|
|
4293
|
+
});
|
|
4294
|
+
if (own) {
|
|
4295
|
+
const written = Date.parse(own.snap.written_at);
|
|
4296
|
+
ownSnapshotAgeMs = Number.isFinite(written) ? Math.max(0, nowMs - written) : null;
|
|
4297
|
+
}
|
|
4298
|
+
}
|
|
4299
|
+
return resolveConnection({ ownSnapshotAgeMs, sawMaindCall, presenceUsable });
|
|
4300
|
+
} catch {
|
|
4301
|
+
return sawMaindCall ? "connected" : "unknown";
|
|
4302
|
+
}
|
|
4303
|
+
}
|
|
3900
4304
|
function presenceSessionId() {
|
|
3901
4305
|
const raw = (process.env.MAIND_SESSION_ID ?? "").trim().toLowerCase();
|
|
3902
4306
|
return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(raw) ? raw : null;
|
|
@@ -3912,7 +4316,7 @@ async function postWithTimeout(apiKey, deviceId, body, timeoutMs) {
|
|
|
3912
4316
|
},
|
|
3913
4317
|
body: JSON.stringify(body)
|
|
3914
4318
|
}).then(() => void 0).catch(() => void 0);
|
|
3915
|
-
const timeout = new Promise((
|
|
4319
|
+
const timeout = new Promise((resolve3) => setTimeout(resolve3, timeoutMs));
|
|
3916
4320
|
await Promise.race([post, timeout]);
|
|
3917
4321
|
}
|
|
3918
4322
|
async function runOnSessionEnd() {
|
|
@@ -3931,6 +4335,10 @@ async function runOnSessionEnd() {
|
|
|
3931
4335
|
analytics.session_id = sessionId;
|
|
3932
4336
|
span.session_id = sessionId;
|
|
3933
4337
|
}
|
|
4338
|
+
analytics.maind_connected = connectionVerdict(
|
|
4339
|
+
analytics.maind_connected === "connected",
|
|
4340
|
+
Date.now()
|
|
4341
|
+
);
|
|
3934
4342
|
if (analytics.session_id) {
|
|
3935
4343
|
const body = ingestBody(analytics, span, {
|
|
3936
4344
|
client_session_id: presenceSessionId(),
|
|
@@ -3953,11 +4361,17 @@ var init_session_end = __esm({
|
|
|
3953
4361
|
"src/session-end/index.ts"() {
|
|
3954
4362
|
"use strict";
|
|
3955
4363
|
init_dist();
|
|
4364
|
+
init_bridge_config();
|
|
3956
4365
|
init_device_id();
|
|
3957
4366
|
init_api();
|
|
4367
|
+
init_edit_guard();
|
|
3958
4368
|
init_hook_input();
|
|
3959
|
-
|
|
4369
|
+
init_hooks2();
|
|
4370
|
+
init_presence();
|
|
4371
|
+
init_presence_snapshot();
|
|
4372
|
+
init_project_key();
|
|
3960
4373
|
init_version();
|
|
4374
|
+
init_connection();
|
|
3961
4375
|
INGEST_ENDPOINT = DEFAULT_INGEST_ENDPOINT;
|
|
3962
4376
|
}
|
|
3963
4377
|
});
|
|
@@ -4633,7 +5047,7 @@ async function pollOnce(url, deviceCode) {
|
|
|
4633
5047
|
return await res.json();
|
|
4634
5048
|
}
|
|
4635
5049
|
function sleep(ms) {
|
|
4636
|
-
return new Promise((
|
|
5050
|
+
return new Promise((resolve3) => setTimeout(resolve3, ms));
|
|
4637
5051
|
}
|
|
4638
5052
|
function printAuthInstructions(start, out2) {
|
|
4639
5053
|
const lines2 = [
|
|
@@ -4675,7 +5089,7 @@ async function openExternalBrowser(url) {
|
|
|
4675
5089
|
args = [url];
|
|
4676
5090
|
break;
|
|
4677
5091
|
}
|
|
4678
|
-
return new Promise((
|
|
5092
|
+
return new Promise((resolve3, reject) => {
|
|
4679
5093
|
try {
|
|
4680
5094
|
const child = spawn(cmd, args, {
|
|
4681
5095
|
stdio: "ignore",
|
|
@@ -4683,7 +5097,7 @@ async function openExternalBrowser(url) {
|
|
|
4683
5097
|
});
|
|
4684
5098
|
child.on("error", reject);
|
|
4685
5099
|
child.unref();
|
|
4686
|
-
|
|
5100
|
+
resolve3();
|
|
4687
5101
|
} catch (err) {
|
|
4688
5102
|
reject(err);
|
|
4689
5103
|
}
|
|
@@ -4808,11 +5222,11 @@ var InstallFlagError = class extends Error {
|
|
|
4808
5222
|
function printInstallHelp() {
|
|
4809
5223
|
const help = [
|
|
4810
5224
|
"",
|
|
4811
|
-
"@maind-dev/mcp-bridge install \u2014 one-shot setup for the
|
|
5225
|
+
"@maind-dev/mcp-bridge install \u2014 one-shot setup for the MAIND MCP server.",
|
|
4812
5226
|
"",
|
|
4813
|
-
"Detects your project root, pairs this device with
|
|
5227
|
+
"Detects your project root, pairs this device with MAIND, merges the",
|
|
4814
5228
|
"MCP-server entry into every supported AI-client config it finds, and",
|
|
4815
|
-
"(optionally) writes the
|
|
5229
|
+
"(optionally) writes the MAIND preamble block into CLAUDE.md / AGENTS.md /",
|
|
4816
5230
|
"Cursor / Windsurf / Copilot files. Idempotent \u2014 re-running is safe.",
|
|
4817
5231
|
"",
|
|
4818
5232
|
"Usage:",
|
|
@@ -5012,8 +5426,8 @@ Which one should receive the MCP config and preamble files? [1-${candidates.leng
|
|
|
5012
5426
|
output: process.stdout,
|
|
5013
5427
|
terminal: true
|
|
5014
5428
|
});
|
|
5015
|
-
const answer = await new Promise((
|
|
5016
|
-
rl.question("", (input) =>
|
|
5429
|
+
const answer = await new Promise((resolve3) => {
|
|
5430
|
+
rl.question("", (input) => resolve3(input.trim()));
|
|
5017
5431
|
});
|
|
5018
5432
|
rl.close();
|
|
5019
5433
|
if (answer === "") return candidates[0];
|
|
@@ -6445,8 +6859,8 @@ async function promptYesNo(out2, prompt) {
|
|
|
6445
6859
|
output: out2,
|
|
6446
6860
|
terminal: true
|
|
6447
6861
|
});
|
|
6448
|
-
const answer = await new Promise((
|
|
6449
|
-
rl.question("", (input) =>
|
|
6862
|
+
const answer = await new Promise((resolve3) => {
|
|
6863
|
+
rl.question("", (input) => resolve3(input.trim().toLowerCase()));
|
|
6450
6864
|
});
|
|
6451
6865
|
rl.close();
|
|
6452
6866
|
if (answer === "" || answer === "y" || answer === "yes") return true;
|
|
@@ -6460,41 +6874,8 @@ function errMessage(err) {
|
|
|
6460
6874
|
}
|
|
6461
6875
|
|
|
6462
6876
|
// src/install/working-paths-consent.ts
|
|
6877
|
+
init_bridge_config();
|
|
6463
6878
|
import * as readline3 from "node:readline";
|
|
6464
|
-
|
|
6465
|
-
// src/bridge-config.ts
|
|
6466
|
-
init_device_id();
|
|
6467
|
-
import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
|
|
6468
|
-
import { join as join8 } from "node:path";
|
|
6469
|
-
function bridgeConfigPath() {
|
|
6470
|
-
return join8(configDir(), "config.json");
|
|
6471
|
-
}
|
|
6472
|
-
function readBridgeConfig() {
|
|
6473
|
-
try {
|
|
6474
|
-
const file = bridgeConfigPath();
|
|
6475
|
-
if (!existsSync3(file)) return null;
|
|
6476
|
-
const raw = JSON.parse(readFileSync3(file, "utf8"));
|
|
6477
|
-
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
6478
|
-
return null;
|
|
6479
|
-
}
|
|
6480
|
-
const o = raw;
|
|
6481
|
-
const config = {};
|
|
6482
|
-
if (typeof o.auto_announce === "boolean") {
|
|
6483
|
-
config.auto_announce = o.auto_announce;
|
|
6484
|
-
}
|
|
6485
|
-
if (typeof o.machine_label === "string") {
|
|
6486
|
-
config.machine_label = o.machine_label;
|
|
6487
|
-
}
|
|
6488
|
-
if (typeof o.auto_working_paths === "boolean") {
|
|
6489
|
-
config.auto_working_paths = o.auto_working_paths;
|
|
6490
|
-
}
|
|
6491
|
-
return config;
|
|
6492
|
-
} catch {
|
|
6493
|
-
return null;
|
|
6494
|
-
}
|
|
6495
|
-
}
|
|
6496
|
-
|
|
6497
|
-
// src/install/working-paths-consent.ts
|
|
6498
6879
|
var TARGET_KEY = "config:auto_working_paths";
|
|
6499
6880
|
var WORKING_PATHS_CONSENT_PROMPT = '\nEnable presence enrichment (auto working_paths)?\nWith this ON, the bridge includes the repo-relative PARENT DIRECTORIES of your\nlocally changed files (from `git status`, max 8, re-derived at most every 45s)\nin its presence announce \u2014 so your own parallel sessions can warn each other\nbefore editing the same area. Directory names only: never file contents, never\nabsolute paths. Server-side these paths are account-private (org members never\nsee them) and revocable any time on the dashboard consent page or via\n{"auto_working_paths": false} in the bridge config.\n[y/N]: ';
|
|
6500
6881
|
async function applyWorkingPathsConsent(opts) {
|
|
@@ -6576,8 +6957,8 @@ async function promptYesNoDefaultNo(out2, prompt) {
|
|
|
6576
6957
|
output: out2,
|
|
6577
6958
|
terminal: true
|
|
6578
6959
|
});
|
|
6579
|
-
const answer = await new Promise((
|
|
6580
|
-
rl.question("", (input) =>
|
|
6960
|
+
const answer = await new Promise((resolve3) => {
|
|
6961
|
+
rl.question("", (input) => resolve3(input.trim().toLowerCase()));
|
|
6581
6962
|
});
|
|
6582
6963
|
rl.close();
|
|
6583
6964
|
return answer === "y" || answer === "yes";
|
|
@@ -6770,7 +7151,7 @@ function validateTokenShape(token) {
|
|
|
6770
7151
|
}
|
|
6771
7152
|
if (!/^mnd_[A-Za-z0-9_]+$/.test(trimmed)) {
|
|
6772
7153
|
throw new Error(
|
|
6773
|
-
"--token does not match
|
|
7154
|
+
"--token does not match MAIND api-key shape (expected mnd_<\u2026>) \u2014 did you paste a URL instead of the token?"
|
|
6774
7155
|
);
|
|
6775
7156
|
}
|
|
6776
7157
|
return trimmed;
|
|
@@ -6843,7 +7224,7 @@ function parseNodeMajor(version) {
|
|
|
6843
7224
|
}
|
|
6844
7225
|
|
|
6845
7226
|
// src/local-tools/engine.ts
|
|
6846
|
-
import { execFileSync as
|
|
7227
|
+
import { execFileSync as execFileSync6 } from "node:child_process";
|
|
6847
7228
|
import { createRequire as createRequire3 } from "node:module";
|
|
6848
7229
|
|
|
6849
7230
|
// ../../packages/code-index/build/node.js
|
|
@@ -7658,7 +8039,7 @@ function isNativeStoreUnavailable(err) {
|
|
|
7658
8039
|
var NATIVE_STORE_UNAVAILABLE_HINT = "codebase_* tools are unavailable on this machine: no usable SQLite backend (node:sqlite needs Node >= 22.16, and better-sqlite3 could not be loaded). The MCP bridge itself is unaffected. To enable the local codebase tools, update Node to a version with builtin SQLite (>= 22.16), or run `npm rebuild better-sqlite3` in the bridge's install prefix.";
|
|
7659
8040
|
function resolveRepoRoot2(cwd = process.cwd()) {
|
|
7660
8041
|
try {
|
|
7661
|
-
const top =
|
|
8042
|
+
const top = execFileSync6("git", ["rev-parse", "--show-toplevel"], {
|
|
7662
8043
|
cwd,
|
|
7663
8044
|
encoding: "utf8",
|
|
7664
8045
|
stdio: ["ignore", "pipe", "ignore"],
|
|
@@ -7875,7 +8256,7 @@ Finished in ${wallClockSec}s. Restart your MCP client so it picks up the new ser
|
|
|
7875
8256
|
|
|
7876
8257
|
// src/local-tools/savings.ts
|
|
7877
8258
|
import { readFileSync as readFileSync6 } from "node:fs";
|
|
7878
|
-
import { join as
|
|
8259
|
+
import { join as join12 } from "node:path";
|
|
7879
8260
|
|
|
7880
8261
|
// src/local-tools/token-estimate.ts
|
|
7881
8262
|
var CHARS_PER_TOKEN = 4;
|
|
@@ -7930,14 +8311,14 @@ function measureLocalToolSaved(name, result, serialized, repoRoot) {
|
|
|
7930
8311
|
if (files.length === 0) return 0;
|
|
7931
8312
|
let wholeTokens = 0;
|
|
7932
8313
|
for (const fp of files) {
|
|
7933
|
-
wholeTokens += estimateTokens(readFileCapped(
|
|
8314
|
+
wholeTokens += estimateTokens(readFileCapped(join12(repoRoot, fp)));
|
|
7934
8315
|
}
|
|
7935
8316
|
return Math.max(0, wholeTokens - resultTokens);
|
|
7936
8317
|
}
|
|
7937
8318
|
if (name === "codebase_snippet") {
|
|
7938
8319
|
const fp = result?.filePath;
|
|
7939
8320
|
if (typeof fp !== "string" || fp.length === 0) return 0;
|
|
7940
|
-
const wholeTokens = estimateTokens(readFileCapped(
|
|
8321
|
+
const wholeTokens = estimateTokens(readFileCapped(join12(repoRoot, fp)));
|
|
7941
8322
|
return Math.max(0, wholeTokens - resultTokens);
|
|
7942
8323
|
}
|
|
7943
8324
|
return 0;
|
|
@@ -8568,198 +8949,8 @@ async function postSavingsMetric(input) {
|
|
|
8568
8949
|
}
|
|
8569
8950
|
}
|
|
8570
8951
|
|
|
8571
|
-
// src/presence.ts
|
|
8572
|
-
import { execFile } from "node:child_process";
|
|
8573
|
-
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
8574
|
-
var REFRESH_THROTTLE_MS = 45e3;
|
|
8575
|
-
var TTL_MINUTES = 120;
|
|
8576
|
-
var BACKOFF_BASE_MS = 3e4;
|
|
8577
|
-
var BACKOFF_CAP_MS = 15 * 6e4;
|
|
8578
|
-
var END_TIMEOUT_MS = 1500;
|
|
8579
|
-
var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
8580
|
-
function resolveClientSessionId(env) {
|
|
8581
|
-
const fromEnv = (env.MAIND_SESSION_ID ?? "").trim().toLowerCase();
|
|
8582
|
-
return UUID_RE2.test(fromEnv) ? fromEnv : randomUUID2();
|
|
8583
|
-
}
|
|
8584
|
-
function autoAnnounceDisabled(env, config) {
|
|
8585
|
-
const raw = (env.MAIND_AUTO_ANNOUNCE ?? "").trim().toLowerCase();
|
|
8586
|
-
if (raw === "off" || raw === "0" || raw === "false") return true;
|
|
8587
|
-
return config?.auto_announce === false;
|
|
8588
|
-
}
|
|
8589
|
-
function autoWorkingPathsEnabled(env, config) {
|
|
8590
|
-
const raw = (env.MAIND_AUTO_WORKING_PATHS ?? "").trim().toLowerCase();
|
|
8591
|
-
if (raw === "on" || raw === "1" || raw === "true") return true;
|
|
8592
|
-
if (raw === "off" || raw === "0" || raw === "false") return false;
|
|
8593
|
-
return config?.auto_working_paths === true;
|
|
8594
|
-
}
|
|
8595
|
-
var PresenceAnnouncer = class {
|
|
8596
|
-
projectKey;
|
|
8597
|
-
postToolCall;
|
|
8598
|
-
now;
|
|
8599
|
-
gitBranch;
|
|
8600
|
-
log;
|
|
8601
|
-
machineLabel;
|
|
8602
|
-
enabled;
|
|
8603
|
-
// ADR-277: consented enrichment + snapshot sink (both optional, fail-open).
|
|
8604
|
-
workingPathsEnabled;
|
|
8605
|
-
deriveWorkingPaths;
|
|
8606
|
-
snapshot;
|
|
8607
|
-
lastBranch = null;
|
|
8608
|
-
sessionId;
|
|
8609
|
-
lastAnnounceAt = 0;
|
|
8610
|
-
inFlight = false;
|
|
8611
|
-
consecutiveFailures = 0;
|
|
8612
|
-
nextAttemptAt = 0;
|
|
8613
|
-
ended = false;
|
|
8614
|
-
constructor(deps) {
|
|
8615
|
-
const env = deps.env ?? process.env;
|
|
8616
|
-
const config = (deps.readConfig ?? readBridgeConfig)();
|
|
8617
|
-
this.projectKey = deps.projectKey;
|
|
8618
|
-
this.postToolCall = deps.postToolCall;
|
|
8619
|
-
this.now = deps.now ?? Date.now;
|
|
8620
|
-
this.gitBranch = deps.gitBranch ?? defaultGitBranch;
|
|
8621
|
-
this.log = deps.log ?? ((msg) => process.stderr.write(msg + "\n"));
|
|
8622
|
-
this.machineLabel = normalizeMachineLabel(config?.machine_label);
|
|
8623
|
-
this.enabled = this.projectKey !== null && !autoAnnounceDisabled(env, config);
|
|
8624
|
-
this.workingPathsEnabled = autoWorkingPathsEnabled(env, config);
|
|
8625
|
-
this.deriveWorkingPaths = deps.deriveWorkingPaths ?? null;
|
|
8626
|
-
this.snapshot = deps.snapshot ?? null;
|
|
8627
|
-
this.sessionId = resolveClientSessionId(env);
|
|
8628
|
-
}
|
|
8629
|
-
get isEnabled() {
|
|
8630
|
-
return this.enabled;
|
|
8631
|
-
}
|
|
8632
|
-
/**
|
|
8633
|
-
* Called once the forwarder's MCP session is established (initialize
|
|
8634
|
-
* response captured). Fires the first announce — the session becomes visible
|
|
8635
|
-
* on /planning without any agent involvement (C1).
|
|
8636
|
-
*/
|
|
8637
|
-
onSessionReady() {
|
|
8638
|
-
if (!this.enabled || this.ended) return;
|
|
8639
|
-
if (this.lastAnnounceAt > 0) return;
|
|
8640
|
-
void this.announce("active");
|
|
8641
|
-
}
|
|
8642
|
-
/**
|
|
8643
|
-
* Called on every real tool-call passing through the bridge. Throttled
|
|
8644
|
-
* re-announce keeps the session fresh WHILE it is actually working; an idle
|
|
8645
|
-
* session stops refreshing and goes stale on the renderer — honest freshness.
|
|
8646
|
-
*/
|
|
8647
|
-
onActivity() {
|
|
8648
|
-
if (!this.enabled || this.ended) return;
|
|
8649
|
-
if (this.lastAnnounceAt === 0) return;
|
|
8650
|
-
if (this.now() - this.lastAnnounceAt < REFRESH_THROTTLE_MS) return;
|
|
8651
|
-
void this.announce("active");
|
|
8652
|
-
}
|
|
8653
|
-
/**
|
|
8654
|
-
* Best-effort `status:'ended'` on shutdown, bounded by END_TIMEOUT_MS so it
|
|
8655
|
-
* can never hold the process open. The server TTL is the fallback.
|
|
8656
|
-
*/
|
|
8657
|
-
async end() {
|
|
8658
|
-
if (!this.enabled || this.ended) return;
|
|
8659
|
-
this.ended = true;
|
|
8660
|
-
if (this.lastAnnounceAt === 0) return;
|
|
8661
|
-
const timeout = new Promise(
|
|
8662
|
-
(resolve2) => setTimeout(resolve2, END_TIMEOUT_MS).unref()
|
|
8663
|
-
);
|
|
8664
|
-
await Promise.race([this.send("ended"), timeout]);
|
|
8665
|
-
}
|
|
8666
|
-
async announce(status) {
|
|
8667
|
-
if (this.inFlight) return;
|
|
8668
|
-
if (this.now() < this.nextAttemptAt) return;
|
|
8669
|
-
this.inFlight = true;
|
|
8670
|
-
try {
|
|
8671
|
-
await this.send(status);
|
|
8672
|
-
if (this.consecutiveFailures > 0) {
|
|
8673
|
-
this.log("[maind-mcp-bridge] presence announce recovered.");
|
|
8674
|
-
}
|
|
8675
|
-
this.consecutiveFailures = 0;
|
|
8676
|
-
this.nextAttemptAt = 0;
|
|
8677
|
-
this.lastAnnounceAt = this.now();
|
|
8678
|
-
} catch (err) {
|
|
8679
|
-
this.consecutiveFailures += 1;
|
|
8680
|
-
const backoff = Math.min(
|
|
8681
|
-
BACKOFF_BASE_MS * 2 ** (this.consecutiveFailures - 1),
|
|
8682
|
-
BACKOFF_CAP_MS
|
|
8683
|
-
);
|
|
8684
|
-
this.nextAttemptAt = this.now() + backoff;
|
|
8685
|
-
if (this.consecutiveFailures === 1) {
|
|
8686
|
-
this.log(
|
|
8687
|
-
`[maind-mcp-bridge] presence announce failed (advisory, backing off): ${err instanceof Error ? err.message : String(err)}`
|
|
8688
|
-
);
|
|
8689
|
-
}
|
|
8690
|
-
} finally {
|
|
8691
|
-
this.inFlight = false;
|
|
8692
|
-
}
|
|
8693
|
-
}
|
|
8694
|
-
async send(status) {
|
|
8695
|
-
if (this.projectKey === null) return;
|
|
8696
|
-
const args = {
|
|
8697
|
-
project_key: this.projectKey,
|
|
8698
|
-
session_id: this.sessionId,
|
|
8699
|
-
status,
|
|
8700
|
-
ttl_minutes: TTL_MINUTES,
|
|
8701
|
-
// Self-declaration (migration 20260801120000). The server CANNOT derive
|
|
8702
|
-
// this: our announce rides the very same forwarder — headers included —
|
|
8703
|
-
// as an `announce_session` the agent writes itself, so the two requests
|
|
8704
|
-
// are byte-identical apart from these args. Without the marker a
|
|
8705
|
-
// skeleton row is indistinguishable from a sloppy agent session, which
|
|
8706
|
-
// is how 16 of 23 rows came to say nothing AND not say why. Display hint
|
|
8707
|
-
// only; the server keeps 'agent' once an agent has enriched the row.
|
|
8708
|
-
// ADR-277: the server ALSO keys its consent enforcement on this
|
|
8709
|
-
// self-declaration — infra-supplied working_paths are consent-gated,
|
|
8710
|
-
// deliberate agent declarations are not.
|
|
8711
|
-
announce_source: "bridge"
|
|
8712
|
-
};
|
|
8713
|
-
if (status === "active") {
|
|
8714
|
-
const branch = await this.gitBranch();
|
|
8715
|
-
if (branch) args.branch = branch;
|
|
8716
|
-
this.lastBranch = branch;
|
|
8717
|
-
if (this.machineLabel) args.machine_label = this.machineLabel;
|
|
8718
|
-
if (this.workingPathsEnabled && this.deriveWorkingPaths) {
|
|
8719
|
-
try {
|
|
8720
|
-
const wp = await this.deriveWorkingPaths();
|
|
8721
|
-
if (wp && wp.length > 0) args.working_paths = wp;
|
|
8722
|
-
} catch {
|
|
8723
|
-
}
|
|
8724
|
-
}
|
|
8725
|
-
}
|
|
8726
|
-
const payload = await this.postToolCall("announce_session", args);
|
|
8727
|
-
if (this.snapshot) {
|
|
8728
|
-
try {
|
|
8729
|
-
if (status === "ended") {
|
|
8730
|
-
this.snapshot.endSession();
|
|
8731
|
-
} else if (payload !== null && payload !== void 0) {
|
|
8732
|
-
this.snapshot.write(payload, {
|
|
8733
|
-
sessionId: this.sessionId,
|
|
8734
|
-
branch: this.lastBranch
|
|
8735
|
-
});
|
|
8736
|
-
}
|
|
8737
|
-
} catch {
|
|
8738
|
-
}
|
|
8739
|
-
}
|
|
8740
|
-
}
|
|
8741
|
-
};
|
|
8742
|
-
async function defaultGitBranch() {
|
|
8743
|
-
return await new Promise((resolve2) => {
|
|
8744
|
-
execFile(
|
|
8745
|
-
"git",
|
|
8746
|
-
["rev-parse", "--abbrev-ref", "HEAD"],
|
|
8747
|
-
{ timeout: 2e3, encoding: "utf8" },
|
|
8748
|
-
(err, stdout) => {
|
|
8749
|
-
if (err) return resolve2(null);
|
|
8750
|
-
const branch = stdout.trim();
|
|
8751
|
-
resolve2(branch.length > 0 && branch !== "HEAD" ? branch : null);
|
|
8752
|
-
}
|
|
8753
|
-
);
|
|
8754
|
-
});
|
|
8755
|
-
}
|
|
8756
|
-
function normalizeMachineLabel(raw) {
|
|
8757
|
-
if (typeof raw !== "string") return null;
|
|
8758
|
-
const v = raw.trim().slice(0, 100);
|
|
8759
|
-
return v.length > 0 ? v : null;
|
|
8760
|
-
}
|
|
8761
|
-
|
|
8762
8952
|
// src/index.ts
|
|
8953
|
+
init_presence();
|
|
8763
8954
|
init_presence_snapshot();
|
|
8764
8955
|
|
|
8765
8956
|
// src/working-paths.ts
|
|
@@ -8790,12 +8981,12 @@ async function deriveWorkingPaths(runGitStatus = defaultGitStatus) {
|
|
|
8790
8981
|
return dirs.length > 0 ? dirs : null;
|
|
8791
8982
|
}
|
|
8792
8983
|
async function defaultGitStatus() {
|
|
8793
|
-
return await new Promise((
|
|
8984
|
+
return await new Promise((resolve3) => {
|
|
8794
8985
|
execFile2(
|
|
8795
8986
|
"git",
|
|
8796
8987
|
["status", "--porcelain"],
|
|
8797
8988
|
{ timeout: 2e3, encoding: "utf8", maxBuffer: 1024 * 1024 },
|
|
8798
|
-
(err, stdout) =>
|
|
8989
|
+
(err, stdout) => resolve3(err ? null : stdout)
|
|
8799
8990
|
);
|
|
8800
8991
|
});
|
|
8801
8992
|
}
|
|
@@ -8858,7 +9049,7 @@ async function main() {
|
|
|
8858
9049
|
process.exit(await runOnSessionEnd2());
|
|
8859
9050
|
}
|
|
8860
9051
|
if (firstPositional !== void 0 && isHookSubcommand(firstPositional)) {
|
|
8861
|
-
const hooks = await Promise.resolve().then(() => (
|
|
9052
|
+
const hooks = await Promise.resolve().then(() => (init_hooks2(), hooks_exports));
|
|
8862
9053
|
const run = {
|
|
8863
9054
|
"on-session-start": hooks.runOnSessionStart,
|
|
8864
9055
|
"on-tool-use": hooks.runOnToolUse,
|