@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.
package/README.md CHANGED
@@ -444,7 +444,15 @@ an earlier version copied into `~/.mainwave/hooks/` once nothing runs them. To d
444
444
  the plan snapshot included, re-run setup with `--no-markers` — the entries are removed cleanly. `doctor` checks that the entry is installed, that it names an installed release with every
445
445
  script, and that every Mainwave hook group is in the background and narrowed by its matcher.
446
446
 
447
- Codex gets the same session-start hook in `~/.codex/hooks.json`, with `--host codex` added to the
447
+ Codex keeps its config in `$CODEX_HOME` when that is set, and in `~/.codex` otherwise. Setup,
448
+ `doctor` and the hooks follow the same rule, so run setup with the `CODEX_HOME` you run Codex
449
+ with, for example `CODEX_HOME=~/.codex-work npx @mainwave/cli setup codex`. Each Codex home gets
450
+ its own config and hooks. Setup says where it writes when `CODEX_HOME` is set, and warns when that
451
+ directory belongs to a launcher: Orca sets `CODEX_HOME` to its own copy of `~/.codex` in every
452
+ terminal it opens, so run setup from there with `env -u CODEX_HOME` to set up the Codex you start
453
+ yourself.
454
+
455
+ Codex gets the same session-start hook in its `hooks.json`, with `--host codex` added to the
448
456
  command (on Windows, where Codex runs hooks through `cmd.exe`, an equivalent `cmd` command). It
449
457
  installs the latest release's scripts and adds any hook that setup told you about and the file
450
458
  lacks. It never edits or removes a hook already in the file, because Codex trusts each hook by a
@@ -470,7 +478,62 @@ included. Until then no Mainwave hook runs in Codex, and `codex exec` skips them
470
478
  with `--dangerously-bypass-hook-trust`. Codex checks each hook's definition against what you
471
479
  approved, so it asks again after any change to a Mainwave hook, such as a setup run that adds a
472
480
  route or a release that changes a command. Setup says all of this when it finishes, and `doctor`
473
- lists the Mainwave hooks Codex is skipping, read from the trust records in `~/.codex/config.toml`.
481
+ lists the Mainwave hooks Codex is skipping, read from the trust records in Codex's `config.toml`.
482
+
483
+ **Sending telemetry from only some Codex sessions.** Plain `setup codex` makes every session in a
484
+ Codex home report. To report from some sessions only, pick one of two routes by what your Codex
485
+ sessions share:
486
+
487
+ - A separate Codex home, when the Codex login differs between kinds of work. Run
488
+ `CODEX_HOME=<dir> mainwave-cli setup codex`, then run Codex with that `CODEX_HOME`. The new home
489
+ needs its own login, MCP servers, project trust and history.
490
+ - A Codex profile, when one Codex login is shared. Run `mainwave-cli setup codex --profile <name>`,
491
+ then start Codex with `codex --profile <name>`. Login, MCP servers, project trust and history stay
492
+ shared. Profiles need Codex 0.169 or later, and setup and `doctor` warn on an older Codex.
493
+
494
+ For a profile, setup writes the telemetry settings and the Mainwave hooks into
495
+ `<codex home>/<name>.config.toml`, and writes none to `config.toml` or `hooks.json`. A session
496
+ started without `--profile <name>` sends nothing to Mainwave and runs no Mainwave hook. If the Codex
497
+ home already has the all-sessions setup, the same run removes it from `config.toml` and
498
+ `hooks.json`, so the home never holds both. The setup preview lists every file it changes. Once a
499
+ profile is set up, running setup again with the same `--profile` changes nothing. The first run on a
500
+ profile file that already has content appends Mainwave's hook tables at the end of the file, moves
501
+ any `[[hooks.<Event>]]` tables already there to join them, and keeps the rest as it was.
502
+
503
+ A profile name is 1 to 64 letters, digits, `_` or `-`, and does not start with `-`. `default` is
504
+ reserved by Codex. Setup refuses a name whose file already has an `[otel]` table that isn't
505
+ Mainwave's, so pick another name or remove that table. It also refuses, and leaves unchanged, a
506
+ profile file with `"""` or `'''` on any line, a comment included, since setup does not edit a file
507
+ with multi-line strings, and one with hooks written as keys (`[hooks]` with `Stop = [...]`) rather
508
+ than `[[hooks.<Event>]]` tables. `doctor` reports such a file as unreadable.
509
+
510
+ Setup writes no hook approvals. Start `codex --profile <name>` once and choose "Trust all" at the
511
+ "Hooks need review" prompt. Until then `codex exec --profile <name>` skips the Mainwave hooks.
512
+
513
+ Codex applies a profile to one process, so `codex resume` without `--profile <name>` sends nothing.
514
+ Add a separate alias, for example `alias codex-mw='codex --profile mainwave'`, and never one named
515
+ `codex`. `--profile` goes before the subcommand: `codex --profile mainwave exec resume <id>` resumes
516
+ with the profile, and `codex exec resume --profile mainwave` exits with an error.
517
+
518
+ `setup codex --remove` is not available for Codex. To remove a profile setup, delete
519
+ `<codex home>/<name>.config.toml` if it holds nothing else of yours, or remove its `[otel.*]` tables
520
+ and the `[[hooks.<Event>]]` tables whose commands name `mainwave-hook.sh` or `install-hooks`. That
521
+ file holds your Mainwave API key.
522
+
523
+ Plain `setup codex` in a home that has a profile setup asks whether to update the profile or to
524
+ switch to all sessions, which removes Mainwave from the profile file. Without a terminal it exits
525
+ with code 1 and names the `--profile` command, and `--yes` doesn't choose.
526
+
527
+ `doctor codex` checks the all-sessions setup and each profile setup it finds, each in a report of
528
+ its own. A profile's report is titled `Codex CLI, profile <name>`, lists the profile file as
529
+ `Profile <name>` and its hooks as `Profile <name> hooks file`, and checks the endpoint, the
530
+ authorization header, the metrics exporter and the hook approvals recorded in the profile file. It
531
+ warns when a home holds Mainwave settings or hooks for all sessions and in a profile at once. Codex
532
+ merges `config.toml` under the profile file table by table, so in profile sessions any header or
533
+ setting of another vendor's `[otel]` exporter in `config.toml` that the profile does not set is also
534
+ sent to Mainwave's collector. Mainwave's key is not sent to the other collector. `setup codex
535
+ --profile` and `doctor` both warn about that. `status codex` lists each profile setup by name after
536
+ the all-sessions files, and its `--json` output marks a profile entry with `"setup": "profile <name>"`.
474
537
 
