@pugi/cli 0.1.0-beta.12 → 0.1.0-beta.13

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 (57) hide show
  1. package/dist/core/consensus/diff-capture.js +73 -0
  2. package/dist/core/context/index.js +7 -0
  3. package/dist/core/context/markdown-traverse.js +255 -0
  4. package/dist/core/edits/dispatch.js +218 -2
  5. package/dist/core/edits/journal.js +199 -0
  6. package/dist/core/edits/layer-d-ast.js +557 -14
  7. package/dist/core/edits/verify-hook.js +273 -0
  8. package/dist/core/engine/anvil-client.js +80 -5
  9. package/dist/core/engine/context-prefix.js +155 -0
  10. package/dist/core/engine/intent.js +260 -0
  11. package/dist/core/engine/native-pugi.js +663 -249
  12. package/dist/core/engine/prompts.js +52 -2
  13. package/dist/core/engine/tool-bridge.js +311 -9
  14. package/dist/core/lsp/client.js +57 -0
  15. package/dist/core/mcp/client.js +9 -0
  16. package/dist/core/mcp/http-server.js +553 -0
  17. package/dist/core/mcp/permission.js +190 -0
  18. package/dist/core/mcp/server-tools.js +219 -0
  19. package/dist/core/mcp/server.js +397 -0
  20. package/dist/core/repl/history.js +11 -1
  21. package/dist/core/repl/model-pricing.js +135 -0
  22. package/dist/core/repl/session.js +328 -12
  23. package/dist/core/repl/slash-commands.js +18 -4
  24. package/dist/core/settings.js +43 -0
  25. package/dist/core/subagents/dispatcher-real.js +600 -0
  26. package/dist/core/subagents/dispatcher.js +113 -24
  27. package/dist/core/subagents/index.js +18 -5
  28. package/dist/core/subagents/isolation-matrix.js +213 -0
  29. package/dist/core/subagents/spawn.js +19 -4
  30. package/dist/core/transport/version-interceptor.js +166 -0
  31. package/dist/index.js +28 -0
  32. package/dist/runtime/bootstrap.js +190 -0
  33. package/dist/runtime/cli.js +534 -268
  34. package/dist/runtime/commands/lsp.js +165 -5
  35. package/dist/runtime/commands/mcp.js +537 -0
  36. package/dist/runtime/headless.js +543 -0
  37. package/dist/runtime/load-hooks-or-exit.js +71 -0
  38. package/dist/runtime/version.js +65 -0
  39. package/dist/tools/agent-tool.js +192 -0
  40. package/dist/tools/apply-patch.js +62 -1
  41. package/dist/tools/mcp-tool.js +260 -0
  42. package/dist/tools/multi-edit.js +361 -0
  43. package/dist/tools/registry.js +5 -0
  44. package/dist/tools/web-fetch.js +147 -2
  45. package/dist/tools/web-search.js +458 -0
  46. package/dist/tui/agent-tree.js +10 -0
  47. package/dist/tui/ask-modal.js +2 -2
  48. package/dist/tui/conversation-pane.js +1 -1
  49. package/dist/tui/input-box.js +1 -1
  50. package/dist/tui/markdown-render.js +4 -4
  51. package/dist/tui/repl-render.js +105 -15
  52. package/dist/tui/repl-splash.js +2 -2
  53. package/dist/tui/repl.js +10 -4
  54. package/dist/tui/splash.js +1 -1
  55. package/dist/tui/status-bar.js +94 -16
  56. package/dist/tui/update-banner.js +20 -2
  57. package/package.json +5 -4
