@hop-top/kit 0.5.0-alpha.10 → 0.5.0-alpha.11

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 (58) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +4 -4
  3. package/dist/alias.js +3 -3
  4. package/dist/{chunk-T46YPHKN.js → chunk-4FMALWYB.js} +45 -45
  5. package/dist/{chunk-WWUKGJB5.js → chunk-4GPCWBBA.js} +60 -7
  6. package/dist/{chunk-JZ22ZUFA.js → chunk-65VPWMPV.js} +4 -1
  7. package/dist/{chunk-YGYQUFGY.js → chunk-BXJ2J27B.js} +10 -10
  8. package/dist/chunk-CXBZTONY.js +65 -0
  9. package/dist/{chunk-K7VCKJ27.js → chunk-EE4M2UOF.js} +8 -4
  10. package/dist/{chunk-72XZWQX7.js → chunk-GFRAYYRD.js} +475 -162
  11. package/dist/{chunk-2JV3A7OP.js → chunk-IVQHLI56.js} +6 -10
  12. package/dist/{chunk-NLMS7HGP.js → chunk-IZ6Q4SE3.js} +3 -3
  13. package/dist/chunk-MFVUENZR.js +1549 -0
  14. package/dist/{chunk-BLS2OBIQ.js → chunk-ML7D5DWY.js} +2 -2
  15. package/dist/{chunk-GGWJRWWA.js → chunk-RYKLVOVK.js} +7 -7
  16. package/dist/{chunk-QPUCXQXT.js → chunk-T6OZMPPV.js} +2 -1
  17. package/dist/{chunk-MUIQVU6E.js → chunk-VGOA5Y7S.js} +11 -11
  18. package/dist/{chunk-ABQSE7AI.js → chunk-VWGP4NVJ.js} +38 -38
  19. package/dist/cli-RSRk1M36.d.ts +707 -0
  20. package/dist/cli.d.ts +1 -1
  21. package/dist/cli.js +60 -5
  22. package/dist/completion.js +2 -2
  23. package/dist/{index-DCe1boBz.d.ts → index-CGE5yLBj.d.ts} +1 -1
  24. package/dist/index.d.ts +3 -3
  25. package/dist/index.js +22 -22
  26. package/dist/llm-anthropic.js +5 -5
  27. package/dist/llm-openai.js +5 -5
  28. package/dist/llm.js +3 -3
  29. package/dist/log.js +3 -3
  30. package/dist/mcp/index.js +3 -2
  31. package/dist/output.js +2 -4
  32. package/dist/routellm.js +6 -6
  33. package/dist/toolspec.js +4 -4
  34. package/dist/tui/index.d.ts +2 -2
  35. package/dist/tui/index.js +3 -3
  36. package/dist/{upgrade-p_zh3pvV.d.ts → upgrade-C3RWGwRi.d.ts} +23 -0
  37. package/dist/upgrade.d.ts +1 -1
  38. package/dist/upgrade.js +2 -2
  39. package/package.json +1 -1
  40. package/src/cli.root.conformance.test.ts +166 -0
  41. package/src/cli.ts +39 -0
  42. package/src/completion.conformance.test.ts +3 -2
  43. package/src/completion.test.ts +12 -0
  44. package/src/completion.ts +8 -3
  45. package/src/delegation.test.ts +299 -0
  46. package/src/delegation.ts +807 -0
  47. package/src/mcp/bridge.test.ts +28 -0
  48. package/src/mcp/bridge.ts +5 -10
  49. package/src/plan.ts +89 -0
  50. package/src/policy.ts +472 -0
  51. package/src/sideeffect.ts +105 -0
  52. package/src/toolspec-manifest.ts +7 -2
  53. package/src/upgrade.test.ts +291 -0
  54. package/src/upgrade.ts +116 -7
  55. package/dist/chunk-GHPJJV5L.js +0 -613
  56. package/dist/chunk-IXVQ62NZ.js +0 -334
  57. package/dist/cli-C5B5tnpA.d.ts +0 -400
  58. package/dist/{chunk-PSFYJGDG.js → chunk-K7E34Q3A.js} +2 -2
