@hop-top/kit 0.5.0-alpha.1 → 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.
- package/CHANGELOG.md +275 -0
- package/LICENSE +1 -1
- package/LICENSE-cobra.txt +174 -0
- package/NOTICE +15 -0
- package/README.md +55 -259
- package/dist/aim-DZHwwiIc.d.ts +139 -0
- package/dist/aim.d.ts +1 -116
- package/dist/aim.js +13 -414
- package/dist/alias-D9_qFlyP.d.ts +174 -0
- package/dist/alias.d.ts +2 -73
- package/dist/alias.js +27 -207
- package/dist/api-DAexsu2H.d.ts +77 -0
- package/dist/api.d.ts +1 -62
- package/dist/api.js +10 -164
- package/dist/auth-2-jfgiHn.d.ts +34 -0
- package/dist/auth.d.ts +1 -26
- package/dist/auth.js +6 -40
- package/dist/chunk-3FIKGFKI.js +54 -0
- package/dist/chunk-4FMALWYB.js +669 -0
- package/dist/chunk-4GPCWBBA.js +143 -0
- package/dist/chunk-4UE5TCMQ.js +104 -0
- package/dist/chunk-65VPWMPV.js +1134 -0
- package/dist/chunk-6HFAEZ52.js +29 -0
- package/dist/chunk-6SVOHNIC.js +17 -0
- package/dist/chunk-BDNNPRX6.js +41 -0
- package/dist/chunk-BRNEKPWX.js +37 -0
- package/dist/chunk-BXJ2J27B.js +219 -0
- package/dist/chunk-CSJWB6D3.js +151 -0
- package/dist/chunk-CXBZTONY.js +65 -0
- package/dist/chunk-EE4M2UOF.js +818 -0
- package/dist/chunk-GFRAYYRD.js +817 -0
- package/dist/chunk-IVQHLI56.js +1890 -0
- package/dist/chunk-IZ6Q4SE3.js +178 -0
- package/dist/chunk-JKMQSAJP.js +174 -0
- package/dist/chunk-K7E34Q3A.js +1445 -0
- package/dist/chunk-KVG7YCTS.js +115 -0
- package/dist/chunk-L23O2FFE.js +51 -0
- package/dist/chunk-MFVUENZR.js +1549 -0
- package/dist/chunk-ML7D5DWY.js +263 -0
- package/dist/chunk-MQXYDYRD.js +968 -0
- package/dist/chunk-POR5L2DG.js +247 -0
- package/dist/chunk-QJVSKKRQ.js +369 -0
- package/dist/chunk-QQQYCWSC.js +240 -0
- package/dist/chunk-R5U7XKVJ.js +16 -0
- package/dist/chunk-RYKLVOVK.js +309 -0
- package/dist/chunk-SNVGDYX7.js +187 -0
- package/dist/chunk-T6OZMPPV.js +68 -0
- package/dist/chunk-UKZIAQA7.js +26 -0
- package/dist/chunk-VGOA5Y7S.js +251 -0
- package/dist/chunk-VWGP4NVJ.js +513 -0
- package/dist/chunk-WBVO43HU.js +355 -0
- package/dist/chunk-WUOAQVOA.js +86 -0
- package/dist/chunk-XJTRY453.js +868 -0
- package/dist/chunk-YOBAUCVN.js +583 -0
- package/dist/cli-RSRk1M36.d.ts +707 -0
- package/dist/cli.d.ts +7 -309
- package/dist/cli.js +125 -945
- package/dist/completion-csVun6SP.d.ts +112 -0
- package/dist/completion-values-By-mnjNt.d.ts +142 -0
- package/dist/completion-values.d.ts +1 -0
- package/dist/completion-values.js +29 -0
- package/dist/completion.d.ts +3 -0
- package/dist/completion.js +34 -0
- package/dist/compliance-AxFf-uMy.d.ts +60 -0
- package/dist/compliance.d.ts +1 -0
- package/dist/compliance.js +17 -0
- package/dist/config-CaK60ByQ.d.ts +241 -0
- package/dist/config.d.ts +1 -97
- package/dist/config.js +8 -78
- package/dist/errcorrect-BcX1Ft0K.d.ts +44 -0
- package/dist/errcorrect.d.ts +1 -37
- package/dist/errcorrect.js +8 -68
- package/dist/error-Do8Qji43.d.ts +231 -0
- package/dist/id/index.d.ts +2 -83
- package/dist/id/index.js +14 -65
- package/dist/index-BKJZClJx.d.ts +1486 -0
- package/dist/index-C3Zw4wDJ.d.ts +359 -0
- package/dist/index-CGE5yLBj.d.ts +328 -0
- package/dist/index-VLDcI5NF.d.ts +95 -0
- package/dist/index.d.ts +37 -0
- package/dist/index.js +132 -0
- package/dist/llm-DYuR7_uX.d.ts +1069 -0
- package/dist/llm-anthropic-Cd_I2xXB.d.ts +67 -0
- package/dist/llm-anthropic.d.ts +2 -0
- package/dist/llm-anthropic.js +13 -0
- package/dist/llm-openai-DyFrucmV.d.ts +87 -0
- package/dist/llm-openai.d.ts +2 -0
- package/dist/llm-openai.js +19 -0
- package/dist/llm.d.ts +1 -188
- package/dist/llm.js +101 -356
- package/dist/log-CkaxMX3U.d.ts +115 -0
- package/dist/log.d.ts +2 -0
- package/dist/log.js +14 -0
- package/dist/mcp/index.d.ts +4 -0
- package/dist/mcp/index.js +185 -0
- package/dist/netpolicy-Brx5XZUB.d.ts +151 -0
- package/dist/netpolicy.d.ts +1 -0
- package/dist/netpolicy.js +25 -0
- package/dist/output-CjZWmL8s.d.ts +420 -0
- package/dist/output.d.ts +3 -213
- package/dist/output.js +135 -447
- package/dist/parity-CvMuYcVI.d.ts +61 -0
- package/dist/progress-CAzyxeWl.d.ts +38 -0
- package/dist/progress.d.ts +1 -30
- package/dist/progress.js +6 -55
- package/dist/provenance-SMFHm5gx.d.ts +30 -0
- package/dist/provenance.d.ts +1 -24
- package/dist/provenance.js +6 -31
- package/dist/routellm-B0nv59mH.d.ts +111 -0
- package/dist/routellm.d.ts +2 -64
- package/dist/routellm.js +13 -255
- package/dist/rpc-D31Lg0Kc.d.ts +32 -0
- package/dist/rpc.d.ts +2 -25
- package/dist/rpc.js +4 -98
- package/dist/safety-CUaYEjZc.d.ts +30 -0
- package/dist/safety.d.ts +1 -24
- package/dist/safety.js +6 -43
- package/dist/scope-BrhYB4ij.d.ts +141 -0
- package/dist/scope.d.ts +1 -121
- package/dist/scope.js +20 -377
- package/dist/serve-D8yWMrTc.d.ts +646 -0
- package/dist/serve.d.ts +3 -0
- package/dist/serve.js +75 -0
- package/dist/sqlstore.js +6 -39
- package/dist/stream-CrjeCp0M.d.ts +44 -0
- package/dist/stream.d.ts +1 -35
- package/dist/stream.js +8 -51
- package/dist/telemetry/index.d.ts +1 -315
- package/dist/telemetry/index.js +26 -599
- package/dist/toolspec-DcPwwoAZ.d.ts +368 -0
- package/dist/toolspec.d.ts +2 -0
- package/dist/toolspec.js +37 -0
- package/dist/tui/index.d.ts +6 -298
- package/dist/tui/index.js +17 -381
- package/dist/upgrade-C3RWGwRi.d.ts +125 -0
- package/dist/upgrade.d.ts +1 -95
- package/dist/upgrade.js +6 -114
- package/dist/xdg-DB7Shoib.d.ts +179 -0
- package/dist/xdg.d.ts +1 -169
- package/dist/xdg.js +14 -128
- package/package.json +192 -24
- package/src/README.md +15 -0
- package/src/alias.conformance.test.ts +250 -0
- package/src/alias.test.ts +206 -2
- package/src/alias.ts +196 -21
- package/src/cli.help-command.test.ts +105 -0
- package/src/cli.offline.test.ts +93 -0
- package/src/cli.parity.test.ts +192 -0
- package/src/cli.root.conformance.test.ts +166 -0
- package/src/cli.test.ts +95 -1
- package/src/cli.ts +234 -25
- package/src/completion-scripts.ts +16 -0
- package/src/completion-values.test.ts +76 -16
- package/src/completion-values.ts +170 -66
- package/src/completion.conformance.test.ts +298 -0
- package/src/completion.test.ts +268 -145
- package/src/completion.ts +772 -121
- package/src/compliance.test.ts +196 -2
- package/src/compliance.ts +440 -20
- package/src/config-merge.test.ts +425 -0
- package/src/config.test.ts +228 -1
- package/src/config.ts +429 -16
- package/src/delegation.test.ts +299 -0
- package/src/delegation.ts +807 -0
- package/src/gen/crud_pb.ts +7 -7
- package/src/id/README.md +38 -0
- package/src/id/contract.test.ts +1 -1
- package/src/id/index.test.ts +1 -1
- package/src/id/index.ts +3 -2
- package/src/index.test.ts +71 -0
- package/src/index.ts +46 -0
- package/src/llm-anthropic.conformance.test.ts +1135 -0
- package/src/llm-anthropic.test.ts +152 -0
- package/src/llm-anthropic.ts +940 -0
- package/src/llm-choice-hermetic.test.ts +335 -0
- package/src/llm-config.test.ts +232 -0
- package/src/llm-config.ts +106 -0
- package/src/llm-endpoint.ts +254 -0
- package/src/llm-error.ts +17 -0
- package/src/llm-errors.ts +152 -0
- package/src/llm-file.ts +126 -0
- package/src/llm-http.ts +317 -0
- package/src/llm-keys.ts +167 -0
- package/src/llm-media.conformance.test.ts +87 -0
- package/src/llm-media.test.ts +279 -0
- package/src/llm-media.ts +322 -0
- package/src/llm-openai.conformance.test.ts +407 -0
- package/src/llm-openai.test.ts +510 -0
- package/src/llm-openai.ts +708 -0
- package/src/llm-payload.ts +155 -0
- package/src/llm-quote.ts +46 -0
- package/src/llm-routellm.conformance.test.ts +44 -0
- package/src/llm-toolnames.conformance.test.ts +112 -0
- package/src/llm-toolnames.test.ts +132 -0
- package/src/llm-toolnames.ts +298 -0
- package/src/llm-uri.ts +99 -0
- package/src/llm.test.ts +43 -15
- package/src/llm.toolcall.test.ts +175 -0
- package/src/llm.ts +602 -190
- package/src/log.parity.test.ts +105 -0
- package/src/log.test.ts +270 -1
- package/src/log.ts +228 -49
- package/src/mcp/README.md +63 -0
- package/src/mcp/args-separator.test.ts +164 -0
- package/src/mcp/args.test.ts +223 -0
- package/src/mcp/args.ts +160 -0
- package/src/mcp/audit.test.ts +520 -0
- package/src/mcp/audit.ts +70 -0
- package/src/mcp/bridge.test.ts +250 -0
- package/src/mcp/bridge.ts +286 -0
- package/src/mcp/conformance.test.ts +357 -0
- package/src/mcp/dispatch.ts +359 -0
- package/src/mcp/identity.test.ts +166 -0
- package/src/mcp/identity.ts +72 -0
- package/src/mcp/index.ts +176 -0
- package/src/mcp/legacy-notify.test.ts +59 -0
- package/src/mcp/legacy.ts +367 -0
- package/src/mcp/mcp.test.ts +707 -0
- package/src/mcp/modern-confirm.test.ts +520 -0
- package/src/mcp/modern-confirm.ts +484 -0
- package/src/mcp/modern.ts +788 -0
- package/src/mcp/stdio.test.ts +313 -0
- package/src/mcp/stdio.ts +254 -0
- package/src/mcp/tasks.ts +82 -0
- package/src/mcp/testtree.ts +250 -0
- package/src/mcp/toolname.test.ts +147 -0
- package/src/mcp/types.ts +689 -0
- package/src/netpolicy.test.ts +280 -0
- package/src/netpolicy.ts +256 -0
- package/src/output/README.md +46 -0
- package/src/output/builtins.ts +5 -5
- package/src/output/dispatch.ts +10 -2
- package/src/output/error.ts +459 -0
- package/src/output/formatter.ts +29 -5
- package/src/output/formatters/README.md +50 -0
- package/src/output/formatters/csv.ts +48 -12
- package/src/output/formatters/json.ts +4 -25
- package/src/output/formatters/project.ts +34 -0
- package/src/output/formatters/table.ts +8 -6
- package/src/output/formatters/text.ts +7 -3
- package/src/output/formatters/yaml.ts +5 -22
- package/src/output/projection.test.ts +298 -0
- package/src/output/projection.ts +33 -59
- package/src/output/template.ts +11 -21
- package/src/output.surface.test.ts +41 -0
- package/src/output.ts +64 -3
- package/src/plan.ts +89 -0
- package/src/policy.ts +472 -0
- package/src/published-types.test.ts +133 -0
- package/src/routellm.test.ts +209 -28
- package/src/routellm.toolcall.test.ts +521 -0
- package/src/routellm.ts +213 -177
- package/src/router/README.md +44 -0
- package/src/router/server.test.ts +41 -0
- package/src/router/server.ts +11 -0
- package/src/safety.test.ts +19 -9
- package/src/scope-defaults.json +29 -29
- package/src/serve.test.ts +1257 -0
- package/src/serve.ts +1665 -0
- package/src/sideeffect.ts +105 -0
- package/src/telemetry/README.md +48 -0
- package/src/telemetry/client.test.ts +31 -0
- package/src/telemetry/client.ts +12 -6
- package/src/telemetry/offline.test.ts +64 -0
- package/src/toolspec-internal.ts +279 -0
- package/src/toolspec-manifest.test.ts +167 -0
- package/src/toolspec-manifest.ts +415 -0
- package/src/toolspec-spec-schemas.ts +12 -0
- package/src/toolspec-spec.test.ts +273 -0
- package/src/toolspec-spec.ts +458 -0
- package/src/toolspec.from-command.test.ts +350 -0
- package/src/toolspec.test.ts +2 -2
- package/src/toolspec.ts +222 -0
- package/src/triton/README.md +34 -0
- package/src/tui/README.md +42 -0
- package/src/tui/parity.test.ts +120 -31
- package/src/tui/parity.ts +58 -7
- package/src/upgrade.test.ts +291 -0
- package/src/upgrade.ts +116 -7
- package/src/wizard.test.ts +7 -7
- package/test/llm/conformance-helpers.ts +100 -0
- package/test/output/csv.test.ts +164 -0
- package/test/output/dispatch.test.ts +1 -2
- package/test/output/error.test.ts +277 -0
- package/test/output/smoke-capture.ts +2 -2
- package/test/output/smoke.test.ts +2 -2
- package/test/output/taxonomy-contract.test.ts +148 -0
- package/test/setup-env.ts +16 -0
- package/test/toolspec/fixture.ts +79 -0
- package/tsconfig.json +3 -1
- package/tsconfig.test.json +10 -0
- package/vitest.config.ts +9 -0
- package/src/tui/parity.json +0 -74
|
@@ -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
|
+
}
|