π The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
feat(init): auto-detect OpenAI Codex CLI and configure its MCP server + skills (#2667)
rUvdc625e8a9948
diff --git a/v3/@claude-flow/cli/src/commands/init.ts b/v3/@claude-flow/cli/src/commands/init.tsindex bfc85359b4..4c85709805 100644--- a/v3/@claude-flow/cli/src/commands/init.ts+++ b/v3/@claude-flow/cli/src/commands/init.ts@@ -22,6 +22,7 @@ import {recordEnrollmentOutcome,shouldOfferEnrollment,} from '../funnel/enrollment.js';+import { commandExists } from '../services/harness-hosts.js';/*** ADR-302 post-init capability enrollment. One-time, interactive-TTY-only,@@ -54,6 +55,106 @@ async function offerCapabilityEnrollment(ctx: CommandContext): Promise<void> {}}+// Dynamic import of the optional @claude-flow/codex package. Returns+// undefined (never throws) when the package isn't resolvable anywhere β+// callers decide whether that's a hard error (explicit --codex/--dual) or a+// silent skip (auto-detect during a plain `ruflo init`).+interface CodexInitResult {+ success: boolean;+ errors?: string[];+ filesCreated: string[];+ skillsGenerated: string[];+ warnings?: string[];+}+type CodexInitializerCtor = new () => { initialize: (options: Record<string, unknown>) => Promise<CodexInitResult> };++async function resolveCodexInitializer(cwd: string): Promise<CodexInitializerCtor | undefined> {+ // Use a variable to prevent TypeScript from statically resolving the optional module+ const codexModuleId = '@claude-flow/codex';+ const resolutionStrategies = [+ // Strategy 1: Direct import (works if installed as CLI dependency)+ async () => (await import(codexModuleId)).CodexInitializer,+ // Strategy 2: Project node_modules (works if installed in user's project)+ async () => {+ const projectPath = path.join(cwd, 'node_modules', '@claude-flow', 'codex', 'dist', 'index.js');+ if (fs.existsSync(projectPath)) {+ const mod = await import(`file://${projectPath}`);+ return mod.CodexInitializer;+ }+ throw new Error('Not found in project');+ },+ // Strategy 3: Global node_modules+ async () => {+ const { execSync } = await import('child_process');+ const globalPath = execSync('npm root -g', { encoding: 'utf-8' }).trim();+ const codexPath = path.join(globalPath, '@claude-flow', 'codex', 'dist', 'index.js');+ if (fs.existsSync(codexPath)) {+ const mod = await import(`file://${codexPath}`);+ return mod.CodexInitializer;+ }+ throw new Error('Not found globally');+ },+ ];++ for (const strategy of resolutionStrategies) {+ try {+ const ctor = await strategy();+ if (ctor) return ctor;+ } catch {+ // Try next strategy+ }+ }+ return undefined;+}++// #2666-adjacent β quietly wire up Codex too when a plain `ruflo init` (no+// --codex/--dual) runs on a machine that also has the OpenAI Codex CLI on+// PATH: registers its MCP server and installs skills alongside the Claude+// Code setup that just happened. Best-effort and silent-by-default β must+// never fail or noisily interrupt a normal init. Opt out with+// --no-codex-detect. Skipped entirely under --skip-claude (runtime-only+// init) and scripted `--format json` output.+async function maybeAutoDetectCodex(+ ctx: CommandContext,+ options: { force: boolean; minimal: boolean; full: boolean },+): Promise<void> {+ try {+ if (ctx.flags['no-codex-detect'] === true) return;+ if (ctx.flags.format === 'json') return; // scripted output stays pure+ if (!commandExists('codex')) return;++ const CodexInitializer = await resolveCodexInitializer(ctx.cwd);+ if (!CodexInitializer) {+ output.writeln();+ output.printInfo('Detected the OpenAI Codex CLI β install @claude-flow/codex to auto-configure its MCP server and skills:');+ output.writeln(output.dim(' npm install @claude-flow/codex && ruflo init --codex'));+ return;+ }++ const initializer = new CodexInitializer();+ const result = await initializer.initialize({+ projectPath: ctx.cwd,+ template: (options.minimal ? 'minimal' : options.full ? 'full' : 'default') as 'minimal' | 'default' | 'full' | 'enterprise',+ force: options.force,+ dual: false, // Claude Code files were already written by the main init flow above+ });++ if (!result.success) return; // best-effort β never fail the primary init over this++ output.writeln();+ output.printBox(+ [+ `AGENTS.md: Codex project instructions`,+ `.agents/config.toml: MCP server + skills config`,+ `.agents/skills/: ${result.skillsGenerated.length} skills`,+ ].join('\n'),+ 'OpenAI Codex detected β configured'+ );+ } catch {+ // Codex auto-detect is a bonus, never a requirement β swallow everything.+ }+}+// Codex initialization actionasync function initCodexAction(ctx: CommandContext,@@ -72,52 +173,7 @@ async function initCodexAction(spinner.start();try {- // Dynamic import of the Codex initializer with lazy loading fallback- interface CodexInitResult {- success: boolean;- errors?: string[];- filesCreated: string[];- skillsGenerated: string[];- warnings?: string[];- }- let CodexInitializer: (new () => { initialize: (options: Record<string, unknown>) => Promise<CodexInitResult> }) | undefined;-- // Try multiple resolution strategies for the @claude-flow/codex package- // Use a variable to prevent TypeScript from statically resolving the optional module- const codexModuleId = '@claude-flow/codex';- const resolutionStrategies = [- // Strategy 1: Direct import (works if installed as CLI dependency)- async () => (await import(codexModuleId)).CodexInitializer,- // Strategy 2: Project node_modules (works if installed in user's project)- async () => {- const projectPath = path.join(ctx.cwd, 'node_modules', '@claude-flow', 'codex', 'dist', 'index.js');- if (fs.existsSync(projectPath)) {- const mod = await import(`file://${projectPath}`);- return mod.CodexInitializer;- }- throw new Error('Not found in project');- },- // Strategy 3: Global node_modules- async () => {- const { execSync } = await import('child_process');- const globalPath = execSync('npm root -g', { encoding: 'utf-8' }).trim();- const codexPath = path.join(globalPath, '@claude-flow', 'codex', 'dist', 'index.js');- if (fs.existsSync(codexPath)) {- const mod = await import(`file://${codexPath}`);- return mod.CodexInitializer;- }- throw new Error('Not found globally');- },- ];-- for (const strategy of resolutionStrategies) {- try {- CodexInitializer = await strategy();- if (CodexInitializer) break;- } catch {- // Try next strategy- }- }+ const CodexInitializer = await resolveCodexInitializer(ctx.cwd);if (!CodexInitializer) {throw new Error('Cannot find module @claude-flow/codex');@@ -428,6 +484,11 @@ const initAction = async (ctx: CommandContext): Promise<CommandResult> => {output.writeln();}+ // #2666-adjacent β auto-detect + configure OpenAI Codex CLI if present+ if (!skipClaude) {+ await maybeAutoDetectCodex(ctx, { force, minimal, full });+ }+// Handle --start-all or --start-daemonconst startAll = ctx.flags['start-all'] || ctx.flags.startAll;const startDaemon = ctx.flags['start-daemon'] || ctx.flags.startDaemon || startAll;@@ -1263,6 +1324,12 @@ export const initCommand: Command = {type: 'boolean',default: false,},+ {+ name: 'no-codex-detect',+ description: 'Skip auto-detecting the OpenAI Codex CLI and configuring its MCP server + skills',+ type: 'boolean',+ default: false,+ },{name: 'all-agents',description: 'Install all agent categories (ADR-128: default is ~24 substrate agents; this restores the full set of ~89)',@@ -1290,6 +1357,7 @@ export const initCommand: Command = {{ command: 'claude-flow init --codex', description: 'Initialize for OpenAI Codex (AGENTS.md)' },{ command: 'claude-flow init --codex --full', description: 'Codex init with all 137+ skills' },{ command: 'claude-flow init --dual', description: 'Initialize for both Claude Code and Codex' },+ { command: 'claude-flow init --no-codex-detect', description: 'Skip auto-configuring OpenAI Codex even if it is installed' },{ command: 'claude-flow init --all-agents', description: 'Install all agent categories (~89 agents; ADR-128 opt-in)' },],action: initAction,diff --git a/v3/@claude-flow/codex/src/initializer.ts b/v3/@claude-flow/codex/src/initializer.tsindex 871438ed00..428435f7cb 100644--- a/v3/@claude-flow/codex/src/initializer.ts+++ b/v3/@claude-flow/codex/src/initializer.ts@@ -330,14 +330,35 @@ export class CodexInitializer {};}- // Check if already registered+ // Check if already registered. Prefer the structured `--json` output+ // (each entry has a `name` field β confirmed current as of the 2026+ // `codex mcp` CLI) over a plain substring match against the human+ // -readable table, which false-positives on any server whose name or+ // command merely contains "ruflo" and breaks silently if the table+ // formatting changes.try {- const list = execSync('codex mcp list 2>&1', { encoding: 'utf-8' });- if (list.includes('ruflo')) {+ const listJson = execSync('codex mcp list --json 2>&1', { encoding: 'utf-8' });+ const parsed = JSON.parse(listJson);+ // Confirmed shape (2026 `codex mcp` CLI) is a bare array; tolerate a+ // future `{ servers: [...] }` wrapper but otherwise treat an+ // unrecognized shape as "unknown" rather than silently concluding+ // not-registered β falls through to the safe text-based fallback.+ const servers = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.servers) ? parsed.servers : null;+ if (!servers) throw new Error('unrecognized `codex mcp list --json` shape');+ if (servers.some((s: unknown) => s && typeof s === 'object' && (s as { name?: unknown }).name === 'ruflo')) {return { registered: true }; // Already registered}} catch {- // Ignore list errors+ // --json unsupported (older codex CLI) or unparsable β fall back to+ // the plain-text listing so registration still no-ops idempotently.+ try {+ const list = execSync('codex mcp list 2>&1', { encoding: 'utf-8' });+ if (list.includes('ruflo')) {+ return { registered: true };+ }+ } catch {+ // Ignore list errors β fall through to (re-)register below.+ }}// Register the MCP serverdiff --git a/v3/implementation/adrs/ADR-080-codex-auto-detect-on-init.md b/v3/implementation/adrs/ADR-080-codex-auto-detect-on-init.mdnew file mode 100644index 0000000000..37edbd42d4--- /dev/null+++ b/v3/implementation/adrs/ADR-080-codex-auto-detect-on-init.md@@ -0,0 +1,123 @@+# ADR-080: Auto-Detect OpenAI Codex CLI During `ruflo init`++## Status: ACCEPTED β implemented++## Date: 2026-07-14++## Authors: Claude Flow Team++## Context++ADR-027 added first-class Codex support to `ruflo init` β `AGENTS.md`, `.agents/config.toml`,+`.agents/skills/`, and MCP server registration via the separate `@claude-flow/codex` package.+But that whole path is **opt-in only**: it runs exclusively behind the explicit `--codex` or+`--dual` flags (`v3/@claude-flow/cli/src/commands/init.ts`, `initCodexAction`). A developer who+has the OpenAI Codex CLI installed alongside Claude Code, and runs a plain `ruflo init`, gets+nothing for Codex β no MCP server, no skills β unless they already know the flag exists.++Separately, `services/harness-hosts.ts` (ADR-176 phase 7, MetaHarness fan-out) already+maintains a small host-detection registry with a working `codex` adapter+(`detect: () => commandExists('codex')`), but nothing in the `init` path reused it β the+`@claude-flow/codex` package's own `registerMCPServer()` does its own ad hoc `which codex`+check instead.++Before writing new code against the real Codex CLI, its actual current MCP/skills surface was+verified against OpenAI's live docs (not assumed from training-data priors, which for a+fast-moving external CLI are unreliable):++- `developers.openai.com/codex/mcp` (β `learn.chatgpt.com/docs/extend/mcp?surface=cli`):+ `codex mcp add <name> [--env K=V ...] -- <command> [args...]`, config stored under+ `[mcp_servers.<name>]` in `~/.codex/config.toml` (or a trusted project's `.codex/config.toml`),+ `codex mcp list` / `list --json` / `get <name>` / `remove <name>`.+- `developers.openai.com/codex/skills` (β `learn.chatgpt.com/docs/build-skills`): Codex scans+ `.agents/skills` from cwd up through the repo root, then `$HOME/.agents/skills`, then+ `/etc/codex/skills` β a `SKILL.md` with `name` + `description` frontmatter per skill.++Both match what `@claude-flow/codex` already generates β the package's core mechanics were not+stale. The one real gap: `registerMCPServer()` checked "already registered" by substring+-matching `'ruflo'` against the human-readable `codex mcp list` table, which false-positives on+any unrelated server whose name/command happens to contain "ruflo" and silently breaks if the+table formatting changes. `codex mcp list --json` (confirmed current: an array of objects, each+with a `name` field) is the robust, intended way to check this.++## Decision++1. **Auto-detect during plain `ruflo init`.** `commands/init.ts`'s `initAction` now calls a new+ `maybeAutoDetectCodex()` after the normal Claude Code init succeeds (only when `--codex`/+ `--dual` weren't already explicitly used, since those already cover this). It:+ - Returns immediately, silently, if `codex` isn't on `PATH` (`commandExists('codex')`,+ imported from `services/harness-hosts.ts` β reusing the existing detection convention+ instead of duplicating it a third time).+ - If `codex` is present but `@claude-flow/codex` isn't resolvable, prints one informational+ line with the install hint β never an error, never a failed exit code.+ - If both are present, resolves `CodexInitializer` (the same three-strategy dynamic-import+ resolution `initCodexAction` already used β extracted into a shared+ `resolveCodexInitializer()` helper so both call sites stay in sync) and calls+ `initialize({ ..., dual: false })`. `dual: false` is deliberate: the Claude Code files were+ already written by the main init flow moments earlier, so this only adds the Codex-side+ artifacts (`AGENTS.md`, `.agents/config.toml`, `.agents/skills/`, MCP registration) without+ re-touching `CLAUDE.md`.+ - Wrapped in a top-level `try/catch` that swallows everything β this is a bonus, never a+ requirement, and must not affect `ruflo init`'s exit code or interrupt Claude Code setup.+ - Skipped under `--skip-claude` (runtime-only init) and `--format json` (scripted output+ stays pure), and can be turned off explicitly with `--no-codex-detect`.++2. **Revise `registerMCPServer()`** (`v3/@claude-flow/codex/src/initializer.ts`) to check+ `codex mcp list --json` first, matching on the `name` field, with the old plain-text+ substring check kept only as a fallback for an older Codex CLI that doesn't support `--json`+ or an unrecognized response shape.++## Consequences++### Positive+- Zero-flag Codex support: a machine with both `claude` and `codex` on `PATH` gets both+ configured by one `ruflo init`, matching how the rest of this session's work made previously+ -manual steps (statusline promo, AgentDB memory) the default.+- The "already registered" check no longer false-positives/silently-breaks on CLI output format+ drift.+- No new required dependency β `@claude-flow/codex` remains fully optional; its absence degrades+ to a one-line hint, matching the MetaHarness "removable augmentation" pattern this codebase+ already follows elsewhere (ADR-150 Β§"architectural constraint").++### Negative+- One more thing happening silently during `init` β a user who has `codex` installed for+ unrelated reasons (not intending to use it with this project) gets `.agents/` files created+ without being asked. Mitigated by `--no-codex-detect` and by `initialize()`'s own+ don't-overwrite-without-`--force` behavior on repeat runs.+- Adds one more `execFileSync('codex', ['--version'])` / `execSync('codex mcp list --json')`+ subprocess spawn to every `ruflo init` run on a machine with Codex installed (bounded by a+ 3s timeout in `commandExists`).++### Mitigations+- Silent-by-default, best-effort, never fails the primary init.+- `--no-codex-detect` opt-out.+- Detection reuses the existing `harness-hosts.ts` registry rather than adding a fourth ad hoc+ `which codex` check.++## Implementation++- `v3/@claude-flow/cli/src/commands/init.ts` β `resolveCodexInitializer()` (extracted, shared),+ `maybeAutoDetectCodex()` (new), wired into `initAction` after the Claude Code summary output;+ `--no-codex-detect` flag registered.+- `v3/@claude-flow/codex/src/initializer.ts` β `registerMCPServer()` now checks+ `codex mcp list --json` first, text-substring fallback second.++## Success Metrics++- `ruflo init` on a machine with `codex` + `@claude-flow/codex` installed produces+ `.agents/config.toml`, `.agents/skills/`, `AGENTS.md`, and a `ruflo` entry in+ `codex mcp list --json` β without any `--codex`/`--dual` flag.+- `ruflo init` on a machine without `codex` on `PATH` behaves byte-for-byte identically to+ before this change (no new files, no new output).+- `ruflo init --no-codex-detect` on a machine with `codex` present produces no Codex-side+ artifacts.++## Related Decisions++- [ADR-027: Codex Integration](ADR-027-codex-integration.md) β the underlying `--codex`/`--dual`+ flags and `@claude-flow/codex` package this ADR auto-triggers.+- [ADR-176](.) β MetaHarness host fan-out, origin of `services/harness-hosts.ts`'s+ `commandExists`/`codex` detection convention reused here.+- ADR-034 (`Optional MCP Backends β Claude Code, Gemini, Codex`, chat-ui-mcp bridge repo) β a+ sibling decision in a different subsystem treating Codex as an opt-in backend; not the same+ code path but the same "Codex is optional, degrade gracefully" posture.