475
538
  On Windows, the Claude Code hooks need Git for Windows. Claude Code runs hook commands through Git
476
539
  Bash, and through PowerShell when it finds none, where the entry's shell command can't run. Without
@@ -507,6 +570,11 @@ every settings file that installs the hooks and warns when two of them would fir
507
570
  ticket or PR. The org-wide setup follows how Claude Code 2.1.282 and later apply managed settings;
508
571
  `doctor` warns on an older install.
509
572
 
573
+ Mainwave's Org-wide setup page lists the developers whose Claude Code telemetry arrives while their
574
+ hooks send nothing, with the day their hooks stopped, or "Never". It lists apart the developers it
575
+ can't check: a session on an API key or a cloud provider sends no plan snapshot, so only their
576
+ commits, PRs and tickets send hook telemetry. Run `doctor` on such a developer's machine to check.
577
+
510
578
  Two kinds of session don't get the admin console's markers or plan snapshot:
511
579
 
512
580
  - A session that skips server-managed settings: one started with a `CLAUDE_CODE_USE_*` provider
@@ -1,9 +1,9 @@
1
1
  import { spawnSync } from 'node:child_process';
2
- import { accessSync, constants as fsConstants, promises as fs } from 'node:fs';
2
+ import { promises as fs } from 'node:fs';
3
3
  import { homedir } from 'node:os';
4
- import { delimiter, isAbsolute, join, resolve } from 'node:path';
4
+ import { join, resolve } from 'node:path';
5
5
  import { jsonEnvCodec } from '../core/codecs/json-env.js';
6
- import { hasBinary, hasPath } from '../core/detect.js';
6
+ import { hasBinary, hasPath, trustedBinary, trustedPath } from '../core/detect.js';
7
7
  import { tildify } from '../core/post-setup.js';
8
8
  import { isErrnoCode } from '../core/settings.js';