@@ -0,0 +1,807 @@
1
+ /**
2
+ * @module delegation
3
+ * @package @hop-top/kit
4
+ *
5
+ * The delegation gates a leaf passes before its handler runs, in Go's
6
+ * order (`policy_runE.go`, `global_dryrun.go`): `--dry-run` enforcement,
7
+ * the named `--policy`, the `--confirm` matrix with the typed
8
+ * `--confirm-token`, and the `--max-ops` budget accounted after a
9
+ * successful mutating run.
10
+ *
11
+ * `createCLI` installs the root flags and the hooks; adopters declare
12
+ * `kit/side-effect` on a leaf and the gates follow.
13
+ */
14
+
15
+ import { createHash } from 'node:crypto';
16
+ import * as fs from 'node:fs';
17
+ import { Command, Option } from 'commander';
18
+
19
+ import {
20
+ type CliError,
21
+ EXIT_USAGE,
22
+ rateLimitedError,
23
+ renderError,
24
+ TRANSIENCE_TRANSIENT,
25
+ unauthorizedError,
26
+ usageError,
27
+ withTransience,
28
+ } from './output/error.js';
29
+ import { renderPlan } from './plan.js';
30
+ import {
31
+ Engine,
32
+ emptyPolicy,
33
+ KIT_DEFAULT_NAME,
34
+ kitDefault,
35
+ MaxOpsExceededError,
36
+ type Policy,
37
+ type PolicyLoader,
38
+ } from './policy.js';
39
+ import {
40
+ gateSideEffect,
41
+ isDestructiveLike,
42
+ inferredDestructive,
43
+ isDestructiveName,
44
+ isValidSideEffect,
45
+ isWriteLike,
46
+ SIDE_EFFECT_ANNOTATION,
47
+ } from './sideeffect.js';
48
+
49
+ /** `kit/destructive-token: required` demands `--confirm-token=<sha>` too. */
50
+ export const DESTRUCTIVE_TOKEN_ANNOTATION = 'kit/destructive-token';
51
+ /** `kit/dry-run`: `supported` (legacy) or `opted-out`. */
52
+ export const DRY_RUN_ANNOTATION = 'kit/dry-run';
53
+ /** Why a command opted out of `--dry-run`. */
54
+ export const DRY_RUN_RATIONALE_ANNOTATION = 'kit/dry-run-rationale';
55
+
56
+ const CONFIRM_TOKEN_FLAG = '--confirm-token';
57
+ const SUPERVISOR_COMMAND = 'serve';
58
+ const BUILTIN_NAMES = new Set(['help', 'completion', '__complete', '__completeNoDesc']);
59
+
60
+ type Annotations = Readonly<Record<string, string>>;
61
+
62
+ // ---------------------------------------------------------------------------
63
+ // Prompt source
64
+ // ---------------------------------------------------------------------------
65
+
66
+ /** The terminal an interactive prompt asks on. */
67
+ export interface Prompter {
68
+ /**
69
+ * Writes `question` and reads one line of answer, lowercased and
70
+ * trimmed; `null` on end of input.
71
+ */
72
+ ask(question: string): string | null;
73
+ }
74
+
75
+ /** Supplies the prompt terminal: `null` means nobody to ask. */
76
+ export type PromptSource = () => Prompter | null;
77
+
78
+ /** No terminal: every prompt is refused and an unset `--confirm` is `no`. */
79
+ export const noPrompt: PromptSource = () => null;
80
+
81
+ /** A scripted terminal answering from `answers`, one per question. */
82
+ export function scriptedPrompt(answers: readonly string[]): PromptSource {
83
+ const queue = [...answers];
84
+ const p: Prompter = {
85
+ ask() {
86
+ const a = queue.shift();
87
+ return a === undefined ? null : a.trim().toLowerCase();
88
+ },
89
+ };
90
+ return () => p;
91
+ }
92
+
93
+ let ttyPrompter: Prompter | null | undefined;
94
+
95
+ /**
96
+ * The process's controlling terminal (`/dev/tty`), opened once; none
97
+ * where there is no such terminal. The default. Both halves go to the
98
+ * terminal, never to stdin or stderr: reading stdin would consume the
99
+ * command's payload, and writing a redirected stderr would put the
100
+ * question where the operator cannot see it.
101
+ */
102
+ export const controllingTTY: PromptSource = () => {
103
+ if (ttyPrompter !== undefined) return ttyPrompter;
104
+ try {
105
+ const fd = fs.openSync('/dev/tty', 'r+');
106
+ ttyPrompter = {
107
+ ask(question) {
108
+ fs.writeSync(fd, question);
109
+ const buf = Buffer.alloc(1);
110
+ let line = '';
111
+ for (;;) {
112
+ let n = 0;
113
+ try {
114
+ n = fs.readSync(fd, buf, 0, 1, null);
115
+ } catch {
116
+ n = 0;
117
+ }
118
+ if (n === 0) return line === '' ? null : line.trim().toLowerCase();
119
+ const ch = buf.toString('utf8');
120
+ if (ch === '\n') return line.trim().toLowerCase();
121
+ line += ch;
122
+ }
123
+ },
124
+ };
125
+ } catch {
126
+ ttyPrompter = null;
127
+ }
128
+ return ttyPrompter;
129
+ };
130
+
131
+ // ---------------------------------------------------------------------------
132
+ // Confirm mode
133
+ // ---------------------------------------------------------------------------
134
+
135
+ export type ConfirmMode = 'auto' | 'yes' | 'no' | 'prompt';
136
+
137
+ /**
138
+ * Parses `--confirm`: empty or unknown defaults to `prompt` when there is
139
+ * a terminal to ask on and `no` otherwise. Interactivity is the
140
+ * terminal's availability, not isatty on stdin.
141
+ */
142
+ export function resolveConfirmMode(src: PromptSource, raw: string): ConfirmMode {
143
+ const v = raw.trim().toLowerCase();
144
+ if (v === 'yes' || v === 'no' || v === 'auto' || v === 'prompt') return v;
145
+ return src() !== null ? 'prompt' : 'no';
146
+ }
147
+
148
+ /**
149
+ * The token a typed-confirmation command demands: the first 12 hex
150
+ * characters of the sha256 of its full command path.
151
+ */
152
+ export function destructiveToken(commandPath: string): string {
153
+ return createHash('sha256').update(commandPath).digest('hex').slice(0, 12);
154
+ }
155
+
156
+ function requiresToken(ann: Annotations): boolean {
157
+ const v = ann[DESTRUCTIVE_TOKEN_ANNOTATION];
158
+ return v === 'required' || v === 'true';
159
+ }
160
+
161
+ // ---------------------------------------------------------------------------
162
+ // Dry-run policy
163
+ // ---------------------------------------------------------------------------
164
+
165
+ /** What `--dry-run` does on a leaf, by its annotations. */
166
+ export type DryRunPolicy =
167
+ | 'allow'
168
+ | 'noop'
169
+ | 'reject-interactive'
170
+ | 'reject-opt-out'
171
+ | 'reject-untagged'
172
+ | 'reject-malformed';
173
+
174
+ /**
175
+ * The dry-run table: opted-out refuses; legacy `supported` allows; write
176
+ * and destructive tiers allow; read is a silent no-op; interactive
177
+ * refuses; malformed values refuse. An unannotated command with a
178
+ * destructive name is the inferred destructive tier, so it previews like a
179
+ * declared one; any other untagged command refuses.
180
+ */
181
+ export function resolveDryRunPolicy(name: string, ann: Annotations): DryRunPolicy {
182
+ switch (ann[DRY_RUN_ANNOTATION]) {
183
+ case 'opted-out':
184
+ return 'reject-opt-out';
185
+ case 'supported':
186
+ return 'allow';
187
+ }
188
+ const s = ann[SIDE_EFFECT_ANNOTATION];
189
+ if (s === undefined || s === '') {
190
+ return isDestructiveName(name) ? 'allow' : 'reject-untagged';
191
+ }
192
+ if (isWriteLike(s) || isDestructiveLike(s)) return 'allow';
193
+ if (s === 'read') return 'noop';
194
+ if (s === 'interactive') return 'reject-interactive';
195
+ return 'reject-malformed';
196
+ }
197
+
198
+ function dryRunRefusal(path: string, ann: Annotations, p: DryRunPolicy): CliError | null {
199
+ let msg: string;
200
+ let fix: string;
201
+ switch (p) {
202
+ case 'reject-interactive':
203
+ msg =
204
+ `${JSON.stringify(path)} does not accept --dry-run: interactive ` +
205
+ 'sessions have no batch boundary to scope the preview';
206
+ fix = 'run without --dry-run';
207
+ break;
208
+ case 'reject-opt-out':
209
+ msg =
210
+ `${JSON.stringify(path)} does not support --dry-run: the command ` +
211
+ 'explicitly opted out via cli.OptOutDryRun';
212
+ if (ann[DRY_RUN_RATIONALE_ANNOTATION]) msg += ` (${ann[DRY_RUN_RATIONALE_ANNOTATION]})`;
213
+ fix = "run without --dry-run; see the command's documentation for the rationale";
214
+ break;
215
+ case 'reject-untagged':
216
+ msg =
217
+ `${JSON.stringify(path)} cannot apply --dry-run: the command is ` +
218
+ 'missing the required kit/side-effect tag';
219
+ fix = 'adopter must declare the tier with the kit/side-effect annotation';
220
+ break;
221
+ case 'reject-malformed':
222
+ msg =
223
+ `${JSON.stringify(path)} cannot apply --dry-run: the command has a ` +
224
+ `malformed kit/side-effect tag ${JSON.stringify(ann[SIDE_EFFECT_ANNOTATION] ?? '')} ` +
225
+ 'that names no tier';
226
+ fix = 'adopter must declare one of the kit side-effect tiers';
227
+ break;
228
+ default:
229
+ return null;
230
+ }
231
+ return { ...usageError(msg), suggested_fix: fix };
232
+ }
233
+
234
+ // ---------------------------------------------------------------------------
235
+ // Installation
236
+ // ---------------------------------------------------------------------------
237
+
238
+ /** Options {@link installDelegation} takes; `createCLI` forwards its own. */
239
+ export interface DelegationOptions {
240
+ /**
241
+ * Resolves a named `--policy`. Undefined wires none: only the reserved
242
+ * `kit-default` resolves, and any other name is a usage error.
243
+ */
244
+ policy?: PolicyLoader;
245
+ /** The terminal prompts use; defaults to the controlling terminal. */
246
+ promptSource?: PromptSource;
247
+ /** Drop `--dry-run` (it is then never applied). */
248
+ disableDryRun?: boolean;
249
+ }
250
+
251
+ interface Run {
252
+ engine: Engine;
253
+ dryRun: boolean;
254
+ tier: string | undefined;
255
+ }
256
+
257
+ interface State {
258
+ opts: DelegationOptions;
259
+ /** Gate flags read from before a shadowing command, for this parse. */
260
+ shadow: Map<string, string | boolean>;
261
+ runs: WeakMap<Command, Run>;
262
+ }
263
+
264
+ const states = new WeakMap<Command, State>();
265
+
266
+ const GATE_FLAGS: ReadonlyArray<{ long: string; value: boolean }> = [
267
+ { long: '--confirm', value: true },
268
+ { long: '--max-ops', value: true },
269
+ { long: '--policy', value: true },
270
+ { long: '--dry-run', value: false },
271
+ ];
272
+
273
+ function annotationsOf(cmd: Command): Annotations {
274
+ return (cmd as { annotations?: Record<string, string> }).annotations ?? {};
275
+ }
276
+
277
+ function isRunnable(cmd: Command): boolean {
278
+ return (cmd as unknown as { _actionHandler?: unknown })._actionHandler != null;
279
+ }
280
+
281
+ function isBuiltin(cmd: Command): boolean {
282
+ return BUILTIN_NAMES.has(cmd.name()) || cmd.parent?.name() === 'completion';
283
+ }
284
+
285
+ function camel(long: string): string {
286
+ return long.replace(/^--/, '').replace(/-([a-z])/g, (_, c: string) => c.toUpperCase());
287
+ }
288
+
289
+ /** `tool a b`: the root name and the command path. */
290
+ function commandPath(cmd: Command): string {
291
+ const names: string[] = [];
292
+ for (let c: Command | null = cmd; c; c = c.parent) names.unshift(c.name());
293
+ return names.join(' ');
294
+ }
295
+
296
+ /** `a b`: the path below the root, which policy globs match. */
297
+ function verbOf(cmd: Command): string {
298
+ const names: string[] = [];
299
+ for (let c: Command | null = cmd; c?.parent; c = c.parent) names.unshift(c.name());
300
+ return names.join(' ');
301
+ }
302
+
303
+ function rootOf(cmd: Command): Command {
304
+ let c = cmd;
305
+ while (c.parent) c = c.parent;
306
+ return c;
307
+ }
308
+
309
+ function declares(cmd: Command, long: string): boolean {
310
+ return cmd.options.some((o) => o.long === long);
311
+ }
312
+
313
+ /**
314
+ * Installs the delegation gates on `program`: the root flags `--dry-run`,
315
+ * `--confirm`, `--max-ops` and `--policy` (hidden, as in Go), the
316
+ * pre-action gate and the post-action ops accounting, and the parse
317
+ * wrappers that register `--confirm-token` on `kit/destructive-token`
318
+ * leaves and keep a leaf-local flag of a gate flag's name from being read
319
+ * as the gate.
320
+ */
321
+ export function installDelegation(program: Command, opts: DelegationOptions = {}): void {
322
+ if (states.has(program)) return;
323
+ const st: State = { opts, shadow: new Map(), runs: new WeakMap() };
324
+ states.set(program, st);
325
+
326
+ const hidden = (o: Option): Option => o.hideHelp();
327
+ if (!opts.disableDryRun) {
328
+ program.addOption(
329
+ hidden(new Option('--dry-run', 'Preview side effects without applying them (must be supported by the command).')),
330
+ );
331
+ }
332
+ program.addOption(
333
+ hidden(
334
+ new Option(
335
+ '--confirm <mode>',
336
+ 'Confirmation policy for destructive commands (auto|yes|no|prompt). Default: prompt on a TTY, no otherwise.',
337
+ ),
338
+ ),
339
+ );
340
+ program.addOption(
341
+ hidden(
342
+ new Option('--max-ops <n>', 'Cap mutating operations per invocation. 0 = unlimited.').argParser(
343
+ (v: string): number => {
344
+ if (!/^[-+]?\d+$/.test(v)) {
345
+ program.error(`error: option '--max-ops <n>' argument '${v}' is invalid. expected an integer`, {
346
+ exitCode: EXIT_USAGE,
347
+ code: 'commander.invalidArgument',
348
+ });
349
+ }
350
+ return Number.parseInt(v, 10);
351
+ },
352
+ ),
353
+ ),
354
+ );
355
+ program.addOption(
356
+ hidden(
357
+ new Option(
358
+ '--policy <name>',
359
+ 'Named delegation policy (loaded from $XDG_CONFIG_HOME/<tool>/policies/<name>.yaml).',
360
+ ),
361
+ ),
362
+ );
363
+
364
+ program.hook('preAction', (_this, action) => {
365
+ if (isBuiltin(action)) return;
366
+ gate(program, st, action);
367
+ });
368
+ program.hook('postAction', (_this, action) => {
369
+ const run = st.runs.get(action);
370
+ if (!run || run.dryRun) return;
371
+ if (run.tier === undefined || !(isWriteLike(run.tier) || isDestructiveLike(run.tier))) return;
372
+ try {
373
+ run.engine.recordOp();
374
+ } catch (e) {
375
+ if (e instanceof MaxOpsExceededError) {
376
+ refuse(program, rateLimitedError(`max-ops budget exceeded after running ${commandPath(action)}`));
377
+ }
378
+ throw e;
379
+ }
380
+ });
381
+
382
+ wrapParse(program, st);
383
+ }
384
+
385
+ /** True when kit applied `--dry-run` to the running leaf (it previews). */
386
+ export function dryRunApplied(cmd: Command): boolean {
387
+ const st = states.get(rootOf(cmd));
388
+ return st?.runs.get(cmd)?.dryRun === true;
389
+ }
390
+
391
+ /**
392
+ * True when the command runs as a dry run: kit applied `--dry-run`, or the
393
+ * flag was given (a read command accepts it and still runs). Handlers call
394
+ * this and build a {@link Plan} instead of acting.
395
+ */
396
+ export function isDryRun(cmd: Command): boolean {
397
+ if (dryRunApplied(cmd)) return true;
398
+ const root = rootOf(cmd);
399
+ const st = states.get(root);
400
+ return st?.shadow.get('--dry-run') === true || root.getOptionValue('dryRun') === true;
401
+ }
402
+
403
+ // ---------------------------------------------------------------------------
404
+ // Flag reads
405
+ // ---------------------------------------------------------------------------
406
+
407
+ /** The root's value of gate flag `long`, honoring flags read before a shadowing command. */
408
+ function rootFlag(program: Command, st: State, long: string): unknown {
409
+ return st.shadow.has(long) ? st.shadow.get(long) : program.getOptionValue(camel(long));
410
+ }
411
+
412
+ /**
413
+ * A persistent flag's string value visible to `cmd`: the nearest command
414
+ * declaring it wins, as Go's flagValue walks up the parent chain.
415
+ */
416
+ function flagValue(program: Command, st: State, cmd: Command, long: string): string {
417
+ for (let c: Command | null = cmd; c; c = c.parent) {
418
+ if (c === program) return stringOf(rootFlag(program, st, long));
419
+ if (declares(c, long)) return stringOf(c.getOptionValue(camel(long)));
420
+ }
421
+ return '';
422
+ }
423
+
424
+ function stringOf(v: unknown): string {
425
+ return v === undefined || v === null ? '' : String(v);
426
+ }
427
+
428
+ function flagInt(program: Command, st: State, cmd: Command, long: string): number {
429
+ const m = /^[-+]?\d+/.exec(flagValue(program, st, cmd, long));
430
+ return m ? Number.parseInt(m[0], 10) : 0;
431
+ }
432
+
433
+ // ---------------------------------------------------------------------------
434
+ // The gate
435
+ // ---------------------------------------------------------------------------
436
+
437
+ function buildEngine(st: State, name: string, maxOps: number): Engine {
438
+ let policy: Policy;
439
+ if (name === KIT_DEFAULT_NAME) {
440
+ policy = kitDefault();
441
+ } else if (name !== '') {
442
+ if (!st.opts.policy) {
443
+ throw usageError('--policy is set but no policy loader is wired (createCLI policy option)');
444
+ }
445
+ try {
446
+ policy = st.opts.policy(name);
447
+ } catch (e) {
448
+ // A policy that cannot be read or parsed is a usage failure, not an
449
+ // authorization refusal: the gate never ran.
450
+ throw usageError(`policy ${JSON.stringify(name)}: ${(e as Error).message}`);
451
+ }
452
+ } else {
453
+ policy = emptyPolicy();
454
+ }
455
+ return new Engine(policy, maxOps);
456
+ }
457
+
458
+ function startsServices(program: Command, cmd: Command): boolean {
459
+ return cmd.parent === program && cmd.name() === SUPERVISOR_COMMAND;
460
+ }
461
+
462
+ function gate(program: Command, st: State, cmd: Command): void {
463
+ const ann = annotationsOf(cmd);
464
+ const tier = gateSideEffect(cmd.name(), ann);
465
+ const path = commandPath(cmd);
466
+
467
+ try {
468
+ // Fail closed, as Go's Root.Validate does: a declared tier outside the
469
+ // closed set would match no class and run unconfirmed.
470
+ const declared = ann[SIDE_EFFECT_ANNOTATION];
471
+ if (declared !== undefined && declared !== '' && !isValidSideEffect(declared)) {
472
+ throw {
473
+ ...usageError(
474
+ `${JSON.stringify(path)} has a malformed kit/side-effect tag ${JSON.stringify(declared)} that names no tier`,
475
+ ),
476
+ suggested_fix: 'declare one of the kit side-effect tiers',
477
+ };
478
+ }
479
+
480
+ let dryRun = false;
481
+ if (!st.opts.disableDryRun && rootFlag(program, st, '--dry-run') === true) {
482
+ const p = resolveDryRunPolicy(cmd.name(), ann);
483
+ const refusal = dryRunRefusal(path, ann, p);
484
+ if (refusal) throw refusal;
485
+ dryRun = p === 'allow';
486
+ }
487
+
488
+ // --policy is read from the root only: a command's own --policy is
489
+ // not a delegation policy name.
490
+ const policyName = stringOf(rootFlag(program, st, '--policy'));
491
+ const engine = buildEngine(st, policyName, flagInt(program, st, cmd, '--max-ops'));
492
+ st.runs.set(cmd, { engine, dryRun, tier });
493
+
494
+ // Policy first: a refusal here is final and --confirm=yes does not lift it.
495
+ let policyConfirm = false;
496
+ if (!startsServices(program, cmd)) {
497
+ const v = engine.authorize({ verb: verbOf(cmd), sideEffect: tier });
498
+ if (!v.allowed) throw unauthorizedError(v.reason);
499
+ policyConfirm = v.requireConfirm;
500
+ }
501
+
502
+ // An inferred destructive leaf never promised to honor --dry-run, so its
503
+ // handler may really mutate: kit renders the preview itself and never
504
+ // invokes the handler. Authorized above, so a policy refusal still wins.
505
+ if (dryRun && inferredDestructive(cmd.name(), ann) && ann[DRY_RUN_ANNOTATION] === undefined) {
506
+ previewInferred(program, cmd, path);
507
+ }
508
+
509
+ // Skipped only for a dry run kit applied: the bare flag is not enough,
510
+ // since on a leaf that does not honor it the command would act unconfirmed.
511
+ if (!dryRun && ((tier !== undefined && isDestructiveLike(tier)) || policyConfirm)) {
512
+ gateConfirm(program, st, cmd, tier ?? '', path, ann);
513
+ }
514
+ } catch (e) {
515
+ if (isEnvelope(e)) refuse(program, e);
516
+ throw e;
517
+ }
518
+ }
519
+
520
+ function previewInferred(program: Command, cmd: Command, path: string): never {
521
+ const chunks: string[] = [];
522
+ renderPlan(
523
+ { write: (c: string) => chunks.push(c) },
524
+ activeFormat(program),
525
+ {
526
+ command: path,
527
+ effects: [{ kind: cmd.name(), target: path, reversible: false, detail: 'inferred destructive-shared; a real run requires --confirm' }],
528
+ warnings: ['kit/side-effect is not declared: the handler was not invoked'],
529
+ },
530
+ path,
531
+ );
532
+ program.configureOutput().writeOut?.(chunks.join(''));
533
+ return (program as unknown as { _exit(code: number, name: string, msg: string): never })._exit(
534
+ 0,
535
+ 'kit.dryRunPreview',
536
+ 'dry-run preview',
537
+ );
538
+ }
539
+
540
+ function isEnvelope(e: unknown): e is CliError {
541
+ return typeof e === 'object' && e !== null && 'code' in e && 'exit_code' in e;
542
+ }
543
+
544
+ function gateConfirm(
545
+ program: Command,
546
+ st: State,
547
+ cmd: Command,
548
+ tier: string,
549
+ path: string,
550
+ ann: Annotations,
551
+ ): void {
552
+ const src = st.opts.promptSource ?? controllingTTY;
553
+ const mode = resolveConfirmMode(src, flagValue(program, st, cmd, '--confirm'));
554
+
555
+ // Typed-token destructives never let --confirm=yes alone proceed.
556
+ if (requiresToken(ann)) {
557
+ const expected = destructiveToken(path);
558
+ const got = stringOf(cmd.getOptionValue('confirmToken'));
559
+ if (got === '') {
560
+ const refusal = unauthorizedError(`destructive command ${path} requires ${CONFIRM_TOKEN_FLAG}=${expected}`);
561
+ if (isMachineFormat(program)) {
562
+ // The preview would leave stderr unparseable; the envelope carries
563
+ // the instruction instead.
564
+ refusal.suggested_fix = `re-run with ${CONFIRM_TOKEN_FLAG}=${expected} to proceed`;
565
+ } else {
566
+ writeErr(
567
+ program,
568
+ 'This is a destructive operation requiring typed confirmation.\n' +
569
+ `Token: ${expected}\nRe-run with ${CONFIRM_TOKEN_FLAG}=${expected} to proceed.\n`,
570
+ );
571
+ }
572
+ throw refusal;
573
+ }
574
+ if (got !== expected) {
575
+ throw unauthorizedError(`${CONFIRM_TOKEN_FLAG} mismatch for ${path}; expected ${expected}`);
576
+ }
577
+ return;
578
+ }
579
+
580
+ switch (mode) {
581
+ case 'yes':
582
+ case 'auto':
583
+ return;
584
+ case 'no':
585
+ // Transient: the caller clears it by re-invoking with --confirm=yes.
586
+ throw withTransience(
587
+ unauthorizedError(`destructive command ${path} refused: --confirm=no (or non-TTY default)`),
588
+ TRANSIENCE_TRANSIENT,
589
+ );
590
+ case 'prompt': {
591
+ const answer = src()?.ask(`This is a ${tier} operation (${path}). Continue? [y/N] `) ?? null;
592
+ if (answer === 'y' || answer === 'yes') return;
593
+ throw withTransience(
594
+ unauthorizedError(`aborted by user at confirm prompt for ${path}`),
595
+ TRANSIENCE_TRANSIENT,
596
+ );
597
+ }
598
+ }
599
+ }
600
+
601
+ // ---------------------------------------------------------------------------
602
+ // Refusal output
603
+ // ---------------------------------------------------------------------------
604
+
605
+ function activeFormat(program: Command): string {
606
+ return stringOf(program.getOptionValue('format'));
607
+ }
608
+
609
+ function isMachineFormat(program: Command): boolean {
610
+ const f = activeFormat(program);
611
+ return f === 'json' || f === 'yaml';
612
+ }
613
+
614
+ function writeErr(program: Command, s: string): void {
615
+ program.configureOutput().writeErr?.(s);
616
+ }
617
+
618
+ /**
619
+ * Renders `e` once on stderr in the active `--format` and exits with its
620
+ * code, through commander's exit path so `exitOverride` still applies.
621
+ */
622
+ function refuse(program: Command, e: CliError): never {
623
+ const chunks: string[] = [];
624
+ renderError({ write: (c: string) => chunks.push(c) }, activeFormat(program), e);
625
+ writeErr(program, chunks.join(''));
626
+ return (program as unknown as { _exit(code: number, name: string, msg: string): never })._exit(
627
+ e.exit_code,
628
+ 'kit.delegation',
629
+ e.message,
630
+ );
631
+ }
632
+
633
+ // ---------------------------------------------------------------------------
634
+ // Parse wrappers
635
+ // ---------------------------------------------------------------------------
636
+
637
+ function walkAll(cmd: Command, visit: (c: Command) => void): void {
638
+ visit(cmd);
639
+ for (const c of cmd.commands as Command[]) walkAll(c, visit);
640
+ }
641
+
642
+ /**
643
+ * Registers `--confirm-token` on every runnable leaf opting in via the
644
+ * `kit/destructive-token` annotation. Idempotent.
645
+ */
646
+ export function installConfirmTokenFlag(program: Command): void {
647
+ walkAll(program, (c) => {
648
+ if (c === program || c.commands.length > 0 || !isRunnable(c) || isBuiltin(c)) return;
649
+ if (!requiresToken(annotationsOf(c)) || declares(c, CONFIRM_TOKEN_FLAG)) return;
650
+ c.option(
651
+ `${CONFIRM_TOKEN_FLAG} <token>`,
652
+ "Typed confirmation token (sha) printed by the command's prompt. Required for kit/destructive-token commands.",
653
+ );
654
+ });
655
+ }
656
+
657
+ type ParseFrom = 'node' | 'electron' | 'user';
658
+
659
+ interface Scan {
660
+ user: string[];
661
+ /** Gate flags whose root option is withdrawn for this parse. */
662
+ shadowed: string[];
663
+ }
664
+
665
+ /** The option `tok` names on `cur` or the root, for arity decisions. */
666
+ function findOption(program: Command, cur: Command, tok: string): Option | undefined {
667
+ const long = tok.startsWith('--') ? tok.split('=')[0]! : undefined;
668
+ const match = (o: Option): boolean => (long ? o.long === long : o.short === tok);
669
+ return cur.options.find(match) ?? program.options.find(match);
670
+ }
671
+
672
+ /**
673
+ * Reads the gate flags a command-line gives the root, leaving a flag a
674
+ * selected command declares itself to that command. Commander hands every
675
+ * known root option to the root wherever it appears; Go's persistent flags
676
+ * yield to a command's own flag of the same name, and so must this.
677
+ */
678
+ function scan(program: Command, st: State, user: string[]): Scan {
679
+ const conflicts = new Set<string>();
680
+ walkAll(program, (c) => {
681
+ if (c === program) return;
682
+ for (const g of GATE_FLAGS) if (declares(c, g.long)) conflicts.add(g.long);
683
+ });
684
+ if (conflicts.size === 0) return { user, shadowed: [] };
685
+
686
+ // Resolve the selected command path and each command's name position.
687
+ const nameAt: Array<{ cmd: Command; idx: number }> = [];
688
+ let cur = program;
689
+ let resolving = true;
690
+ for (let i = 0; i < user.length && resolving; i++) {
691
+ const tok = user[i]!;
692
+ if (tok === '--') break;
693
+ if (tok.startsWith('-') && tok !== '-') {
694
+ const opt = findOption(program, cur, tok);
695
+ if (opt && !tok.includes('=') && (opt.required || (opt.optional && !(user[i + 1] ?? '-').startsWith('-')))) i++;
696
+ continue;
697
+ }
698
+ const sub = (cur.commands as Command[]).find((c) => c.name() === tok || c.aliases().includes(tok));
699
+ if (sub) {
700
+ cur = sub;
701
+ nameAt.push({ cmd: sub, idx: i });
702
+ } else {
703
+ resolving = false;
704
+ }
705
+ }
706
+
707
+ // The shallowest selected command declaring a gate flag owns it from its name on.
708
+ const boundary = new Map<string, number>();
709
+ for (const g of GATE_FLAGS) {
710
+ const owner = nameAt.find((n) => declares(n.cmd, g.long));
711
+ if (owner) boundary.set(g.long, owner.idx);
712
+ }
713
+ if (boundary.size === 0) return { user, shadowed: [] };
714
+
715
+ const out: string[] = [];
716
+ for (let i = 0; i < user.length; i++) {
717
+ const tok = user[i]!;
718
+ if (tok === '--') {
719
+ out.push(...user.slice(i));
720
+ break;
721
+ }
722
+ const g = tok.startsWith('--') ? GATE_FLAGS.find((f) => tok === f.long || tok.startsWith(`${f.long}=`)) : undefined;
723
+ const b = g ? boundary.get(g.long) : undefined;
724
+ if (g && b !== undefined && i < b) {
725
+ if (!g.value) {
726
+ st.shadow.set(g.long, true);
727
+ } else if (tok.includes('=')) {
728
+ st.shadow.set(g.long, tok.slice(tok.indexOf('=') + 1));
729
+ } else {
730
+ st.shadow.set(g.long, user[i + 1] ?? '');
731
+ i++;
732
+ }
733
+ continue;
734
+ }
735
+ out.push(tok);
736
+ // Skip the value of any other value-taking option so it is not mistaken for a flag.
737
+ if (tok.startsWith('-') && tok !== '-' && !tok.includes('=')) {
738
+ let c = program;
739
+ for (const n of nameAt) if (n.idx < i) c = n.cmd;
740
+ const opt = findOption(program, c, tok);
741
+ if (opt?.required && i + 1 < user.length) out.push(user[++i]!);
742
+ }
743
+ }
744
+ return { user: out, shadowed: [...boundary.keys()] };
745
+ }
746
+
747
+ function wrapParse(program: Command, st: State): void {
748
+ const origParse = program.parse.bind(program);
749
+ const origParseAsync = program.parseAsync.bind(program);
750
+
751
+ /** Runs `go` with the argv rewritten for shadowing, restoring root options after. */
752
+ const prepare = <R>(
753
+ argv: readonly string[] | undefined,
754
+ options: { from?: ParseFrom } | undefined,
755
+ go: (argv: readonly string[] | undefined, options: { from?: ParseFrom } | undefined) => R,
756
+ after: (r: R, restore: () => void) => R,
757
+ ): R => {
758
+ installConfirmTokenFlag(program);
759
+ st.shadow.clear();
760
+ let from: ParseFrom = options?.from ?? 'node';
761
+ let args = argv;
762
+ if (args === undefined) {
763
+ if (process.versions['electron']) from = options?.from ?? 'electron';
764
+ args = process.argv;
765
+ }
766
+ const skip = from === 'user' ? 0 : from === 'electron' && !(process as { defaultApp?: boolean }).defaultApp ? 1 : 2;
767
+ const sc = scan(program, st, args.slice(skip));
768
+ if (sc.shadowed.length === 0) return go(argv, options);
769
+
770
+ const removed: Option[] = [];
771
+ for (const long of sc.shadowed) {
772
+ const opts = program.options as Option[];
773
+ const i = opts.findIndex((o) => o.long === long);
774
+ if (i >= 0) removed.push(...opts.splice(i, 1));
775
+ }
776
+ const restore = (): void => {
777
+ (program.options as Option[]).push(...removed);
778
+ };
779
+ let r: R;
780
+ try {
781
+ r = go([...args.slice(0, skip), ...sc.user], { ...options, from });
782
+ } catch (e) {
783
+ restore();
784
+ throw e;
785
+ }
786
+ return after(r, restore);
787
+ };
788
+
789
+ program.parse = ((argv?: readonly string[], options?: { from?: ParseFrom }) =>
790
+ prepare(
791
+ argv,
792
+ options,
793
+ (a, o) => origParse(a as string[] | undefined, o as { from: ParseFrom } | undefined),
794
+ (r, restore) => {
795
+ restore();
796
+ return r;
797
+ },
798
+ )) as typeof program.parse;
799
+
800
+ program.parseAsync = ((argv?: readonly string[], options?: { from?: ParseFrom }) =>
801
+ prepare(
802
+ argv,
803
+ options,
804
+ (a, o) => origParseAsync(a as string[] | undefined, o as { from: ParseFrom } | undefined),
805
+ (r, restore) => r.finally(restore),
806
+ )) as typeof program.parseAsync;
807
+ }