@brunobracaioli/aibrain 0.4.0-beta.24 → 0.4.0-beta.26

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/dist/cli.mjs CHANGED
@@ -38,12 +38,17 @@ import {
38
38
  writeStoredLocale,
39
39
  } from './engineering-pack.mjs';
40
40
  import { initCommand } from './engineering-init.mjs';
41
- import { manifestDoctorSection, resolveReleaseManifest } from './release-manifest.mjs';
41
+ import {
42
+ installedClientVersion,
43
+ manifestDoctorSection,
44
+ resolveReleaseManifest,
45
+ } from './release-manifest.mjs';
42
46
  import {
43
47
  isChannel,
44
48
  isHostMode,
45
49
  isUpdateMode,
46
50
  readReleaseSettings,
51
+ recordHostSelection,
47
52
  writeReleaseSettings,
48
53
  } from './release-settings.mjs';
49
54
  import {
@@ -58,6 +63,7 @@ import {
58
63
  import {
59
64
  describeManagedHost,
60
65
  hostFallbackLine,
66
+ hostRecoveryLine,
61
67
  resolveHostExecutable,
62
68
  takeHostFlag,
63
69
  } from './managed-host.mjs';
@@ -69,8 +75,14 @@ import { readCodexGuardrails } from './guardrails-plugin.mjs';
69
75
  import { codexHooksStatus, supportsCodexHooks } from './codex-hooks.mjs';
70
76
  import { managerDoctorLine, managerDoctorSection, takeRoleFlags } from './manager/launch-role.mjs';
71
77
  import { WORKERS_USAGE, workersCommand } from './manager/workers-cli.mjs';
78
+ import {
79
+ describePermissionError,
80
+ describeRoleError,
81
+ launchFeedbackLocale,
82
+ } from './launch-feedback.mjs';
83
+ import { parseCodexLaunchArgs } from './codex-permissions.mjs';
72
84
 
73
- const VERSION = '0.4.0-beta.24';
85
+ const VERSION = '0.4.0-beta.26';
74
86
  // The command is `aisac`; `aibrain` is an alias installed from the same entry.
75
87
  const COMMAND = 'aisac';
76
88
  /** `aisac scan` could not scan as asked (scan spec D6); 1 means findings, 2 a usage error. */
@@ -81,7 +93,7 @@ const LEGACY_DISCLOSURE_VERSION = 'aibrain-paid-context-v1-2026-10-09';
81
93
 
82
94
  function usage() {
83
95
  console.log(
84
- `${COMMAND} ${VERSION}\n\nUsage:\n ${COMMAND} setup [--client claude|codex|both] [--context-profile upstream|conservative]\n [--compact-at 1..95] [--keep-threshold 0..1] [--preserve-recent 1..100]\n [--min-reduction 0..1] [--truncate-head-chars 0..4096]\n [--max-state-tokens 1000..25000] [--max-request-tokens 1000..30000]\n [--tool-policy compatible|read_only] [--goal TEXT]\n [--update-mode auto|notify|off] [--channel beta|latest] [--host-claude managed|system]\n ${COMMAND} doctor [--json]\n ${COMMAND} status [--json]\n ${COMMAND} update [--check] [--rollback] [--yes] [--json]\n ${COMMAND} disable\n ${COMMAND} setup --undo\n ${COMMAND} claude [--host managed|system] [--manager | --worker <name>] [--room <name>]\n [-- native-args...]\n ${COMMAND} codex [--worker <name> [--room <name>]] [-- native-args...]\n${WORKERS_USAGE.map((line) => ` ${COMMAND} ${line}\n`).join('')} ${COMMAND} init [dir] [--lang pt-BR|en] [--stack node|python|none] [--dry-run] [--json]\n ${COMMAND} scan [dir] [--fail-on critical|high|medium|low|none] [--only <kinds>]\n [--skip <kinds>] [--history] [--no-docker] [--lang pt-BR|en] [--json]\n [--check-tools] [--timeout <seconds>]\n\nPolicy notes:\n Automatic monitoring asks for compaction at compact-at percent; state/request\n limits are estimated upper bounds and do not override server quotas.\n min-reduction, truncate-head-chars and tool-policy apply only to Claude;\n Codex keeps native compaction and same-session recovery.`,
96
+ `${COMMAND} ${VERSION}\n\nUsage:\n ${COMMAND} setup [--client claude|codex|both] [--context-profile upstream|conservative]\n [--compact-at 1..95] [--keep-threshold 0..1] [--preserve-recent 1..100]\n [--min-reduction 0..1] [--truncate-head-chars 0..4096]\n [--max-state-tokens 1000..25000] [--max-request-tokens 1000..30000]\n [--tool-policy compatible|read_only] [--goal TEXT]\n [--update-mode auto|notify|off] [--channel beta|latest] [--host-claude managed|system]\n [--host-codex managed|system]\n ${COMMAND} doctor [--json]\n ${COMMAND} status [--json]\n ${COMMAND} update [--check] [--rollback] [--yes] [--json]\n ${COMMAND} disable\n ${COMMAND} setup --undo\n ${COMMAND} claude [--host managed|system] [--manager | --worker <name> [--bus]] [--room <name>]\n [-- native-args...]\n ${COMMAND} codex [--host managed|system] [--manager | --worker <name> [--room <name>]] [-- native-args...]\n${WORKERS_USAGE.map((line) => ` ${COMMAND} ${line}\n`).join('')} ${COMMAND} init [dir] [--lang pt-BR|en] [--stack node|python|none] [--dry-run] [--json]\n ${COMMAND} scan [dir] [--fail-on critical|high|medium|low|none] [--only <kinds>]\n [--skip <kinds>] [--history] [--no-docker] [--lang pt-BR|en] [--json]\n [--check-tools] [--timeout <seconds>]\n\nPolicy notes:\n Automatic monitoring asks for compaction at compact-at percent; state/request\n limits are estimated upper bounds and do not override server quotas.\n min-reduction, truncate-head-chars and tool-policy apply only to Claude;\n Codex keeps native compaction and same-session recovery.`,
85
97
  );
86
98
  console.log(
87
99
  'Clients: setup without --client configures the clients installed on PATH (Claude Code, Codex, or both).',
@@ -111,10 +123,13 @@ function usage() {
111
123
  'Updates: at launch `aisac` reads the signed release manifest and, in `auto` mode, installs the newer listed version into its own npm prefix and restarts; `notify` (the default) prints the command; `off` stays quiet. `aisac update` does it on demand (`--check` only looks, `--rollback` returns to the previous version, `--yes` for scripts); setup --update-mode and --channel record the choice; AISAC_NO_SELF_UPDATE=1 turns it off for one launch.',
112
124
  );
113
125
  console.log(
114
- 'Managed host: `aisac setup --host-claude managed` (or `aisac claude --host managed` for one session) runs the Claude Code version the signed manifest pins, installed from the npm registry under the aisac state directory with scripts off; the installer never touches your own `claude`, your `~/.claude` (the managed copy shares your login and settings) or your shell profile. `system` (the default) keeps your binary; AISAC_HOST_MODE=system turns the managed host off for one launch; doctor reports it under `hosts`. After a failed install the launches of the next hour keep your binary without trying again; `aisac claude --host managed` tries at once.',
126
+ 'Managed hosts: `aisac setup --host-claude managed` or `--host-codex managed` selects the signed Claude Code or Codex pin under the aisac state directory; `aisac claude --host managed` and `aisac codex --host managed` select it for one session. Installs use scripts off and never replace your global CLI, shell profile or host configuration. The managed copy shares your existing host login. `system` keeps the global binary; AISAC_HOST_MODE=system forces that choice for one launch. Doctor reports the selected mode and compatibility under `hosts`.',
127
+ );
128
+ console.log(
129
+ "Manager and workers (licensed accounts): `aisac claude --manager` or `aisac codex --manager` coordinates Codex sessions started with `aisac codex --worker <name>` and opt-in Claude Code bus sessions started with `aisac claude --worker <name> --bus` in the same repository (or `--room <name>`): each manager_* send starts one worker turn under that worker's sandbox and approval policy, and the reply is read as untrusted output. A Codex manager receives content-free wake notices on its idle terminal; Claude Code workers on the native session-messaging channel remain unreachable from Codex. A Claude manager reaches native Claude Code workers through Claude Code's own session messaging. `aisac workers` lists the room. `aisac workers allow-sends [--for 8h]` must be confirmed in your own terminal before a Codex manager can send or cancel to bus workers; it expires after 10 minutes to 24 hours and `--off` revokes it. `aisac workers delegate [<name>...] [--for 8h]` remains a separate terminal grant for a manager to answer Codex worker approval prompts, except the fixed reserve; Claude Code approvals stay with the user. `aisac workers delegate --off` ends the grant and `aisac workers decisions` shows what was decided. Messages are local files under the aisac state directory, deleted when read; message and reply text reaches the involved model providers like anything typed in their sessions.",
115
130
  );
116
131
  console.log(
117
- "Manager and workers (licensed accounts): `aisac claude --manager` coordinates the Codex sessions started with `aisac codex --worker <name>` in the same repository (or the same `--room <name>`): its manager_* tools send a message to a worker, which runs it as one turn under its own sandbox and approval policy, and read the reply; you can still type in any worker. `aisac claude --worker <name>` opens a Claude Code session that the room lists and names: it and the manager talk through Claude Code's own session messaging, so the queue, cancelling and delegated approvals do not apply to it. `aisac workers` lists the room; `aisac workers delegate [<name>...] [--for 8h]`, typed by you on a terminal, lets the manager answer the workers' approval prompts for a limited time, except a fixed reserve that always stays with you; `aisac workers delegate --off` ends it and `aisac workers decisions` shows what was decided. Messages are local files under the aisac state directory, deleted when read; a message becomes part of the other session's conversation, so its text reaches that session's model provider like anything typed there.",
132
+ 'Claude Code bus workers are opt-in and require all live room participants to use an AISAC client with Claude bus support; update and restart room sessions before starting `aisac claude --worker <name> --bus`.',
118
133
  );
119
134
  }
120
135
 
@@ -502,22 +517,23 @@ async function disclosureAccepted(
502
517
  * also needs `node`, the same pair the explicit `--client codex` path checks.
503
518
  * @returns {'claude' | 'codex' | 'both' | null}
504
519
  */
505
- function detectedClients() {
520
+ function detectedClients(managedCodex = false) {
506
521
  const hasClaude = resolveNative('claude') !== null;
507
- const hasCodex = resolveNative('codex') !== null && resolveNative('node') !== null;
522
+ const hasCodex =
523
+ (managedCodex || resolveNative('codex') !== null) && resolveNative('node') !== null;
508
524
  if (hasClaude && hasCodex) return 'both';
509
525
  if (hasClaude) return 'claude';
510
526
  return hasCodex ? 'codex' : null;
511
527
  }
512
528
 
513
- /** @param {string | undefined} requested @returns {'claude' | 'codex' | 'both'} */
514
- function setupClients(requested) {
529
+ /** @param {string | undefined} requested @param {boolean} [managedCodex] @returns {'claude' | 'codex' | 'both'} */
530
+ function setupClients(requested, managedCodex = false) {
515
531
  if (requested !== undefined) {
516
532
  if (requested !== 'claude' && requested !== 'codex' && requested !== 'both')
517
533
  throw new Error('invalid_client');
518
534
  return requested;
519
535
  }
520
- const detected = detectedClients();
536
+ const detected = detectedClients(managedCodex);
521
537
  if (detected === null) throw new Error('no_native_client_found');
522
538
  console.log(`Clients detected on PATH: ${detected} (pass --client to choose).`);
523
539
  return detected;
@@ -532,7 +548,8 @@ function setupClients(requested) {
532
548
  * @param {string} root @param {'pt-BR' | 'en'} locale
533
549
  * @param {{ mode: import('./release-settings.mjs').UpdateMode | undefined,
534
550
  * channel: import('./release-settings.mjs').Channel | undefined,
535
- * hostClaude: import('./release-settings.mjs').HostMode | undefined }} requested
551
+ * hostClaude: import('./release-settings.mjs').HostMode | undefined,
552
+ * hostCodex: import('./release-settings.mjs').HostMode | undefined }} requested
536
553
  */
537
554
  async function recordSetupConsent(root, locale, requested) {
538
555
  const settings = await readReleaseSettings(root);
@@ -544,21 +561,42 @@ async function recordSetupConsent(root, locale, requested) {
544
561
  }
545
562
  const channel = requested.channel ?? settings.update.channel;
546
563
  const hosts =
547
- requested.hostClaude === undefined
564
+ requested.hostClaude === undefined && requested.hostCodex === undefined
548
565
  ? settings.hosts
549
- : { ...settings.hosts, claude: requested.hostClaude };
566
+ : {
567
+ ...settings.hosts,
568
+ ...(requested.hostClaude === undefined ? {} : { claude: requested.hostClaude }),
569
+ ...(requested.hostCodex === undefined ? {} : { codex: requested.hostCodex }),
570
+ };
550
571
  if (mode !== undefined) {
551
572
  await recordReleaseConsent(root, settings, mode, {
552
573
  ...(requested.channel === undefined ? {} : { channel: requested.channel }),
553
574
  hosts,
554
575
  });
576
+ await recordHostSelection(root, settings, { ...settings, status: 'valid', hosts }, [
577
+ ...(requested.hostClaude === undefined ? [] : ['claude']),
578
+ ...(requested.hostCodex === undefined ? [] : ['codex']),
579
+ ]);
555
580
  console.log(`Self-update ${mode} on channel ${channel}; recorded in ${root}/release.json.`);
556
581
  } else {
557
- if (requested.channel !== undefined || requested.hostClaude !== undefined)
582
+ if (
583
+ requested.channel !== undefined ||
584
+ requested.hostClaude !== undefined ||
585
+ requested.hostCodex !== undefined
586
+ )
558
587
  await writeReleaseSettings(
559
588
  { consent: settings.consent, update: { ...settings.update, channel }, hosts },
560
589
  root,
561
590
  );
591
+ if (
592
+ requested.channel !== undefined ||
593
+ requested.hostClaude !== undefined ||
594
+ requested.hostCodex !== undefined
595
+ )
596
+ await recordHostSelection(root, settings, { ...settings, status: 'valid', hosts }, [
597
+ ...(requested.hostClaude === undefined ? [] : ['claude']),
598
+ ...(requested.hostCodex === undefined ? [] : ['codex']),
599
+ ]);
562
600
  console.log(
563
601
  settings.consent === null
564
602
  ? `Release disclosure not answered; aisac keeps notifying about updates on channel ${channel} until an interactive launch asks (pass --update-mode auto|notify|off to answer now).`
@@ -567,6 +605,8 @@ async function recordSetupConsent(root, locale, requested) {
567
605
  }
568
606
  if (requested.hostClaude !== undefined)
569
607
  console.log(`Claude Code host ${requested.hostClaude}; recorded in ${root}/release.json.`);
608
+ if (requested.hostCodex !== undefined)
609
+ console.log(`Codex host ${requested.hostCodex}; recorded in ${root}/release.json.`);
570
610
  }
571
611
 
572
612
  /** @param {string[]} args */
@@ -577,7 +617,9 @@ function requestedReleaseSettings(args) {
577
617
  if (channel !== undefined && !isChannel(channel)) throw new Error('invalid_channel');
578
618
  const hostClaude = option(args, '--host-claude');
579
619
  if (hostClaude !== undefined && !isHostMode(hostClaude)) throw new Error('invalid_host_mode');
580
- return { mode, channel, hostClaude };
620
+ const hostCodex = option(args, '--host-codex');
621
+ if (hostCodex !== undefined && !isHostMode(hostCodex)) throw new Error('invalid_host_mode');
622
+ return { mode, channel, hostClaude, hostCodex };
581
623
  }
582
624
 
583
625
  /** @param {string[]} args */
@@ -602,6 +644,7 @@ async function setup(args) {
602
644
  '--update-mode',
603
645
  '--channel',
604
646
  '--host-claude',
647
+ '--host-codex',
605
648
  ]),
606
649
  new Set([
607
650
  '--client',
@@ -617,6 +660,7 @@ async function setup(args) {
617
660
  '--update-mode',
618
661
  '--channel',
619
662
  '--host-claude',
663
+ '--host-codex',
620
664
  ]),
621
665
  );
622
666
  if (args.includes('--undo') && args.length !== 1)
@@ -628,15 +672,16 @@ async function setup(args) {
628
672
  // `--lang` alone only switches the language of an existing setup. Before the first
629
673
  // setup it runs the full setup (token included) and stores the language at the end.
630
674
  if (lang !== undefined && args.length === 2 && previous !== null) return setPackLocale(lang);
631
- // `--update-mode`, `--channel` and `--host-claude` alone change the release settings
675
+ // `--update-mode`, `--channel` and host flags alone change the release settings
632
676
  // of an existing setup, offline (FR7, FR5); an explicit update flag is the answer to
633
677
  // the disclosure, the host flag alone leaves the consent as it is. The managed copy
634
678
  // is installed by the next launch, not here.
635
- const releaseFlags = ['--update-mode', '--channel', '--host-claude'];
679
+ const releaseFlags = ['--update-mode', '--channel', '--host-claude', '--host-codex'];
636
680
  const releaseOnly =
637
681
  (release.mode !== undefined ||
638
682
  release.channel !== undefined ||
639
- release.hostClaude !== undefined) &&
683
+ release.hostClaude !== undefined ||
684
+ release.hostCodex !== undefined) &&
640
685
  args.every((argument, index) =>
641
686
  [...releaseFlags, '--accept-disclosure'].includes(argument)
642
687
  ? true
@@ -645,10 +690,11 @@ async function setup(args) {
645
690
  if (releaseOnly && previous !== null) {
646
691
  const root = await ensureStateRoot();
647
692
  const settings = await readReleaseSettings(root);
648
- const hosts =
649
- release.hostClaude === undefined
650
- ? settings.hosts
651
- : { ...settings.hosts, claude: release.hostClaude };
693
+ const hosts = {
694
+ ...settings.hosts,
695
+ ...(release.hostClaude === undefined ? {} : { claude: release.hostClaude }),
696
+ ...(release.hostCodex === undefined ? {} : { codex: release.hostCodex }),
697
+ };
652
698
  if (release.mode !== undefined || release.channel !== undefined) {
653
699
  await recordReleaseConsent(root, settings, release.mode ?? settings.update.mode, {
654
700
  ...(release.channel === undefined ? {} : { channel: release.channel }),
@@ -663,10 +709,18 @@ async function setup(args) {
663
709
  root,
664
710
  );
665
711
  }
712
+ await recordHostSelection(root, settings, { ...settings, status: 'valid', hosts }, [
713
+ ...(release.hostClaude === undefined ? [] : ['claude']),
714
+ ...(release.hostCodex === undefined ? [] : ['codex']),
715
+ ]);
666
716
  if (release.hostClaude !== undefined)
667
717
  console.log(
668
718
  `Claude Code host ${release.hostClaude}; recorded in ${root}/release.json. No network call was made.`,
669
719
  );
720
+ if (release.hostCodex !== undefined)
721
+ console.log(
722
+ `Codex host ${release.hostCodex}; recorded in ${root}/release.json. No network call was made.`,
723
+ );
670
724
  return;
671
725
  }
672
726
  if (await updateLocalOptOut(previous, args)) return;
@@ -676,7 +730,7 @@ async function setup(args) {
676
730
  if (localOptOut) return disableTelemetryLocally(previous);
677
731
  const platform = platformCheck();
678
732
  if (!platform.ok) throw new Error(`${platform.code}:${platform.message}`);
679
- const clients = setupClients(option(args, '--client'));
733
+ const clients = setupClients(option(args, '--client'), release.hostCodex === 'managed');
680
734
  if (
681
735
  clients === 'codex' &&
682
736
  (option(args, '--claude-shadow') !== undefined ||
@@ -685,6 +739,8 @@ async function setup(args) {
685
739
  throw new Error('claude_observation_requires_claude_client');
686
740
  if (clients === 'codex' && release.hostClaude !== undefined)
687
741
  throw new Error('host_claude_requires_claude_client');
742
+ if (clients === 'claude' && release.hostCodex !== undefined)
743
+ throw new Error('host_codex_requires_codex_client');
688
744
  const endpoint = option(args, '--endpoint') ?? ENDPOINT;
689
745
  validateEndpoint(endpoint);
690
746
  const selection = selectedPolicy(args, previous, clients);
@@ -721,9 +777,11 @@ async function setup(args) {
721
777
  }
722
778
  token = token.trim();
723
779
  if (!token) throw setupTokenError('empty_token', locale, endpoint);
724
- const codex = resolveNative('codex');
780
+ let codex = resolveNative('codex');
725
781
  const node = resolveNative('node');
726
782
  let claude = resolveNative('claude');
783
+ /** @type {Awaited<ReturnType<typeof resolveCodexCompatibility>> | null} */
784
+ let codexCompatibility = null;
727
785
  /** @type {import('./claude-compatibility.mjs').ClaudeCompatibility | null} */
728
786
  let claudeCompatibility = null;
729
787
  // A managed Claude host asked for at setup (ADR-0056 R4, FR5): the pinned copy is
@@ -752,11 +810,41 @@ async function setup(args) {
752
810
  });
753
811
  if (managed.mode === 'managed') {
754
812
  claude = managed.executable;
755
- claudeCompatibility = managed.compatibility;
813
+ claudeCompatibility =
814
+ /** @type {import('./claude-compatibility.mjs').ClaudeCompatibility | null} */ (
815
+ managed.compatibility
816
+ );
756
817
  } else console.error(hostFallbackLine('claude', managed, locale));
757
818
  }
819
+ if ((clients === 'codex' || clients === 'both') && release.hostCodex === 'managed') {
820
+ const releaseSettings = await readReleaseSettings(root);
821
+ const manifest = await resolveReleaseManifest({
822
+ root,
823
+ packageRoot: PACKAGE_ROOT,
824
+ endpoint,
825
+ token,
826
+ host: 'codex',
827
+ }).catch(() => null);
828
+ const managed = await resolveHostExecutable({
829
+ host: 'codex',
830
+ root,
831
+ packageRoot: PACKAGE_ROOT,
832
+ manifest,
833
+ settings: { ...releaseSettings, hosts: { ...releaseSettings.hosts, codex: 'managed' } },
834
+ env: process.env,
835
+ flag: 'managed',
836
+ clientVersion: VERSION,
837
+ locale,
838
+ progress: (line) => console.error(line),
839
+ });
840
+ codex = managed.executable;
841
+ codexCompatibility = managed.compatibility;
842
+ if (managed.mode !== 'managed') console.error(hostFallbackLine('codex', managed, locale));
843
+ }
758
844
  if ((clients === 'claude' || clients === 'both') && !claude) throw new Error('claude_not_found');
759
- if ((clients === 'codex' || clients === 'both') && (!codex || !node))
845
+ if ((clients === 'codex' || clients === 'both') && !node)
846
+ throw new Error('codex_or_node_not_found');
847
+ if ((clients === 'codex' || clients === 'both') && !codex)
760
848
  throw new Error('codex_or_node_not_found');
761
849
  if (
762
850
  claudeCompatibility === null &&
@@ -767,9 +855,8 @@ async function setup(args) {
767
855
  if (claudeCompatibility?.status === 'rejected')
768
856
  throw new Error(claudeCompatibilityError(claudeCompatibility));
769
857
  const claudeVersion = claudeCompatibility?.version ?? (claude ? nativeVersion(claude) : null);
770
- let codexCompatibility = null;
771
858
  if (clients === 'codex' || clients === 'both') {
772
- codexCompatibility = codex ? await resolveCodexCompatibility(codex) : null;
859
+ codexCompatibility ??= codex ? await resolveCodexCompatibility(codex) : null;
773
860
  if (codexCompatibility?.status === 'rejected')
774
861
  throw new Error(codexCompatibilityError(codexCompatibility));
775
862
  }
@@ -939,9 +1026,9 @@ async function doctor(json) {
939
1026
  token: config?.token ?? null,
940
1027
  }).catch(() => null);
941
1028
  const releaseSettings = await readReleaseSettings(stateRoot());
942
- // Managed hosts (ADR-0056 R4, FR8): the host a launch would run and the state of
1029
+ // Managed hosts (ADR-0056 R4/R5, FR8): the host a launch would run and the state of
943
1030
  // the pinned copy; doctor installs nothing. A ready managed copy is the binary the
944
- // compatibility fields describe, since it is the one `aisac claude` runs.
1031
+ // compatibility fields describe, since it is the one `aisac claude` or `aisac codex` runs.
945
1032
  /** @param {'claude' | 'codex'} host */
946
1033
  const describeHost = (host) =>
947
1034
  describeManagedHost({
@@ -955,15 +1042,16 @@ async function doctor(json) {
955
1042
  }).catch(() => null);
956
1043
  const managedHosts = { claude: await describeHost('claude'), codex: await describeHost('codex') };
957
1044
  const claudeExecutable = managedHosts.claude?.executable ?? native.claude;
1045
+ const codexExecutable = managedHosts.codex?.executable ?? native.codex;
958
1046
  const claudeCompatibility =
959
1047
  claudeExecutable !== null
960
1048
  ? await resolveClaudeCompatibility(claudeExecutable, PACKAGE_ROOT)
961
1049
  : null;
962
1050
  const codexCompatibility =
963
- native.codex !== null ? await resolveCodexCompatibility(native.codex) : null;
1051
+ codexExecutable !== null ? await resolveCodexCompatibility(codexExecutable) : null;
964
1052
  const rawNativeVersions = {
965
1053
  claude: claudeCompatibility?.version ?? '',
966
- codex: native.codex ? nativeVersion(native.codex) : '',
1054
+ codex: codexCompatibility?.version ?? (codexExecutable ? nativeVersion(codexExecutable) : ''),
967
1055
  };
968
1056
  const nativeVersions = {
969
1057
  ...rawNativeVersions,
@@ -982,7 +1070,7 @@ async function doctor(json) {
982
1070
  (claudeCompatibility?.status === 'qualified' ||
983
1071
  claudeCompatibility?.status === 'host_checked'))) &&
984
1072
  (!needsCodex ||
985
- (native.codex !== null &&
1073
+ (codexExecutable !== null &&
986
1074
  native.node !== null &&
987
1075
  captureLockPlatform?.ok === true &&
988
1076
  (codexCompatibility?.status === 'qualified' ||
@@ -1035,7 +1123,7 @@ async function doctor(json) {
1035
1123
  env: process.env,
1036
1124
  manifest: releaseManifest,
1037
1125
  }).catch(() => null),
1038
- // Managed hosts (ADR-0056 R4, FR8): the decision and the pinned copy, no path.
1126
+ // Managed hosts (ADR-0056 R4/R5, FR8): the decision and the pinned copy, no path.
1039
1127
  hosts: {
1040
1128
  managed: {
1041
1129
  claude: hostDoctorSection(managedHosts.claude),
@@ -1043,15 +1131,19 @@ async function doctor(json) {
1043
1131
  },
1044
1132
  },
1045
1133
  extensions: await doctorExtensions({
1046
- executable: native.codex,
1134
+ executable: codexExecutable,
1047
1135
  version: codexCompatibility?.version,
1048
1136
  }),
1049
1137
  scan: await doctorScan(json),
1050
1138
  // Manager and workers (ADR-0058, FR11): role support and the live rooms, no path.
1051
1139
  manager: await managerDoctorSection({
1052
1140
  root: stateRoot(),
1053
- claude: native.claude !== null,
1054
- codexVersion: native.codex === null ? null : (codexCompatibility?.version ?? null),
1141
+ claude: claudeExecutable !== null,
1142
+ claudeVersion: claudeCompatibility?.version ?? null,
1143
+ claudeAccepted:
1144
+ claudeCompatibility?.status === 'qualified' ||
1145
+ claudeCompatibility?.status === 'host_checked',
1146
+ codexVersion: codexExecutable === null ? null : (codexCompatibility?.version ?? null),
1055
1147
  // The worker role needs a Codex this client runs (D14); a refused one never has it.
1056
1148
  codexAccepted:
1057
1149
  codexCompatibility?.status === 'qualified' ||
@@ -1082,6 +1174,7 @@ function hostDoctorSection(described) {
1082
1174
  return {
1083
1175
  mode: described.mode,
1084
1176
  reason: described.reason,
1177
+ selection_source: described.selection_source,
1085
1178
  pinned: described.pinned,
1086
1179
  platform: described.platform,
1087
1180
  installed: described.installed,
@@ -1116,7 +1209,9 @@ function releaseDoctorLines(result) {
1116
1209
  ? `${name} unknown`
1117
1210
  : `${name} ${section.mode}${section.pinned === null ? '' : `, pinned ${section.pinned}`}${
1118
1211
  section.mode === 'managed' ? (section.installed ? ', installed' : ', not installed') : ''
1119
- }${section.reason === null ? '' : ` (${section.reason})`}`;
1212
+ }${section.selection_source === 'unknown' ? ', selection source unknown' : ''}${
1213
+ section.reason === null ? '' : ` (${section.reason})`
1214
+ }`;
1120
1215
  return [
1121
1216
  `manifest: ${manifest}`,
1122
1217
  `update: ${update}`,
@@ -1243,7 +1338,74 @@ async function main(argv) {
1243
1338
  return;
1244
1339
  }
1245
1340
  if (command === 'hooks') return hooksCommand(rest);
1246
- if (command === 'mcp') return mcpCommand(rest);
1341
+ if (command === 'mcp') {
1342
+ if (rest[0] !== 'login') return mcpCommand(rest);
1343
+ return mcpCommand(rest, {
1344
+ resolveCodex: async () => {
1345
+ const root = stateRoot();
1346
+ const config = await readConfig();
1347
+ const locale = resolvePackLocale(await readStoredLocale(root), process.env);
1348
+ const manifest = await resolveReleaseManifest({
1349
+ root,
1350
+ packageRoot: PACKAGE_ROOT,
1351
+ endpoint: config?.endpoint ?? null,
1352
+ token: config?.token ?? null,
1353
+ host: 'codex',
1354
+ }).catch(() => null);
1355
+ const host = await resolveHostExecutable({
1356
+ host: 'codex',
1357
+ root,
1358
+ packageRoot: PACKAGE_ROOT,
1359
+ manifest,
1360
+ settings: await readReleaseSettings(root),
1361
+ env: process.env,
1362
+ flag: null,
1363
+ clientVersion: await installedClientVersion(PACKAGE_ROOT),
1364
+ locale,
1365
+ progress: (line) => process.stderr.write(`${line}\n`),
1366
+ });
1367
+ if (host.fallback !== null && host.compatibility?.status !== 'rejected')
1368
+ process.stderr.write(`${hostFallbackLine('codex', host, locale)}\n`);
1369
+ if (host.executable === null) {
1370
+ const error = new Error('codex_or_node_not_found');
1371
+ Object.assign(error, {
1372
+ guide: hostRecoveryLine(
1373
+ 'codex',
1374
+ host.pinned,
1375
+ host.reason ?? 'codex_not_found',
1376
+ locale,
1377
+ host.reason === 'host_mode_env',
1378
+ ),
1379
+ });
1380
+ throw error;
1381
+ }
1382
+ const compatibility =
1383
+ host.compatibility ?? (await resolveCodexCompatibility(host.executable));
1384
+ if (compatibility.status === 'rejected') {
1385
+ const message =
1386
+ host.fallback === null
1387
+ ? codexCompatibilityError(compatibility)
1388
+ : `${codexCompatibilityError(compatibility)}; managed recovery failed (${host.fallback})`;
1389
+ const error = new Error(message);
1390
+ Object.assign(error, {
1391
+ guide: hostRecoveryLine(
1392
+ 'codex',
1393
+ compatibility.version,
1394
+ compatibility.reason,
1395
+ locale,
1396
+ host.reason === 'host_mode_env',
1397
+ ),
1398
+ });
1399
+ throw error;
1400
+ }
1401
+ return {
1402
+ executable: host.executable,
1403
+ managed: host.mode === 'managed',
1404
+ directory: host.directory,
1405
+ };
1406
+ },
1407
+ });
1408
+ }
1247
1409
  if (command === 'init')
1248
1410
  return initCommand(rest, {
1249
1411
  packageRoot: PACKAGE_ROOT,
@@ -1289,17 +1451,43 @@ async function main(argv) {
1289
1451
  // metadata only, so patch updates do not block a fresh compatibility check.
1290
1452
  if (command === 'codex' && typeof config.codexVersion !== 'string')
1291
1453
  throw new Error('codex_version_unverified');
1292
- // `--host managed|system` belongs to the launcher, not the host (ADR-0056 R4,
1293
- // FR5); a managed Codex arrives with R5.
1294
- const launch = takeHostFlag(rest);
1295
- if (command === 'codex' && launch.hostMode === 'managed')
1296
- throw new Error('host_mode_unsupported');
1454
+ // `--host managed|system` belongs to the launcher, not the host (ADR-0056 R5).
1455
+ const root = stateRoot();
1456
+ const locale = launchFeedbackLocale(await readStoredLocale(root));
1457
+ let launch;
1458
+ try {
1459
+ launch = takeHostFlag(rest);
1460
+ } catch (error) {
1461
+ const guide = describePermissionError(error, rest, locale);
1462
+ if (guide !== null && error instanceof Error) Object.assign(error, { guide, exitCode: 2 });
1463
+ throw error;
1464
+ }
1297
1465
  // `--manager`, `--worker <name>` and `--room <name>` belong to the launcher as
1298
1466
  // well (spec aisac-engineering-manager D2): a manager is a Claude Code session,
1299
1467
  // a worker a Codex session.
1300
- const role = takeRoleFlags(launch.args, command);
1468
+ let role;
1469
+ try {
1470
+ role = takeRoleFlags(launch.args, command);
1471
+ } catch (error) {
1472
+ const code = error instanceof Error ? error.message : String(error);
1473
+ const guide =
1474
+ describeRoleError(code, launch.args, command, locale) ??
1475
+ describePermissionError(error, launch.args, locale);
1476
+ if (guide !== null && error instanceof Error) Object.assign(error, { guide, exitCode: 2 });
1477
+ throw error;
1478
+ }
1301
1479
  const nativeArgs = role.args[0] === '--' ? role.args.slice(1) : role.args;
1302
- const root = stateRoot();
1480
+ if (command === 'codex') {
1481
+ try {
1482
+ // Permission arguments are validated before self-update or any host
1483
+ // probe so a bad root cannot start or change anything.
1484
+ await parseCodexLaunchArgs(nativeArgs, process.cwd(), locale);
1485
+ } catch (error) {
1486
+ const guide = describePermissionError(error, nativeArgs, locale);
1487
+ if (guide !== null && error instanceof Error) Object.assign(error, { guide, exitCode: 2 });
1488
+ throw error;
1489
+ }
1490
+ }
1303
1491
  try {
1304
1492
  // Self-update (ADR-0056 R3, FR6) before any host work: the one-time consent
1305
1493
  // question on a terminal, then install + re-exec in `auto` mode, one line in
@@ -1338,7 +1526,7 @@ async function main(argv) {
1338
1526
  root,
1339
1527
  nativeArgs,
1340
1528
  {},
1341
- { role: role.request },
1529
+ { hostMode: launch.hostMode, role: role.request },
1342
1530
  ));
1343
1531
  process.exitCode = result;
1344
1532
  return;
@@ -362,11 +362,27 @@ function runBounded(executable, args, environment) {
362
362
  });
363
363
  }
364
364
 
365
- /** @param {string} executable @param {NodeJS.ProcessEnv} [baseEnvironment] */
366
- export async function resolveCodexCompatibility(executable, baseEnvironment = process.env) {
365
+ /**
366
+ * @param {string} executable @param {NodeJS.ProcessEnv} [baseEnvironment]
367
+ * @param {string | null} [managedPackageRoot] Private npm package root when the binary is a managed copy.
368
+ */
369
+ export async function resolveCodexCompatibility(
370
+ executable,
371
+ baseEnvironment = process.env,
372
+ managedPackageRoot = null,
373
+ ) {
367
374
  if (!PAGINATION_CONTRACT_VALID)
368
375
  return { status: 'rejected', reason: 'protocol_fingerprint_invalid', version: null };
369
- const environment = { PATH: baseEnvironment.PATH ?? '', LANG: 'C.UTF-8' };
376
+ const environment = {
377
+ PATH: baseEnvironment.PATH ?? '',
378
+ LANG: 'C.UTF-8',
379
+ ...(managedPackageRoot === null
380
+ ? {}
381
+ : {
382
+ CODEX_MANAGED_BY_NPM: '1',
383
+ CODEX_MANAGED_PACKAGE_ROOT: managedPackageRoot,
384
+ }),
385
+ };
370
386
  const versionRun = await runBounded(executable, ['--version'], {
371
387
  ...environment,
372
388
  CODEX_COMPAT_CWD: process.cwd(),