9
9
  const MANAGED_ENV_KEYS = [
@@ -238,24 +238,7 @@ const isHonoredOffValue = (key, value) => {
238
238
  return false;
239
239
  };
240
240
  let installedVersionCache;
241
- const trustedPath = (env = process.env) => (env.PATH ?? '')
242
- .split(delimiter)
243
- .filter((dir) => dir && isAbsolute(dir) && !/[\\/]node_modules[\\/]\.bin[\\/]?$/.test(dir))
244
- .join(delimiter);
245
- export const trustedClaudeBinary = (env = process.env) => {
246
- for (const dir of trustedPath(env).split(delimiter)) {
247
- if (!dir)
248
- continue;
249
- const candidate = join(dir, 'claude');
250
- try {
251
- accessSync(candidate, fsConstants.X_OK);
252
- return candidate;
253
- }
254
- catch {
255
- }
256
- }
257
- return undefined;
258
- };
241
+ export const trustedClaudeBinary = (env = process.env) => trustedBinary('claude', env);
259
242
  const installedClaudeCodeVersion = () => {
260
243
  if (process.platform === 'win32')
261
244
  return undefined;
@@ -1,9 +1,54 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { readdirSync, readFileSync, realpathSync } from 'node:fs';
1
3
  import { homedir } from 'node:os';
2
- import { join } from 'node:path';
4
+ import { join, resolve } from 'node:path';
3
5
  import { jsonEnvCodec } from '../core/codecs/json-env.js';
4
- import { hasBinary, hasPath } from '../core/detect.js';
6
+ import { hasBinary, hasPath, trustedBinary, trustedPath } from '../core/detect.js';
5
7
  import { tomlOtelCodec } from '../core/codecs/toml-otel.js';
8
+ import { tomlProfileCodec } from '../core/codecs/toml-profile.js';
6
9
  import { UCID_SOURCE_EXPLICIT } from '../core/headers.js';
10
+ import { versionAtLeast } from '../core/layer-policy.js';
11
+ import { commandOwnership } from '../core/markers.js';
12
+ export const codexHome = (env = process.env) => {
13
+ const dir = env.CODEX_HOME;
14
+ if (dir === undefined || dir === '')
15
+ return join(homedir(), '.codex');
16
+ try {
17
+ return realpathSync(resolve(dir));
18
+ }
19
+ catch {
20
+ return resolve(dir);
21
+ }
22
+ };
23
+ const LAUNCHER_HOME_MARKERS = [
24
+ { file: '.orca-managed-home', launcher: 'Orca' },
25
+ ];
26
+ export const codexHomeIssues = (env = process.env) => {
27
+ if (env.CODEX_HOME === undefined || env.CODEX_HOME === '')
28
+ return [];
29
+ const dir = codexHome(env);
30
+ const managed = LAUNCHER_HOME_MARKERS.find((m) => hasPath(join(dir, m.file)));
31
+ if (managed === undefined) {
32
+ return [
33
+ hasPath(dir)
34
+ ? { level: 'info', message: `CODEX_HOME is set, so Codex config and hooks live in ${dir}.` }
35
+ : {
36
+ level: 'warn',
37
+ message: `CODEX_HOME is set to ${dir}, which doesn't exist. Codex refuses to start until it does; ` +
38
+ 'setup creates it. Check the path if you expected an existing Codex home.',
39
+ },
40
+ ];
41
+ }
42
+ return [
43
+ {
44
+ level: 'warn',
45
+ message: `CODEX_HOME is set to ${dir}, a Codex home that ${managed.launcher} manages (it holds ${managed.file}). ` +
46
+ `Codex started outside ${managed.launcher} reads ~/.codex instead, and ${managed.launcher} may overwrite them when it syncs that copy. ` +
47
+ 'To set up the Codex you start yourself, run setup again with CODEX_HOME unset (`env -u CODEX_HOME …`) ' +
48
+ 'or set to the home you start Codex with.',
49
+ },
50
+ ];
51
+ };
7
52
  const SOURCE_VALUE = 'coding_agent.codex_cli';
8
53
  const SIGNAL_BLOCKS = ['exporter', 'trace_exporter', 'metrics_exporter'];
9
54
  const SIGNAL_PATH = {
@@ -130,7 +175,7 @@ const collectFileChecks = (scans) => {
130
175
  return issues;
131
176
  };
132
177
  const collectChecks = (env) => {
133
- const issues = [];
178
+ const issues = [...codexHomeIssues()];
134
179
  if (!env[endpointKey('metrics_exporter')]) {
135
180
  issues.push({
136
181
  level: 'warn',
@@ -145,56 +190,333 @@ const collectChecks = (env) => {
145
190
  });
146
191
  return issues;
147
192
  };
148
- const HIERARCHY = [
149
- {
150
- id: 'projectLocal',
151
- label: 'Project (local)',
152
- path: join('.codex', 'config.toml'),
153
- kind: 'file',
154
- },
155
- {
156
- id: 'user',
157
- label: 'User (global)',
158
- path: join(homedir(), '.codex', 'config.toml'),
159
- kind: 'file',
160
- },
161
- ];
162
- export const codexCli = {
163
- name: 'codex',
164
- displayName: 'Codex CLI',
165
- runInstruction: 'codex',
166
- detect: () => hasPath(join(homedir(), '.codex')) || hasBinary('codex'),
167
- instructionSurface: {
168
- kind: 'instructions-file',
169
- global: join(homedir(), '.codex', 'AGENTS.md'),
170
- local: 'AGENTS.md',
171
- label: 'AGENTS.md',
172
- },
173
- paths: {
174
- local: join('.codex', 'config.toml'),
175
- global: join(homedir(), '.codex', 'config.toml'),
193
+ export const CODEX_ADAPTER_NAME = 'codex';
194
+ const PROFILE_NAME_RE = /^[A-Za-z0-9_][A-Za-z0-9_-]{0,63}$/;
195
+ export const parseProfileName = (raw) => {
196
+ if (raw === undefined || raw === '') {
197
+ throw new Error('--profile requires a name, e.g. --profile mainwave');
198
+ }
199
+ if (!PROFILE_NAME_RE.test(raw)) {
200
+ throw new Error(`--profile ${JSON.stringify(raw)}: a profile name is 1 to 64 letters, digits, "_" or "-", ` +
201
+ 'not starting with "-"');
202
+ }
203
+ if (raw === 'default') {
204
+ throw new Error('--profile default: Codex reserves "default"; pick another name');
205
+ }
206
+ return raw;
207
+ };
208
+ export const homeTarget = (env = process.env) => ({
209
+ kind: 'home',
210
+ home: codexHome(env),
211
+ });
212
+ export const profileTarget = (profile, env = process.env) => ({ kind: 'profile', home: codexHome(env), profile });
213
+ const PROFILE_FILE_SUFFIX = '.config.toml';
214
+ export const profileFileName = (profile) => `${profile}${PROFILE_FILE_SUFFIX}`;
215
+ const profileFile = (home, profile) => join(home, profileFileName(profile));
216
+ export const profileProcessNote = (profile) => `The profile applies to one Codex process: a session started without \`--profile ${profile}\`, ` +
217
+ `\`codex resume\` included, sends nothing to Mainwave. Add a separate alias rather than ` +
218
+ `typing the flag, for example \`alias codex-mw='codex --profile ${profile}'\`.`;
219
+ const holdsMainwaveExporter = (env) => Object.keys(env).some((key) => {
220
+ const m = /^(otel\..+)\.headers\.X-Mainwave-Source$/.exec(key);
221
+ return (m !== null &&
222
+ env[`${m[1]}.endpoint`] !== undefined &&
223
+ env[`${m[1]}.headers.Authorization`] !== undefined);
224
+ });
225
+ const EXPORTER_KEY = /^otel\.(?:exporter|trace_exporter|metrics_exporter)\./;
226
+ const holdsOtherExporter = (env) => !holdsMainwaveExporter(env) && Object.keys(env).some((k) => EXPORTER_KEY.test(k));
227
+ export const otherExporterNote = (config, profiles) => `${config} has telemetry settings for another collector. Codex applies config.toml under ` +
228
+ `${profiles.map((p) => p.file).join(' and ')}, so in sessions started with ` +
229
+ `${profiles.map((p) => `\`codex --profile ${p.profile}\``).join(' or ')}, any header or setting ` +
230
+ "from that collector's exporter that the profile does not set is also sent to Mainwave's " +
231
+ "collector. Mainwave's key is not sent to the other collector. If that matters, move the other " +
232
+ "collector's settings into a profile file of their own, or set Mainwave up in a separate Codex " +
233
+ 'home with CODEX_HOME.';
234
+ export const profileOtherExporterWarning = (home, profile) => {
235
+ const config = join(home, 'config.toml');
236
+ let env;
237
+ try {
238
+ env = tomlOtelCodec.readEnv(tomlOtelCodec.parse(readFileSync(config, 'utf8'), config));
239
+ }
240
+ catch {
241
+ return undefined;
242
+ }
243
+ return holdsOtherExporter(env)
244
+ ? otherExporterNote(config, [{ profile, file: profileFile(home, profile) }])
245
+ : undefined;
246
+ };
247
+ const readConfigEnv = (path, codec = tomlProfileCodec) => {
248
+ try {
249
+ return codec.readEnv(codec.parse(readFileSync(path, 'utf8'), path));
250
+ }
251
+ catch {
252
+ return undefined;
253
+ }
254
+ };
255
+ const holdsProfileSetup = (path) => {
256
+ const env = readConfigEnv(path);
257
+ if (env !== undefined)
258
+ return holdsMainwaveExporter(env);
259
+ try {
260
+ return readFileSync(path, 'utf8').includes('X-Mainwave-Source');
261
+ }
262
+ catch {
263
+ return false;
264
+ }
265
+ };
266
+ export const findCodexProfileSetups = (home) => {
267
+ let names;
268
+ try {
269
+ names = readdirSync(home);
270
+ }
271
+ catch {
272
+ return [];
273
+ }
274
+ return names
275
+ .filter((n) => n.endsWith(PROFILE_FILE_SUFFIX))
276
+ .map((n) => n.slice(0, -PROFILE_FILE_SUFFIX.length))
277
+ .filter((n) => PROFILE_NAME_RE.test(n) && n !== 'default')
278
+ .filter((n) => holdsProfileSetup(profileFile(home, n)))
279
+ .sort();
280
+ };
281
+ export const profileConflict = (home, profile) => {
282
+ const path = profileFile(home, profile);
283
+ const env = readConfigEnv(path);
284
+ if (env === undefined || holdsMainwaveExporter(env))
285
+ return undefined;
286
+ if (!Object.keys(env).some((k) => k === 'otel' || k.startsWith('otel.')))
287
+ return undefined;
288
+ return (`${path} already has an [otel] table that is not Mainwave's. Setup won't replace another ` +
289
+ 'collector: pick another --profile name, or remove that table and re-run setup.');
290
+ };
291
+ const holdsMainwaveHooks = (path) => {
292
+ let doc;
293
+ try {
294
+ doc = JSON.parse(readFileSync(path, 'utf8'));
295
+ }
296
+ catch {
297
+ return false;
298
+ }
299
+ const hooks = doc?.hooks;
300
+ if (hooks === null || typeof hooks !== 'object')
301
+ return false;
302
+ return Object.values(hooks).some((groups) => Array.isArray(groups) &&
303
+ groups.some((g) => Array.isArray(g?.hooks) &&
304
+ g.hooks.some((h) => typeof h?.command === 'string' && commandOwnership(h.command) === 'cli')));
305
+ };
306
+ const codexDoctorSetups = (home) => {
307
+ const profiles = findCodexProfileSetups(home);
308
+ if (profiles.length === 0)
309
+ return undefined;
310
+ const allSessions = { kind: 'home', home };
311
+ const profileTargets = profiles.map((profile) => ({
312
+ kind: 'profile',
313
+ home,
314
+ profile,
315
+ }));
316
+ const { own: config, codec, hooksFile } = targetParts(allSessions);
317
+ const hooksJson = hooksFile.path;
318
+ const configEnv = readConfigEnv(config, codec) ?? {};
319
+ const homeConfig = holdsMainwaveExporter(configEnv);
320
+ const homeHooks = holdsMainwaveHooks(hooksJson);
321
+ const files = profileTargets.map((t) => targetParts(t).own).join(', ');
322
+ const which = `${profiles.length === 1 ? 'profile' : 'profiles'} ${profiles.join(', ')} (${files})`;
323
+ const rerun = `mainwave-cli setup codex --profile ${profiles.length === 1 ? profiles[0] : '<name>'}`;
324
+ const issues = [];
325
+ if (homeConfig) {
326
+ const where = homeHooks ? `${config} and ${hooksJson}` : config;
327
+ issues.push({
328
+ level: 'warn',
329
+ message: `Mainwave is set up for every Codex session (${where}) and in ${which}. Sessions started ` +
330
+ 'without --profile still send to Mainwave' +
331
+ (homeHooks ? ', and a session started with it runs the Mainwave hooks twice' : '') +
332
+ '. Run setup again with the route you want: ' +
333
+ `\`${rerun}\` keeps only the profile, \`mainwave-cli setup codex\` only every session.`,
334
+ });
335
+ }
336
+ else if (homeHooks) {
337
+ issues.push({
338
+ level: 'warn',
339
+ message: `Mainwave hooks are still in ${hooksJson}, which every Codex session runs, while the Mainwave ` +
340
+ `config is in ${which}. They send nothing, since ${config} has no Mainwave settings. ` +
341
+ `Run \`${rerun}\` again to remove them, or \`mainwave-cli setup codex\` to switch to every session.`,
342
+ });
343
+ }
344
+ else if (holdsOtherExporter(configEnv)) {
345
+ issues.push({
346
+ level: 'warn',
347
+ message: otherExporterNote(config, profileTargets.map((t, i) => ({ profile: profiles[i], file: targetParts(t).own }))),
348
+ });
349
+ }
350
+ return {
351
+ setups: [
352
+ ...(homeConfig ? [{ label: 'every session', adapter: codexCliFor(allSessions) }] : []),
353
+ ...profiles.map((profile, i) => ({
354
+ label: `profile ${profile}`,
355
+ adapter: codexCliFor(profileTargets[i]),
356
+ })),
357
+ ],
358
+ issues,
359
+ };
360
+ };
361
+ const projectLayer = {
362
+ id: 'projectLocal',
363
+ label: 'Project (local)',
364
+ path: join('.codex', 'config.toml'),
365
+ kind: 'file',
366
+ };
367
+ const userLayer = (home) => ({
368
+ id: 'user',
369
+ label: 'User (global)',
370
+ path: join(home, 'config.toml'),
371
+ kind: 'file',
372
+ });
373
+ let codexVersionCache;
374
+ export const CODEX_CLI = {
375
+ version: () => {
376
+ if (process.platform === 'win32')
377
+ return undefined;
378
+ if (!codexVersionCache) {
379
+ let value;
380
+ const bin = trustedBinary('codex');
381
+ try {
382
+ const r = bin
383
+ ? spawnSync(bin, ['--version'], {
384
+ encoding: 'utf8',
385
+ timeout: 5000,
386
+ env: { ...process.env, PATH: trustedPath() },
387
+ })
388
+ : undefined;
389
+ value = r?.status === 0 ? /\d+\.\d+\.\d+/.exec(r.stdout)?.[0] : undefined;
390
+ }
391
+ catch {
392
+ value = undefined;
393
+ }
394
+ codexVersionCache = { value };
395
+ }
396
+ return codexVersionCache.value;
176
397
  },
177
- injectsIdentity: true,
178
- codec: tomlOtelCodec,
179
- managedEnvKeys: MANAGED_ENV_KEYS,
180
- retiredEnvKeys: RETIRED_ENV_KEYS,
181
- alwaysOnOptIns: { toolDetails: true, toolContent: true },
182
- hierarchy: HIERARCHY,
183
- buildEnv,
184
- parseEnv,
185
- collectChecks,
186
- collectFileChecks,
187
- normalizeForGenericChecks,
188
- markers: {
189
- disclosure: 'Sends Linear/Jira issue ids and GitHub PR / GitLab MR urls to the collector — never ticket bodies or diff content. ' +
190
- 'It also sends, for each Codex turn, the session, turn and subagent ids, the working directory, the name of a tool ' +
191
- 'call waiting for your approval, and when the turn, the wait and the subagent started and ended — ids and ' +
192
- 'timestamps, never prompt or response text.',
193
- hooksFile: {
194
- path: join(homedir(), '.codex', 'hooks.json'),
195
- localPath: join('.codex', 'hooks.json'),
196
- codec: jsonEnvCodec,
398
+ };
399
+ const CODEX_PROFILE_MIN_VERSION = '0.169.0';
400
+ const tooOldForProfile = (version, profile) => version !== undefined && versionAtLeast(version, CODEX_PROFILE_MIN_VERSION) === false
401
+ ? `Codex ${version} is installed, and Codex reads profile files from ${CODEX_PROFILE_MIN_VERSION}, ` +
402
+ `so sessions started with \`codex --profile ${profile}\` send nothing to Mainwave until Codex is upgraded.`
403
+ : undefined;
404
+ const profileVersionIssues = (profile) => {
405
+ if (process.platform === 'win32')
406
+ return [];
407
+ const version = CODEX_CLI.version();
408
+ if (version === undefined) {
409
+ return [
410
+ {
411
+ level: 'info',
412
+ message: `Couldn't read the Codex version (\`codex --version\`); a profile setup needs Codex ` +
413
+ `${CODEX_PROFILE_MIN_VERSION} or later.`,
414
+ },
415
+ ];
416
+ }
417
+ const old = tooOldForProfile(version, profile);
418
+ return old === undefined ? [] : [{ level: 'warn', message: old }];
419
+ };
420
+ const profilePostSetup = (profile) => {
421
+ const old = tooOldForProfile(CODEX_CLI.version(), profile);
422
+ return `${old === undefined ? '' : `! ${old}\n`}` + profileNext(profile);
423
+ };
424
+ const profileNext = (profile) => `Next for Codex CLI: start \`codex --profile ${profile}\` and trust the Mainwave hooks once there ` +
425
+ `("Trust all" at the "Hooks need review" prompt). Until then \`codex exec --profile ${profile}\` ` +
426
+ `skips them. ${profileProcessNote(profile)}`;
427
+ const targetParts = (target) => {
428
+ const { home } = target;
429
+ const config = join(home, 'config.toml');
430
+ switch (target.kind) {
431
+ case 'home':
432
+ return {
433
+ own: config,
434
+ runInstruction: 'codex',
435
+ codec: tomlOtelCodec,
436
+ trustFiles: [config],
437
+ hierarchy: [projectLayer, userLayer(home)],
438
+ hooksFile: {
439
+ path: join(home, 'hooks.json'),
440
+ localPath: join('.codex', 'hooks.json'),
441
+ codec: jsonEnvCodec,
442
+ },
443
+ collectChecks,
444
+ kindOnly: { doctorSetups: () => codexDoctorSetups(home) },
445
+ };
446
+ case 'profile': {
447
+ const { profile } = target;
448
+ const own = profileFile(home, profile);
449
+ return {
450
+ own,
451
+ runInstruction: `codex --profile ${profile}`,
452
+ codec: tomlProfileCodec,
453
+ trustFiles: [config, own],
454
+ hierarchy: [
455
+ projectLayer,
456
+ { id: 'profile', label: `Profile ${profile}`, path: own, kind: 'file' },
457
+ userLayer(home),
458
+ ],
459
+ hooksFile: { path: own, codec: tomlProfileCodec },
460
+ hookArgs: ['--codex-profile', profile],
461
+ collectChecks: (env) => [
462
+ ...collectChecks(env),
463
+ { level: 'info', message: profileProcessNote(profile) },
464
+ ...profileVersionIssues(profile),
465
+ ],
466
+ kindOnly: {
467
+ codexProfile: profile,
468
+ replaces: [codexCliFor({ kind: 'home', home })],
469
+ setupArgs: ['--profile', profile],
470
+ printPostSetupInstructions: () => profilePostSetup(profile),
471
+ },
472
+ };
473
+ }
474
+ default: {
475
+ const unreachable = target;
476
+ throw new Error(`unknown Codex target ${JSON.stringify(unreachable)}`);
477
+ }
478
+ }
479
+ };
480
+ export const codexCliFor = (target) => {
481
+ const { home } = target;
482
+ const parts = targetParts(target);
483
+ return {
484
+ name: 'codex',
485
+ displayName: 'Codex CLI',
486
+ runInstruction: parts.runInstruction,
487
+ detect: () => hasPath(home) || hasBinary('codex'),
488
+ instructionSurface: {
489
+ kind: 'instructions-file',
490
+ global: join(home, 'AGENTS.md'),
491
+ local: 'AGENTS.md',
492
+ label: 'AGENTS.md',
197
493
  },
198
- runtimeTool: 'codex',
199
- },
494
+ paths: {
495
+ local: join('.codex', 'config.toml'),
496
+ global: parts.own,
497
+ },
498
+ trustFiles: parts.trustFiles,
499
+ injectsIdentity: true,
500
+ codec: parts.codec,
501
+ managedEnvKeys: MANAGED_ENV_KEYS,
502
+ retiredEnvKeys: RETIRED_ENV_KEYS,
503
+ alwaysOnOptIns: { toolDetails: true, toolContent: true },
504
+ hierarchy: parts.hierarchy,
505
+ buildEnv,
506
+ parseEnv,
507
+ collectChecks: parts.collectChecks,
508
+ collectFileChecks,
509
+ normalizeForGenericChecks,
510
+ holdsOwnSetup: holdsMainwaveExporter,
511
+ ...parts.kindOnly,
512
+ markers: {
513
+ disclosure: 'Sends Linear/Jira issue ids and GitHub PR / GitLab MR urls to the collector — never ticket bodies or diff content. ' +
514
+ 'It also sends, for each Codex turn, the session, turn and subagent ids, the working directory, the name of a tool ' +
515
+ 'call waiting for your approval, and when the turn, the wait and the subagent started and ended — ids and ' +
516
+ 'timestamps, never prompt or response text.',
517
+ hooksFile: parts.hooksFile,
518
+ runtimeTool: 'codex',
519
+ ...(parts.hookArgs === undefined ? {} : { hookArgs: parts.hookArgs }),
520
+ },
521
+ };
200
522
  };
@@ -1,6 +1,6 @@
1
1
  import { claudeCode } from './claude-code.js';
2
2
  import { claudeDesktop } from './claude-desktop.js';
3
- import { codexCli } from './codex-cli.js';
3
+ import { CODEX_ADAPTER_NAME, codexCliFor, homeTarget } from './codex-cli.js';
4
4
  import { copilotChat } from './copilot-chat.js';
5
5
  import { copilotCli } from './copilot-cli.js';
6
6
  import { cursor } from './cursor.js';
@@ -9,7 +9,9 @@ import { kiroCli, kiroIde } from './kiro.js';
9
9
  export const adapters = {
10
10
  [claudeCode.name]: claudeCode,
11
11
  [claudeDesktop.name]: claudeDesktop,
12
- [codexCli.name]: codexCli,
12
+ get [CODEX_ADAPTER_NAME]() {
13
+ return codexCliFor(homeTarget());
14
+ },
13
15
  [copilotChat.name]: copilotChat,
14
16
  [copilotCli.name]: copilotCli,
15
17
  [cursor.name]: cursor,
package/dist/commands.js CHANGED
@@ -76,6 +76,11 @@ export const COMMANDS = [
76
76
  ' the hooks still strip credentials by default',
77
77
  ' --no-redact-secrets stop stripping credentials (API keys, tokens, private keys) from',
78
78
  ' the spans the hooks send; --redact-secrets restores the default',
79
+ ' --profile <name> Codex only: send telemetry and run the Mainwave hooks only in',
80
+ ' sessions started with `codex --profile <name>`, from',
81
+ ' <codex home>/<name>.config.toml. Moves an all-sessions Codex',
82
+ ' setup there. Other tools named with it are set up as usual;',
83
+ ' without codex among the tools it is an error',
79
84
  ' --yes --json --no-verify --verify-timeout <seconds>',
80
85
  ' --skills / --no-skills install the agent skills payload (default: ask, or on in scripts)',
81
86
  ' --skills-only install only the skills, touching no telemetry config',
@@ -106,6 +111,7 @@ export const COMMANDS = [
106
111
  f('--no-skills'),
107
112
  f('--skills-only'),
108
113
  f('--remove'),
114
+ f('--profile'),
109
115
  removed('--scope'),
110
116
  ],
111
117
  },
@@ -163,7 +169,7 @@ export const COMMANDS = [
163
169
  },
164
170
  {
165
171
  name: 'install-hooks',
166
- usage: '[--quiet] [--host codex] [--redaction-packs <list>]',
172
+ usage: '[--quiet] [--host codex [--codex-profile <name>]] [--redaction-packs <list>]',
167
173
  summary: [
168
174
  'install or refresh the Mainwave hook entry and the',
169
175
  "latest release's hook scripts, with no prompts or",
@@ -171,11 +177,14 @@ export const COMMANDS = [
171
177
  "settings, and by setup's own session-start hook).",
172
178
  "--host codex: refresh Codex's hooks file instead of Claude",
173
179
  "Code's settings (run by the session-start hook in it)",
180
+ '--codex-profile <name>: refresh the hooks in that Codex',
181
+ "profile's file instead of hooks.json (run by the",
182
+ 'session-start hook in a profile file setup wrote)',
174
183
  "--redaction-packs: the packs an org's managed settings",
175
184
  'apply to every Mainwave hook; recorded only from them',
176
185
  ],
177
186
  adapters: 'none',
178
- flags: [f('--quiet'), f('--host'), f('--redaction-packs')],
187
+ flags: [f('--quiet'), f('--host'), f('--codex-profile'), f('--redaction-packs')],
179
188
  },
180
189
  ];
181
190
  export const isCommand = (name) => COMMANDS.some((c) => c.name === name);