@mainwave/cli 0.13.0 → 0.14.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.
@@ -1,6 +1,6 @@
1
1
  import { spawnSync } from 'node:child_process';
2
2
  import { platform as osPlatform } from 'node:os';
3
- import { dirname, isAbsolute, join, resolve } from 'node:path';
3
+ import { dirname, isAbsolute } from 'node:path';
4
4
  import { envFileCodec } from './codecs/env-file.js';
5
5
  import { countTrust, readCodexTrust } from './codex-trust.js';
6
6
  import { activeHierarchy, computeEffective, effectiveFrom, flattenEffective, nativeIdentityReason, } from './effective-settings.js';
@@ -464,8 +464,8 @@ const renderAdditionalWrites = async (adapter) => {
464
464
  }
465
465
  }
466
466
  };
467
- const renderChecks = (issues) => {
468
- console.log(color.bold('Checks:'));
467
+ const renderChecks = (issues, title = 'Checks:') => {
468
+ console.log(color.bold(title));
469
469
  if (issues.length === 0) {
470
470
  console.log(color.green(' ✓ no issues detected'));
471
471
  return;
@@ -541,7 +541,15 @@ const markerLayers = async (adapter) => {
541
541
  ...(hooksFile.localPath
542
542
  ? [{ id: 'project', label: 'Project hooks file', path: hooksFile.localPath, kind: 'file' }]
543
543
  : []),
544
- { id: 'user', label: 'User hooks file', path: hooksFile.path, kind: 'file' },
544
+ {
545
+ id: 'user',
546
+ label: adapter.codexProfile === undefined
547
+ ? 'User hooks file'
548
+ : `Profile ${adapter.codexProfile} hooks file`,
549
+ path: hooksFile.path,
550
+ kind: 'file',
551
+ codec: hooksFile.codec,
552
+ },
545
553
  ];
546
554
  };
547
555
  const markerIssuesFor = async (adapter, effective, redaction) => adapter.markers
@@ -558,20 +566,7 @@ const codexTrustIssues = (adapter) => {
558
566
  const hooksFile = adapter.markers?.hooksFile;
559
567
  if (hooksFile === undefined || adapter.markers?.runtimeTool !== 'codex')
560
568
  return [];
561
- const codexHome = process.env.CODEX_HOME;
562
- if (codexHome !== undefined &&
563
- codexHome !== '' &&
564
- resolve(codexHome) !== dirname(resolve(hooksFile.path))) {
565
- return [
566
- {
567
- level: 'warn',
568
- message: `CODEX_HOME is set to ${codexHome}, so Codex reads its hooks from ${join(codexHome, 'hooks.json')}, ` +
569
- `not ${hooksFile.path}, where setup wrote the Mainwave hooks. None of them run, and trusting them in /hooks ` +
570
- "won't change that: setup doesn't follow CODEX_HOME yet.",
571
- },
572
- ];
573
- }
574
- const reading = readCodexTrust(hooksFile.path, adapter.paths.global);
569
+ const reading = readCodexTrust(hooksFile.path, adapter.trustFiles ?? [], hooksFile.path, hooksFile.codec);
575
570
  if (reading.state === 'no-hooks')
576
571
  return [];
577
572
  if (reading.state === 'unreadable') {
@@ -596,13 +591,21 @@ const codexTrustIssues = (adapter) => {
596
591
  n.modified > 0 ? `${n.modified} whose approval doesn't match the hook as it is now` : '',
597
592
  n.disabled > 0 ? `${n.disabled} turned off in /hooks` : '',
598
593
  ].filter((p) => p !== '');
594
+ const profile = adapter.codexProfile;
595
+ const start = profile === undefined
596
+ ? 'Start Codex and choose "Trust all" at the "Hooks need review" prompt, or open /hooks and trust each one. '
597
+ : `Start \`codex --profile ${profile}\` and choose "Trust all" at the "Hooks need review" prompt there, ` +
598
+ 'or open /hooks in it and trust each one. ';
599
+ const exec = profile === undefined
600
+ ? '`codex exec` skips them too unless it runs with --dangerously-bypass-hook-trust.'
601
+ : `\`codex exec --profile ${profile}\` skips them until then, unless it runs with --dangerously-bypass-hook-trust.`;
599
602
  return [
600
603
  {
601
604
  level: 'warn',
602
605
  message: `Codex skips ${n.total - n.trusted} of ${n.total} Mainwave hooks in ${hooksFile.path} (${parts.join(', ')}), ` +
603
- 'so they send nothing. Start Codex and choose "Trust all" at the "Hooks need review" prompt, or open /hooks and trust each one. ' +
606
+ `so they send nothing. ${start}` +
604
607
  'Every change to a Mainwave hook needs a new approval, such as setup adding a route or a release changing a command. ' +
605
- '`codex exec` skips them too unless it runs with --dangerously-bypass-hook-trust.',
608
+ exec,
606
609
  },
607
610
  ];
608
611
  };
@@ -665,9 +668,43 @@ const doctorJson = async (adapter, effective, issues, validation, redaction) =>
665
668
  validation,
666
669
  });
667
670
  export const runDoctor = async (adapter, options = {}) => {
668
- if (options.json)
669
- return runDoctorJson(adapter, options);
670
- console.log(color.bold(`mainwave-cli doctor — ${adapter.displayName}`));
671
+ const many = adapter.doctorSetups?.();
672
+ if (many === undefined) {
673
+ return options.json ? runDoctorJson(adapter, options) : reportSetup(adapter, options);
674
+ }
675
+ const together = many.issues.some((i) => i.level === 'error') ? 1 : 0;
676
+ if (options.json) {
677
+ const setups = [];
678
+ let code = together;
679
+ for (const { label, adapter: setup } of many.setups) {
680
+ const { doc, failed } = await setupJson(setup, options);
681
+ setups.push({ setup: label, ...doc });
682
+ if (failed)
683
+ code = 1;
684
+ }
685
+ emitJson({
686
+ adapter: adapter.name,
687
+ displayName: adapter.displayName,
688
+ setups,
689
+ issues: many.issues.map((issue) => ({ level: issue.level, message: issue.message })),
690
+ });
691
+ return code;
692
+ }
693
+ let code = together;
694
+ for (const [i, { label, adapter: setup }] of many.setups.entries()) {
695
+ if (i > 0)
696
+ console.log();
697
+ if ((await reportSetup(setup, options, `${adapter.displayName}, ${label}`)) !== 0)
698
+ code = 1;
699
+ }
700
+ if (many.issues.length > 0) {
701
+ console.log();
702
+ renderChecks(many.issues, `${adapter.displayName} setups together:`);
703
+ }
704
+ return code;
705
+ };
706
+ const reportSetup = async (adapter, options, title = adapter.displayName) => {
707
+ console.log(color.bold(`mainwave-cli doctor — ${title}`));
671
708
  console.log();
672
709
  const effective = await computeEffective(adapter);
673
710
  renderFiles(effective, adapter.hierarchy);
@@ -710,6 +747,11 @@ export const runDoctor = async (adapter, options = {}) => {
710
747
  return hasError || validateFailed ? 1 : 0;
711
748
  };
712
749
  const runDoctorJson = async (adapter, options) => {
750
+ const { doc, failed } = await setupJson(adapter, options);
751
+ emitJson(doc);
752
+ return failed ? 1 : 0;
753
+ };
754
+ const setupJson = async (adapter, options) => {
713
755
  const effective = await computeEffective(adapter);
714
756
  const redaction = redactionView(redactionScope(adapter));
715
757
  const issues = [
@@ -722,6 +764,8 @@ const runDoctorJson = async (adapter, options) => {
722
764
  : []),
723
765
  ];
724
766
  const validation = options.validate ? await runValidate(effective, adapter) : undefined;
725
- emitJson(await doctorJson(adapter, effective, issues, validation, redaction));
726
- return issues.some((i) => i.level === 'error') || validation?.ok === false ? 1 : 0;
767
+ return {
768
+ doc: await doctorJson(adapter, effective, issues, validation, redaction),
769
+ failed: issues.some((i) => i.level === 'error') || validation?.ok === false,
770
+ };
727
771
  };
@@ -81,15 +81,29 @@ export const entryVersionId = (text) => {
81
81
  const m = /^\s*V='([A-Za-z0-9._+-]+)'$/m.exec(text);
82
82
  return m?.[1];
83
83
  };
84
- export const entryCommand = (host, event, route) => `f="$HOME/.mainwave/hooks/managed/${HOOK_ENTRY_SCRIPT}"; [ -f "$f" ] && exec sh "$f" ${host} ${event}${route === undefined ? '' : ` ${route}`}; exit 0`;
85
- export const nodeEntryCommand = (nodeEntryPath, host, event, route) => `(if exist "${nodeEntryPath}" node "${nodeEntryPath}" ${host} ${event}${route === undefined ? '' : ` ${route}`}) & exit /b 0`;
86
- export const parseEntryCommand = (command) => {
87
- const m = new RegExp(`${HOOK_ENTRY_SCRIPT.replace('.', '\\.')}"; \\[ -f "\\$f" \\] && exec sh "\\$f" ([A-Za-z0-9_-]+) ([A-Za-z]+)(?: ([A-Za-z0-9_-]+))?; exit 0`).exec(command);
88
- if (!m) {
89
- const loose = new RegExp(`(?:${HOOK_ENTRY_SCRIPT.replace('.', '\\.')}|${HOOK_NODE_ENTRY_SCRIPT.replace('.', '\\.')})"?\\s+([A-Za-z0-9_-]+)\\s+([A-Za-z]+)(?:\\s+([A-Za-z0-9_-]+))?`).exec(command);
90
- if (!loose)
91
- return undefined;
92
- return { host: loose[1], event: loose[2], ...(loose[3] ? { route: loose[3] } : {}) };
84
+ const CODEX_PROFILE_ARGS = String.raw `--codex-profile ([A-Za-z0-9_-]{1,64})`;
85
+ export const safeArgs = (args) => {
86
+ for (const a of args) {
87
+ if (!SAFE_TOKEN.test(a))
88
+ throw new Error(`hook command: unsafe argument ${a}`);
93
89
  }
94
- return { host: m[1], event: m[2], ...(m[3] ? { route: m[3] } : {}) };
90
+ return args;
91
+ };
92
+ const entryWords = (host, event, route, args) => {
93
+ return [host, event, ...(route === undefined ? [] : [route]), ...safeArgs(args)].join(' ');
94
+ };
95
+ export const entryCommand = (host, event, route, args = []) => `f="$HOME/.mainwave/hooks/managed/${HOOK_ENTRY_SCRIPT}"; [ -f "$f" ] && exec sh "$f" ${entryWords(host, event, route, args)}; exit 0`;
96
+ export const nodeEntryCommand = (nodeEntryPath, host, event, route, args = []) => `(if exist "${nodeEntryPath}" node "${nodeEntryPath}" ${entryWords(host, event, route, args)}) & exit /b 0`;
97
+ export const parseEntryCommand = (command) => {
98
+ const strict = new RegExp(`${HOOK_ENTRY_SCRIPT.replace('.', '\\.')}"; \\[ -f "\\$f" \\] && exec sh "\\$f" ([A-Za-z0-9_-]+) ([A-Za-z]+)(?: ([A-Za-z0-9_][A-Za-z0-9_-]*))?(?: ${CODEX_PROFILE_ARGS})?; exit 0`).exec(command);
99
+ const m = strict ??
100
+ new RegExp(`(?:${HOOK_ENTRY_SCRIPT.replace('.', '\\.')}|${HOOK_NODE_ENTRY_SCRIPT.replace('.', '\\.')})"?\\s+([A-Za-z0-9_-]+)\\s+([A-Za-z]+)(?:\\s+([A-Za-z0-9_][A-Za-z0-9_-]*))?(?:\\s+${CODEX_PROFILE_ARGS.replace(' ', '\\s+')}(?![A-Za-z0-9_-]))?`).exec(command);
101
+ if (!m)
102
+ return undefined;
103
+ return {
104
+ host: m[1],
105
+ event: m[2],
106
+ ...(m[3] ? { route: m[3] } : {}),
107
+ ...(m[4] ? { codexProfile: m[4] } : {}),
108
+ };
95
109
  };
@@ -153,7 +153,7 @@ export const installCodexHooks = async (adapter, paths = defaultPaths()) => {
153
153
  return { updated, destDir: paths.destDir, addedToUser: 0, userSettings: undefined };
154
154
  }
155
155
  const disclosedRoutes = stored.routes?.[adapter.name]?.[hooksFile.path] ?? ROUTES_BEFORE_RECORD;
156
- const wanted = userHookGroups(matchersForTool(all, adapter.markers?.runtimeTool ?? DEFAULT_MARKER_TOOL), { markers: stored.markers?.[adapter.name] ?? true }, new Set(), adapter.markers?.runtimeTool).filter((g) => disclosed.includes(groupEvent(g)) &&
156
+ const wanted = userHookGroups(matchersForTool(all, adapter.markers?.runtimeTool ?? DEFAULT_MARKER_TOOL), { markers: stored.markers?.[adapter.name] ?? true }, new Set(), adapter.markers?.runtimeTool, adapter.markers?.hookArgs).filter((g) => disclosed.includes(groupEvent(g)) &&
157
157
  g.hooks.every((h) => {
158
158
  const key = routeKeyOf(h.command, adapter.markers?.runtimeTool);
159
159
  return key === undefined || disclosedRoutes.includes(key);
@@ -5,7 +5,7 @@ import { basename, dirname, join, resolve, win32 } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { dropInNames } from './effective-settings.js';
7
7
  import { GIT_BASH_FIX, GIT_BASH_MISSING_REASON } from './git-bash.js';
8
- import { entryCommand, entryVersionId, HOOK_DISPATCHER_SCRIPT, HOOK_ENTRY_SCRIPT, HOOK_NODE_ENTRY_SCRIPT, nodeEntryCommand, ORG_DELIVERED_MARK, parseEntryCommand, renderHookEntry, } from './entry-script.js';
8
+ import { entryCommand, entryVersionId, HOOK_DISPATCHER_SCRIPT, HOOK_ENTRY_SCRIPT, HOOK_NODE_ENTRY_SCRIPT, nodeEntryCommand, ORG_DELIVERED_MARK, parseEntryCommand, renderHookEntry, safeArgs, } from './entry-script.js';
9
9
  import { isManagedLayer, isPolicyKey } from './layer-policy.js';
10
10
  import { canonicalPacks, packOrder } from './redaction.js';
11
11
  export const MANAGED_BY = '--managed-by @mainwave/cli';
@@ -77,17 +77,21 @@ export const shellHome = (plat = process.platform, env = process.env, dirExists
77
77
  return drivePath;
78
78
  return env.USERPROFILE || homedir();
79
79
  };
80
- export const installHooksCommand = (version, { quiet = true, redactionPacks = [], host = DEFAULT_MARKER_TOOL, } = {}) => `cd "$HOME" && npx -y --registry=https://registry.npmjs.org ` +
80
+ export const installHooksCommand = (version, options = {}) => `cd "$HOME" && ${installHooksNpx(version, options)}`;
81
+ const installHooksNpx = (version, { quiet = true, redactionPacks = [], host = DEFAULT_MARKER_TOOL, args = [] }) => `npx -y --registry=https://registry.npmjs.org ` +
81
82
  `@mainwave/cli@${version} install-hooks${quiet ? ' --quiet' : ''}` +
82
83
  (host === 'codex' ? ' --host codex' : '') +
84
+ safeArgs(args)
85
+ .map((a) => ` ${a}`)
86
+ .join('') +
83
87
  (redactionPacks.length > 0
84
88
  ? ` ${REDACTION_PACKS_FLAG} ${canonicalPacks(redactionPacks).join(',')}`
85
89
  : '');
90
+ export const codexRefreshCommand = (args = []) => installHooksNpx(PAYLOAD_CLI_SPEC, { host: 'codex', args });
86
91
  export const bootstrapCommand = (version, redactionPacks = []) => `{ ${installHooksCommand(version, { redactionPacks })}; } >/dev/null 2>&1; exit 0`;
87
- export const codexBootstrapCommand = (version, plat = process.platform) => plat === 'win32'
88
- ? `(cd /d "%USERPROFILE%" && npx -y --registry=https://registry.npmjs.org ` +
89
- `@mainwave/cli@${version} install-hooks --quiet --host codex) >NUL 2>&1 & exit /b 0`
90
- : `{ ${installHooksCommand(version, { host: 'codex' })}; } >/dev/null 2>&1; exit 0`;
92
+ export const codexBootstrapCommand = (version, plat = process.platform, args = []) => plat === 'win32'
93
+ ? `(cd /d "%USERPROFILE%" && ${installHooksNpx(version, { host: 'codex', args })}) >NUL 2>&1 & exit /b 0`
94
+ : `{ ${installHooksCommand(version, { host: 'codex', args })}; } >/dev/null 2>&1; exit 0`;
91
95
  const REDACTION_PACKS_FLAG = '--redaction-packs';
92
96
  export const redactionPacksIn = (command) => {
93
97
  const args = /\binstall-hooks\b([^;}]*)/.exec(command)?.[1];
@@ -101,14 +105,14 @@ export const redactionPacksIn = (command) => {
101
105
  };
102
106
  export const BOOTSTRAP_MATCHER = 'startup|resume|fork';
103
107
  export const BOOTSTRAP_KEY = 'SessionStart:bootstrap';
104
- export const bootstrapGroup = (redactionPacks = [], host = DEFAULT_MARKER_TOOL) => ({
108
+ export const bootstrapGroup = (redactionPacks = [], host = DEFAULT_MARKER_TOOL, args = []) => ({
105
109
  event: 'SessionStart',
106
110
  matcher: BOOTSTRAP_MATCHER,
107
111
  hooks: [
108
112
  {
109
113
  type: 'command',
110
114
  command: host === 'codex'
111
- ? codexBootstrapCommand(PAYLOAD_CLI_SPEC)
115
+ ? codexBootstrapCommand(PAYLOAD_CLI_SPEC, process.platform, args)
112
116
  : bootstrapCommand(PAYLOAD_CLI_SPEC, redactionPacks),
113
117
  async: true,
114
118
  },
@@ -485,9 +489,9 @@ export const buildScriptHookCommand = (scriptPath, version, plat = process.platf
485
489
  ? `node "${scriptPath}" ${MANAGED_BY}@${version}${toolArg}`
486
490
  : `f="${scriptPath}"; [ -f "$f" ] && exec node "$f" ${MANAGED_BY}@${version}${toolArg}; exit 0`;
487
491
  };
488
- export const buildHookCommand = (host, event, route, plat = process.platform, managedDir = managedHooksDir()) => host === 'codex' && plat === 'win32'
489
- ? nodeEntryCommand(win32.join(managedDir, HOOK_NODE_ENTRY_SCRIPT), host, event, route)
490
- : entryCommand(host, event, route);
492
+ export const buildHookCommand = (host, event, route, plat = process.platform, managedDir = managedHooksDir(), args = []) => host === 'codex' && plat === 'win32'
493
+ ? nodeEntryCommand(win32.join(managedDir, HOOK_NODE_ENTRY_SCRIPT), host, event, route, args)
494
+ : entryCommand(host, event, route, args);
491
495
  export const parseManagedByVersion = (command) => {
492
496
  const re = new RegExp(`${MANAGED_BY.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')}@([^\\s;]+)`);
493
497
  return re.exec(command)?.[1];
@@ -508,10 +512,10 @@ export const hookShape = (event, host = DEFAULT_MARKER_TOOL) => {
508
512
  };
509
513
  const CODEX_STOP_TIMEOUT_SEC = 5;
510
514
  const CODEX_INTERRUPT_TIMEOUT_SEC = 2;
511
- const groupFor = (m, host) => {
515
+ const groupFor = (m, host, args) => {
512
516
  const hook = {
513
517
  type: 'command',
514
- command: buildHookCommand(host, m.event, m.route),
518
+ command: buildHookCommand(host, m.event, m.route, process.platform, managedHooksDir(), args),
515
519
  ...hookShape(m.event, host),
516
520
  };
517
521
  if (m.if !== undefined && host !== 'codex')
@@ -522,13 +526,13 @@ const groupFor = (m, host) => {
522
526
  hooks: [hook],
523
527
  };
524
528
  };
525
- export const buildHookGroups = (matchers, host = DEFAULT_MARKER_TOOL) => matchers.map((m) => groupFor(m, host));
529
+ export const buildHookGroups = (matchers, host = DEFAULT_MARKER_TOOL, args = []) => matchers.map((m) => groupFor(m, host, args));
526
530
  export const hostRunsBootstrap = (host) => host === DEFAULT_MARKER_TOOL || host === 'codex';
527
- export const userHookGroups = (hosted, on, delivered, host = DEFAULT_MARKER_TOOL) => {
531
+ export const userHookGroups = (hosted, on, delivered, host = DEFAULT_MARKER_TOOL, args = []) => {
528
532
  const selected = selectHookMatchers(hosted, on);
529
533
  const groups = [
530
- ...(hostRunsBootstrap(host) && selected.length > 0 ? [bootstrapGroup([], host)] : []),
531
- ...buildHookGroups(selected, host),
534
+ ...(hostRunsBootstrap(host) && selected.length > 0 ? [bootstrapGroup([], host, args)] : []),
535
+ ...buildHookGroups(selected, host, args),
532
536
  ];
533
537
  return groups.filter((g) => {
534
538
  const command = g.hooks[0]?.command ?? '';
@@ -769,9 +773,10 @@ const managedLockValue = (v) => {
769
773
  return v;
770
774
  return v !== 'false';
771
775
  };
772
- const readSettingsDoc = async (path) => {
776
+ const readSettingsDoc = async (path, codec) => {
773
777
  try {
774
- return JSON.parse(await fs.readFile(path, 'utf8'));
778
+ const body = await fs.readFile(path, 'utf8');
779
+ return codec === undefined ? JSON.parse(body) : codec.parse(body, path);
775
780
  }
776
781
  catch {
777
782
  return null;
@@ -787,7 +792,7 @@ export const scanForMarkers = async (layers) => {
787
792
  .map((name) => join(layer.path, name))
788
793
  : [layer.path];
789
794
  for (const path of paths) {
790
- const doc = await readSettingsDoc(path);
795
+ const doc = await readSettingsDoc(path, layer.codec);
791
796
  if (!isPlainObject(doc))
792
797
  continue;
793
798
  out.push({
@@ -1,10 +1,10 @@
1
1
  import { adapterNames, adapters } from '../adapters/index.js';
2
- import { adapterEffective } from './status.js';
2
+ import { adapterEffective, statusSetups } from './status.js';
3
3
  export const pinnedUseCase = async (settings, targets = adapterNames().map((n) => adapters[n])) => {
4
4
  const stored = settings.useCase;
5
5
  if (!stored)
6
6
  return undefined;
7
7
  const developerTools = targets.filter((a) => !a.teamUcid);
8
- const effective = await Promise.all(developerTools.map(adapterEffective));
8
+ const effective = await Promise.all(developerTools.flatMap(statusSetups).map((s) => adapterEffective(s.adapter)));
9
9
  return effective.some((e) => e.ucid === stored.id) ? stored : undefined;
10
10
  };
@@ -1,5 +1,6 @@
1
1
  import { checkbox, confirm, input, password, select } from '@inquirer/prompts';
2
2
  import { maskSecret } from './format.js';
3
+ import { profileFileName } from '../adapters/codex-cli.js';
3
4
  const EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
4
5
  export const promptAdapters = async (candidates) => {
5
6
  const detected = candidates.filter((c) => c.detected);
@@ -76,3 +77,17 @@ export const promptConfirmWrite = async () => confirm({
76
77
  message: 'Write file?',
77
78
  default: true,
78
79
  });
80
+ export const promptCodexProfileChoice = async (profiles) => {
81
+ const files = profiles.map(profileFileName).join(', ');
82
+ const choice = await select({
83
+ message: `Codex sends to Mainwave only from ${profiles.length === 1 ? 'profile' : 'profiles'} ${profiles.join(', ')}. What should setup do?`,
84
+ choices: [
85
+ ...profiles.map((p) => ({ name: `update profile ${p}`, value: `profile:${p}` })),
86
+ {
87
+ name: `switch to all sessions (removes Mainwave from ${files})`,
88
+ value: 'home',
89
+ },
90
+ ],
91
+ });
92
+ return choice === 'home' ? { kind: 'home' } : { kind: 'profile', profile: choice.slice(8) };
93
+ };
@@ -206,9 +206,16 @@ const renderFile = (state, isLast, labelWidth) => {
206
206
  });
207
207
  return lines;
208
208
  };
209
- const renderAdapter = async (adapter) => {
209
+ export const statusSetups = (adapter) => [
210
+ { adapter },
211
+ ...(adapter.doctorSetups?.()?.setups ?? [])
212
+ .filter((s) => s.adapter.paths.global !== adapter.paths.global)
213
+ .map((s) => ({ adapter: s.adapter, setup: s.label })),
214
+ ];
215
+ const renderAdapter = async (adapter, setup) => {
210
216
  const lines = [''];
211
- lines.push(`${color.bold(adapter.name)} ${color.dim(`(${adapter.displayName})`)}`);
217
+ const title = setup === undefined ? adapter.displayName : `${adapter.displayName}, ${setup}`;
218
+ lines.push(`${color.bold(adapter.name)} ${color.dim(`(${title})`)}`);
212
219
  const rows = fileRowsFor(adapter);
213
220
  const states = await Promise.all(rows.map(inspectFile));
214
221
  const effective = await withNativeIdentity(adapter, states);
@@ -234,13 +241,14 @@ const renderAdapter = async (adapter) => {
234
241
  });
235
242
  return lines;
236
243
  };
237
- const statusJsonFor = async (adapter) => {
244
+ const statusJsonFor = async (adapter, setup) => {
238
245
  const states = await Promise.all(fileRowsFor(adapter).map(inspectFile));
239
246
  const effective = await withNativeIdentity(adapter, states);
240
247
  const attribution = attributionOf(effective, adapter);
241
248
  return {
242
249
  adapter: adapter.name,
243
250
  displayName: adapter.displayName,
251
+ ...(setup === undefined ? {} : { setup }),
244
252
  effective: {
245
253
  ...(effective.ucid !== undefined ? { ucid: effective.ucid } : {}),
246
254
  ...(effective.collectorUrl !== undefined ? { collectorUrl: effective.collectorUrl } : {}),
@@ -261,7 +269,7 @@ const statusJsonFor = async (adapter) => {
261
269
  };
262
270
  };
263
271
  export const runStatus = async (adapter, options = {}) => {
264
- const targets = adapter !== undefined ? [adapter] : adapterNames().map((n) => adapters[n]);
272
+ const targets = (adapter !== undefined ? [adapter] : adapterNames().map((n) => adapters[n])).flatMap(statusSetups);
265
273
  const redaction = redactionView();
266
274
  const unredacted = redaction.state === 'off'
267
275
  ? []
@@ -269,7 +277,7 @@ export const runStatus = async (adapter, options = {}) => {
269
277
  if (options.json) {
270
278
  emitJson({
271
279
  redaction: redaction.state === 'off' ? redaction : { ...redaction, unredactedHooks: unredacted },
272
- adapters: await Promise.all(targets.map(statusJsonFor)),
280
+ adapters: await Promise.all(targets.map((t) => statusJsonFor(t.adapter, t.setup))),
273
281
  });
274
282
  return 0;
275
283
  }
@@ -285,8 +293,8 @@ export const runStatus = async (adapter, options = {}) => {
285
293
  ? ` ✗ ${copy.what} in ${tildify(copy.path)} predate your organization's redaction packs and send spans without them. ${copyAdvice(copy)}`
286
294
  : ` ${serious ? '✗' : '!'} ${copy.what} in ${tildify(copy.path)} predate redaction and send spans without it. ${copyAdvice(copy)}`));
287
295
  }
288
- for (const a of targets) {
289
- for (const line of await renderAdapter(a)) {
296
+ for (const t of targets) {
297
+ for (const line of await renderAdapter(t.adapter, t.setup)) {
290
298
  console.log(line);
291
299
  }
292
300
  }
@@ -7,7 +7,7 @@ import { PlatformError, ValidateError, WizardAbort } from './errors.js';
7
7
  import { color } from './format.js';
8
8
  import { runInterview } from './interview.js';
9
9
  import { redeemInvite } from './platform.js';
10
- import { promptApiKey, promptCollectorUrl, promptConfirmWrite, promptSkills } from './prompts.js';
10
+ import { promptApiKey, promptCodexProfileChoice, promptCollectorUrl, promptConfirmWrite, promptSkills, } from './prompts.js';
11
11
  import { checkRedactionFile, hasRulesFile, nextRedactionChoice, redactionLines, redactionView, sendsUnredactedContent, uncoveredNotice, } from './redaction.js';
12
12
  import { describeBreaks, flatRefreshBreaks, refreshInstalledHooks } from './hook-copies.js';
13
13
  import { installSkillsPayload } from './skills.js';
@@ -19,6 +19,7 @@ import { VERSION } from './version.js';
19
19
  import { emitJson, say, setJsonMode } from './ui.js';
20
20
  import { validateCollector } from './validate.js';
21
21
  import { runVerify } from './verify.js';
22
+ import { CODEX_ADAPTER_NAME, codexCliFor, codexHome, codexHomeIssues, findCodexProfileSetups, parseProfileName, profileConflict, profileFileName, profileOtherExporterWarning, } from '../adapters/codex-cli.js';
22
23
  const validateWithRetry = async (initialUrl, initialKey, interactive) => {
23
24
  let url = initialUrl;
24
25
  let key = initialKey;
@@ -240,9 +241,51 @@ export const redeemInviteToOverrides = async (token, apiUrl, options) => {
240
241
  userEmailFromInvite: true,
241
242
  };
242
243
  };
243
- export const runSetup = async (adapters, rawOptions = {}) => {
244
+ const resolveCodexAdapters = async (adapters, profile, interactive) => {
245
+ const hasCodex = adapters.some((a) => a.name === CODEX_ADAPTER_NAME);
246
+ if (!hasCodex) {
247
+ if (profile !== undefined) {
248
+ throw new WizardAbort('--profile applies to Codex only: name codex among the tools, e.g. `setup codex --profile ' +
249
+ `${profile}\``);
250
+ }
251
+ return { adapters: [...adapters] };
252
+ }
253
+ const home = codexHome();
254
+ const swap = (codex) => adapters.map((a) => (a.name === CODEX_ADAPTER_NAME ? codex : a));
255
+ const toProfile = (codexProfile) => ({
256
+ adapters: swap(codexCliFor({ kind: 'profile', home, profile: codexProfile })),
257
+ codexProfile,
258
+ });
259
+ if (profile !== undefined) {
260
+ const conflict = profileConflict(home, profile);
261
+ if (conflict !== undefined)
262
+ throw new WizardAbort(conflict);
263
+ return toProfile(profile);
264
+ }
265
+ const found = findCodexProfileSetups(home);
266
+ if (found.length === 0)
267
+ return { adapters: [...adapters] };
268
+ if (!interactive) {
269
+ const files = found.map(profileFileName).join(', ');
270
+ throw new WizardAbort(`Codex sends to Mainwave only from ${found.length === 1 ? 'profile' : 'profiles'} ${found.join(', ')} (${files} in ${home}). ` +
271
+ `To update it, run \`mainwave-cli setup codex --profile ${found[0]}\`. ` +
272
+ 'To send from every Codex session instead, run `mainwave-cli setup codex` in a terminal and choose ' +
273
+ '"switch to all sessions"; that removes Mainwave from the profile files.');
274
+ }
275
+ const choice = await promptCodexProfileChoice(found);
276
+ if (choice.kind === 'profile')
277
+ return toProfile(parseProfileName(choice.profile));
278
+ return {
279
+ adapters: swap({
280
+ ...codexCliFor({ kind: 'home', home }),
281
+ replaces: found.map((p) => codexCliFor({ kind: 'profile', home, profile: p })),
282
+ }),
283
+ };
284
+ };
285
+ export const runSetup = async (requested, rawOptions = {}) => {
244
286
  setJsonMode(rawOptions.json === true);
245
287
  const interactive = isInteractive();
288
+ const { adapters, codexProfile } = await resolveCodexAdapters(requested, rawOptions.profile, interactive);
246
289
  const redactionFile = rawOptions.redactionFile === undefined
247
290
  ? undefined
248
291
  : checkRedactionFile(rawOptions.redactionFile);
@@ -255,6 +298,11 @@ export const runSetup = async (adapters, rawOptions = {}) => {
255
298
  let credentials = await readCredentials();
256
299
  let session = activeSession(credentials, endpoints.apiUrl);
257
300
  say(color.bold(`mainwave-cli — setup ${adapters.map((a) => a.displayName).join(', ')}`));
301
+ if (adapters.some((a) => a.name === CODEX_ADAPTER_NAME)) {
302
+ for (const issue of codexHomeIssues()) {
303
+ say(issue.level === 'warn' ? color.yellow(`⚠ ${issue.message}`) : color.dim(issue.message));
304
+ }
305
+ }
258
306
  const options = rawOptions.invite
259
307
  ? await redeemInviteToOverrides(rawOptions.invite, endpoints.apiUrl, rawOptions)
260
308
  : rawOptions;
@@ -322,6 +370,11 @@ export const runSetup = async (adapters, rawOptions = {}) => {
322
370
  `(${plan.keptPin.name ?? plan.keptPin.id}). Pass --no-use-case to unpin it.`));
323
371
  }
324
372
  }
373
+ const otherExporter = codexProfile === undefined ? undefined : profileOtherExporterWarning(codexHome(), codexProfile);
374
+ if (otherExporter !== undefined) {
375
+ say('');
376
+ say(color.yellow(`⚠ ${otherExporter}`));
377
+ }
325
378
  if (planHasChanges(plans) && !options.yes) {
326
379
  if (!interactive) {
327
380
  throw new WizardAbort('refusing to write without confirmation — pass --yes');
@@ -385,6 +438,14 @@ export const runSetup = async (adapters, rawOptions = {}) => {
385
438
  { ...hooks.routes?.[p.adapter.name], [userHooksPath(p.adapter)]: [...p.hookRoutes] },
386
439
  ])),
387
440
  };
441
+ for (const p of markerTools) {
442
+ for (const file of p.replacedHooksFiles) {
443
+ if (file === userHooksPath(p.adapter))
444
+ continue;
445
+ delete hooks.events[p.adapter.name]?.[file];
446
+ delete hooks.routes[p.adapter.name]?.[file];
447
+ }
448
+ }
388
449
  }
389
450
  await updateSettings({
390
451
  hooks,
package/dist/main.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { claudeCodeFor } from './adapters/claude-code.js';
2
- import { codexCli } from './adapters/codex-cli.js';
2
+ import { codexCliFor, homeTarget, parseProfileName, profileTarget } from './adapters/codex-cli.js';
3
3
  import { adapterNames, adapters } from './adapters/index.js';
4
4
  import { commandFlags, detailsBlock, isCommand, usageBlock } from './commands.js';
5
5
  import { runLogin, runLogout, runWhoami } from './core/auth-commands.js';
@@ -111,7 +111,20 @@ const setupOptions = (parsed) => {
111
111
  flags.bool('skills-only') === true) {
112
112
  throw new WizardAbort('--skills-only touches no telemetry config, so redaction flags do not apply');
113
113
  }
114
+ let profile;
115
+ if (flags.has('profile')) {
116
+ if (flags.bool('skills-only') === true) {
117
+ throw new WizardAbort('--skills-only touches no telemetry config, so --profile does not apply');
118
+ }
119
+ try {
120
+ profile = parseProfileName(flags.value('profile'));
121
+ }
122
+ catch (err) {
123
+ throw new WizardAbort(err instanceof Error ? err.message : String(err));
124
+ }
125
+ }
114
126
  return {
127
+ profile,
115
128
  invite,
116
129
  redactionFile,
117
130
  noRedaction,
@@ -251,8 +264,24 @@ const HANDLERS = {
251
264
  process.stderr.write(`mainwave-cli install-hooks: --host takes \`codex\`, not "${host}"\n`);
252
265
  return 1;
253
266
  }
267
+ if (flags.has('codex-profile') && host !== 'codex') {
268
+ process.stderr.write('mainwave-cli install-hooks: --codex-profile needs --host codex\n');
269
+ return 1;
270
+ }
254
271
  if (host === 'codex') {
255
- return runInstallCodexHooks(codexCli, { quiet: flags.bool('quiet') === true });
272
+ let target;
273
+ try {
274
+ target = flags.has('codex-profile')
275
+ ? profileTarget(parseProfileName(flags.value('codex-profile')))
276
+ : homeTarget();
277
+ }
278
+ catch (err) {
279
+ process.stderr.write(`mainwave-cli install-hooks: ${err instanceof Error ? err.message : String(err)}\n`);
280
+ return 1;
281
+ }
282
+ return runInstallCodexHooks(codexCliFor(target), {
283
+ quiet: flags.bool('quiet') === true,
284
+ });
256
285
  }
257
286
  const dir = await sessionConfigDir();
258
287
  return runInstallHooks(dir === undefined ? undefined : claudeCodeFor(dir), {
@@ -271,6 +300,9 @@ const HANDLERS = {
271
300
  if (named.length === 0) {
272
301
  throw new WizardAbort('--remove needs the tools to remove, e.g. `setup kiro-ide --remove`');
273
302
  }
303
+ if (flags.has('profile')) {
304
+ throw new WizardAbort('--profile does not combine with --remove');
305
+ }
274
306
  return await runRemove(named, {
275
307
  yes: flags.bool('yes') === true,
276
308
  json: flags.bool('json') === true,
@@ -42,9 +42,10 @@ import {
42
42
  writeFileSync,
43
43
  } from 'node:fs'
44
44
  import { homedir } from 'node:os'
45
- import { isAbsolute, join } from 'node:path'
45
+ import { basename, isAbsolute, join } from 'node:path'
46
46
 
47
47
  import {
48
+ codexConfigFile,
48
49
  emitMarker,
49
50
  hookFlag,
50
51
  loadOtelConfig,
@@ -568,9 +569,18 @@ export const handle = async (
568
569
  if (closed.length === 0) return
569
570
 
570
571
  const tool = markerTool(argv)
571
- const { endpoint, bearer, resourceAttrs } = loadOtelConfig(undefined, {}, tool)
572
+ const { endpoint, bearer, resourceAttrs } = loadOtelConfig(
573
+ undefined,
574
+ {},
575
+ tool,
576
+ undefined,
577
+ {},
578
+ argv,
579
+ )
572
580
  if (!endpoint || !bearer) {
573
- log(`skip ${closed.length} codex span(s): collector endpoint/bearer not found in config.toml`)
581
+ const file = codexConfigFile(argv)
582
+ const where = file === undefined ? 'no valid --codex-profile name' : basename(file)
583
+ log(`skip ${closed.length} codex span(s): no Mainwave collector in ${where}`)
574
584
  return
575
585
  }
576
586
  await emit({
@@ -353,7 +353,14 @@ export const handle = async (payload, { argv = process.argv, emit = emitMarker }
353
353
  const tool = markerTool(argv)
354
354
  const managedDir = markerManagedDir(argv)
355
355
  const env = markerSessionEnv(tool, payload)
356
- const { endpoint, bearer, resourceAttrs } = loadOtelConfig(projectDir, env, tool, managedDir)
356
+ const { endpoint, bearer, resourceAttrs } = loadOtelConfig(
357
+ projectDir,
358
+ env,
359
+ tool,
360
+ managedDir,
361
+ {},
362
+ argv,
363
+ )
357
364
  log(
358
365
  `commits=${shas.length} endpoint=${endpoint ? 'set' : 'MISSING'} ` +
359
366
  `bearer=${bearer ? 'set' : 'MISSING'} ucid=${resourceAttrs['mainwave.ucid'] || 'MISSING'}`,