@pugi/cli 0.1.0-beta.2 → 0.1.0-beta.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/THIRD_PARTY_NOTICES.md +40 -0
  2. package/assets/pugi-mascot.ansi +15 -40
  3. package/bin/run.js +33 -1
  4. package/dist/commands/jobs-watch.js +201 -0
  5. package/dist/commands/jobs.js +15 -0
  6. package/dist/core/agent-progress/cleanup.js +134 -0
  7. package/dist/core/agent-progress/schema.js +144 -0
  8. package/dist/core/agent-progress/writer.js +101 -0
  9. package/dist/core/compact/auto-trigger.js +96 -0
  10. package/dist/core/compact/buffer-rewriter.js +115 -0
  11. package/dist/core/compact/summarizer.js +196 -0
  12. package/dist/core/compact/token-counter.js +108 -0
  13. package/dist/core/consensus/diff-capture.js +73 -0
  14. package/dist/core/context/index.js +7 -0
  15. package/dist/core/context/markdown-traverse.js +255 -0
  16. package/dist/core/cost/rate-card.js +129 -0
  17. package/dist/core/cost/tracker.js +221 -0
  18. package/dist/core/denial-tracking/index.js +8 -0
  19. package/dist/core/denial-tracking/state.js +264 -0
  20. package/dist/core/diagnostics/probe-runner.js +93 -0
  21. package/dist/core/diagnostics/probes/api.js +46 -0
  22. package/dist/core/diagnostics/probes/auth.js +86 -0
  23. package/dist/core/diagnostics/probes/cli-version.js +127 -0
  24. package/dist/core/diagnostics/probes/config.js +72 -0
  25. package/dist/core/diagnostics/probes/denial-tracking.js +57 -0
  26. package/dist/core/diagnostics/probes/disk.js +81 -0
  27. package/dist/core/diagnostics/probes/git.js +65 -0
  28. package/dist/core/diagnostics/probes/mcp.js +75 -0
  29. package/dist/core/diagnostics/probes/node.js +59 -0
  30. package/dist/core/diagnostics/probes/pnpm.js +36 -0
  31. package/dist/core/diagnostics/probes/session.js +74 -0
  32. package/dist/core/diagnostics/probes/status-snapshot.js +442 -0
  33. package/dist/core/diagnostics/probes/workspace.js +63 -0
  34. package/dist/core/diagnostics/types.js +70 -0
  35. package/dist/core/edits/dispatch.js +218 -2
  36. package/dist/core/edits/journal.js +199 -0
  37. package/dist/core/edits/layer-d-ast.js +557 -14
  38. package/dist/core/edits/verify-hook.js +273 -0
  39. package/dist/core/edits/worktree.js +111 -18
  40. package/dist/core/engine/anvil-client.js +115 -5
  41. package/dist/core/engine/budgets.js +89 -0
  42. package/dist/core/engine/context-prefix.js +155 -0
  43. package/dist/core/engine/intent.js +260 -0
  44. package/dist/core/engine/native-pugi.js +744 -210
  45. package/dist/core/engine/prompts.js +61 -6
  46. package/dist/core/engine/strip-internal-fields.js +124 -0
  47. package/dist/core/engine/tool-bridge.js +818 -31
  48. package/dist/core/file-cache.js +113 -1
  49. package/dist/core/init/scaffold.js +195 -0
  50. package/dist/core/lsp/client.js +174 -29
  51. package/dist/core/mcp/client.js +75 -6
  52. package/dist/core/mcp/http-server.js +553 -0
  53. package/dist/core/mcp/permission.js +190 -0
  54. package/dist/core/mcp/registry.js +24 -2
  55. package/dist/core/mcp/server-tools.js +219 -0
  56. package/dist/core/mcp/server.js +397 -0
  57. package/dist/core/permissions/gate.js +187 -0
  58. package/dist/core/permissions/index.js +18 -0
  59. package/dist/core/permissions/mode.js +102 -0
  60. package/dist/core/permissions/state.js +160 -0
  61. package/dist/core/permissions/tool-class.js +93 -0
  62. package/dist/core/repl/codebase-survey.js +308 -0
  63. package/dist/core/repl/history.js +11 -1
  64. package/dist/core/repl/init-interview.js +457 -0
  65. package/dist/core/repl/model-pricing.js +135 -0
  66. package/dist/core/repl/onboarding-state.js +297 -0
  67. package/dist/core/repl/session.js +719 -29
  68. package/dist/core/repl/slash-commands.js +133 -9
  69. package/dist/core/retry-budget/budget.js +284 -0
  70. package/dist/core/retry-budget/index.js +5 -0
  71. package/dist/core/settings.js +71 -0
  72. package/dist/core/skills/defaults.js +457 -0
  73. package/dist/core/subagents/dispatcher-real.js +600 -0
  74. package/dist/core/subagents/dispatcher.js +113 -24
  75. package/dist/core/subagents/index.js +18 -5
  76. package/dist/core/subagents/isolation-matrix.js +213 -0
  77. package/dist/core/subagents/spawn.js +19 -4
  78. package/dist/core/transport/version-interceptor.js +166 -0
  79. package/dist/index.js +28 -0
  80. package/dist/runtime/bootstrap.js +190 -0
  81. package/dist/runtime/cli.js +1588 -266
  82. package/dist/runtime/commands/compact.js +296 -0
  83. package/dist/runtime/commands/cost.js +199 -0
  84. package/dist/runtime/commands/delegate.js +289 -0
  85. package/dist/runtime/commands/doctor.js +369 -0
  86. package/dist/runtime/commands/lsp.js +187 -5
  87. package/dist/runtime/commands/mcp.js +824 -0
  88. package/dist/runtime/commands/patch.js +17 -0
  89. package/dist/runtime/commands/permissions.js +87 -0
  90. package/dist/runtime/commands/report.js +299 -0
  91. package/dist/runtime/commands/review-consensus.js +17 -2
  92. package/dist/runtime/commands/roster.js +117 -0
  93. package/dist/runtime/commands/status.js +178 -0
  94. package/dist/runtime/commands/worktree.js +50 -6
  95. package/dist/runtime/headless.js +543 -0
  96. package/dist/runtime/load-hooks-or-exit.js +71 -0
  97. package/dist/runtime/plan-decompose.js +531 -0
  98. package/dist/runtime/version.js +65 -0
  99. package/dist/tools/agent-tool.js +206 -0
  100. package/dist/tools/apply-patch.js +281 -39
  101. package/dist/tools/ask-user-question.js +213 -0
  102. package/dist/tools/ask-user.js +115 -0
  103. package/dist/tools/file-tools.js +85 -14
  104. package/dist/tools/mcp-tool.js +260 -0
  105. package/dist/tools/multi-edit.js +361 -0
  106. package/dist/tools/registry.js +22 -2
  107. package/dist/tools/skill-tool.js +96 -0
  108. package/dist/tools/tasks.js +208 -0
  109. package/dist/tools/web-fetch.js +147 -2
  110. package/dist/tools/web-search.js +458 -0
  111. package/dist/tui/agent-progress-card.js +111 -0
  112. package/dist/tui/agent-tree.js +10 -0
  113. package/dist/tui/ask-modal.js +2 -2
  114. package/dist/tui/ask-user-question-prompt.js +192 -0
  115. package/dist/tui/compact-banner.js +54 -0
  116. package/dist/tui/conversation-pane.js +69 -8
  117. package/dist/tui/cost-table.js +111 -0
  118. package/dist/tui/doctor-table.js +31 -0
  119. package/dist/tui/input-box.js +1 -1
  120. package/dist/tui/markdown-render.js +4 -4
  121. package/dist/tui/repl-render.js +276 -37
  122. package/dist/tui/repl-splash.js +2 -2
  123. package/dist/tui/repl.js +25 -6
  124. package/dist/tui/splash.js +1 -1
  125. package/dist/tui/status-bar.js +94 -16
  126. package/dist/tui/status-table.js +7 -0
  127. package/dist/tui/tool-stream-pane.js +7 -0
  128. package/dist/tui/update-banner.js +20 -2
  129. package/docs/examples/codegraph.mcp.json +10 -0
  130. package/package.json +9 -6
