@mainwave/cli 0.11.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +203 -16
- package/dist/adapters/claude-code.js +3 -3
- package/dist/adapters/claude-desktop.js +35 -1
- package/dist/adapters/codex-cli.js +16 -16
- package/dist/adapters/cursor.js +7 -2
- package/dist/adapters/kiro.js +13 -8
- package/dist/commands.js +219 -0
- package/dist/core/apply.js +47 -8
- package/dist/core/auth-commands.js +2 -1
- package/dist/core/codecs/kiro-hooks-json.js +1 -1
- package/dist/core/codex-trust.js +178 -0
- package/dist/core/doctor.js +144 -12
- package/dist/core/entry-script.js +2 -3
- package/dist/core/format.js +0 -1
- package/dist/core/hook-copies.js +157 -0
- package/dist/core/install-hooks.js +198 -15
- package/dist/core/interview.js +36 -16
- package/dist/core/markers.js +209 -44
- package/dist/core/redaction.js +188 -0
- package/dist/core/skills.js +3 -11
- package/dist/core/status.js +21 -1
- package/dist/core/store.js +254 -4
- package/dist/core/wizard.js +91 -6
- package/dist/main.js +173 -163
- package/hooks/codex-turns.mjs +584 -0
- package/hooks/kiro-otlp.mjs +10 -1
- package/hooks/mainwave-hook.mjs +27 -3
- package/hooks/marker-core.mjs +66 -8
- package/hooks/matchers.json +98 -1
- package/hooks/redaction-data.mjs +209 -0
- package/hooks/redaction-json.mjs +215 -0
- package/hooks/redaction-pattern.mjs +503 -0
- package/hooks/redaction.d.mts +84 -0
- package/hooks/redaction.mjs +701 -0
- package/hooks/vocabulary.mjs +41 -2
- package/package.json +3 -1
- package/skills/mainwave-instrument/SKILL.md +24 -6
- package/skills/mainwave-instrument/reference/frameworks.md +4 -2
- package/skills/mainwave-instrument/reference/troubleshooting.md +4 -0
- package/skills/mainwave-instrument-node/SKILL.md +83 -38
- package/skills/mainwave-instrument-node/reference/api.md +16 -16
- package/skills/mainwave-instrument-node/reference/frameworks.md +42 -27
- package/skills/mainwave-instrument-node/reference/troubleshooting.md +11 -7
package/dist/commands.js
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import { flagBool, flagValue, hasFlag } from './core/flags.js';
|
|
2
|
+
const f = (spelling, hidden) => hidden ? { spelling, hidden } : { spelling };
|
|
3
|
+
const removed = (spelling) => ({ spelling, hidden: true, removed: true });
|
|
4
|
+
export const COMMANDS = [
|
|
5
|
+
{
|
|
6
|
+
name: 'login',
|
|
7
|
+
usage: '[--password] [--device] [--no-browser] [--api-url <u>] [--json]',
|
|
8
|
+
summary: [
|
|
9
|
+
'sign in to Mainwave: shows a code and opens the app to',
|
|
10
|
+
'approve it. --password uses email + password instead',
|
|
11
|
+
'(MAINWAVE_EMAIL / MAINWAVE_PASSWORD drive it',
|
|
12
|
+
'non-interactively); --device forces the browser flow',
|
|
13
|
+
'without a terminal (coding agents); --no-browser',
|
|
14
|
+
'prints the URL',
|
|
15
|
+
],
|
|
16
|
+
adapters: 'none',
|
|
17
|
+
flags: [
|
|
18
|
+
f('--password'),
|
|
19
|
+
f('--device'),
|
|
20
|
+
f('--no-browser'),
|
|
21
|
+
f('--api-url'),
|
|
22
|
+
f('--json'),
|
|
23
|
+
f('--email', true),
|
|
24
|
+
f('--device-timeout', true),
|
|
25
|
+
f('--force', true),
|
|
26
|
+
],
|
|
27
|
+
},
|
|
28
|
+
{
|
|
29
|
+
name: 'logout',
|
|
30
|
+
usage: '',
|
|
31
|
+
summary: ['forget the stored session'],
|
|
32
|
+
adapters: 'none',
|
|
33
|
+
flags: [f('--json', true)],
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
name: 'whoami',
|
|
37
|
+
usage: '[--json]',
|
|
38
|
+
summary: ['print the signed-in user, org, and endpoints'],
|
|
39
|
+
adapters: 'none',
|
|
40
|
+
flags: [f('--api-url', true), f('--json')],
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
name: 'setup',
|
|
44
|
+
usage: '[<adapter>...]',
|
|
45
|
+
summary: [
|
|
46
|
+
'run the interactive setup wizard; with no adapter,',
|
|
47
|
+
'every detected tool is configured and the rest are',
|
|
48
|
+
'offered, and with several, configure them all in',
|
|
49
|
+
'one pass. Always writes user-global config',
|
|
50
|
+
],
|
|
51
|
+
adapters: 'many',
|
|
52
|
+
details: [
|
|
53
|
+
'Setup flags (every prompt has one, so scripts and coding agents can drive it):',
|
|
54
|
+
' --api-key <k> --collector-url <u> --api-url <u>',
|
|
55
|
+
' --ucid <id|url> --use-case <name> pin every tool to one use case (by default none',
|
|
56
|
+
" is written: each tool's activity is attributed at ingest",
|
|
57
|
+
' from your identity). A pin survives later default runs;',
|
|
58
|
+
' --no-use-case removes it',
|
|
59
|
+
' --email <e> --new-key',
|
|
60
|
+
' --invite <token> redeem an account-less developer invite: no login, no key',
|
|
61
|
+
' to paste — the token brings its own key, collector, and',
|
|
62
|
+
' identity (mutually exclusive with --api-key/--ucid/--use-case)',
|
|
63
|
+
' --opt-in prompts,tool-details,tool-content,repository|all|none content capture',
|
|
64
|
+
' (default: all on — "--opt-in none" sends metadata only;',
|
|
65
|
+
' repository = repository names on Claude Code telemetry)',
|
|
66
|
+
' --no-markers skip the Mainwave hooks (installed by default): the ticket',
|
|
67
|
+
' & PR markers and, for Claude Code, the plan snapshot',
|
|
68
|
+
' --redaction-file <path> redact the spans the Mainwave hooks send with the rules in',
|
|
69
|
+
' this JSON file, the format the Mainwave SDKs read (flag only:',
|
|
70
|
+
' no prompt). Setup records the path, not a copy, so edits',
|
|
71
|
+
' apply at the next hook run; a file that goes missing or',
|
|
72
|
+
' invalid makes the hooks send nothing. Content a tool exports',
|
|
73
|
+
' through its own OpenTelemetry exporter is not covered:',
|
|
74
|
+
' use --opt-in none to stop sending it',
|
|
75
|
+
' --no-redaction remove the recorded rules file (a run with neither flag keeps it);',
|
|
76
|
+
' the hooks still strip credentials by default',
|
|
77
|
+
' --no-redact-secrets stop stripping credentials (API keys, tokens, private keys) from',
|
|
78
|
+
' the spans the hooks send; --redact-secrets restores the default',
|
|
79
|
+
' --yes --json --no-verify --verify-timeout <seconds>',
|
|
80
|
+
' --skills / --no-skills install the agent skills payload (default: ask, or on in scripts)',
|
|
81
|
+
' --skills-only install only the skills, touching no telemetry config',
|
|
82
|
+
" --remove take this CLI's config for the named tools back off this",
|
|
83
|
+
' machine (Kiro: its hooks file entries and kiro.env)',
|
|
84
|
+
],
|
|
85
|
+
flags: [
|
|
86
|
+
f('--api-key'),
|
|
87
|
+
f('--collector-url'),
|
|
88
|
+
f('--api-url'),
|
|
89
|
+
f('--ucid'),
|
|
90
|
+
f('--use-case'),
|
|
91
|
+
f('--no-use-case'),
|
|
92
|
+
f('--email'),
|
|
93
|
+
f('--new-key'),
|
|
94
|
+
f('--invite'),
|
|
95
|
+
f('--opt-in'),
|
|
96
|
+
f('--no-markers'),
|
|
97
|
+
f('--redaction-file'),
|
|
98
|
+
f('--no-redaction'),
|
|
99
|
+
f('--redact-secrets'),
|
|
100
|
+
f('--no-redact-secrets'),
|
|
101
|
+
f('--yes'),
|
|
102
|
+
f('--json'),
|
|
103
|
+
f('--no-verify'),
|
|
104
|
+
f('--verify-timeout'),
|
|
105
|
+
f('--skills'),
|
|
106
|
+
f('--no-skills'),
|
|
107
|
+
f('--skills-only'),
|
|
108
|
+
f('--remove'),
|
|
109
|
+
removed('--scope'),
|
|
110
|
+
],
|
|
111
|
+
},
|
|
112
|
+
{
|
|
113
|
+
name: 'verify',
|
|
114
|
+
usage: '[--ucid <id|url>] [--no-sample] [--timeout <s>] [--json]',
|
|
115
|
+
summary: [
|
|
116
|
+
'push a sample trace and wait for it to land, then',
|
|
117
|
+
'print where your activity appears',
|
|
118
|
+
],
|
|
119
|
+
adapters: 'none',
|
|
120
|
+
flags: [
|
|
121
|
+
f('--ucid'),
|
|
122
|
+
f('--no-sample'),
|
|
123
|
+
f('--timeout'),
|
|
124
|
+
f('--json'),
|
|
125
|
+
f('--api-url', true),
|
|
126
|
+
f('--collector-url', true),
|
|
127
|
+
f('--api-key', true),
|
|
128
|
+
],
|
|
129
|
+
},
|
|
130
|
+
{
|
|
131
|
+
name: 'status',
|
|
132
|
+
usage: '[<adapter>] [--json]',
|
|
133
|
+
summary: ['show current on-disk config for all (or one) adapter'],
|
|
134
|
+
adapters: 'optional',
|
|
135
|
+
flags: [f('--json')],
|
|
136
|
+
},
|
|
137
|
+
{
|
|
138
|
+
name: 'edit',
|
|
139
|
+
usage: '<adapter> [--local|--global]',
|
|
140
|
+
summary: [
|
|
141
|
+
'open a settings file in $EDITOR (interactive picker by default;',
|
|
142
|
+
'flag is required in non-TTY)',
|
|
143
|
+
],
|
|
144
|
+
adapters: 'one',
|
|
145
|
+
flags: [f('--local'), f('--global')],
|
|
146
|
+
},
|
|
147
|
+
{
|
|
148
|
+
name: 'doctor',
|
|
149
|
+
usage: '<adapter> [--validate] [--json]',
|
|
150
|
+
summary: ['show settings hierarchy and run health checks'],
|
|
151
|
+
adapters: 'one',
|
|
152
|
+
flags: [f('--validate'), f('--json')],
|
|
153
|
+
},
|
|
154
|
+
{
|
|
155
|
+
name: 'env',
|
|
156
|
+
usage: '<adapter>',
|
|
157
|
+
summary: [
|
|
158
|
+
'print export lines for shell-sourceable adapters',
|
|
159
|
+
'(usage: `eval "$(mainwave-cli env <adapter>)"`)',
|
|
160
|
+
],
|
|
161
|
+
adapters: 'one',
|
|
162
|
+
flags: [],
|
|
163
|
+
},
|
|
164
|
+
{
|
|
165
|
+
name: 'install-hooks',
|
|
166
|
+
usage: '[--quiet] [--host codex] [--redaction-packs <list>]',
|
|
167
|
+
summary: [
|
|
168
|
+
'install or refresh the Mainwave hook entry and the',
|
|
169
|
+
"latest release's hook scripts, with no prompts or",
|
|
170
|
+
"sign-in (run at session start by an org's managed",
|
|
171
|
+
"settings, and by setup's own session-start hook).",
|
|
172
|
+
"--host codex: refresh Codex's hooks file instead of Claude",
|
|
173
|
+
"Code's settings (run by the session-start hook in it)",
|
|
174
|
+
"--redaction-packs: the packs an org's managed settings",
|
|
175
|
+
'apply to every Mainwave hook; recorded only from them',
|
|
176
|
+
],
|
|
177
|
+
adapters: 'none',
|
|
178
|
+
flags: [f('--quiet'), f('--host'), f('--redaction-packs')],
|
|
179
|
+
},
|
|
180
|
+
];
|
|
181
|
+
export const isCommand = (name) => COMMANDS.some((c) => c.name === name);
|
|
182
|
+
export const commandFlags = (_command, parsed) => {
|
|
183
|
+
return {
|
|
184
|
+
value: (name) => flagValue(parsed, name),
|
|
185
|
+
bool: (name) => flagBool(parsed, name),
|
|
186
|
+
has: (name) => hasFlag(parsed, name),
|
|
187
|
+
};
|
|
188
|
+
};
|
|
189
|
+
const SUMMARY_COLUMN = 42;
|
|
190
|
+
export const usageBlock = () => COMMANDS.flatMap((c) => {
|
|
191
|
+
const head = ` mainwave-cli ${c.name}${c.usage === '' ? '' : ` ${c.usage}`}`;
|
|
192
|
+
const indent = ' '.repeat(SUMMARY_COLUMN);
|
|
193
|
+
const [first, ...rest] = c.summary;
|
|
194
|
+
const tail = rest.map((line) => `${indent}${line}`);
|
|
195
|
+
if (first === undefined)
|
|
196
|
+
return [head];
|
|
197
|
+
return head.length < SUMMARY_COLUMN - 1
|
|
198
|
+
? [`${head.padEnd(SUMMARY_COLUMN)}${first}`, ...tail]
|
|
199
|
+
: [head, `${indent}${first}`, ...tail];
|
|
200
|
+
}).join('\n');
|
|
201
|
+
export const detailsBlock = () => COMMANDS.flatMap((c) => c.details ?? []).join('\n');
|
|
202
|
+
export const helpSpellings = (c) => [
|
|
203
|
+
...new Set([c.usage, ...c.summary, ...(c.details ?? [])].join('\n').match(/(?<![\w-])--[a-z][a-z-]*/g) ??
|
|
204
|
+
[]),
|
|
205
|
+
];
|
|
206
|
+
export const commandsManifest = (adapterNames) => ({
|
|
207
|
+
commands: COMMANDS.map((c) => ({
|
|
208
|
+
name: c.name,
|
|
209
|
+
usage: c.usage,
|
|
210
|
+
summary: c.summary.join(' '),
|
|
211
|
+
adapters: c.adapters,
|
|
212
|
+
flags: c.flags.map((flag) => ({
|
|
213
|
+
spelling: flag.spelling,
|
|
214
|
+
hidden: flag.hidden === true,
|
|
215
|
+
removed: flag.removed === true,
|
|
216
|
+
})),
|
|
217
|
+
})),
|
|
218
|
+
adapters: [...adapterNames],
|
|
219
|
+
});
|
package/dist/core/apply.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
2
|
import { dirname, resolve } from 'node:path';
|
|
3
3
|
import { adapters } from '../adapters/index.js';
|
|
4
|
+
import { countTrust, readCodexTrust } from './codex-trust.js';
|
|
4
5
|
import { activeHierarchy, effectiveEnv } from './effective-settings.js';
|
|
5
6
|
import { color, renderDiff } from './format.js';
|
|
6
7
|
import { claudeHookShellMissing, GIT_BASH_FIX, GIT_BASH_MISSING_REASON } from './git-bash.js';
|
|
@@ -66,7 +67,10 @@ const decideTeamUcid = async (adapter, existing, stored) => {
|
|
|
66
67
|
}
|
|
67
68
|
return { status: 'kept', id: existing };
|
|
68
69
|
};
|
|
69
|
-
export const effectiveOptIns = (adapter, optIns, explicit) =>
|
|
70
|
+
export const effectiveOptIns = (adapter, optIns, explicit) => ({
|
|
71
|
+
...(explicit ? optIns : { ...optIns, ...adapter.defaultOptIns }),
|
|
72
|
+
...adapter.alwaysOnOptIns,
|
|
73
|
+
});
|
|
70
74
|
export const planAdapter = async (adapter, answers, context = {}) => {
|
|
71
75
|
const { primary, additional } = writeTargets(adapter);
|
|
72
76
|
const explicitUcid = adapter.carriesNoUcid ? undefined : answers.ucid;
|
|
@@ -94,7 +98,7 @@ export const planAdapter = async (adapter, answers, context = {}) => {
|
|
|
94
98
|
const primaryUpdate = await prepareUpdate({
|
|
95
99
|
path: primary,
|
|
96
100
|
newEnv: adapter.buildEnv(input),
|
|
97
|
-
managedKeys: adapter.managedEnvKeys,
|
|
101
|
+
managedKeys: [...adapter.managedEnvKeys, ...(adapter.retiredEnvKeys ?? [])],
|
|
98
102
|
codec: adapter.codec,
|
|
99
103
|
});
|
|
100
104
|
const markersOn = adapter.markers ? answers.markers : null;
|
|
@@ -260,12 +264,12 @@ export const renderPlan = (plan) => {
|
|
|
260
264
|
}
|
|
261
265
|
};
|
|
262
266
|
export const planHasChanges = (plans) => plans.some((p) => p.changed.length > 0);
|
|
263
|
-
const defaultHookDirs = () => ({
|
|
267
|
+
export const defaultHookDirs = () => ({
|
|
264
268
|
managedDir: managedHooksDir(),
|
|
265
269
|
flatDir: installedHooksDir(),
|
|
266
270
|
});
|
|
267
271
|
export const userHooksPath = (adapter) => adapter.markers?.hooksFile?.path ?? adapter.paths.global;
|
|
268
|
-
export const writePlan = async (plan, dirs = defaultHookDirs()) => {
|
|
272
|
+
export const writePlan = async (plan, dirs = defaultHookDirs(), holdFlat = false) => {
|
|
269
273
|
if (plan.stageHooks) {
|
|
270
274
|
const updated = await syncManagedHooks(await readPackagedMatchers(), packagedHooksDir(), dirs.managedDir, VERSION);
|
|
271
275
|
say('');
|
|
@@ -280,7 +284,7 @@ export const writePlan = async (plan, dirs = defaultHookDirs()) => {
|
|
|
280
284
|
}
|
|
281
285
|
}
|
|
282
286
|
const bundled = plan.adapter.bundledHookScripts ?? [];
|
|
283
|
-
if (bundled.length > 0) {
|
|
287
|
+
if (bundled.length > 0 && !holdFlat) {
|
|
284
288
|
const dest = await copyHookScripts(bundled, packagedHooksDir(), dirs.flatDir);
|
|
285
289
|
say('');
|
|
286
290
|
say(color.dim(`Hook scripts refreshed in ${dest}.`));
|
|
@@ -354,6 +358,29 @@ export const printMarkerCoexistenceNotes = async (adapter, targetPath, markersOn
|
|
|
354
358
|
}
|
|
355
359
|
}
|
|
356
360
|
};
|
|
361
|
+
const codexTrustNote = (reading, hooksPath) => {
|
|
362
|
+
const how = 'Start Codex and choose "Trust all" at the "Hooks need review" prompt, or open /hooks and trust each ' +
|
|
363
|
+
'Mainwave hook, the session-start hook included. Codex asks again whenever a Mainwave hook changes, such as ' +
|
|
364
|
+
'when a setup run adds a route or a release changes a command, so approve again after such a run; a run that ' +
|
|
365
|
+
"removes a Mainwave hook moves the hooks after it, so Codex may ask about other tools' hooks too. " +
|
|
366
|
+
'`codex exec` skips them unless it runs with --dangerously-bypass-hook-trust. ' +
|
|
367
|
+
'`mainwave-cli doctor` reports the hooks Codex skips.';
|
|
368
|
+
if (reading?.state === 'read') {
|
|
369
|
+
const n = countTrust(reading.hooks);
|
|
370
|
+
if (n.trusted === n.total)
|
|
371
|
+
return `Codex already trusts the Mainwave hooks in ${hooksPath}.`;
|
|
372
|
+
const why = [
|
|
373
|
+
n.untrusted > 0 ? `${n.untrusted} not yet approved` : '',
|
|
374
|
+
n.modified > 0 ? `${n.modified} changed since you approved them` : '',
|
|
375
|
+
n.disabled > 0 ? `${n.disabled} turned off in /hooks` : '',
|
|
376
|
+
].filter((p) => p !== '');
|
|
377
|
+
return `Codex skips ${n.total - n.trusted} of ${n.total} Mainwave hooks until you trust them (${why.join(', ')}). ${how}`;
|
|
378
|
+
}
|
|
379
|
+
if (reading?.state === 'unreadable') {
|
|
380
|
+
return `Codex skips a hook until you trust it, and setup can't tell which Mainwave hooks Codex trusts: ${reading.reason}. ${how}`;
|
|
381
|
+
}
|
|
382
|
+
return `Codex skips a hook until you trust it. ${how}`;
|
|
383
|
+
};
|
|
357
384
|
export const printPostSetup = (plan) => {
|
|
358
385
|
if (plan.hookShellMissing && plan.markersOn === true) {
|
|
359
386
|
say('');
|
|
@@ -368,9 +395,21 @@ export const printPostSetup = (plan) => {
|
|
|
368
395
|
}
|
|
369
396
|
if (plan.hookEvents.includes('SessionStart')) {
|
|
370
397
|
say('');
|
|
371
|
-
say(color.dim(
|
|
372
|
-
|
|
373
|
-
|
|
398
|
+
say(color.dim(plan.hookHost === 'codex'
|
|
399
|
+
? `${plan.adapter.displayName} also runs \`npx @mainwave/cli@latest install-hooks --host codex\` in the background ` +
|
|
400
|
+
'when a session starts, resumes or forks: it refreshes the hook scripts from the latest release and adds hooks ' +
|
|
401
|
+
'a later release brings to the events above, never changing one you approved.'
|
|
402
|
+
: `${plan.adapter.displayName} also runs \`npx @mainwave/cli@latest install-hooks\` in the background when a session ` +
|
|
403
|
+
'starts, resumes or forks: it refreshes the hook scripts from the latest release and keeps the hooks above ' +
|
|
404
|
+
'current, on the same events only — a new kind of hook waits for your next setup run.'));
|
|
405
|
+
}
|
|
406
|
+
if (plan.hookHost === 'codex' && plan.markersOn === true && !plan.hookShellMissing) {
|
|
407
|
+
const hooksFile = plan.adapter.markers?.hooksFile;
|
|
408
|
+
const reading = hooksFile === undefined
|
|
409
|
+
? undefined
|
|
410
|
+
: readCodexTrust(hooksFile.path, plan.adapter.paths.global);
|
|
411
|
+
say('');
|
|
412
|
+
say(color.dim(codexTrustNote(reading, hooksFile?.path)));
|
|
374
413
|
}
|
|
375
414
|
const snippet = plan.adapter.printPostSetupInstructions?.(plan.input);
|
|
376
415
|
if (snippet) {
|
|
@@ -5,7 +5,7 @@ import { color } from './format.js';
|
|
|
5
5
|
import { pinnedUseCase } from './pinned-use-case.js';
|
|
6
6
|
import { login, me, publicConfig, tokenExpiry } from './platform.js';
|
|
7
7
|
import { isInteractive } from './tty.js';
|
|
8
|
-
import { activeSession, clearSession, readCredentials, readSettings, resolveEndpoints, updateSettings, writeCredentials, } from './store.js';
|
|
8
|
+
import { activeSession, assertSettingsWritable, clearSession, readCredentials, readSettings, resolveEndpoints, updateSettings, writeCredentials, } from './store.js';
|
|
9
9
|
const usesPasswordFlow = (options) => {
|
|
10
10
|
if (options.usePassword === true)
|
|
11
11
|
return true;
|
|
@@ -61,6 +61,7 @@ export const runLogin = async (options = {}) => {
|
|
|
61
61
|
}
|
|
62
62
|
return 0;
|
|
63
63
|
}
|
|
64
|
+
await assertSettingsWritable();
|
|
64
65
|
const token = usesPasswordFlow(options)
|
|
65
66
|
? await passwordLogin(apiUrl, options)
|
|
66
67
|
: await deviceLogin(apiUrl, {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { commandOwnership } from '../markers.js';
|
|
2
2
|
export const KIRO_HOOK_TIMEOUT_SECONDS = 10;
|
|
3
|
-
|
|
3
|
+
const kiroHookName = (trigger) => `Mainwave: ${trigger}`;
|
|
4
4
|
const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
5
5
|
const isCommandEntry = (v) => isPlainObject(v) &&
|
|
6
6
|
typeof v.trigger === 'string' &&
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { commandOwnership } from './markers.js';
|
|
4
|
+
const EVENTS_WITHOUT_MATCHER = new Set([
|
|
5
|
+
'PreModelRequest',
|
|
6
|
+
'PostModelRequest',
|
|
7
|
+
'UserPromptSubmit',
|
|
8
|
+
'Stop',
|
|
9
|
+
'Interrupt',
|
|
10
|
+
]);
|
|
11
|
+
const eventLabel = (event) => event.replace(/(?<!^)([A-Z])/g, '_$1').toLowerCase();
|
|
12
|
+
const sortedJson = (value) => {
|
|
13
|
+
if (Array.isArray(value))
|
|
14
|
+
return `[${value.map(sortedJson).join(',')}]`;
|
|
15
|
+
if (value !== null && typeof value === 'object') {
|
|
16
|
+
const entries = Object.entries(value)
|
|
17
|
+
.filter(([, v]) => v !== undefined)
|
|
18
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
19
|
+
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${sortedJson(v)}`).join(',')}}`;
|
|
20
|
+
}
|
|
21
|
+
return JSON.stringify(value);
|
|
22
|
+
};
|
|
23
|
+
export const codexHookHash = (event, matcher, handler) => {
|
|
24
|
+
const sessionEnd = event === 'SessionEnd' || event === 'Interrupt';
|
|
25
|
+
const timeout = sessionEnd
|
|
26
|
+
? Math.min(Math.max(handler.timeout ?? 1, 1), 3)
|
|
27
|
+
: Math.max(handler.timeout ?? 600, 1);
|
|
28
|
+
const identity = {
|
|
29
|
+
event_name: eventLabel(event),
|
|
30
|
+
hooks: [
|
|
31
|
+
{
|
|
32
|
+
type: 'command',
|
|
33
|
+
command: handler.command,
|
|
34
|
+
timeout,
|
|
35
|
+
async: handler.async === true,
|
|
36
|
+
statusMessage: handler.statusMessage,
|
|
37
|
+
},
|
|
38
|
+
],
|
|
39
|
+
matcher: EVENTS_WITHOUT_MATCHER.has(event) ? undefined : matcher,
|
|
40
|
+
};
|
|
41
|
+
return `sha256:${createHash('sha256').update(sortedJson(identity)).digest('hex')}`;
|
|
42
|
+
};
|
|
43
|
+
const unescapeBasic = (s) => s.replace(/\\(u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8}|.)/g, (_m, c) => {
|
|
44
|
+
if (c[0] === 'u' || c[0] === 'U')
|
|
45
|
+
return String.fromCodePoint(parseInt(c.slice(1), 16));
|
|
46
|
+
return { n: '\n', t: '\t', r: '\r', b: '\b', f: '\f', '"': '"', '\\': '\\' }[c] ?? c;
|
|
47
|
+
});
|
|
48
|
+
const QUOTED_KEY = String.raw `(?:"((?:[^"\\]|\\.)*)"|'([^']*)')`;
|
|
49
|
+
const DOT = String.raw `\s*\.\s*`;
|
|
50
|
+
const quotedKey = (m, at) => m[at] !== undefined ? unescapeBasic(m[at]) : m[at + 1];
|
|
51
|
+
const tablePath = (line) => {
|
|
52
|
+
const header = new RegExp(String.raw `^\[\s*hooks(?:${DOT}state(?:${DOT}${QUOTED_KEY})?)?\s*\]\s*(?:#.*)?$`).exec(line);
|
|
53
|
+
if (header === null)
|
|
54
|
+
return undefined;
|
|
55
|
+
if (header[1] !== undefined || header[2] !== undefined) {
|
|
56
|
+
return ['hooks', 'state', quotedKey(header, 1)];
|
|
57
|
+
}
|
|
58
|
+
return /state\s*\]/.test(line) ? ['hooks', 'state'] : ['hooks'];
|
|
59
|
+
};
|
|
60
|
+
export const readHookStates = (toml) => {
|
|
61
|
+
const states = new Map();
|
|
62
|
+
const stateOf = (key) => {
|
|
63
|
+
const found = states.get(key);
|
|
64
|
+
if (found !== undefined)
|
|
65
|
+
return found;
|
|
66
|
+
const created = {};
|
|
67
|
+
states.set(key, created);
|
|
68
|
+
return created;
|
|
69
|
+
};
|
|
70
|
+
let path = [];
|
|
71
|
+
for (const raw of toml.split(/\r?\n/)) {
|
|
72
|
+
const line = raw.trim();
|
|
73
|
+
if (line.startsWith('[')) {
|
|
74
|
+
path = line.startsWith('[[') ? undefined : tablePath(line);
|
|
75
|
+
if (path?.length === 3)
|
|
76
|
+
stateOf(path[2]);
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
if (path === undefined || line === '' || line.startsWith('#'))
|
|
80
|
+
continue;
|
|
81
|
+
const lead = ['hooks', 'state'].slice(Math.min(path.length, 2));
|
|
82
|
+
const prefix = lead.map((part) => `${part}${DOT}`).join('');
|
|
83
|
+
const keyPart = path.length === 3 ? '' : `${QUOTED_KEY}${DOT}`;
|
|
84
|
+
const field = new RegExp(String.raw `^${prefix}${keyPart}(trusted_hash|enabled)\s*=\s*(.*)$`).exec(line);
|
|
85
|
+
if (field !== null) {
|
|
86
|
+
const key = path.length === 3 ? path[2] : quotedKey(field, 1);
|
|
87
|
+
const name = path.length === 3 ? field[1] : field[3];
|
|
88
|
+
const value = path.length === 3 ? field[2] : field[4];
|
|
89
|
+
const state = stateOf(key);
|
|
90
|
+
if (name === 'trusted_hash') {
|
|
91
|
+
const hash = /^"([^"]*)"/.exec(value);
|
|
92
|
+
if (hash !== null)
|
|
93
|
+
state.trustedHash = hash[1];
|
|
94
|
+
}
|
|
95
|
+
else {
|
|
96
|
+
const enabled = /^(true|false)\b/.exec(value);
|
|
97
|
+
if (enabled !== null)
|
|
98
|
+
state.enabled = enabled[1] === 'true';
|
|
99
|
+
}
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
const along = [...lead, QUOTED_KEY].slice(0, path.length === 3 ? 0 : undefined);
|
|
103
|
+
const inline = along.map((_, i) => along.slice(0, i + 1).join(DOT));
|
|
104
|
+
if (inline.some((lhs) => new RegExp(String.raw `^${lhs}\s*=\s*\{`).test(line))) {
|
|
105
|
+
return undefined;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return states;
|
|
109
|
+
};
|
|
110
|
+
const readText = (path) => {
|
|
111
|
+
try {
|
|
112
|
+
return readFileSync(path, 'utf8');
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
return undefined;
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
const isRecord = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
119
|
+
export const readCodexTrust = (hooksPath, configPath) => {
|
|
120
|
+
const body = readText(hooksPath);
|
|
121
|
+
let doc;
|
|
122
|
+
try {
|
|
123
|
+
doc = body === undefined ? undefined : JSON.parse(body);
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
return { state: 'no-hooks' };
|
|
127
|
+
}
|
|
128
|
+
if (!isRecord(doc) || !isRecord(doc.hooks))
|
|
129
|
+
return { state: 'no-hooks' };
|
|
130
|
+
const states = readHookStates(readText(configPath) ?? '');
|
|
131
|
+
if (states === undefined) {
|
|
132
|
+
return {
|
|
133
|
+
state: 'unreadable',
|
|
134
|
+
reason: `${configPath} records hook state in a form doctor does not read`,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
const hooks = [];
|
|
138
|
+
for (const [event, groups] of Object.entries(doc.hooks)) {
|
|
139
|
+
if (!Array.isArray(groups))
|
|
140
|
+
continue;
|
|
141
|
+
for (const [gi, group] of groups.entries()) {
|
|
142
|
+
if (!isRecord(group) || !Array.isArray(group.hooks))
|
|
143
|
+
continue;
|
|
144
|
+
for (const [hi, handler] of group.hooks.entries()) {
|
|
145
|
+
if (!isRecord(handler) || typeof handler.command !== 'string')
|
|
146
|
+
continue;
|
|
147
|
+
if (commandOwnership(handler.command) !== 'cli')
|
|
148
|
+
continue;
|
|
149
|
+
const key = `${hooksPath}:${eventLabel(event)}:${gi}:${hi}`;
|
|
150
|
+
const state = states.get(key);
|
|
151
|
+
const current = codexHookHash(event, typeof group.matcher === 'string' ? group.matcher : undefined, {
|
|
152
|
+
type: 'command',
|
|
153
|
+
command: handler.command,
|
|
154
|
+
...(typeof handler.timeout === 'number' ? { timeout: handler.timeout } : {}),
|
|
155
|
+
...(handler.async === true ? { async: true } : {}),
|
|
156
|
+
...(typeof handler.statusMessage === 'string'
|
|
157
|
+
? { statusMessage: handler.statusMessage }
|
|
158
|
+
: {}),
|
|
159
|
+
});
|
|
160
|
+
const trust = state?.trustedHash === undefined
|
|
161
|
+
? 'untrusted'
|
|
162
|
+
: state.trustedHash !== current
|
|
163
|
+
? 'modified'
|
|
164
|
+
: state.enabled === false
|
|
165
|
+
? 'disabled'
|
|
166
|
+
: 'trusted';
|
|
167
|
+
hooks.push({ key, event, trust });
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return hooks.length === 0 ? { state: 'no-hooks' } : { state: 'read', hooks };
|
|
172
|
+
};
|
|
173
|
+
export const countTrust = (hooks) => {
|
|
174
|
+
const counts = { trusted: 0, untrusted: 0, modified: 0, disabled: 0, total: hooks.length };
|
|
175
|
+
for (const h of hooks)
|
|
176
|
+
counts[h.trust]++;
|
|
177
|
+
return counts;
|
|
178
|
+
};
|