@maind-dev/mcp-bridge 0.1.0 → 0.3.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.
@@ -0,0 +1,187 @@
1
+ // Install sub-command orchestrator.
2
+ //
3
+ // Invocation:
4
+ // npx -y @maind-dev/mcp-bridge install [flags]
5
+ //
6
+ // Phases (in order):
7
+ // 1. parse flags
8
+ // 2. resolve PROJECT_ROOT (auto-detect or --project-root)
9
+ // 3. browser-pair OR use --token to obtain a device-bound api-key
10
+ // 4. build the client-target list (apply --client / --skip-codex filters)
11
+ // 5. for each target: JSON or TOML merge
12
+ // 6. unless --no-preamble: write the 5 preamble files + reminder file
13
+ // 7. unless --no-hook: optionally merge the SessionStart hook
14
+ // 8. if --telemetry: post anonymized summary (best-effort)
15
+ // 9. print the final report table; exit with appropriate code
16
+ //
17
+ // STDOUT is the user-facing channel here (NOT the MCP framing channel as
18
+ // in the bridge-proxy mode). Errors that happen before the report is built
19
+ // are printed to STDERR. After report is built, the table goes to STDOUT.
20
+ import * as os from "node:os";
21
+ import { BRIDGE_VERSION } from "../version.js";
22
+ import { parseInstallFlags, printInstallHelp, InstallFlagError } from "./flags.js";
23
+ import { InstallReport } from "./report.js";
24
+ import { detectProjectRoot, disambiguateProjectRoot, findAllProjectRoots, } from "./project-root.js";
25
+ import { buildMaindServerEntry, filterTargetsByFamily, getClientTargets, makeDefaultContext, } from "./client-targets.js";
26
+ import { mergeJsonConfig } from "./json-merge.js";
27
+ import { mergeTomlConfig } from "./toml-merge.js";
28
+ import { writePreambleFiles } from "./preamble.js";
29
+ import { mergeSessionStartHook } from "./hook-merge.js";
30
+ import { pairOrUseToken } from "./browser-pair.js";
31
+ import { postInstallTelemetry } from "./telemetry.js";
32
+ const DEFAULT_MCP_URL = "https://mcp.maind.dev/mcp";
33
+ export async function runInstall(argv) {
34
+ const startTime = Date.now();
35
+ let flags;
36
+ try {
37
+ flags = parseInstallFlags(argv);
38
+ }
39
+ catch (err) {
40
+ if (err instanceof InstallFlagError) {
41
+ process.stderr.write(`error: ${err.message}\n`);
42
+ process.stderr.write("Run `npx -y @maind-dev/mcp-bridge install --help` for usage.\n");
43
+ return 2;
44
+ }
45
+ throw err;
46
+ }
47
+ if (flags.help) {
48
+ printInstallHelp();
49
+ return 0;
50
+ }
51
+ const isTtyStdin = Boolean(process.stdin.isTTY);
52
+ const isInteractive = isTtyStdin && !flags.nonInteractive;
53
+ const homeDir = os.homedir();
54
+ if (homeDir.trim().length === 0) {
55
+ process.stderr.write("error: could not resolve home directory (os.homedir() returned empty)\n");
56
+ return 2;
57
+ }
58
+ // ----- Phase 1: project root -----
59
+ let projectRoot;
60
+ if (flags.projectRoot !== null) {
61
+ projectRoot = flags.projectRoot;
62
+ }
63
+ else {
64
+ const candidates = await findAllProjectRoots(process.cwd());
65
+ if (candidates.length === 0) {
66
+ projectRoot = await detectProjectRoot(process.cwd());
67
+ }
68
+ else if (candidates.length === 1) {
69
+ projectRoot = candidates[0];
70
+ }
71
+ else {
72
+ const chosen = await disambiguateProjectRoot(candidates, isInteractive);
73
+ if (chosen === null) {
74
+ process.stderr.write("error: multiple project roots found and we cannot prompt (non-interactive). " +
75
+ "Pass --project-root <path> to pick one explicitly.\n");
76
+ for (const c of candidates)
77
+ process.stderr.write(` candidate: ${c}\n`);
78
+ return 2;
79
+ }
80
+ projectRoot = chosen;
81
+ }
82
+ }
83
+ const report = new InstallReport();
84
+ const mcpUrl = (process.env.MAIND_MCP_URL ?? "").trim() || DEFAULT_MCP_URL;
85
+ if (flags.dryRun) {
86
+ process.stdout.write("DRY RUN — computing the plan, no files will be modified.\n");
87
+ }
88
+ process.stdout.write(`maind install — project root: ${projectRoot}\n`);
89
+ process.stdout.write(` — mcp endpoint: ${mcpUrl}\n\n`);
90
+ // ----- Phase 2: pair / token -----
91
+ const pairOutcome = await pairOrUseToken({
92
+ bridgeVersion: BRIDGE_VERSION,
93
+ token: flags.token,
94
+ dryRun: flags.dryRun,
95
+ });
96
+ report.add(pairOutcome.result);
97
+ if (pairOutcome.result.status === "failed") {
98
+ process.stderr.write(`\npairing failed: ${pairOutcome.result.detail ?? "unknown"}\nSkipping remaining steps.\n`);
99
+ report.print(process.stdout);
100
+ return 2;
101
+ }
102
+ // ----- Phase 3: build client targets -----
103
+ const ctx = makeDefaultContext({
104
+ projectRoot,
105
+ homeDir,
106
+ platform: process.platform,
107
+ env: process.env,
108
+ });
109
+ let targets = getClientTargets(ctx);
110
+ targets = filterTargetsByFamily(targets, flags.client);
111
+ if (flags.skipCodex) {
112
+ targets = targets.filter((t) => t.key !== "codex-cli");
113
+ }
114
+ if (targets.length === 0) {
115
+ process.stderr.write(flags.client !== null
116
+ ? `error: --client "${flags.client}" matched no known target. Run --help for the list.\n`
117
+ : "error: no client targets selected (did you skip all of them?)\n");
118
+ report.print(process.stdout);
119
+ return 2;
120
+ }
121
+ // ----- Phase 4: JSON + TOML merges (sequential, deterministic order) -----
122
+ for (const target of targets) {
123
+ const serverEntry = buildMaindServerEntry({
124
+ mcpUrl,
125
+ clientFamily: target.clientFamilyEnv,
126
+ });
127
+ let result;
128
+ if (target.kind === "json") {
129
+ result = await mergeJsonConfig(target, serverEntry, flags.dryRun);
130
+ }
131
+ else {
132
+ result = await mergeTomlConfig(target, serverEntry, flags.dryRun);
133
+ }
134
+ report.add(result);
135
+ }
136
+ // ----- Phase 5: preamble files -----
137
+ if (!flags.noPreamble) {
138
+ const preambleResults = await writePreambleFiles({ projectRoot, homeDir }, flags.dryRun);
139
+ for (const r of preambleResults)
140
+ report.add(r);
141
+ }
142
+ else {
143
+ report.add({
144
+ target: "preamble:*",
145
+ action: "skip",
146
+ status: "skipped",
147
+ detail: "--no-preamble",
148
+ });
149
+ }
150
+ // ----- Phase 6: SessionStart hook -----
151
+ const hookResult = await mergeSessionStartHook({
152
+ homeDir,
153
+ isInteractive,
154
+ full: flags.full,
155
+ skip: flags.noHook,
156
+ dryRun: flags.dryRun,
157
+ out: process.stdout,
158
+ });
159
+ report.add(hookResult);
160
+ // ----- Phase 7: telemetry (best-effort, never in dry-run) -----
161
+ if (!flags.dryRun) {
162
+ await postInstallTelemetry({
163
+ enabled: flags.telemetry || flags.full,
164
+ installerVersion: BRIDGE_VERSION,
165
+ summary: report.summary(),
166
+ steps: report.results_(),
167
+ wallClockMs: Date.now() - startTime,
168
+ apiKey: pairOutcome.apiKey,
169
+ clientFamilyFilter: flags.client,
170
+ });
171
+ }
172
+ // ----- Phase 8: report -----
173
+ report.print(process.stdout);
174
+ const exitCode = report.exitCode();
175
+ const wallClockSec = ((Date.now() - startTime) / 1000).toFixed(1);
176
+ if (flags.dryRun) {
177
+ process.stdout.write(`\nDRY RUN finished in ${wallClockSec}s. No files were modified. Re-run without --dry-run to apply.\n`);
178
+ }
179
+ else {
180
+ process.stdout.write(`\nFinished in ${wallClockSec}s. Restart your MCP client so it picks up the new server entry.\n`);
181
+ }
182
+ if (exitCode === 1) {
183
+ process.stdout.write("Note: some steps were skipped or failed — review the table above. The MCP setup is usable as long as 'browser-pair' and at least one JSON/TOML target succeeded.\n");
184
+ }
185
+ return exitCode;
186
+ }
187
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/install/index.ts"],"names":[],"mappings":"AAAA,oCAAoC;AACpC,EAAE;AACF,cAAc;AACd,iDAAiD;AACjD,EAAE;AACF,qBAAqB;AACrB,mBAAmB;AACnB,4DAA4D;AAC5D,oEAAoE;AACpE,4EAA4E;AAC5E,2CAA2C;AAC3C,wEAAwE;AACxE,gEAAgE;AAChE,6DAA6D;AAC7D,gEAAgE;AAChE,EAAE;AACF,yEAAyE;AACzE,2EAA2E;AAC3E,0EAA0E;AAE1E,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,Y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AO,CAAC,MAAM,CAAC,KAAK,CAClB,yBAAyB,YAAY,iEAAiE,CACvG,CAAC;IACJ,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,MAAM,CAAC,KAAK,CAClB,iBAAiB,YAAY,mEAAmE,CACjG,CAAC;IACJ,CAAC;IACD,IAAI,QAAQ,KAAK,CAAC,EAAE,CAAC;QACnB,OAAO,CAAC,MAAM,CAAC,KAAK,CAClB,oKAAoK,CACrK,CAAC;IACJ,CAAC;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC"}
@@ -0,0 +1,160 @@
1
+ // Idempotent JSON-config merge for all six JSON-based MCP-client targets.
2
+ //
3
+ // Semantics:
4
+ // - The file is treated as an object. We only set `mcpServers.maind` (or
5
+ // `maind` at root for the ~/.claude.json user-scope shape — see below).
6
+ // - All other keys are preserved verbatim, including `mcpServers.<other>`
7
+ // and comments-as-keys some tooling injects. We never re-key.
8
+ // - Idempotent: re-running yields a byte-stable file (modulo Node's stable
9
+ // JSON.stringify key order on the maind object we wrote).
10
+ //
11
+ // Shape variants:
12
+ // - Standard: { "mcpServers": { "maind": { ... } } }
13
+ // - Claude Code user: { "maind": { ... } } at root (legacy ~/.claude.json)
14
+ //
15
+ // The Claude-Code user-scope is a historical exception. Both shapes work in
16
+ // Claude Code; we use whichever the file already has, defaulting to the
17
+ // modern `mcpServers.maind` shape when creating from scratch.
18
+ import { atomicWriteFile, readFileSafe } from "./atomic-write.js";
19
+ const MAIND_SERVER_KEY = "maind";
20
+ export async function mergeJsonConfig(target, serverEntry, dryRun = false) {
21
+ if (target.kind !== "json") {
22
+ return {
23
+ target: target.key,
24
+ action: "merge",
25
+ status: "failed",
26
+ detail: `expected json target, got ${target.kind}`,
27
+ };
28
+ }
29
+ let raw;
30
+ try {
31
+ raw = await readFileSafe(target.path);
32
+ }
33
+ catch (err) {
34
+ return failed(target, "read", err);
35
+ }
36
+ let parsed;
37
+ let action = "create";
38
+ if (raw === null || raw.trim().length === 0) {
39
+ parsed = {};
40
+ }
41
+ else {
42
+ action = "merge";
43
+ try {
44
+ parsed = JSON.parse(raw);
45
+ }
46
+ catch (err) {
47
+ return failed(target, "parse", err);
48
+ }
49
+ }
50
+ if (!isObject(parsed)) {
51
+ return {
52
+ target: target.key,
53
+ action: "merge",
54
+ status: "failed",
55
+ detail: "existing file is not a JSON object at root",
56
+ };
57
+ }
58
+ // Decide which shape to use.
59
+ const useRootShape = target.key === "claude-code-user" && hasRootShape(parsed);
60
+ let nextConfig;
61
+ let alreadyConsistent = false;
62
+ if (useRootShape) {
63
+ const existing = parsed[MAIND_SERVER_KEY];
64
+ if (isObject(existing) && serverEntriesEqual(existing, serverEntry)) {
65
+ alreadyConsistent = true;
66
+ }
67
+ nextConfig = { ...parsed, [MAIND_SERVER_KEY]: serverEntry };
68
+ }
69
+ else {
70
+ const mcpServers = isObject(parsed.mcpServers) ? parsed.mcpServers : {};
71
+ const existing = mcpServers[MAIND_SERVER_KEY];
72
+ if (isObject(existing) && serverEntriesEqual(existing, serverEntry)) {
73
+ alreadyConsistent = true;
74
+ }
75
+ nextConfig = {
76
+ ...parsed,
77
+ mcpServers: { ...mcpServers, [MAIND_SERVER_KEY]: serverEntry },
78
+ };
79
+ }
80
+ if (alreadyConsistent && raw !== null) {
81
+ return {
82
+ target: target.key,
83
+ action: "merge",
84
+ status: "skipped",
85
+ detail: "maind entry already up-to-date",
86
+ };
87
+ }
88
+ const nextRaw = JSON.stringify(nextConfig, null, 2) + "\n";
89
+ if (dryRun) {
90
+ return {
91
+ target: target.key,
92
+ action: action === "create" ? "write" : "merge",
93
+ status: action === "create" ? "would-create" : "would-merge",
94
+ detail: target.path,
95
+ };
96
+ }
97
+ try {
98
+ await atomicWriteFile(target.path, nextRaw);
99
+ }
100
+ catch (err) {
101
+ return failed(target, "write", err);
102
+ }
103
+ return {
104
+ target: target.key,
105
+ action: action === "create" ? "write" : "merge",
106
+ status: action === "create" ? "created" : "merged",
107
+ detail: target.path,
108
+ };
109
+ }
110
+ function hasRootShape(parsed) {
111
+ // True if there's a top-level `maind` key AND no top-level `mcpServers`.
112
+ // If both exist (rare but possible), the modern shape wins.
113
+ if ("mcpServers" in parsed)
114
+ return false;
115
+ if (!(MAIND_SERVER_KEY in parsed))
116
+ return false;
117
+ return true;
118
+ }
119
+ function serverEntriesEqual(a, b) {
120
+ if (!isObject(a))
121
+ return false;
122
+ if (a.command !== b.command)
123
+ return false;
124
+ if (!arrayEquals(a.args, b.args))
125
+ return false;
126
+ if (!isObject(a.env))
127
+ return false;
128
+ for (const key of Object.keys(b.env)) {
129
+ if (a.env[key] !== b.env[key])
130
+ return false;
131
+ }
132
+ // We don't fail if `a.env` has extra keys beyond ours — preserves user
133
+ // additions like `MAIND_FUNCTIONS_ORIGIN`. But we DO update if any maind
134
+ // key drifted.
135
+ return true;
136
+ }
137
+ function arrayEquals(a, b) {
138
+ if (!Array.isArray(a))
139
+ return false;
140
+ if (a.length !== b.length)
141
+ return false;
142
+ for (let i = 0; i < a.length; i++) {
143
+ if (a[i] !== b[i])
144
+ return false;
145
+ }
146
+ return true;
147
+ }
148
+ function isObject(v) {
149
+ return typeof v === "object" && v !== null && !Array.isArray(v);
150
+ }
151
+ function failed(target, phase, err) {
152
+ const message = err instanceof Error ? err.message : String(err);
153
+ return {
154
+ target: target.key,
155
+ action: "merge",
156
+ status: "failed",
157
+ detail: `${phase}: ${message}`,
158
+ };
159
+ }
160
+ //# sourceMappingURL=json-merge.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"json-merge.js","sourceRoot":"","sources":["../../src/install/json-merge.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,EAAE;AACF,aAAa;AACb,2EAA2E;AAC3E,4EAA4E;AAC5E,4EAA4E;AAC5E,kEAAkE;AAClE,6EAA6E;AAC7E,8DAA8D;AAC9D,EAAE;AACF,kBAAkB;AAClB,iEAAiE;AACjE,+EAA+E;AAC/E,EAAE;AACF,4EAA4E;AAC5E,wEAAwE;AACxE,8DAA8D;AAE9D,OA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Y,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IACjE,OAAO;QACL,MAAM,EAAE,MAAM,CAAC,GAAG;QAClB,MAAM,EAAE,OAAO;QACf,MAAM,EAAE,QAAQ;QAChB,MAAM,EAAE,GAAG,KAAK,KAAK,OAAO,EAAE;KAC/B,CAAC;AACJ,CAAC"}
@@ -0,0 +1,119 @@
1
+ // Preamble-file writer — appends the maind MCP-integration block to the
2
+ // canonical agent-orientation files of the project, plus the user-scoped
3
+ // SessionStart-reminder file.
4
+ //
5
+ // Targets:
6
+ // - <PROJECT_ROOT>/CLAUDE.md
7
+ // - <PROJECT_ROOT>/AGENTS.md
8
+ // - <PROJECT_ROOT>/.github/copilot-instructions.md
9
+ // - <PROJECT_ROOT>/.cursorrules
10
+ // - <PROJECT_ROOT>/.windsurfrules
11
+ // - <HOMEDIR>/.claude/maind-session-start-reminder.md (re-used by the
12
+ // optional SessionStart hook)
13
+ //
14
+ // Idempotency: a file is considered "already configured" if any line starts
15
+ // with `## maind MCP integration` — both the legacy soft variant and the
16
+ // hardened v1.1 block share that header prefix (intentional, see ADR-099).
17
+ // Re-running this on an already-configured file produces a `skipped` result.
18
+ //
19
+ // Source of truth for the block content: MAIND_MCP_INTEGRATION_BLOCK in
20
+ // `@maind-dev/integration-snippets`. Importing it (instead of duplicating)
21
+ // prevents drift between bridge, dashboard snippets, and server-instructions.
22
+ import * as path from "node:path";
23
+ import { MAIND_MCP_INTEGRATION_BLOCK } from "@maind-dev/integration-snippets";
24
+ import { atomicWriteFile, ensureDir, hasLinePrefix, readFileSafe, } from "./atomic-write.js";
25
+ export const PREAMBLE_HEADER_PREFIX = "## maind MCP integration";
26
+ function buildPreambleTargets(ctx) {
27
+ return [
28
+ {
29
+ key: "preamble:CLAUDE.md",
30
+ path: path.join(ctx.projectRoot, "CLAUDE.md"),
31
+ mayNeedParentDir: false,
32
+ },
33
+ {
34
+ key: "preamble:AGENTS.md",
35
+ path: path.join(ctx.projectRoot, "AGENTS.md"),
36
+ mayNeedParentDir: false,
37
+ },
38
+ {
39
+ key: "preamble:.github/copilot-instructions.md",
40
+ path: path.join(ctx.projectRoot, ".github", "copilot-instructions.md"),
41
+ mayNeedParentDir: true,
42
+ },
43
+ {
44
+ key: "preamble:.cursorrules",
45
+ path: path.join(ctx.projectRoot, ".cursorrules"),
46
+ mayNeedParentDir: false,
47
+ },
48
+ {
49
+ key: "preamble:.windsurfrules",
50
+ path: path.join(ctx.projectRoot, ".windsurfrules"),
51
+ mayNeedParentDir: false,
52
+ },
53
+ {
54
+ key: "preamble:~/.claude/maind-session-start-reminder.md",
55
+ path: path.join(ctx.homeDir, ".claude", "maind-session-start-reminder.md"),
56
+ mayNeedParentDir: true,
57
+ },
58
+ ];
59
+ }
60
+ export async function writePreambleFiles(ctx, dryRun = false) {
61
+ const targets = buildPreambleTargets(ctx);
62
+ const results = [];
63
+ for (const t of targets) {
64
+ results.push(await writeOnePreambleFile(t, dryRun));
65
+ }
66
+ return results;
67
+ }
68
+ async function writeOnePreambleFile(target, dryRun) {
69
+ try {
70
+ if (target.mayNeedParentDir && !dryRun) {
71
+ await ensureDir(path.dirname(target.path));
72
+ }
73
+ const alreadyPresent = await hasLinePrefix(target.path, PREAMBLE_HEADER_PREFIX);
74
+ if (alreadyPresent) {
75
+ return {
76
+ target: target.key,
77
+ action: "skip",
78
+ status: "skipped",
79
+ detail: "## maind MCP integration header already present",
80
+ };
81
+ }
82
+ const existing = await readFileSafe(target.path);
83
+ if (dryRun) {
84
+ return {
85
+ target: target.key,
86
+ action: existing === null ? "write" : "append",
87
+ status: existing === null ? "would-create" : "would-merge",
88
+ detail: target.path,
89
+ };
90
+ }
91
+ const nextContent = existing === null || existing.length === 0
92
+ ? `${MAIND_MCP_INTEGRATION_BLOCK}\n`
93
+ : ensureTrailingBlankLine(existing) + `${MAIND_MCP_INTEGRATION_BLOCK}\n`;
94
+ await atomicWriteFile(target.path, nextContent);
95
+ return {
96
+ target: target.key,
97
+ action: existing === null ? "write" : "append",
98
+ status: existing === null ? "created" : "merged",
99
+ detail: target.path,
100
+ };
101
+ }
102
+ catch (err) {
103
+ const message = err instanceof Error ? err.message : String(err);
104
+ return {
105
+ target: target.key,
106
+ action: "append",
107
+ status: "failed",
108
+ detail: message,
109
+ };
110
+ }
111
+ }
112
+ function ensureTrailingBlankLine(content) {
113
+ if (content.endsWith("\n\n"))
114
+ return content;
115
+ if (content.endsWith("\n"))
116
+ return content + "\n";
117
+ return content + "\n\n";
118
+ }
119
+ //# sourceMappingURL=preamble.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"preamble.js","sourceRoot":"","sources":["../../src/install/preamble.ts"],"names":[],"mappings":"AAAA,wEAAwE;AACxE,yEAAyE;AACzE,8BAA8B;AAC9B,EAAE;AACF,WAAW;AACX,+BAA+B;AAC/B,+BAA+B;AAC/B,qDAAqD;AACrD,kCAAkC;AAClC,oCAAoC;AACpC,wEAAwE;AACxE,kCAAkC;AAClC,EAAE;AACF,4EAA4E;AAC5E,yEAAyE;AACzE,2EAA2E;AAC3E,6EAA6E;AAC7E,EAAE;AACF,wEAAwE;AACxE,2EAA2E;AAC3E,8EAA8E;AAE9E,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,2BAA2B,EAAE,MAAM,iCAAiC,CAAC;AAC9E,OAAO,EACL,eAAe,EACf,SAAS,EACT,aAAa,EACb,YAAY,GACb,MAAM,mBAAmB,CAAC;AAG3B,MAAM,CAAC,MAAM,sBAAsB,GAAG,0BAA0B,CAAC;AAcjE,SAAS,oBAAoB,CAAC,GAAoB;IAChD,OAAO;QACL;YACE,GAAG,EAAE,oBAAoB;YACzB,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,WAAW,EAAE,WAAW,CAAC;YAC7C,gBAAgB,EAAE,KAAK;SACxB;QACD;YACE,GAAG,EAAE,oBAAoB;YACzB,IAAI,EAA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AAI;SACpB,CAAC;IACJ,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,OAAO,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QACjE,OAAO;YACL,MAAM,EAAE,MAAM,CAAC,GAAG;YAClB,MAAM,EAAE,QAAQ;YAChB,MAAM,EAAE,QAAQ;YAChB,MAAM,EAAE,OAAO;SAChB,CAAC;IACJ,CAAC;AACH,CAAC;AAED,SAAS,uBAAuB,CAAC,OAAe;IAC9C,IAAI,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC;QAAE,OAAO,OAAO,CAAC;IAC7C,IAAI,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC;QAAE,OAAO,OAAO,GAAG,IAAI,CAAC;IAClD,OAAO,OAAO,GAAG,MAAM,CAAC;AAC1B,CAAC"}
@@ -0,0 +1,120 @@
1
+ // PROJECT_ROOT detection for the install sub-command.
2
+ //
3
+ // Strategy: walk up from `process.cwd()` until we hit a directory that looks
4
+ // like the root of a project — i.e. contains one of the marker files below.
5
+ // Stops at the OS filesystem root.
6
+ //
7
+ // Marker files (any one is sufficient):
8
+ // - package.json (Node/JS/TS)
9
+ // - .git/ (any git repo)
10
+ // - pyproject.toml (modern Python)
11
+ // - Cargo.toml (Rust)
12
+ // - go.mod (Go)
13
+ // - .hg/ (Mercurial)
14
+ //
15
+ // If no marker is found, the start dir itself is returned — the user is
16
+ // presumably in an empty workspace or a not-yet-initialised project. The
17
+ // orchestrator will still write into that dir (it's just `process.cwd()`).
18
+ import * as fs from "node:fs/promises";
19
+ import * as path from "node:path";
20
+ import * as readline from "node:readline";
21
+ const PROJECT_MARKERS = [
22
+ "package.json",
23
+ ".git",
24
+ "pyproject.toml",
25
+ "Cargo.toml",
26
+ "go.mod",
27
+ ".hg",
28
+ ];
29
+ /**
30
+ * Detects the project root by walking up from `startDir`. Returns the first
31
+ * directory containing a project-marker file. Falls back to `startDir` if
32
+ * the walk reaches the filesystem root without a match.
33
+ */
34
+ export async function detectProjectRoot(startDir) {
35
+ const resolved = path.resolve(startDir);
36
+ let current = resolved;
37
+ while (true) {
38
+ if (await hasAnyMarker(current)) {
39
+ return current;
40
+ }
41
+ const parent = path.dirname(current);
42
+ if (parent === current) {
43
+ // Reached the FS root without a hit — return the start dir, the
44
+ // caller will treat it as a "loose" project root.
45
+ return resolved;
46
+ }
47
+ current = parent;
48
+ }
49
+ }
50
+ /**
51
+ * Detects ALL plausible project roots between cwd and the FS root, not just
52
+ * the closest one. Used to surface monorepo ambiguity to the user.
53
+ *
54
+ * Returns the candidates in walk-up order (closest first). If the result
55
+ * has length > 1, the orchestrator should disambiguate via prompt or fail.
56
+ */
57
+ export async function findAllProjectRoots(startDir) {
58
+ const resolved = path.resolve(startDir);
59
+ let current = resolved;
60
+ const hits = [];
61
+ while (true) {
62
+ if (await hasAnyMarker(current)) {
63
+ hits.push(current);
64
+ }
65
+ const parent = path.dirname(current);
66
+ if (parent === current)
67
+ break;
68
+ current = parent;
69
+ }
70
+ return hits;
71
+ }
72
+ async function hasAnyMarker(dir) {
73
+ for (const marker of PROJECT_MARKERS) {
74
+ try {
75
+ await fs.access(path.join(dir, marker));
76
+ return true;
77
+ }
78
+ catch {
79
+ // marker not present, try next
80
+ }
81
+ }
82
+ return false;
83
+ }
84
+ /**
85
+ * Disambiguates among multiple project-root candidates by asking the user
86
+ * (TTY only). Non-interactive mode returns `null` and the caller should
87
+ * fail with a clear error message ("pass --project-root explicitly").
88
+ */
89
+ export async function disambiguateProjectRoot(candidates, isInteractive) {
90
+ if (candidates.length === 0)
91
+ return null;
92
+ if (candidates.length === 1)
93
+ return candidates[0];
94
+ if (!isInteractive) {
95
+ return null;
96
+ }
97
+ process.stdout.write("\nMultiple project roots found between cwd and the filesystem root:\n");
98
+ candidates.forEach((c, i) => {
99
+ process.stdout.write(` [${i + 1}] ${c}\n`);
100
+ });
101
+ process.stdout.write(`\nWhich one should receive the MCP config and preamble files? [1-${candidates.length}, default 1]: `);
102
+ const rl = readline.createInterface({
103
+ input: process.stdin,
104
+ output: process.stdout,
105
+ terminal: true,
106
+ });
107
+ const answer = await new Promise((resolve) => {
108
+ rl.question("", (input) => resolve(input.trim()));
109
+ });
110
+ rl.close();
111
+ if (answer === "")
112
+ return candidates[0];
113
+ const index = Number.parseInt(answer, 10);
114
+ if (Number.isNaN(index) || index < 1 || index > candidates.length) {
115
+ process.stdout.write(`Invalid selection "${answer}", aborting. Re-run with --project-root <path>.\n`);
116
+ return null;
117
+ }
118
+ return candidates[index - 1];
119
+ }
120
+ //# sourceMappingURL=project-root.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"project-root.js","sourceRoot":"","sources":["../../src/install/project-root.ts"],"names":[],"mappings":"AAAA,sDAAsD;AACtD,EAAE;AACF,6EAA6E;AAC7E,4EAA4E;AAC5E,mCAAmC;AACnC,EAAE;AACF,wCAAwC;AACxC,mCAAmC;AACnC,qCAAqC;AACrC,sCAAsC;AACtC,6BAA6B;AAC7B,2BAA2B;AAC3B,kCAAkC;AAClC,EAAE;AACF,wEAAwE;AACxE,yEAAyE;AACzE,2EAA2E;AAE3E,OAAO,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACvC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,KAAK,QAAQ,MAAM,eAAe,CAAC;AAE1C,MAAM,eAAe,GAAG;IACtB,cAAc;IACd,MAAM;IACN,gBAAgB;IAChB,YAAY;IACZ,QAAQ;IACR,KAAK;CACG,CAAC;AAEX;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB,CAAC,QAAgB;IACtD,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IACxC,IAAI,OAAO,GAAG,QAAQ,CAAC;IAEvB,OAAO,IAAI,EAAE,CAAC;QACZ,IAAI,MAAM,YAAY,CAAC,OAAO,C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