@@ -0,0 +1,824 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { isAbsolute, resolve } from 'node:path';
5
+ import { FileReadCache } from '../../core/file-cache.js';
6
+ import { openSession } from '../../core/session.js';
7
+ import { loadSettings } from '../../core/settings.js';
8
+ import { isAlive } from '../../core/mcp/client.js';
9
+ import { loadMcpRegistry, mcpLogPath } from '../../core/mcp/registry.js';
10
+ import { listMcpTrust, setMcpTrust } from '../../core/mcp/trust.js';
11
+ import { createPugiMcpServer, serveStdio } from '../../core/mcp/server.js';
12
+ import { buildPugiMcpTools } from '../../core/mcp/server-tools.js';
13
+ import { serveHttp } from '../../core/mcp/http-server.js';
14
+ import { listMcpPermissions, clearMcpPermission, } from '../../core/mcp/permission.js';
15
+ export async function runMcpCommand(args, ctx) {
16
+ const sub = args[0] ?? 'list';
17
+ switch (sub) {
18
+ case 'list':
19
+ return runMcpList(ctx);
20
+ case 'trust':
21
+ return runMcpFlip(args.slice(1), ctx, 'trusted');
22
+ case 'deny':
23
+ return runMcpFlip(args.slice(1), ctx, 'denied');
24
+ case 'install':
25
+ return runMcpInstall(args.slice(1), ctx);
26
+ case 'remove':
27
+ case 'uninstall':
28
+ return runMcpRemove(args.slice(1), ctx);
29
+ case 'doctor':
30
+ return runMcpDoctor(args.slice(1), ctx);
31
+ case 'logs':
32
+ return runMcpLogs(args.slice(1), ctx);
33
+ case 'restart':
34
+ return runMcpRestart(args.slice(1), ctx);
35
+ case 'serve':
36
+ return runMcpServe(args.slice(1), ctx);
37
+ case 'perms':
38
+ return runMcpPerms(args.slice(1), ctx);
39
+ case 'help':
40
+ case '--help':
41
+ case '-h':
42
+ ctx.writeOutput({ command: 'mcp', usage: USAGE_LINES }, USAGE_LINES.join('\n'));
43
+ return;
44
+ default:
45
+ throw new Error(`Unknown sub-command "pugi mcp ${sub}". Try one of: list, trust, deny, install, remove, doctor, logs, restart, serve, perms.`);
46
+ }
47
+ }
48
+ const USAGE_LINES = [
49
+ 'Usage: pugi mcp <sub-command>',
50
+ '',
51
+ ' list List declared MCP servers + trust state + surfaced tools',
52
+ ' trust <name> Mark a server as trusted (operator-side ledger)',
53
+ ' deny <name> Mark a server as denied',
54
+ ' install <name> <command...> Add a server to .pugi/mcp.json (workspace scope).',
55
+ ' <command> must be an absolute path OR a binary',
56
+ ' resolvable via `which` on the operator PATH.',
57
+ ' remove <name> Remove a server from .pugi/mcp.json (workspace scope).',
58
+ ' Trust ledger entry is preserved — re-install reuses it.',
59
+ ' doctor [--connect] Print per-server health (handshake, tool count, last error).',
60
+ ' --connect actually spawns the children (slow, ~5s/server).',
61
+ ' Without --connect, reports the declared state only.',
62
+ ' logs <name> [--tail N] Tail the per-server log file at .pugi/logs/mcp-<name>.log.',
63
+ ' Default tail is 40 lines.',
64
+ ' restart <name> Bounce a server: tear down the connection, reload the',
65
+ ' config, re-handshake. Surfaces the new tool count.',
66
+ ' serve [options] Run Pugi as an MCP server',
67
+ ' --http :<port> HTTP+SSE transport (default: stdio)',
68
+ ' --host <ip> HTTP bind host (default: 127.0.0.1)',
69
+ ' --token <bearer> HTTP bearer token (env: PUGI_MCP_TOKEN).',
70
+ ' Required for --http unless --print-token is set.',
71
+ ' --print-token Auto-generate a random bearer token and print it',
72
+ ' to stderr. Opt-in for ad-hoc local testing only.',
73
+ ' --read-only Expose read/grep/glob only (default for HTTP).',
74
+ ' --allow-write Expose edit/write (default off — explicit opt-in).',
75
+ ' --allow-bash Expose the bash tool (default off — explicit opt-in).',
76
+ ' --no-bash Deprecated alias (bash is already off by default).',
77
+ ' perms list Show cached per-(server, tool) decisions',
78
+ ' perms reset <server>:<tool> Forget one cached decision',
79
+ ];
80
+ /* ---------- list ------------------------------------------------------- */
81
+ async function runMcpList(ctx) {
82
+ const registry = await loadMcpRegistry(ctx.workspaceRoot, { connect: false });
83
+ const declared = Array.from(registry.servers.values()).map((state) => ({
84
+ name: state.name,
85
+ command: state.config.command,
86
+ args: state.config.args,
87
+ trust: state.trust,
88
+ surfacedTools: state.surfacedTools.length,
89
+ lastError: state.lastError ?? null,
90
+ }));
91
+ const ledger = await listMcpTrust();
92
+ await registry.shutdown();
93
+ if (declared.length === 0) {
94
+ ctx.writeOutput({ command: 'mcp.list', servers: [], ledger }, 'No MCP servers declared. Add one with `pugi mcp install <name> <command...>`.');
95
+ return;
96
+ }
97
+ ctx.writeOutput({ command: 'mcp.list', servers: declared, ledger }, [
98
+ 'MCP servers:',
99
+ ...declared.map((server) => ` ${server.name.padEnd(20)} ${server.trust.padEnd(8)} ${server.command} ${server.args.join(' ')}`),
100
+ ].join('\n'));
101
+ }
102
+ /* ---------- trust / deny ---------------------------------------------- */
103
+ async function runMcpFlip(args, ctx, state) {
104
+ const name = args[0];
105
+ if (!name) {
106
+ throw new Error(`pugi mcp ${state === 'trusted' ? 'trust' : 'deny'} requires a server name.`);
107
+ }
108
+ const by = resolveDecidedBy();
109
+ await setMcpTrust(name, state, by);
110
+ ctx.writeOutput({ command: `mcp.${state === 'trusted' ? 'trust' : 'deny'}`, name, state, decidedBy: by }, state === 'trusted'
111
+ ? `MCP server "${name}" is now trusted.`
112
+ : `MCP server "${name}" is now denied.`);
113
+ }
114
+ /* ---------- install --------------------------------------------------- */
115
+ async function runMcpInstall(args, ctx) {
116
+ const name = args[0];
117
+ const command = args[1];
118
+ const rest = args.slice(2);
119
+ if (!name || !command) {
120
+ throw new Error('Usage: pugi mcp install <name> <command> [args...]');
121
+ }
122
+ if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
123
+ throw new Error(`pugi mcp install: server name "${name}" must be [a-zA-Z0-9_-]+`);
124
+ }
125
+ // β4 r1 P1 #6 — validate the executable path. Trust ledger gating is
126
+ // not enough: a cloned-and-trusted repo could declare a relative
127
+ // command (`./malicious-shim.sh`) that resolves at runtime via the
128
+ // shell PATH or the workspace cwd. Require an ABSOLUTE path OR a
129
+ // `which`-resolvable binary so the operator sees the canonical
130
+ // executable before granting trust.
131
+ const resolved = resolveExecutablePath(command);
132
+ if (!resolved) {
133
+ throw new Error(`pugi mcp install: command "${command}" must be an absolute path or a binary on PATH. ` +
134
+ `Pass the full path (e.g. /usr/local/bin/node) or install the binary first.`);
135
+ }
136
+ // Reject shell metacharacters in args — they survive into the spawn
137
+ // call as positional args (no shell), but a metachar in the COMMAND
138
+ // slot would be a clearer foot-gun and we already validated above.
139
+ for (const arg of [command, ...rest]) {
140
+ if (containsShellMetachar(arg)) {
141
+ throw new Error(`pugi mcp install: argument "${arg}" contains shell metacharacters; pass tokens individually instead of a shell string.`);
142
+ }
143
+ }
144
+ const mcpJsonPath = resolve(ctx.workspaceRoot, '.pugi/mcp.json');
145
+ mkdirSync(resolve(ctx.workspaceRoot, '.pugi'), { recursive: true });
146
+ let existing = { servers: {} };
147
+ if (existsSync(mcpJsonPath)) {
148
+ try {
149
+ const raw = readFileSync(mcpJsonPath, 'utf8');
150
+ if (raw.trim().length > 0) {
151
+ const parsed = JSON.parse(raw);
152
+ existing = { servers: parsed.servers ?? {} };
153
+ }
154
+ }
155
+ catch (error) {
156
+ throw new Error(`pugi mcp install: cannot parse existing .pugi/mcp.json: ${error.message}. ` +
157
+ `Fix the file by hand or delete it and re-run.`);
158
+ }
159
+ }
160
+ if (existing.servers[name]) {
161
+ throw new Error(`pugi mcp install: server "${name}" already declared. Remove it from .pugi/mcp.json first.`);
162
+ }
163
+ // β4 r2 P1 #1 — persist the RESOLVED absolute path as `command`, not the
164
+ // original input. Before this fix the install path verified `resolved` but
165
+ // wrote the operator's literal `command` argument back to .pugi/mcp.json;
166
+ // the spawn at connect-time re-walked the PATH via `spawn(command, ...)`,
167
+ // which defeated the P1 #6 (β4 r1) hardening — a workspace-cwd shim
168
+ // (`./malicious-node`) inserted between install and trust could intercept
169
+ // the call because PATH search includes cwd on many shells.
170
+ //
171
+ // The original input is preserved as `originalCommand` for display / debug
172
+ // surfaces (`pugi mcp list`, audit logs) so operators can still see how
173
+ // they typed the install call. The runtime spawn path consumes `command`,
174
+ // so the absolute path is always what we actually exec.
175
+ existing.servers[name] = {
176
+ command: resolved,
177
+ originalCommand: command,
178
+ args: rest,
179
+ env: {},
180
+ // Workspace declarations start `pending` — trust must be granted
181
+ // explicitly via `pugi mcp trust <name>`. This matches the
182
+ // server-level trust ledger override semantics in registry.ts.
183
+ trust: 'pending',
184
+ };
185
+ writeFileSync(mcpJsonPath, `${JSON.stringify(existing, null, 2)}\n`, { mode: 0o600 });
186
+ // Surface the resolved binary loudly so the operator sees the canonical
187
+ // executable before granting trust. β4 r1 P1 #6.
188
+ process.stderr.write(`pugi mcp install: starting executable resolves to ${resolved}\n`);
189
+ ctx.writeOutput({
190
+ command: 'mcp.install',
191
+ name,
192
+ // `executable` keeps the legacy field name (= what we will actually
193
+ // spawn). `originalCommand` is the operator's literal input.
194
+ executable: resolved,
195
+ originalCommand: command,
196
+ executableResolved: resolved,
197
+ args: rest,
198
+ configPath: mcpJsonPath,
199
+ }, [
200
+ `Added MCP server "${name}" to ${mcpJsonPath}.`,
201
+ `Resolved executable: ${resolved}`,
202
+ `It starts as pending. Run \`pugi mcp trust ${name}\` to enable it.`,
203
+ ].join('\n'));
204
+ }
205
+ /**
206
+ * Resolve a command to its canonical executable path. Returns null if the
207
+ * input is neither an absolute path that exists nor a binary resolvable
208
+ * via `which` on the operator PATH.
209
+ */
210
+ function resolveExecutablePath(command) {
211
+ if (isAbsolute(command)) {
212
+ return existsSync(command) ? command : null;
213
+ }
214
+ // Reject relative paths — `./shim.sh` could be a freshly-cloned
215
+ // attacker binary in the workspace cwd. Require absolute OR PATH.
216
+ if (command.includes('/') || command.includes('\\'))
217
+ return null;
218
+ try {
219
+ // `which` exits 0 with the path on stdout. We pass exactly one
220
+ // argument (the binary name we just validated) so no shell metachar
221
+ // path is possible.
222
+ const out = execFileSync('/usr/bin/which', [command], {
223
+ stdio: ['ignore', 'pipe', 'ignore'],
224
+ encoding: 'utf8',
225
+ timeout: 5000,
226
+ }).trim();
227
+ return out.length > 0 ? out : null;
228
+ }
229
+ catch {
230
+ return null;
231
+ }
232
+ }
233
+ function containsShellMetachar(value) {
234
+ // Reject the obvious shell control characters. We are not building a
235
+ // full lexer; the install path passes the args verbatim to spawn (no
236
+ // shell), so the goal here is purely surfacing operator surprise — a
237
+ // `;` in an arg almost always means the user thought they were typing
238
+ // a shell pipeline.
239
+ return /[;|&`$<>(){}\n\r]/.test(value);
240
+ }
241
+ /* ---------- remove ---------------------------------------------------- */
242
+ async function runMcpRemove(args, ctx) {
243
+ const name = args[0];
244
+ if (!name) {
245
+ throw new Error('Usage: pugi mcp remove <name>');
246
+ }
247
+ if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
248
+ throw new Error(`pugi mcp remove: server name "${name}" must be [a-zA-Z0-9_-]+`);
249
+ }
250
+ const mcpJsonPath = resolve(ctx.workspaceRoot, '.pugi/mcp.json');
251
+ if (!existsSync(mcpJsonPath)) {
252
+ throw new Error(`pugi mcp remove: no .pugi/mcp.json at ${mcpJsonPath}. Nothing to remove.`);
253
+ }
254
+ let existing;
255
+ try {
256
+ const raw = readFileSync(mcpJsonPath, 'utf8');
257
+ if (raw.trim().length === 0) {
258
+ existing = { servers: {} };
259
+ }
260
+ else {
261
+ const parsed = JSON.parse(raw);
262
+ existing = { servers: parsed.servers ?? {} };
263
+ }
264
+ }
265
+ catch (error) {
266
+ throw new Error(`pugi mcp remove: cannot parse .pugi/mcp.json: ${error.message}. ` +
267
+ `Fix the file by hand or delete it and re-run.`);
268
+ }
269
+ if (!existing.servers[name]) {
270
+ throw new Error(`pugi mcp remove: server "${name}" not declared in ${mcpJsonPath}. ` +
271
+ `Run \`pugi mcp list\` to see declared servers.`);
272
+ }
273
+ // Preserve the trust ledger entry on purpose — a re-install of the same
274
+ // server name should land back at its old trust state so the operator
275
+ // does not have to re-approve it. To wipe trust as well, run
276
+ // `pugi mcp deny <name>` (or edit ~/.pugi/trust-mcp.json by hand).
277
+ delete existing.servers[name];
278
+ writeFileSync(mcpJsonPath, `${JSON.stringify(existing, null, 2)}\n`, { mode: 0o600 });
279
+ ctx.writeOutput({
280
+ command: 'mcp.remove',
281
+ name,
282
+ configPath: mcpJsonPath,
283
+ remaining: Object.keys(existing.servers),
284
+ }, [
285
+ `Removed MCP server "${name}" from ${mcpJsonPath}.`,
286
+ `Trust ledger entry preserved — re-install reuses it.`,
287
+ `Remaining servers: ${Object.keys(existing.servers).length === 0 ? '(none)' : Object.keys(existing.servers).join(', ')}.`,
288
+ ].join('\n'));
289
+ }
290
+ /* ---------- doctor ---------------------------------------------------- */
291
+ async function runMcpDoctor(args, ctx) {
292
+ // `--connect` forces the doctor to actually spawn children + handshake.
293
+ // Default behaviour is dry-run (config + trust ledger only) so a routine
294
+ // `pugi doctor` does not block on a misbehaving server's 5s timeout per
295
+ // entry. Operators investigating an outage pass `--connect` explicitly.
296
+ const wantsConnect = args.includes('--connect');
297
+ const registry = await loadMcpRegistry(ctx.workspaceRoot, { connect: wantsConnect });
298
+ const ledger = await listMcpTrust();
299
+ const rows = [];
300
+ for (const state of registry.servers.values()) {
301
+ const conn = state.connection;
302
+ let handshake;
303
+ if (!wantsConnect) {
304
+ handshake = 'not-attempted';
305
+ }
306
+ else if (state.lastError) {
307
+ handshake = 'failed';
308
+ }
309
+ else if (conn && isAlive(conn)) {
310
+ handshake = 'ok';
311
+ }
312
+ else {
313
+ handshake = 'failed';
314
+ }
315
+ rows.push({
316
+ name: state.name,
317
+ trust: state.trust,
318
+ handshake,
319
+ pid: conn?.child.pid ?? null,
320
+ tools: state.surfacedTools.length,
321
+ uptimeMs: conn ? Date.now() - conn.startedAt : null,
322
+ lastError: state.lastError ?? null,
323
+ logFile: mcpLogPath(ctx.workspaceRoot, state.name),
324
+ });
325
+ }
326
+ rows.sort((a, b) => a.name.localeCompare(b.name));
327
+ await registry.shutdown();
328
+ if (rows.length === 0) {
329
+ ctx.writeOutput({ command: 'mcp.doctor', rows, ledger, connectAttempted: wantsConnect }, 'No MCP servers declared. Add one with `pugi mcp install <name> <command...>`.');
330
+ return;
331
+ }
332
+ const headerLines = [
333
+ `MCP doctor (${wantsConnect ? 'live handshake' : 'declared state only — pass --connect for live probe'}):`,
334
+ '',
335
+ ` ${'NAME'.padEnd(20)} ${'TRUST'.padEnd(8)} ${'HANDSHAKE'.padEnd(14)} ${'TOOLS'.padEnd(6)} ${'PID'.padEnd(7)} NOTE`,
336
+ ];
337
+ for (const row of rows) {
338
+ const note = row.lastError
339
+ ? `error: ${truncate(row.lastError, 60)}`
340
+ : row.handshake === 'ok'
341
+ ? `uptime ${formatUptime(row.uptimeMs ?? 0)}`
342
+ : row.handshake === 'failed'
343
+ ? 'see log file'
344
+ : '';
345
+ headerLines.push(` ${row.name.padEnd(20)} ${row.trust.padEnd(8)} ${row.handshake.padEnd(14)} ${String(row.tools).padEnd(6)} ${String(row.pid ?? '-').padEnd(7)} ${note}`);
346
+ }
347
+ headerLines.push('', `Log dir: ${resolve(ctx.workspaceRoot, '.pugi/logs')}`);
348
+ if (!wantsConnect) {
349
+ headerLines.push('Hint: pass --connect to actually spawn the children (slow, ~5s budget/server).');
350
+ }
351
+ ctx.writeOutput({ command: 'mcp.doctor', rows, ledger, connectAttempted: wantsConnect }, headerLines.join('\n'));
352
+ }
353
+ function truncate(value, max) {
354
+ if (value.length <= max)
355
+ return value;
356
+ return `${value.slice(0, max - 1)}…`;
357
+ }
358
+ function formatUptime(ms) {
359
+ if (ms < 1000)
360
+ return `${ms}ms`;
361
+ const sec = Math.floor(ms / 1000);
362
+ if (sec < 60)
363
+ return `${sec}s`;
364
+ const min = Math.floor(sec / 60);
365
+ if (min < 60)
366
+ return `${min}m${sec % 60}s`;
367
+ const hr = Math.floor(min / 60);
368
+ return `${hr}h${min % 60}m`;
369
+ }
370
+ /* ---------- logs ------------------------------------------------------ */
371
+ async function runMcpLogs(args, ctx) {
372
+ const name = args[0];
373
+ if (!name || name.startsWith('--')) {
374
+ throw new Error('Usage: pugi mcp logs <name> [--tail N]');
375
+ }
376
+ if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
377
+ throw new Error(`pugi mcp logs: server name "${name}" must be [a-zA-Z0-9_-]+`);
378
+ }
379
+ // `--tail N` and `--tail=N` both supported. Default 40 lines — matches
380
+ // typical `tail -n 40` muscle memory.
381
+ let tail = 40;
382
+ for (let i = 1; i < args.length; i += 1) {
383
+ const arg = args[i] ?? '';
384
+ if (arg === '--tail') {
385
+ const next = args[i + 1];
386
+ if (!next)
387
+ throw new Error('pugi mcp logs: --tail requires a value');
388
+ const n = Number.parseInt(next, 10);
389
+ if (!Number.isInteger(n) || n <= 0) {
390
+ throw new Error(`pugi mcp logs: --tail must be a positive integer (got "${next}")`);
391
+ }
392
+ tail = n;
393
+ i += 1;
394
+ }
395
+ else if (arg.startsWith('--tail=')) {
396
+ const n = Number.parseInt(arg.slice('--tail='.length), 10);
397
+ if (!Number.isInteger(n) || n <= 0) {
398
+ throw new Error(`pugi mcp logs: --tail must be a positive integer (got "${arg}")`);
399
+ }
400
+ tail = n;
401
+ }
402
+ else {
403
+ throw new Error(`pugi mcp logs: unknown flag "${arg}"`);
404
+ }
405
+ }
406
+ const path = mcpLogPath(ctx.workspaceRoot, name);
407
+ if (!existsSync(path)) {
408
+ ctx.writeOutput({ command: 'mcp.logs', name, path, tail, lines: [] }, `No log file at ${path}. The server has not produced stderr output yet (or has never been started).`);
409
+ return;
410
+ }
411
+ let raw;
412
+ try {
413
+ raw = readFileSync(path, 'utf8');
414
+ }
415
+ catch (error) {
416
+ throw new Error(`pugi mcp logs: cannot read ${path}: ${error.message}.`);
417
+ }
418
+ const allLines = raw.split('\n');
419
+ // `split('\n')` of a trailing-newline file yields an empty last element.
420
+ // Drop it so the displayed tail matches `wc -l` expectations.
421
+ if (allLines.length > 0 && allLines[allLines.length - 1] === '') {
422
+ allLines.pop();
423
+ }
424
+ const tailed = allLines.slice(Math.max(0, allLines.length - tail));
425
+ const sizeBytes = (() => {
426
+ try {
427
+ return statSync(path).size;
428
+ }
429
+ catch {
430
+ return 0;
431
+ }
432
+ })();
433
+ ctx.writeOutput({
434
+ command: 'mcp.logs',
435
+ name,
436
+ path,
437
+ tail,
438
+ totalLines: allLines.length,
439
+ sizeBytes,
440
+ lines: tailed,
441
+ }, [
442
+ `pugi mcp logs ${name} (${path}, ${sizeBytes} bytes, ${allLines.length} total lines, showing last ${Math.min(tail, allLines.length)}):`,
443
+ ...tailed,
444
+ ].join('\n'));
445
+ }
446
+ /* ---------- restart --------------------------------------------------- */
447
+ async function runMcpRestart(args, ctx) {
448
+ const name = args[0];
449
+ if (!name) {
450
+ throw new Error('Usage: pugi mcp restart <name>');
451
+ }
452
+ if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
453
+ throw new Error(`pugi mcp restart: server name "${name}" must be [a-zA-Z0-9_-]+`);
454
+ }
455
+ // `pugi mcp restart` is stateless from the CLI's perspective — the CLI
456
+ // process has no long-lived MCP registry of its own (the REPL owns it
457
+ // and tears it down on exit). What we DO here is: load the config,
458
+ // refuse if the server is not declared or not trusted, then probe-spawn
459
+ // the server with the live handshake. This proves it is reachable +
460
+ // surfaces the tool count for the operator. The REPL picks up the
461
+ // change on its next `loadMcpRegistry` cycle.
462
+ const registry = await loadMcpRegistry(ctx.workspaceRoot, { connect: false });
463
+ const state = registry.servers.get(name);
464
+ if (!state) {
465
+ await registry.shutdown();
466
+ throw new Error(`pugi mcp restart: server "${name}" not declared. Run \`pugi mcp list\` to see declared servers.`);
467
+ }
468
+ if (state.trust !== 'trusted') {
469
+ await registry.shutdown();
470
+ throw new Error(`pugi mcp restart: server "${name}" trust state is "${state.trust}". ` +
471
+ `Run \`pugi mcp trust ${name}\` first.`);
472
+ }
473
+ await registry.shutdown();
474
+ // Re-load WITH connect=true but scoped to a single-server probe via
475
+ // handshakeTimeoutMs (5s default keeps the CLI snappy). We use the same
476
+ // loadMcpRegistry path so log routing + error capture stay consistent.
477
+ const probe = await loadMcpRegistry(ctx.workspaceRoot, { connect: true });
478
+ const probed = probe.servers.get(name);
479
+ const lastError = probed?.lastError ?? null;
480
+ const toolCount = probed?.surfacedTools.length ?? 0;
481
+ const pid = probed?.connection?.child.pid ?? null;
482
+ await probe.shutdown();
483
+ if (lastError) {
484
+ ctx.writeOutput({
485
+ command: 'mcp.restart',
486
+ name,
487
+ ok: false,
488
+ error: lastError,
489
+ logFile: mcpLogPath(ctx.workspaceRoot, name),
490
+ }, [
491
+ `pugi mcp restart ${name}: FAILED`,
492
+ ` error: ${lastError}`,
493
+ ` log file: ${mcpLogPath(ctx.workspaceRoot, name)}`,
494
+ ].join('\n'));
495
+ return;
496
+ }
497
+ ctx.writeOutput({
498
+ command: 'mcp.restart',
499
+ name,
500
+ ok: true,
501
+ pid,
502
+ surfacedTools: toolCount,
503
+ }, [
504
+ `pugi mcp restart ${name}: OK`,
505
+ ` pid: ${pid ?? '-'}`,
506
+ ` surfaced tools: ${toolCount}`,
507
+ ].join('\n'));
508
+ }
509
+ async function runMcpServe(args, ctx) {
510
+ const flags = parseServeFlags(args);
511
+ const session = openSession(ctx.workspaceRoot);
512
+ const settings = loadSettings(ctx.workspaceRoot);
513
+ const toolCtx = {
514
+ root: ctx.workspaceRoot,
515
+ settings,
516
+ session,
517
+ readCache: new FileReadCache(),
518
+ };
519
+ // β4 r1 P1 #2 — surface defaults flip to deny-most-permissive. The
520
+ // previous defaults exposed every tool (read/edit/write/bash) on every
521
+ // transport; an HTTP listener with a leaked bearer = remote shell. We
522
+ // now require explicit opt-in for write + bash. `--read-only` remains
523
+ // the explicit "shrink to read/grep/glob" knob.
524
+ //
525
+ // β4 r2 P1 #2 — `--allow-bash` and `--allow-write` are now INDEPENDENT
526
+ // opt-ins. Before this fix `readOnly` collapsed to `true` whenever
527
+ // `--allow-write` was omitted, which forced `buildPugiMcpTools` to
528
+ // drop the `bash` tool even when the operator had explicitly set
529
+ // `--allow-bash`. The `readOnly` flag below now reflects ONLY the
530
+ // explicit `--read-only` request; the per-capability gates
531
+ // (`bashAllowed` / `writeAllowed`) handle the rest. The permission gate
532
+ // below (`buildServePermissionGate`) still refuses bash/edit per-tool
533
+ // when the corresponding capability is off, so a misconfigured
534
+ // `buildPugiMcpTools` call (advertising `bash` without the gate flag)
535
+ // would still be refused at dispatch.
536
+ const readOnly = flags.readOnly === true;
537
+ const writeAllowed = !readOnly && flags.writeAllowed;
538
+ const bashAllowed = !readOnly && flags.bashAllowed;
539
+ const tools = buildPugiMcpTools(toolCtx, {
540
+ bashAllowed,
541
+ // Keep the legacy contract: `readOnly` for the tool-builder means
542
+ // "do not advertise edit/write tools". Bash advertisement is gated
543
+ // by the independent `bashAllowed` knob. So the builder sees
544
+ // `readOnly = true` whenever the operator did not opt into write
545
+ // explicitly, which preserves the deny-by-default surface for
546
+ // edit/write but no longer accidentally suppresses bash.
547
+ readOnly: readOnly || !writeAllowed,
548
+ });
549
+ // β4 r1 P1 #2 — deny-by-default permissionGate. The MCP cache + FSM
550
+ // are consulted on every dispatch; allow_always-cached entries pass
551
+ // silently, allow_once entries pass and self-clear, deny entries
552
+ // refuse, and unset entries refuse with a hint (operator can grant
553
+ // out-of-band via `pugi mcp perm grant <tool>` — backlog).
554
+ const permissionGate = buildServePermissionGate({
555
+ bashAllowed,
556
+ writeAllowed,
557
+ });
558
+ const server = createPugiMcpServer({
559
+ tools,
560
+ permissionGate,
561
+ ...(ctx.signal ? { signal: ctx.signal } : {}),
562
+ log: (level, message) => {
563
+ // Stdio: keep stderr empty unless explicitly debugging. HTTP:
564
+ // route through writeOutput so operators see lifecycle in JSON
565
+ // mode. For now we honour stderr only — adding a --debug flag
566
+ // is backlog.
567
+ if (level === 'error')
568
+ process.stderr.write(`pugi-mcp: ${message}\n`);
569
+ },
570
+ });
571
+ if (flags.http) {
572
+ // β4 r1 P0 #1 — token resolution. Prefer explicit operator config;
573
+ // fall back to env; only auto-generate when `--print-token` is set.
574
+ // The auto-generated token NEVER lands in stdout — only stderr.
575
+ const envToken = process.env.PUGI_MCP_TOKEN?.trim();
576
+ const explicitToken = flags.bearerToken ?? (envToken && envToken.length > 0 ? envToken : null);
577
+ if (!explicitToken && !flags.printToken) {
578
+ throw new Error('pugi mcp serve --http requires a bearer token. Pass --token <value>, set ' +
579
+ 'PUGI_MCP_TOKEN, or add --print-token to auto-generate one (printed to stderr).');
580
+ }
581
+ const handle = await serveHttp({
582
+ server,
583
+ port: flags.http.port,
584
+ host: flags.http.host,
585
+ ...(explicitToken ? { bearerToken: explicitToken } : {}),
586
+ ...(ctx.signal ? { signal: ctx.signal } : {}),
587
+ log: (_level, message) => {
588
+ process.stderr.write(`pugi-mcp-http: ${message}\n`);
589
+ },
590
+ });
591
+ // Bearer token: print to STDERR only if auto-generated (so it never
592
+ // lands in CI logs / session journals / Anvil events that capture
593
+ // stdout). Operators consuming the JSON envelope must read it from
594
+ // their controlling terminal. β4 r1 P0 #1.
595
+ if (handle.bearerTokenAutoGenerated) {
596
+ process.stderr.write(`pugi-mcp-http: AUTO-GENERATED BEARER TOKEN (use once; --print-token set):\n` +
597
+ ` ${handle.bearerToken}\n` +
598
+ `pugi-mcp-http: prefer --token / PUGI_MCP_TOKEN for persistent setups.\n`);
599
+ }
600
+ // Emit the URL + tool surface to stdout (JSON-safe). Bearer token
601
+ // is intentionally omitted from the JSON payload — operators who
602
+ // need it programmatically supply --token explicitly.
603
+ ctx.writeOutput({
604
+ command: 'mcp.serve',
605
+ transport: 'http',
606
+ url: handle.url,
607
+ bearerTokenSource: handle.bearerTokenAutoGenerated
608
+ ? 'auto-generated (see stderr)'
609
+ : explicitToken === envToken
610
+ ? 'env:PUGI_MCP_TOKEN'
611
+ : 'flag:--token',
612
+ tools: tools.map((t) => t.name),
613
+ }, [
614
+ `pugi mcp serve (http) — listening at ${handle.url}`,
615
+ handle.bearerTokenAutoGenerated
616
+ ? `Bearer token: see stderr (auto-generated, --print-token)`
617
+ : `Bearer token: configured via ${explicitToken === envToken ? 'PUGI_MCP_TOKEN env' : '--token flag'}`,
618
+ `Tools: ${tools.map((t) => t.name).join(', ')}`,
619
+ '',
620
+ 'Endpoints:',
621
+ ' POST /mcp/v1/initialize',
622
+ ' POST /mcp/v1/list',
623
+ ' POST /mcp/v1/call',
624
+ ' POST /mcp/v1/rpc',
625
+ ' GET /mcp/v1/events (SSE)',
626
+ ' GET /mcp/v1/health (no auth)',
627
+ '',
628
+ 'Press Ctrl-C to stop.',
629
+ ].join('\n'));
630
+ // Keep the process alive while the listener is up. The signal +
631
+ // SIGINT handlers below force a graceful close.
632
+ await new Promise((resolveExit) => {
633
+ const onSignal = async () => {
634
+ await handle.close();
635
+ resolveExit();
636
+ };
637
+ process.once('SIGINT', () => void onSignal());
638
+ process.once('SIGTERM', () => void onSignal());
639
+ if (ctx.signal) {
640
+ if (ctx.signal.aborted)
641
+ void onSignal();
642
+ else
643
+ ctx.signal.addEventListener('abort', () => void onSignal(), { once: true });
644
+ }
645
+ });
646
+ return;
647
+ }
648
+ // Stdio transport — default. The handshake + tools/list happen on
649
+ // the wire; nothing is printed unless the parent agent sends a
650
+ // request that returns a response. Operator sees one info line on
651
+ // stderr so they know the server is up.
652
+ process.stderr.write(`pugi-mcp (stdio): ${tools.length} tool(s) — ${tools.map((t) => t.name).join(', ')}\n`);
653
+ await serveStdio({
654
+ server,
655
+ stdin: ctx.stdin ?? process.stdin,
656
+ stdout: ctx.stdout ?? process.stdout,
657
+ ...(ctx.signal ? { signal: ctx.signal } : {}),
658
+ });
659
+ }
660
+ function parseServeFlags(args) {
661
+ const flags = {
662
+ http: null,
663
+ bearerToken: null,
664
+ printToken: false,
665
+ readOnly: false,
666
+ writeAllowed: false,
667
+ bashAllowed: false,
668
+ };
669
+ for (let i = 0; i < args.length; i += 1) {
670
+ const arg = args[i] ?? '';
671
+ if (arg === '--http' || arg === '-h') {
672
+ const next = args[i + 1];
673
+ if (!next)
674
+ throw new Error('--http requires a port (e.g. --http :7100 or --http 7100)');
675
+ flags.http = parseHttpBinding(next);
676
+ i += 1;
677
+ }
678
+ else if (arg.startsWith('--http=')) {
679
+ flags.http = parseHttpBinding(arg.slice('--http='.length));
680
+ }
681
+ else if (arg === '--host') {
682
+ const next = args[i + 1];
683
+ if (!next)
684
+ throw new Error('--host requires a value');
685
+ // Stash on a synthetic http config; binding-port may have been set
686
+ // earlier, OR we initialize with port 0 and require --http.
687
+ if (!flags.http) {
688
+ throw new Error('--host requires --http to be set first');
689
+ }
690
+ flags.http.host = next;
691
+ i += 1;
692
+ }
693
+ else if (arg === '--token') {
694
+ const next = args[i + 1];
695
+ if (!next)
696
+ throw new Error('--token requires a value');
697
+ flags.bearerToken = next;
698
+ i += 1;
699
+ }
700
+ else if (arg.startsWith('--token=')) {
701
+ flags.bearerToken = arg.slice('--token='.length);
702
+ }
703
+ else if (arg === '--print-token') {
704
+ flags.printToken = true;
705
+ }
706
+ else if (arg === '--read-only') {
707
+ flags.readOnly = true;
708
+ }
709
+ else if (arg === '--allow-write') {
710
+ flags.writeAllowed = true;
711
+ }
712
+ else if (arg === '--allow-bash') {
713
+ flags.bashAllowed = true;
714
+ // bash implies write capability is meaningless (bash runs anything);
715
+ // we still keep them orthogonal so an operator can grant bash
716
+ // without exposing the structured `edit` / `write` tools to the
717
+ // MCP surface (which would let an external agent rewrite files
718
+ // without going through the diff escalation pipeline).
719
+ }
720
+ else if (arg === '--no-bash') {
721
+ // Deprecated — bash is already off by default. Kept for back-compat
722
+ // so existing operator scripts do not error.
723
+ flags.bashAllowed = false;
724
+ }
725
+ else if (arg === '--help') {
726
+ // Caller renders USAGE_LINES. We surface the same via top-level
727
+ // dispatch — nothing to do here, just don't error.
728
+ }
729
+ else {
730
+ throw new Error(`pugi mcp serve: unknown flag "${arg}"`);
731
+ }
732
+ }
733
+ return flags;
734
+ }
735
+ /**
736
+ * Build the permission gate for `pugi mcp serve`. Default policy is
737
+ * deny-with-hint. The MCP cache layer at `~/.pugi/mcp-perms.json` is
738
+ * consulted for `allow_always` / `deny` decisions; shell-class tools
739
+ * (bash) can NEVER hold `allow_always` (enforced by `setMcpPermission`),
740
+ * so a cached approval still requires per-call FSM prompt.
741
+ *
742
+ * Wired here as a thin synchronous policy because the serve path runs
743
+ * in a long-lived non-TTY context (HTTP) — interactive prompts would
744
+ * block forever. The future TTY-mode interactive prompt lives on top
745
+ * of this gate in `pugi mcp serve --interactive` (backlog).
746
+ */
747
+ function buildServePermissionGate(opts) {
748
+ return async (input) => {
749
+ const { tool } = input;
750
+ // Surface-level gate: even if the cache says allow_always, the
751
+ // operator's serve-flag opt-in is the ultimate authority. A
752
+ // misconfigured cache entry (legacy approval) cannot override the
753
+ // serve-time policy.
754
+ if (tool.permission === 'bash' && !opts.bashAllowed)
755
+ return false;
756
+ if (tool.permission === 'edit' && !opts.writeAllowed)
757
+ return false;
758
+ return true;
759
+ };
760
+ }
761
+ function parseHttpBinding(input) {
762
+ // Accept `:7100`, `7100`, or `host:7100`.
763
+ let host = '127.0.0.1';
764
+ let portStr = input;
765
+ if (input.startsWith(':')) {
766
+ portStr = input.slice(1);
767
+ }
768
+ else if (input.includes(':')) {
769
+ const idx = input.lastIndexOf(':');
770
+ host = input.slice(0, idx);
771
+ portStr = input.slice(idx + 1);
772
+ }
773
+ const port = Number.parseInt(portStr, 10);
774
+ if (!Number.isInteger(port) || port <= 0 || port > 65535) {
775
+ throw new Error(`invalid --http port: "${input}" (expected :PORT or HOST:PORT)`);
776
+ }
777
+ return { host, port };
778
+ }
779
+ /* ---------- perms ------------------------------------------------------ */
780
+ async function runMcpPerms(args, ctx) {
781
+ const sub = args[0] ?? 'list';
782
+ switch (sub) {
783
+ case 'list': {
784
+ const entries = listMcpPermissions();
785
+ ctx.writeOutput({ command: 'mcp.perms.list', entries }, entries.length === 0
786
+ ? 'No cached MCP permission decisions.'
787
+ : [
788
+ 'MCP permission cache:',
789
+ ...entries.map((entry) => ` ${entry.server.padEnd(16)} ${entry.tool.padEnd(20)} ${entry.decision.padEnd(14)} ${entry.decidedAt}`),
790
+ ].join('\n'));
791
+ return;
792
+ }
793
+ case 'reset': {
794
+ const target = args[1];
795
+ if (!target || !target.includes(':')) {
796
+ throw new Error('Usage: pugi mcp perms reset <server>:<tool>');
797
+ }
798
+ const idx = target.indexOf(':');
799
+ const server = target.slice(0, idx);
800
+ const tool = target.slice(idx + 1);
801
+ const removed = clearMcpPermission(server, tool);
802
+ ctx.writeOutput({ command: 'mcp.perms.reset', server, tool, removed }, removed
803
+ ? `Forgot permission decision for ${server}:${tool}.`
804
+ : `No cached decision for ${server}:${tool}.`);
805
+ return;
806
+ }
807
+ default:
808
+ throw new Error(`Unknown "pugi mcp perms ${sub}". Try: list, reset.`);
809
+ }
810
+ }
811
+ function resolveDecidedBy() {
812
+ return (process.env.PUGI_TRUSTED_BY?.trim() ||
813
+ process.env.USER?.trim() ||
814
+ process.env.USERNAME?.trim() ||
815
+ 'cli');
816
+ }
817
+ /**
818
+ * Resolve the effective user home for diagnostics (e.g. surfacing the
819
+ * trust ledger path in `pugi mcp list --verbose`). Mirrors registry.ts.
820
+ */
821
+ export function pugiHome() {
822
+ return process.env.PUGI_HOME ?? resolve(homedir(), '.pugi');
823
+ }
824
+ //# sourceMappingURL=mcp.js.map