@@ -0,0 +1,537 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { existsSync, mkdirSync, readFileSync, 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 { loadMcpRegistry } from '../../core/mcp/registry.js';
9
+ import { listMcpTrust, setMcpTrust } from '../../core/mcp/trust.js';
10
+ import { createPugiMcpServer, serveStdio } from '../../core/mcp/server.js';
11
+ import { buildPugiMcpTools } from '../../core/mcp/server-tools.js';
12
+ import { serveHttp } from '../../core/mcp/http-server.js';
13
+ import { listMcpPermissions, clearMcpPermission, } from '../../core/mcp/permission.js';
14
+ export async function runMcpCommand(args, ctx) {
15
+ const sub = args[0] ?? 'list';
16
+ switch (sub) {
17
+ case 'list':
18
+ return runMcpList(ctx);
19
+ case 'trust':
20
+ return runMcpFlip(args.slice(1), ctx, 'trusted');
21
+ case 'deny':
22
+ return runMcpFlip(args.slice(1), ctx, 'denied');
23
+ case 'install':
24
+ return runMcpInstall(args.slice(1), ctx);
25
+ case 'serve':
26
+ return runMcpServe(args.slice(1), ctx);
27
+ case 'perms':
28
+ return runMcpPerms(args.slice(1), ctx);
29
+ case 'help':
30
+ case '--help':
31
+ case '-h':
32
+ ctx.writeOutput({ command: 'mcp', usage: USAGE_LINES }, USAGE_LINES.join('\n'));
33
+ return;
34
+ default:
35
+ throw new Error(`Unknown sub-command "pugi mcp ${sub}". Try one of: list, trust, deny, install, serve, perms.`);
36
+ }
37
+ }
38
+ const USAGE_LINES = [
39
+ 'Usage: pugi mcp <sub-command>',
40
+ '',
41
+ ' list List declared MCP servers + trust state + surfaced tools',
42
+ ' trust <name> Mark a server as trusted (operator-side ledger)',
43
+ ' deny <name> Mark a server as denied',
44
+ ' install <name> <command...> Add a server to .pugi/mcp.json (workspace scope).',
45
+ ' <command> must be an absolute path OR a binary',
46
+ ' resolvable via `which` on the operator PATH.',
47
+ ' serve [options] Run Pugi as an MCP server',
48
+ ' --http :<port> HTTP+SSE transport (default: stdio)',
49
+ ' --host <ip> HTTP bind host (default: 127.0.0.1)',
50
+ ' --token <bearer> HTTP bearer token (env: PUGI_MCP_TOKEN).',
51
+ ' Required for --http unless --print-token is set.',
52
+ ' --print-token Auto-generate a random bearer token and print it',
53
+ ' to stderr. Opt-in for ad-hoc local testing only.',
54
+ ' --read-only Expose read/grep/glob only (default for HTTP).',
55
+ ' --allow-write Expose edit/write (default off — explicit opt-in).',
56
+ ' --allow-bash Expose the bash tool (default off — explicit opt-in).',
57
+ ' --no-bash Deprecated alias (bash is already off by default).',
58
+ ' perms list Show cached per-(server, tool) decisions',
59
+ ' perms reset <server>:<tool> Forget one cached decision',
60
+ ];
61
+ /* ---------- list ------------------------------------------------------- */
62
+ async function runMcpList(ctx) {
63
+ const registry = await loadMcpRegistry(ctx.workspaceRoot, { connect: false });
64
+ const declared = Array.from(registry.servers.values()).map((state) => ({
65
+ name: state.name,
66
+ command: state.config.command,
67
+ args: state.config.args,
68
+ trust: state.trust,
69
+ surfacedTools: state.surfacedTools.length,
70
+ lastError: state.lastError ?? null,
71
+ }));
72
+ const ledger = await listMcpTrust();
73
+ await registry.shutdown();
74
+ if (declared.length === 0) {
75
+ ctx.writeOutput({ command: 'mcp.list', servers: [], ledger }, 'No MCP servers declared. Add one with `pugi mcp install <name> <command...>`.');
76
+ return;
77
+ }
78
+ ctx.writeOutput({ command: 'mcp.list', servers: declared, ledger }, [
79
+ 'MCP servers:',
80
+ ...declared.map((server) => ` ${server.name.padEnd(20)} ${server.trust.padEnd(8)} ${server.command} ${server.args.join(' ')}`),
81
+ ].join('\n'));
82
+ }
83
+ /* ---------- trust / deny ---------------------------------------------- */
84
+ async function runMcpFlip(args, ctx, state) {
85
+ const name = args[0];
86
+ if (!name) {
87
+ throw new Error(`pugi mcp ${state === 'trusted' ? 'trust' : 'deny'} requires a server name.`);
88
+ }
89
+ const by = resolveDecidedBy();
90
+ await setMcpTrust(name, state, by);
91
+ ctx.writeOutput({ command: `mcp.${state === 'trusted' ? 'trust' : 'deny'}`, name, state, decidedBy: by }, state === 'trusted'
92
+ ? `MCP server "${name}" is now trusted.`
93
+ : `MCP server "${name}" is now denied.`);
94
+ }
95
+ /* ---------- install --------------------------------------------------- */
96
+ async function runMcpInstall(args, ctx) {
97
+ const name = args[0];
98
+ const command = args[1];
99
+ const rest = args.slice(2);
100
+ if (!name || !command) {
101
+ throw new Error('Usage: pugi mcp install <name> <command> [args...]');
102
+ }
103
+ if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
104
+ throw new Error(`pugi mcp install: server name "${name}" must be [a-zA-Z0-9_-]+`);
105
+ }
106
+ // β4 r1 P1 #6 — validate the executable path. Trust ledger gating is
107
+ // not enough: a cloned-and-trusted repo could declare a relative
108
+ // command (`./malicious-shim.sh`) that resolves at runtime via the
109
+ // shell PATH or the workspace cwd. Require an ABSOLUTE path OR a
110
+ // `which`-resolvable binary so the operator sees the canonical
111
+ // executable before granting trust.
112
+ const resolved = resolveExecutablePath(command);
113
+ if (!resolved) {
114
+ throw new Error(`pugi mcp install: command "${command}" must be an absolute path or a binary on PATH. ` +
115
+ `Pass the full path (e.g. /usr/local/bin/node) or install the binary first.`);
116
+ }
117
+ // Reject shell metacharacters in args — they survive into the spawn
118
+ // call as positional args (no shell), but a metachar in the COMMAND
119
+ // slot would be a clearer foot-gun and we already validated above.
120
+ for (const arg of [command, ...rest]) {
121
+ if (containsShellMetachar(arg)) {
122
+ throw new Error(`pugi mcp install: argument "${arg}" contains shell metacharacters; pass tokens individually instead of a shell string.`);
123
+ }
124
+ }
125
+ const mcpJsonPath = resolve(ctx.workspaceRoot, '.pugi/mcp.json');
126
+ mkdirSync(resolve(ctx.workspaceRoot, '.pugi'), { recursive: true });
127
+ let existing = { servers: {} };
128
+ if (existsSync(mcpJsonPath)) {
129
+ try {
130
+ const raw = readFileSync(mcpJsonPath, 'utf8');
131
+ if (raw.trim().length > 0) {
132
+ const parsed = JSON.parse(raw);
133
+ existing = { servers: parsed.servers ?? {} };
134
+ }
135
+ }
136
+ catch (error) {
137
+ throw new Error(`pugi mcp install: cannot parse existing .pugi/mcp.json: ${error.message}. ` +
138
+ `Fix the file by hand or delete it and re-run.`);
139
+ }
140
+ }
141
+ if (existing.servers[name]) {
142
+ throw new Error(`pugi mcp install: server "${name}" already declared. Remove it from .pugi/mcp.json first.`);
143
+ }
144
+ // β4 r2 P1 #1 — persist the RESOLVED absolute path as `command`, not the
145
+ // original input. Before this fix the install path verified `resolved` but
146
+ // wrote the operator's literal `command` argument back to .pugi/mcp.json;
147
+ // the spawn at connect-time re-walked the PATH via `spawn(command, ...)`,
148
+ // which defeated the P1 #6 (β4 r1) hardening — a workspace-cwd shim
149
+ // (`./malicious-node`) inserted between install and trust could intercept
150
+ // the call because PATH search includes cwd on many shells.
151
+ //
152
+ // The original input is preserved as `originalCommand` for display / debug
153
+ // surfaces (`pugi mcp list`, audit logs) so operators can still see how
154
+ // they typed the install call. The runtime spawn path consumes `command`,
155
+ // so the absolute path is always what we actually exec.
156
+ existing.servers[name] = {
157
+ command: resolved,
158
+ originalCommand: command,
159
+ args: rest,
160
+ env: {},
161
+ // Workspace declarations start `pending` — trust must be granted
162
+ // explicitly via `pugi mcp trust <name>`. This matches the
163
+ // server-level trust ledger override semantics in registry.ts.
164
+ trust: 'pending',
165
+ };
166
+ writeFileSync(mcpJsonPath, `${JSON.stringify(existing, null, 2)}\n`, { mode: 0o600 });
167
+ // Surface the resolved binary loudly so the operator sees the canonical
168
+ // executable before granting trust. β4 r1 P1 #6.
169
+ process.stderr.write(`pugi mcp install: starting executable resolves to ${resolved}\n`);
170
+ ctx.writeOutput({
171
+ command: 'mcp.install',
172
+ name,
173
+ // `executable` keeps the legacy field name (= what we will actually
174
+ // spawn). `originalCommand` is the operator's literal input.
175
+ executable: resolved,
176
+ originalCommand: command,
177
+ executableResolved: resolved,
178
+ args: rest,
179
+ configPath: mcpJsonPath,
180
+ }, [
181
+ `Added MCP server "${name}" to ${mcpJsonPath}.`,
182
+ `Resolved executable: ${resolved}`,
183
+ `It starts as pending. Run \`pugi mcp trust ${name}\` to enable it.`,
184
+ ].join('\n'));
185
+ }
186
+ /**
187
+ * Resolve a command to its canonical executable path. Returns null if the
188
+ * input is neither an absolute path that exists nor a binary resolvable
189
+ * via `which` on the operator PATH.
190
+ */
191
+ function resolveExecutablePath(command) {
192
+ if (isAbsolute(command)) {
193
+ return existsSync(command) ? command : null;
194
+ }
195
+ // Reject relative paths — `./shim.sh` could be a freshly-cloned
196
+ // attacker binary in the workspace cwd. Require absolute OR PATH.
197
+ if (command.includes('/') || command.includes('\\'))
198
+ return null;
199
+ try {
200
+ // `which` exits 0 with the path on stdout. We pass exactly one
201
+ // argument (the binary name we just validated) so no shell metachar
202
+ // path is possible.
203
+ const out = execFileSync('/usr/bin/which', [command], {
204
+ stdio: ['ignore', 'pipe', 'ignore'],
205
+ encoding: 'utf8',
206
+ timeout: 5000,
207
+ }).trim();
208
+ return out.length > 0 ? out : null;
209
+ }
210
+ catch {
211
+ return null;
212
+ }
213
+ }
214
+ function containsShellMetachar(value) {
215
+ // Reject the obvious shell control characters. We are not building a
216
+ // full lexer; the install path passes the args verbatim to spawn (no
217
+ // shell), so the goal here is purely surfacing operator surprise — a
218
+ // `;` in an arg almost always means the user thought they were typing
219
+ // a shell pipeline.
220
+ return /[;|&`$<>(){}\n\r]/.test(value);
221
+ }
222
+ async function runMcpServe(args, ctx) {
223
+ const flags = parseServeFlags(args);
224
+ const session = openSession(ctx.workspaceRoot);
225
+ const settings = loadSettings(ctx.workspaceRoot);
226
+ const toolCtx = {
227
+ root: ctx.workspaceRoot,
228
+ settings,
229
+ session,
230
+ readCache: new FileReadCache(),
231
+ };
232
+ // β4 r1 P1 #2 — surface defaults flip to deny-most-permissive. The
233
+ // previous defaults exposed every tool (read/edit/write/bash) on every
234
+ // transport; an HTTP listener with a leaked bearer = remote shell. We
235
+ // now require explicit opt-in for write + bash. `--read-only` remains
236
+ // the explicit "shrink to read/grep/glob" knob.
237
+ //
238
+ // β4 r2 P1 #2 — `--allow-bash` and `--allow-write` are now INDEPENDENT
239
+ // opt-ins. Before this fix `readOnly` collapsed to `true` whenever
240
+ // `--allow-write` was omitted, which forced `buildPugiMcpTools` to
241
+ // drop the `bash` tool even when the operator had explicitly set
242
+ // `--allow-bash`. The `readOnly` flag below now reflects ONLY the
243
+ // explicit `--read-only` request; the per-capability gates
244
+ // (`bashAllowed` / `writeAllowed`) handle the rest. The permission gate
245
+ // below (`buildServePermissionGate`) still refuses bash/edit per-tool
246
+ // when the corresponding capability is off, so a misconfigured
247
+ // `buildPugiMcpTools` call (advertising `bash` without the gate flag)
248
+ // would still be refused at dispatch.
249
+ const readOnly = flags.readOnly === true;
250
+ const writeAllowed = !readOnly && flags.writeAllowed;
251
+ const bashAllowed = !readOnly && flags.bashAllowed;
252
+ const tools = buildPugiMcpTools(toolCtx, {
253
+ bashAllowed,
254
+ // Keep the legacy contract: `readOnly` for the tool-builder means
255
+ // "do not advertise edit/write tools". Bash advertisement is gated
256
+ // by the independent `bashAllowed` knob. So the builder sees
257
+ // `readOnly = true` whenever the operator did not opt into write
258
+ // explicitly, which preserves the deny-by-default surface for
259
+ // edit/write but no longer accidentally suppresses bash.
260
+ readOnly: readOnly || !writeAllowed,
261
+ });
262
+ // β4 r1 P1 #2 — deny-by-default permissionGate. The MCP cache + FSM
263
+ // are consulted on every dispatch; allow_always-cached entries pass
264
+ // silently, allow_once entries pass and self-clear, deny entries
265
+ // refuse, and unset entries refuse with a hint (operator can grant
266
+ // out-of-band via `pugi mcp perm grant <tool>` — backlog).
267
+ const permissionGate = buildServePermissionGate({
268
+ bashAllowed,
269
+ writeAllowed,
270
+ });
271
+ const server = createPugiMcpServer({
272
+ tools,
273
+ permissionGate,
274
+ ...(ctx.signal ? { signal: ctx.signal } : {}),
275
+ log: (level, message) => {
276
+ // Stdio: keep stderr empty unless explicitly debugging. HTTP:
277
+ // route through writeOutput so operators see lifecycle in JSON
278
+ // mode. For now we honour stderr only — adding a --debug flag
279
+ // is backlog.
280
+ if (level === 'error')
281
+ process.stderr.write(`pugi-mcp: ${message}\n`);
282
+ },
283
+ });
284
+ if (flags.http) {
285
+ // β4 r1 P0 #1 — token resolution. Prefer explicit operator config;
286
+ // fall back to env; only auto-generate when `--print-token` is set.
287
+ // The auto-generated token NEVER lands in stdout — only stderr.
288
+ const envToken = process.env.PUGI_MCP_TOKEN?.trim();
289
+ const explicitToken = flags.bearerToken ?? (envToken && envToken.length > 0 ? envToken : null);
290
+ if (!explicitToken && !flags.printToken) {
291
+ throw new Error('pugi mcp serve --http requires a bearer token. Pass --token <value>, set ' +
292
+ 'PUGI_MCP_TOKEN, or add --print-token to auto-generate one (printed to stderr).');
293
+ }
294
+ const handle = await serveHttp({
295
+ server,
296
+ port: flags.http.port,
297
+ host: flags.http.host,
298
+ ...(explicitToken ? { bearerToken: explicitToken } : {}),
299
+ ...(ctx.signal ? { signal: ctx.signal } : {}),
300
+ log: (_level, message) => {
301
+ process.stderr.write(`pugi-mcp-http: ${message}\n`);
302
+ },
303
+ });
304
+ // Bearer token: print to STDERR only if auto-generated (so it never
305
+ // lands in CI logs / session journals / Anvil events that capture
306
+ // stdout). Operators consuming the JSON envelope must read it from
307
+ // their controlling terminal. β4 r1 P0 #1.
308
+ if (handle.bearerTokenAutoGenerated) {
309
+ process.stderr.write(`pugi-mcp-http: AUTO-GENERATED BEARER TOKEN (use once; --print-token set):\n` +
310
+ ` ${handle.bearerToken}\n` +
311
+ `pugi-mcp-http: prefer --token / PUGI_MCP_TOKEN for persistent setups.\n`);
312
+ }
313
+ // Emit the URL + tool surface to stdout (JSON-safe). Bearer token
314
+ // is intentionally omitted from the JSON payload — operators who
315
+ // need it programmatically supply --token explicitly.
316
+ ctx.writeOutput({
317
+ command: 'mcp.serve',
318
+ transport: 'http',
319
+ url: handle.url,
320
+ bearerTokenSource: handle.bearerTokenAutoGenerated
321
+ ? 'auto-generated (see stderr)'
322
+ : explicitToken === envToken
323
+ ? 'env:PUGI_MCP_TOKEN'
324
+ : 'flag:--token',
325
+ tools: tools.map((t) => t.name),
326
+ }, [
327
+ `pugi mcp serve (http) — listening at ${handle.url}`,
328
+ handle.bearerTokenAutoGenerated
329
+ ? `Bearer token: see stderr (auto-generated, --print-token)`
330
+ : `Bearer token: configured via ${explicitToken === envToken ? 'PUGI_MCP_TOKEN env' : '--token flag'}`,
331
+ `Tools: ${tools.map((t) => t.name).join(', ')}`,
332
+ '',
333
+ 'Endpoints:',
334
+ ' POST /mcp/v1/initialize',
335
+ ' POST /mcp/v1/list',
336
+ ' POST /mcp/v1/call',
337
+ ' POST /mcp/v1/rpc',
338
+ ' GET /mcp/v1/events (SSE)',
339
+ ' GET /mcp/v1/health (no auth)',
340
+ '',
341
+ 'Press Ctrl-C to stop.',
342
+ ].join('\n'));
343
+ // Keep the process alive while the listener is up. The signal +
344
+ // SIGINT handlers below force a graceful close.
345
+ await new Promise((resolveExit) => {
346
+ const onSignal = async () => {
347
+ await handle.close();
348
+ resolveExit();
349
+ };
350
+ process.once('SIGINT', () => void onSignal());
351
+ process.once('SIGTERM', () => void onSignal());
352
+ if (ctx.signal) {
353
+ if (ctx.signal.aborted)
354
+ void onSignal();
355
+ else
356
+ ctx.signal.addEventListener('abort', () => void onSignal(), { once: true });
357
+ }
358
+ });
359
+ return;
360
+ }
361
+ // Stdio transport — default. The handshake + tools/list happen on
362
+ // the wire; nothing is printed unless the parent agent sends a
363
+ // request that returns a response. Operator sees one info line on
364
+ // stderr so they know the server is up.
365
+ process.stderr.write(`pugi-mcp (stdio): ${tools.length} tool(s) — ${tools.map((t) => t.name).join(', ')}\n`);
366
+ await serveStdio({
367
+ server,
368
+ stdin: ctx.stdin ?? process.stdin,
369
+ stdout: ctx.stdout ?? process.stdout,
370
+ ...(ctx.signal ? { signal: ctx.signal } : {}),
371
+ });
372
+ }
373
+ function parseServeFlags(args) {
374
+ const flags = {
375
+ http: null,
376
+ bearerToken: null,
377
+ printToken: false,
378
+ readOnly: false,
379
+ writeAllowed: false,
380
+ bashAllowed: false,
381
+ };
382
+ for (let i = 0; i < args.length; i += 1) {
383
+ const arg = args[i] ?? '';
384
+ if (arg === '--http' || arg === '-h') {
385
+ const next = args[i + 1];
386
+ if (!next)
387
+ throw new Error('--http requires a port (e.g. --http :7100 or --http 7100)');
388
+ flags.http = parseHttpBinding(next);
389
+ i += 1;
390
+ }
391
+ else if (arg.startsWith('--http=')) {
392
+ flags.http = parseHttpBinding(arg.slice('--http='.length));
393
+ }
394
+ else if (arg === '--host') {
395
+ const next = args[i + 1];
396
+ if (!next)
397
+ throw new Error('--host requires a value');
398
+ // Stash on a synthetic http config; binding-port may have been set
399
+ // earlier, OR we initialize with port 0 and require --http.
400
+ if (!flags.http) {
401
+ throw new Error('--host requires --http to be set first');
402
+ }
403
+ flags.http.host = next;
404
+ i += 1;
405
+ }
406
+ else if (arg === '--token') {
407
+ const next = args[i + 1];
408
+ if (!next)
409
+ throw new Error('--token requires a value');
410
+ flags.bearerToken = next;
411
+ i += 1;
412
+ }
413
+ else if (arg.startsWith('--token=')) {
414
+ flags.bearerToken = arg.slice('--token='.length);
415
+ }
416
+ else if (arg === '--print-token') {
417
+ flags.printToken = true;
418
+ }
419
+ else if (arg === '--read-only') {
420
+ flags.readOnly = true;
421
+ }
422
+ else if (arg === '--allow-write') {
423
+ flags.writeAllowed = true;
424
+ }
425
+ else if (arg === '--allow-bash') {
426
+ flags.bashAllowed = true;
427
+ // bash implies write capability is meaningless (bash runs anything);
428
+ // we still keep them orthogonal so an operator can grant bash
429
+ // without exposing the structured `edit` / `write` tools to the
430
+ // MCP surface (which would let an external agent rewrite files
431
+ // without going through the diff escalation pipeline).
432
+ }
433
+ else if (arg === '--no-bash') {
434
+ // Deprecated — bash is already off by default. Kept for back-compat
435
+ // so existing operator scripts do not error.
436
+ flags.bashAllowed = false;
437
+ }
438
+ else if (arg === '--help') {
439
+ // Caller renders USAGE_LINES. We surface the same via top-level
440
+ // dispatch — nothing to do here, just don't error.
441
+ }
442
+ else {
443
+ throw new Error(`pugi mcp serve: unknown flag "${arg}"`);
444
+ }
445
+ }
446
+ return flags;
447
+ }
448
+ /**
449
+ * Build the permission gate for `pugi mcp serve`. Default policy is
450
+ * deny-with-hint. The MCP cache layer at `~/.pugi/mcp-perms.json` is
451
+ * consulted for `allow_always` / `deny` decisions; shell-class tools
452
+ * (bash) can NEVER hold `allow_always` (enforced by `setMcpPermission`),
453
+ * so a cached approval still requires per-call FSM prompt.
454
+ *
455
+ * Wired here as a thin synchronous policy because the serve path runs
456
+ * in a long-lived non-TTY context (HTTP) — interactive prompts would
457
+ * block forever. The future TTY-mode interactive prompt lives on top
458
+ * of this gate in `pugi mcp serve --interactive` (backlog).
459
+ */
460
+ function buildServePermissionGate(opts) {
461
+ return async (input) => {
462
+ const { tool } = input;
463
+ // Surface-level gate: even if the cache says allow_always, the
464
+ // operator's serve-flag opt-in is the ultimate authority. A
465
+ // misconfigured cache entry (legacy approval) cannot override the
466
+ // serve-time policy.
467
+ if (tool.permission === 'bash' && !opts.bashAllowed)
468
+ return false;
469
+ if (tool.permission === 'edit' && !opts.writeAllowed)
470
+ return false;
471
+ return true;
472
+ };
473
+ }
474
+ function parseHttpBinding(input) {
475
+ // Accept `:7100`, `7100`, or `host:7100`.
476
+ let host = '127.0.0.1';
477
+ let portStr = input;
478
+ if (input.startsWith(':')) {
479
+ portStr = input.slice(1);
480
+ }
481
+ else if (input.includes(':')) {
482
+ const idx = input.lastIndexOf(':');
483
+ host = input.slice(0, idx);
484
+ portStr = input.slice(idx + 1);
485
+ }
486
+ const port = Number.parseInt(portStr, 10);
487
+ if (!Number.isInteger(port) || port <= 0 || port > 65535) {
488
+ throw new Error(`invalid --http port: "${input}" (expected :PORT or HOST:PORT)`);
489
+ }
490
+ return { host, port };
491
+ }
492
+ /* ---------- perms ------------------------------------------------------ */
493
+ async function runMcpPerms(args, ctx) {
494
+ const sub = args[0] ?? 'list';
495
+ switch (sub) {
496
+ case 'list': {
497
+ const entries = listMcpPermissions();
498
+ ctx.writeOutput({ command: 'mcp.perms.list', entries }, entries.length === 0
499
+ ? 'No cached MCP permission decisions.'
500
+ : [
501
+ 'MCP permission cache:',
502
+ ...entries.map((entry) => ` ${entry.server.padEnd(16)} ${entry.tool.padEnd(20)} ${entry.decision.padEnd(14)} ${entry.decidedAt}`),
503
+ ].join('\n'));
504
+ return;
505
+ }
506
+ case 'reset': {
507
+ const target = args[1];
508
+ if (!target || !target.includes(':')) {
509
+ throw new Error('Usage: pugi mcp perms reset <server>:<tool>');
510
+ }
511
+ const idx = target.indexOf(':');
512
+ const server = target.slice(0, idx);
513
+ const tool = target.slice(idx + 1);
514
+ const removed = clearMcpPermission(server, tool);
515
+ ctx.writeOutput({ command: 'mcp.perms.reset', server, tool, removed }, removed
516
+ ? `Forgot permission decision for ${server}:${tool}.`
517
+ : `No cached decision for ${server}:${tool}.`);
518
+ return;
519
+ }
520
+ default:
521
+ throw new Error(`Unknown "pugi mcp perms ${sub}". Try: list, reset.`);
522
+ }
523
+ }
524
+ function resolveDecidedBy() {
525
+ return (process.env.PUGI_TRUSTED_BY?.trim() ||
526
+ process.env.USER?.trim() ||
527
+ process.env.USERNAME?.trim() ||
528
+ 'cli');
529
+ }
530
+ /**
531
+ * Resolve the effective user home for diagnostics (e.g. surfacing the
532
+ * trust ledger path in `pugi mcp list --verbose`). Mirrors registry.ts.
533
+ */
534
+ export function pugiHome() {
535
+ return process.env.PUGI_HOME ?? resolve(homedir(), '.pugi');
536
+ }
537
+ //# sourceMappingURL=mcp.js.map