Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor([issue-3618]): collapse per-vendor CLI/TUI dispatch into a PROVIDER_VENDORS registry

[._.]/ Adam Eivydb51ddfd7f19
diff --git a/server/cos-runner/allowedCommands.js b/server/cos-runner/allowedCommands.js
index f1c2c0fc6b..5603c74b30 100644
--- a/server/cos-runner/allowedCommands.js
+++ b/server/cos-runner/allowedCommands.js
@@ -6,6 +6,7 @@
*/
import { basename } from 'path';
+import { PROVIDER_VENDORS, EXTRA_ALLOWED_COMMANDS } from '../lib/providerVendors.js';
/**
* Commands permitted to be spawned by the runner.
@@ -14,18 +15,15 @@ import { basename } from 'path';
* the toolkit's `providers.sample.json`) MUST appear here — a provider whose
* command is missing 400s at `/spawn-tui` and the agent dies before it ever gets
* a shell. `allowedCommands.test.js` enforces that parity.
+ *
+ * Derived from PROVIDER_VENDORS (#3618) so a new vendor row automatically
+ * becomes spawnable here without a second hand-maintained list, plus
+ * EXTRA_ALLOWED_COMMANDS for legacy/custom commands with no vendor row
+ * (aider, copilot).
*/
export const ALLOWED_COMMANDS = new Set([
- 'claude',
- 'aider',
- 'codex',
- 'copilot',
- 'agy',
- 'cursor-agent',
- 'gemini',
- 'grok',
- 'kimi',
- 'opencode'
+ ...PROVIDER_VENDORS.map((vendor) => vendor.inferredCommand),
+ ...EXTRA_ALLOWED_COMMANDS,
]);
/**
diff --git a/server/lib/README.md b/server/lib/README.md
index fe665c1729..da3278e125 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -109,6 +109,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `promptPartials.js` | Mustache-style partial expansion. |
| `mediaModels.js` | Single source of truth for image/video model metadata. |
| `providerModels.js` | Provider model resolution sentinels + helpers (`CODEX_CONFIGURED_DEFAULT` / `ANTIGRAVITY_CONFIGURED_DEFAULT` / `GROK_CONFIGURED_DEFAULT` / `KIMI_CONFIGURED_DEFAULT`, `resolveCliModel`, `filterSelectableModels`, Bedrock/OpenCode model mappers, model-flag scan helpers incl. `stripBrokenModelFlags`, `isCodexProvider`, `isKimiProvider`, `isAntigravityProvider`) plus reasoning-effort helpers for the claude/codex/agy CLIs (`CLAUDE_EFFORT_LEVELS` / `CODEX_EFFORT_LEVELS` / `ANTIGRAVITY_EFFORT_LEVELS` / `EFFORT_LEVELS`, `effortLevelsForProvider`, `resolveCliEffort` — clamps an out-of-range effort to the nearest level the target CLI accepts rather than dropping it, so a value saved against a wider ladder survives a provider switch — `hasEffortFlag`, and `buildEffortArgs` — the one emitter of `--effort <level>` / `-c model_reasoning_effort=<level>`) plus codex startup-arg helpers (`CODEX_UPDATE_CHECK_KEY`, `hasCodexUpdateCheckConfig`, `buildCodexStartupArgs` — the one emitter of `-c check_for_update_on_startup=false`, spread by every codex spawn builder to disable the blocking startup update modal). |
+| `providerVendors.js` | `PROVIDER_VENDORS` — one row per coding-agent CLI/TUI vendor (claude/codex/antigravity/opencode/grok/kimi/cursor, plus a deliberately-incomplete legacy `gemini-cli` row), consumed by every dispatch site that used to hand-roll its own vendor if-chain across ~8 branches in 5 files (#3618): `applyCommandDefaults`/`prepareCliPrompt` (re-exported from `tuiHandshake.js`/`cliProviderArgs.js`), `buildVendorCliArgs`/`buildVendorSpawnConfig` (consumed by `cliProviderArgs.js#buildCliArgs` / `agentCliSpawning.js#buildCliSpawnConfig`), `inferTuiCommand` (re-exported from `tuiHandshake.js`), and `injectTuiModelAndEffort` — the shared antigravity-validates-the-pair-vs-everyone-else `--model`/`--effort` injection used by both `tuiHandshake.js#buildTuiInvocation` and `agentTuiSpawning.js#buildTuiSpawnConfig`, replacing a second copy of that split that had already drifted once before this file existed. Doesn't rewrite any vendor's argv-building logic — that stays in `antigravity.js`/`grok.js`/`kimi.js`/`cursor.js`/`codex.js`. Dependency-light on purpose, mirroring those files. |
| `modelPricing.js` | Per-model API billing rates for the /devtools/usage cost estimates — `resolveModelRates(providerId, model)` (exact → family regex → provider default → blended fallback, with a `matched` tier; also derives `cacheReadPer1M`/`cacheWritePer1M` from the input rate via per-family multipliers), `isFreeProvider` (ollama/lmstudio/`ollamaBacked`/localhost = free), `estimateCostUsd(tokensIn, tokensOut, rates, cache?)` — `tokensIn` is UNCACHED input; cache tiers are priced separately via the optional 4th arg — and `PRICING_AS_OF`. Informational only (PortOS runs on subscriptions); still excludes batch/long-context tiers. |
| `usageRange.js` | `resolveUsageRange({ period, from, to })` — pure period→inclusive-YYYY-MM-DD range resolution for the usage cost report (explicit dates win; `all` unbounded; default 7d). |
| `providerTranscriptUsage.js` | Parsers for the real per-message token counts the coding CLIs write to disk (0 tokens to read) — `parseClaudeTranscript` (`~/.claude/projects/<cwd-slug>/*.jsonl`), `parseCodexRollout` (`~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`), `claudeProjectSlug`, `totalTranscriptTokens`. Both de-duplicate a format hazard that otherwise inflates counts badly: Claude repeats one response across several lines sharing a `message.id`, and Codex's `total_token_usage` is cumulative and repeated. Each parser returns per-model buckets (`byModel`) plus the message keys it counted (`countedKeys`), and accepts an `exclude` set — that is what stops two overlapping PortOS runs from both billing the same messages. Tolerant of truncated (mid-write) files; consumed by `services/usageReconciler.js`. |
@@ -116,6 +117,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `cliChildEnv.js` | The one place the AI-CLI child environment is composed, replacing the hand-rolled copy every spawn site carried — which made each env-level fix an N-file sweep (#3194). `buildCliChildEnv({ baseEnv, before, provider, model, cwd, extra, guard })` returns a COMPLETE env for `spawn`: layers `baseEnv → before → provider.envVars → buildOpencodeEnvVars → extra`, pins `PWD` to `cwd`, strips `CLAUDECODE`, and (with `guard: true`) prepends the pm2 guard shim onto the final `PATH`. `composeProviderEnv({ before, provider, model, extra })` returns just the ordered provider layers, for sites that build a DELTA someone else bases and spawns (the CoS runner payload, a shell-session overlay). The two slots are not interchangeable: `before` sits UNDER `provider.envVars` (forgeTokenEnv/claudeSettingsEnv, so a provider override still wins), `extra` sits OVER it (TERM/COLORTERM for a PTY). `cliChildEnv.test.js` asserts the composed order per call site and **discovers** any new site that hand-rolls the tuple instead of calling these — so the call-site list stays in the test, not in prose here. |
| `cliProviderArgs.js` | Per-CLI argv conventions (`buildCliArgs`) for stdin prompt delivery — dependency-light extraction from runner.js so out-of-process callers (autofixer) can import it. |
| `cliProviderRun.js` | One-shot CLI provider invocation (`pickCliProvider` + `runCliProviderPrompt`) — lightweight path for the autofixer + calendar MCP sync to honor the configured provider/model. |
+| `codex.js` | OpenAI Codex CLI (`codex`) provider helpers — the `CODEX_COMMAND`/`CODEX_CLI_ID` constants, the `isCodexCommand` predicate, and `ensureCodexTuiArgs` (injects `--dangerously-bypass-approvals-and-sandbox` + disables the startup update-check config, skipped when the argv already declares an approval/sandbox posture via `argvHasFlag`). Extracted from `tuiHandshake.js` (#3618) to match the one-file-per-vendor shape of `antigravity.js`/`grok.js`/`kimi.js`/`cursor.js`, which `providerVendors.js` consumes as registry rows. |
| `cursor.js` | Cursor Agent (`cursor-agent`) provider helpers — the `CURSOR_COMMAND` binary constant, the `isCursorCommand` predicate, and the `ensureCursorHeadlessArgs` (`--print --force`) / `ensureCursorTuiArgs` (`--force`) argv builders. `--force` is load-bearing beyond approvals: it also clears cursor's workspace-trust gate, which otherwise EXITS a headless run before any work happens. The prompt rides raw stdin (like claude/codex, unlike grok/kimi), and cursor needs no configured-default sentinel — its `auto` router is a real model id passed straight to `--model`. |
| `grok.js` | xAI Grok Build (`grok`) provider helpers — id/endpoint constants (`GROK_API_ID`/`GROK_CLI_ID`/`GROK_TUI_ID`/`GROK_API_ENDPOINT`), `isGrokCommand`/`isGrokCliProvider`/`isGrokTuiProvider` predicates, `ensureGrokHeadlessArgs`/`ensureGrokTuiArgs` argv builders (grok reads its prompt from `--prompt-file /dev/stdin`, not raw stdin; model selection uses the `GROK_CONFIGURED_DEFAULT` sentinel in `providerModels.js` so PortOS omits `--model` like Antigravity), and `prepareGrokPromptFile` (Windows temp-file delivery fallback). |
| `grokVideoClip.js` | Clip lengths grok's `image_to_video` actually delivers — `GROK_VIDEO_DURATIONS` (`[6, 10]`, measured in #3022: a 2s/3s request returns the same 6.04s clip), `GROK_VIDEO_DEFAULT_DURATION`, `resolveGrokDuration()` (validate an already-grok-shaped request, else default), and `nearestGrokDuration()` (round a length authored against another backend's continuous contract UP to the shortest clip that covers it — for translating a CD/commission `targetDurationSeconds`). Dependency-free so `validation.js` / `routes/videoGen.js` can derive their schemas from the same list the services gate on. |
diff --git a/server/lib/cliProviderArgs.js b/server/lib/cliProviderArgs.js
index e65370cc8c..28fb74b319 100644
--- a/server/lib/cliProviderArgs.js
+++ b/server/lib/cliProviderArgs.js
@@ -19,11 +19,12 @@
* - Claude Code: `-p -` (+ `--model <id>`)
*/
-import { resolveCliModel, hasModelFlag, resolveBedrockCliModel, prefixOpencodeModel, isOpencodeCommand, buildCodexStartupArgs, buildEffortArgs, stripBrokenModelFlags } from './providerModels.js';
-import { ensureAntigravityPrintArgs, isAntigravityCliProvider, isAntigravityCommand, prepareAntigravityPrompt } from './antigravity.js';
-import { isGrokCommand, ensureGrokHeadlessArgs, prepareGrokPromptFile } from './grok.js';
-import { isKimiCommand, ensureKimiHeadlessArgs, prepareKimiPrompt } from './kimi.js';
-import { isCursorCommand, ensureCursorHeadlessArgs } from './cursor.js';
+import { resolveCliModel, stripBrokenModelFlags } from './providerModels.js';
+// buildVendorCliArgs / prepareCliPrompt dispatch through the PROVIDER_VENDORS
+// registry (#3618) instead of a hand-rolled per-vendor if-chain — see
+// providerVendors.js for the vendor rows and its own dependency-light note
+// (this module must stay importable from the standalone autofixer process).
+import { buildVendorCliArgs, prepareCliPrompt } from './providerVendors.js';
/**
* Build CLI args based on provider type. Each CLI provider has different
@@ -43,124 +44,17 @@ import { isCursorCommand, ensureCursorHeadlessArgs } from './cursor.js';
* codex, and is suppressed when the saved args already bake an effort pin.
*/
export function buildCliArgs(provider) {
- const providerId = provider?.id || '';
const effort = provider?.effort || null;
// Sanitize: drop any broken/dangling `--model` / `-m` tokens before
- // appending. hasModelFlag treats those as "not a real pin" so the
- // injection path fires — but if we kept the bogus token in baseArgs the
- // CLI would still see two `--model` occurrences and reject the argv.
+ // appending. hasModelFlag (in providerVendors.js's per-vendor arg builders)
+ // treats those as "not a real pin" so the injection path fires — but if we
+ // kept the bogus token in baseArgs the CLI would still see two `--model`
+ // occurrences and reject the argv.
const baseArgs = stripBrokenModelFlags(Array.isArray(provider?.args) ? provider.args : []);
// Configured-default sentinels (Codex / Antigravity / Grok Build) resolve to
// null so the CLI uses its own latest/default model without a --model flag.
const effectiveDefaultModel = resolveCliModel(provider.defaultModel);
-
- // Codex CLI: `codex exec -` reads prompt from stdin, --model for model.
- // Detect an existing leading `exec` in user/legacy args so we don't end up
- // running `codex exec --full-auto exec -` after migration of legacy
- // configs that already pinned an `exec` subcommand.
- if (providerId === 'codex') {
- const hasExec = baseArgs.includes('exec');
- const args = hasExec ? [...baseArgs] : [...baseArgs, 'exec'];
- // Disable codex's startup update check (see buildCodexStartupArgs) so a run
- // never stalls on the update-check network round-trip or an unattended
- // `brew upgrade` it can't complete headless. No-op when the user pinned it.
- args.push(...buildCodexStartupArgs(baseArgs));
- if (effectiveDefaultModel) {
- args.push('--model', effectiveDefaultModel);
- }
- args.push(...buildEffortArgs(effort, provider, args));
- args.push('-'); // stdin marker
- return args;
- }
-
- // Antigravity CLI (`agy`) replaces the old Gemini CLI for Google's coding
- // agent. Print mode is the headless one-shot interface; the prompt is spliced
- // in as the trailing `--print` value at spawn time (see prepareCliPrompt).
- // `--model` is honored like every other CLI here — the configured-default
- // sentinel resolves to null so agy falls back to its own configured model.
- if (isAntigravityCliProvider(provider)) {
- return ensureAntigravityPrintArgs(baseArgs, {
- model: effectiveDefaultModel,
- effort,
- models: provider?.models,
- });
- }
-
- // Grok Build CLI (`grok`): headless one-shot. The prompt is delivered through
- // `--prompt-file /dev/stdin` (grok reads a single-turn prompt from a file, not
- // raw stdin) so PortOS's existing stdin write feeds it unchanged — see grok.js.
- // `--output-format plain` + `--permission-mode bypassPermissions` are injected
- // there unless the user pinned their own. Model flag gated like the others.
- if (isGrokCommand(provider?.command)) {
- return ensureGrokHeadlessArgs(baseArgs, effectiveDefaultModel);
- }
-
- // Kimi Code CLI (`kimi`): headless one-shot. `--print` runs non-interactive
- // print mode (implies `--afk`, so tool calls auto-approve). The prompt is NOT
- // over stdin — it's spliced in as the `--prompt <value>` at spawn time by
- // prepareKimiPrompt (see below). Model flag gated like the others; the
- // configured-default sentinel resolves to null so `--model` is omitted.
- if (isKimiCommand(provider?.command)) {
- return ensureKimiHeadlessArgs(baseArgs, effectiveDefaultModel);
- }
-
- // Cursor Agent CLI (`cursor-agent`): headless one-shot. `--print` reads the
- // prompt from raw stdin (so the shared stdin delivery works unchanged) and
- // `--force` clears cursor's workspace-trust gate — which otherwise EXITS
- // instead of running — while also auto-approving tool calls. Both are injected
- // by ensureCursorHeadlessArgs unless the user pinned their own. Cursor's `auto`
- // model is a real id, not a sentinel, so it rides `--model` like any other.
- if (isCursorCommand(provider?.command)) {
- return ensureCursorHeadlessArgs(baseArgs, effectiveDefaultModel);
- }
-
- // OpenCode CLI (`opencode run`): the headless, non-interactive subcommand. It
- // reads the prompt from stdin (the runner's shell-pipeline delivery, same as
- // every other CLI here) and selects the model with `-m provider/model`. The
- // OpenCode Ollama provider is namespaced `ollama/<model>` (see
- // prefixOpencodeModel). Ensure the `run` subcommand leads the argv even if the
- // saved provider.args dropped it. Model injection is gated on the user not
- // having hard-coded a `--model`/`-m` of their own, mirroring the claude/gemini
- // gate below.
- if (isOpencodeCommand(provider?.command)) {
- const args = baseArgs.includes('run') ? [...baseArgs] : ['run', ...baseArgs];
- const model = prefixOpencodeModel(provider, effectiveDefaultModel);
- if (model && !hasModelFlag(baseArgs)) {
- args.push('-m', model);
- }
- return args;
- }
-
- // Gemini CLI: prompt is piped via stdin directly. `-m <model>` is gemini-
- // cli's documented short flag for model selection (long form: `--model`).
- // Skip injection when the user's saved args already pin a model (either
- // form) so we don't duplicate the flag.
- if (providerId === 'gemini-cli') {
- const args = [...baseArgs];
- if (effectiveDefaultModel && !hasModelFlag(baseArgs)) {
- args.push('-m', effectiveDefaultModel);
- }
- return args;
- }
-
- // Default (Claude Code CLI): `-p -` means "read prompt from stdin".
- // `--model <id>` is claude-code's model flag; it parses flags
- // positionally so appending after `-p -` is fine. Same gate as gemini-
- // cli — respect user-baked model flags.
- const args = [...baseArgs, '-p', '-'];
- if (effectiveDefaultModel && !hasModelFlag(baseArgs)) {
- // On a Bedrock box a bare `claude-opus-5` is rejected — map it to the
- // region-prefixed Bedrock id just-in-time (no-op off Bedrock / for
- // already-prefixed ids). provider.envVars carries CLAUDE_CODE_USE_BEDROCK
- // for the bedrock provider variants; process.env covers a Bedrock host.
- const model = resolveBedrockCliModel(effectiveDefaultModel, {
- env: { ...process.env, ...provider?.envVars },
- providerId,
- });
- args.push('--model', model);
- }
- args.push(...buildEffortArgs(effort, provider, args));
- return args;
+ return buildVendorCliArgs(provider, baseArgs, { model: effectiveDefaultModel, effort });
}
/**
@@ -183,16 +77,11 @@ export function buildCliArgs(provider) {
* @param {string[]} args - argv as built by buildCliArgs
* @param {string} prompt - the full prompt text
* @returns {{ args: string[], useStdin: boolean, cleanup: () => void }}
+ *
+ * Defined in providerVendors.js (the PROVIDER_VENDORS registry, #3618);
+ * re-exported here for existing importers of this module.
*/
-export function prepareCliPrompt(command, args, prompt) {
- if (isAntigravityCommand(command)) {
- return prepareAntigravityPrompt(args, prompt);
- }
- if (isKimiCommand(command)) {
- return prepareKimiPrompt(args, prompt);
- }
- return prepareGrokPromptFile(args, prompt);
-}
+export { prepareCliPrompt };
// Re-exported from providerModels.js (its home, next to `hasModelFlag`, so the
// antigravity arg builders can share it without importing this module and
diff --git a/server/lib/codex.js b/server/lib/codex.js
new file mode 100644
index 0000000000..24057606d2
--- /dev/null
+++ b/server/lib/codex.js
@@ -0,0 +1,58 @@
+/**
+ * Per-CLI conventions for OpenAI's Codex CLI (binary: `codex`).
+ *
+ * Extracted from `tuiHandshake.js` (where `ensureCodexTuiArgs` used to live as a
+ * private helper) so codex has the same one-file-per-vendor shape as
+ * antigravity.js / grok.js / kimi.js / cursor.js — the shape `providerVendors.js`
+ * consumes as its `PROVIDER_VENDORS` registry rows (#3618).
+ *
+ * Dependency-light on purpose: imports only `providerModels.js` helpers,
+ * mirroring the other vendor files so it stays importable from the standalone
+ * autofixer.
+ */
+
+import { argvHasFlag, buildCodexStartupArgs, commandBasename } from './providerModels.js';
+
+export const CODEX_COMMAND = 'codex';
+export const CODEX_CLI_ID = 'codex';
+
+/**
+ * Match by normalized binary basename (like isGrokCommand/isKimiCommand) so a
+ * path- or `.exe`-configured provider is still recognized.
+ * @param {string|null|undefined} command
+ * @returns {boolean}
+ */
+export function isCodexCommand(command) {
+ return commandBasename(command) === CODEX_COMMAND;
+}
+
+// An approval/sandbox posture already pinned by the user (separated or
+// joined `flag=value` form, via the shared argvHasFlag scan) — codex has no
+// joined form for the two boolean flags, but checking for one is harmless.
+const APPROVAL_POLICY_FLAGS = [
+ '--ask-for-approval', '-a',
+ '--sandbox', '-s',
+ '--dangerously-bypass-approvals-and-sandbox',
+ '--yolo',
+];
+
+// True when the codex argv already declares an approval/sandbox posture, so
+// injecting `--dangerously-bypass-approvals-and-sandbox` would collide with it.
+function codexHasApprovalPolicy(args) {
+ return argvHasFlag(args, APPROVAL_POLICY_FLAGS);
+}
+
+// Disable codex's startup update check (see buildCodexStartupArgs in
+// providerModels.js for the full "Update available!" modal failure mode) and
+// inject the full-yolo bypass. Both are prepended; the update-check disable is
+// independent of the approval posture (the modal is orthogonal to sandboxing),
+// so it rides even when a provider pins its own policy, while the bypass flag is
+// skipped when the argv already declares an approval/sandbox posture.
+export function ensureCodexTuiArgs(args) {
+ const prefix = [];
+ if (!codexHasApprovalPolicy(args)) {
+ prefix.push('--dangerously-bypass-approvals-and-sandbox');
+ }
+ prefix.push(...buildCodexStartupArgs(args));
+ return prefix.length ? [...prefix, ...args] : args;
+}
diff --git a/server/lib/index.js b/server/lib/index.js
index 2e1f8fc7fd..baf2d1aea2 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -92,6 +92,7 @@ export * as antigravity from './antigravity.js';
export * from './cliChildEnv.js';
export * from './cliProviderArgs.js';
export * from './cliProviderRun.js';
+export * from './codex.js';
export * from './codexAssistantExtract.js';
export * from './codexCliOutput.js';
export * from './contextBudget.js';
@@ -113,6 +114,11 @@ export * from './promptRunner.js';
export * from './promptSystemStages.js';
export * from './promptTemplate.js';
export * from './providerModels.js';
+// Namespaced: providerVendors.js re-exports `inferTuiCommand` /
+// `applyCommandDefaults` (from tuiHandshake.js) and `prepareCliPrompt` (from
+// cliProviderArgs.js), which would trip the barrel's duplicate-identifier
+// collision check as flat exports.
+export * as providerVendors from './providerVendors.js';
export * from './providerTranscriptUsage.js';
export * from './quotaBurnConfig.js';
export * from './quotaBurnPresets.js';
diff --git a/server/lib/providerVendors.js b/server/lib/providerVendors.js
new file mode 100644
index 0000000000..0812d2d0c2
--- /dev/null
+++ b/server/lib/providerVendors.js
@@ -0,0 +1,414 @@
+/**
+ * `PROVIDER_VENDORS` — one row per coding-agent CLI/TUI vendor, consumed by
+ * every dispatch point that used to open-code its own vendor if-chain (#3618).
+ *
+ * Before this file, adding a vendor meant touching ~8 branches across 5 files,
+ * and two of them (the TUI model-injection sites) had already drifted apart
+ * before being collapsed into `resolveInjectedTuiModel` — see the doc comment
+ * on that function in `providerModels.js` for the incident. This registry
+ * doesn't rewrite any vendor's actual argv-building logic (that stays in
+ * antigravity.js / grok.js / kimi.js / cursor.js / codex.js, each already
+ * dependency-light and already the "one file per vendor" precedent) — it just
+ * gives every dispatch site ONE table to walk instead of a hand-duplicated
+ * if-chain, so a new vendor is one row instead of N call sites.
+ *
+ * Each row is intentionally sparse: a vendor only defines the fields the sites
+ * that need special-casing for it require. A field left `undefined` means
+ * "this vendor has no special case here — fall through to the generic/default
+ * behavior", exactly matching what the original if-chains did for e.g. claude
+ * and opencode in `applyCommandDefaults` (both fell through unchanged).
+ *
+ * Two per-vendor "identity" checks exist because the original dispatch sites
+ * gated on different things:
+ * - `matchCommand(command)` — basename-based (`isXCommand`), used by
+ * `applyCommandDefaults` / `prepareCliPrompt` (tuiHandshake.js /
+ * cliProviderArgs.js) and by `inferTuiCommand`'s id-substring walk.
+ * - `matchCliProvider(provider)` — provider-level, used by `buildCliArgs` /
+ * `buildCliSpawnConfig`. Most vendors match by command alone, which is
+ * identical to `matchCommand(provider?.command)` — those rows OMIT
+ * `matchCliProvider` and `matchesProvider()` falls back to `matchCommand`
+ * for them. Only codex and the legacy gemini-cli row (match by
+ * `provider.id` alone — their command is inferred, never configured) and
+ * antigravity (matches by id OR command, `isAntigravityCliProvider`)
+ * define their own `matchCliProvider`.
+ *
+ * `claude` MUST stay the LAST row: its `matchCommand`/`matchCliProvider` both
+ * return true unconditionally (it's the historical default), so every
+ * `.find()` below would short-circuit on it if it came first.
+ *
+ * The legacy `gemini-cli` row is a deliberately incomplete vendor: no live
+ * provider in `data.reference/providers.json` uses it (Gemini CLI was
+ * migrated to Antigravity — see `antigravity.js`'s `LEGACY_GEMINI_CLI_ID`),
+ * but old stored configs may still carry it, so `buildCliArgs` and
+ * `inferTuiCommand` still recognize it. It intentionally has no `tuiArgs`,
+ * `preparePrompt`, or `spawnArgs` — matching every one of those dispatch
+ * sites' pre-existing (lack of) gemini-cli handling exactly, including
+ * `buildCliSpawnConfig`'s asymmetry (it has never had a gemini-cli arm, so a
+ * gemini-cli provider silently falls through to the claude row there, exactly
+ * as it did before this file existed).
+ *
+ * Dependency-light on purpose (mirrors cliProviderArgs.js / grok.js / kimi.js /
+ * cursor.js / codex.js): imports only the vendor files above, providerModels.js,
+ * and node builtins, so it stays importable from the standalone autofixer
+ * process (which pulls in cliProviderArgs.js and must NOT drag in the AI
+ * toolkit / data layer).
+ */
+
+import {
+ resolveCliModel,
+ hasModelFlag,
+ resolveInjectedTuiModel,
+ resolveBedrockCliModel,
+ buildCodexStartupArgs,
+ buildEffortArgs,
+ isOpencodeCommand,
+ prefixOpencodeModel,
+ applyLeanClaudeArgs,
+} from './providerModels.js';
+import { isCodexCommand, ensureCodexTuiArgs, CODEX_COMMAND, CODEX_CLI_ID } from './codex.js';
+import {
+ ANTIGRAVITY_COMMAND,
+ isAntigravityCommand,
+ isAntigravityCliProvider,
+ ensureAntigravityTuiArgs,
+ ensureAntigravityPrintArgs,
+ prepareAntigravityPrompt,
+ resolveAntigravityModelAndEffort,
+} from './antigravity.js';
+import { isGrokCommand, ensureGrokTuiArgs, ensureGrokHeadlessArgs, prepareGrokPromptFile } from './grok.js';
+import { isKimiCommand, ensureKimiTuiArgs, ensureKimiHeadlessArgs, prepareKimiPrompt } from './kimi.js';
+import { CURSOR_COMMAND, isCursorCommand, ensureCursorTuiArgs, ensureCursorHeadlessArgs } from './cursor.js';
+
+/**
+ * For every vendor EXCEPT codex/claude, `buildCliSpawnConfig`'s argv is just
+ * `cliArgs` called against `provider.args` (instead of a pre-sanitized
+ * `baseArgs`) plus a static `stdinMode`/fallback `command` — there's no
+ * independent per-vendor spawn convention to preserve. Codex (never forwards
+ * `provider.args`) and claude (an entirely different flag set + streamFormat)
+ * keep their own dedicated `spawnArgs`.
+ */
+function defaultSpawnArgs(cliArgsFn, fallbackCommand) {
+ return (provider, { effectiveModel, effort }) => ({
+ command: provider?.command || fallbackCommand,
+ args: cliArgsFn(provider?.args || [], { model: effectiveModel, effort, provider }),
+ stdinMode: 'prompt',
+ });
+}
+
+// ─── codex ──────────────────────────────────────────────────────────────────
+
+function codexCliArgs(baseArgs, { model, effort, provider }) {
+ // Detect an existing leading `exec` in user/legacy args so we don't end up
+ // running `codex exec --full-auto exec -` after migration of legacy
+ // configs that already pinned an `exec` subcommand.
+ const hasExec = baseArgs.includes('exec');
+ const args = hasExec ? [...baseArgs] : [...baseArgs, 'exec'];
+ args.push(...buildCodexStartupArgs(baseArgs));
+ if (model) {
+ args.push('--model', model);
+ }
+ args.push(...buildEffortArgs(effort, provider, args));
+ args.push('-'); // stdin marker
+ return args;
+}
+
+function codexSpawnArgs(provider, { effectiveModel, effort }) {
+ // Injected UNCONDITIONALLY: this arm builds codex's argv from scratch and
+ // never forwards provider.args, so there's no pin to detect here (see the
+ // long-form comment history on this in agentCliSpawning.js before #3618).
+ const args = ['exec', '--dangerously-bypass-approvals-and-sandbox', ...buildCodexStartupArgs()];
+ if (effectiveModel) {
+ args.push('--model', effectiveModel);
+ }
+ args.push(...buildEffortArgs(effort, provider, args));
+ return { command: provider?.command || CODEX_COMMAND, args, stdinMode: 'prompt' };
+}
+
+const CODEX = {
+ id: 'codex',
+ idFragment: 'codex',
+ inferredCommand: CODEX_COMMAND,
+ matchCommand: isCodexCommand,
+ matchCliProvider: (provider) => provider?.id === CODEX_CLI_ID,
+ tuiArgs: ensureCodexTuiArgs,
+ cliArgs: codexCliArgs,
+ spawnArgs: codexSpawnArgs,
+};
+
+// ─── antigravity ────────────────────────────────────────────────────────────
+
+function antigravityCliArgs(baseArgs, { model, effort, provider }) {
+ return ensureAntigravityPrintArgs(baseArgs, { model, effort, models: provider?.models });
+}
+
+const ANTIGRAVITY = {
+ id: 'antigravity',
+ idFragment: 'antigravity',
+ inferredCommand: ANTIGRAVITY_COMMAND,
+ matchCommand: isAntigravityCommand,
+ // Antigravity is the one non-codex/gemini vendor matched by id OR command
+ // (isAntigravityCliProvider), not command alone — keep its own row.
+ matchCliProvider: isAntigravityCliProvider,
+ tuiArgs: ensureAntigravityTuiArgs,
+ cliArgs: antigravityCliArgs,
+ preparePrompt: prepareAntigravityPrompt,
+ spawnArgs: defaultSpawnArgs(antigravityCliArgs, ANTIGRAVITY_COMMAND),
+};
+
+// ─── opencode ───────────────────────────────────────────────────────────────
+
+function opencodeCliArgs(baseArgs, { model, provider }) {
+ const args = baseArgs.includes('run') ? [...baseArgs] : ['run', ...baseArgs];
+ const resolvedModel = prefixOpencodeModel(provider, model);
+ if (resolvedModel && !hasModelFlag(baseArgs)) {
+ args.push('-m', resolvedModel);
+ }
+ return args;
+}
+
+const OPENCODE = {
+ id: 'opencode',
+ idFragment: 'opencode',
+ inferredCommand: 'opencode',
+ matchCommand: isOpencodeCommand,
+ // No dedicated matchCliProvider — matches by command, same as matchCommand
+ // (buildVendorCliArgs/buildVendorSpawnConfig fall back to matchCommand when
+ // matchCliProvider is absent).
+ cliArgs: opencodeCliArgs,
+ spawnArgs: defaultSpawnArgs(opencodeCliArgs, 'opencode'),
+};
+
+// ─── grok ───────────────────────────────────────────────────────────────────
+
+function grokCliArgs(baseArgs, { model }) {
+ return ensureGrokHeadlessArgs(baseArgs, model);
+}
+
+const GROK = {
+ id: 'grok',
+ idFragment: 'grok',
+ inferredCommand: 'grok',
+ matchCommand: isGrokCommand,
+ // No dedicated matchCliProvider — matches by command, same as matchCommand.
+ tuiArgs: ensureGrokTuiArgs,
+ cliArgs: grokCliArgs,
+ spawnArgs: defaultSpawnArgs(grokCliArgs, 'grok'),
+};
+
+// ─── kimi ───────────────────────────────────────────────────────────────────
+
+function kimiCliArgs(baseArgs, { model }) {
+ return ensureKimiHeadlessArgs(baseArgs, model);
+}
+
+const KIMI = {
+ id: 'kimi',
+ idFragment: 'kimi',
+ inferredCommand: 'kimi',
+ matchCommand: isKimiCommand,
+ // No dedicated matchCliProvider — matches by command, same as matchCommand.
+ tuiArgs: ensureKimiTuiArgs,
+ cliArgs: kimiCliArgs,
+ preparePrompt: prepareKimiPrompt,
+ spawnArgs: defaultSpawnArgs(kimiCliArgs, 'kimi'),
+};
+
+// ─── cursor ─────────────────────────────────────────────────────────────────
+
+function cursorCliArgs(baseArgs, { model }) {
+ return ensureCursorHeadlessArgs(baseArgs, model);
+}
+
+const CURSOR = {
+ id: 'cursor',
+ idFragment: 'cursor',
+ inferredCommand: CURSOR_COMMAND,
+ matchCommand: isCursorCommand,
+ // No dedicated matchCliProvider — matches by command, same as matchCommand.
+ tuiArgs: ensureCursorTuiArgs,
+ cliArgs: cursorCliArgs,
+ spawnArgs: defaultSpawnArgs(cursorCliArgs, CURSOR_COMMAND),
+};
+
+// ─── gemini (legacy — see file header) ─────────────────────────────────────
+
+const GEMINI_LEGACY = {
+ id: 'gemini-legacy',
+ idFragment: 'gemini',
+ inferredCommand: 'gemini',
+ matchCommand: (command) => command != null && String(command).toLowerCase().includes('gemini'),
+ matchCliProvider: (provider) => provider?.id === 'gemini-cli',
+ cliArgs: (baseArgs, { model }) => {
+ const args = [...baseArgs];
+ if (model && !hasModelFlag(baseArgs)) {
+ args.push('-m', model);
+ }
+ return args;
+ },
+ // No tuiArgs / preparePrompt / spawnArgs — see file header on why this row
+ // is deliberately incomplete.
+};
+
+// ─── claude (default fallback — MUST stay last) ────────────────────────────
+
+function claudeCliArgs(baseArgs, { model, effort, provider }) {
+ const args = [...baseArgs, '-p', '-'];
+ if (model && !hasModelFlag(baseArgs)) {
+ const resolvedModel = resolveBedrockCliModel(model, {
+ env: { ...process.env, ...provider?.envVars },
+ providerId: provider?.id || '',
+ });
+ args.push('--model', resolvedModel);
+ }
+ args.push(...buildEffortArgs(effort, provider, args));
+ return args;
+}
+
+function claudeSpawnArgs(provider, { effectiveModel, effort, systemPromptFile, settingsEnv }) {
+ const providerId = provider?.id || 'claude-code';
+ const args = applyLeanClaudeArgs(provider, [
+ '--dangerously-skip-permissions',
+ '--print',
+ '--output-format', 'stream-json',
+ '--verbose',
+ '--include-partial-messages',
+ ...(provider?.args || []),
+ ], provider?.command || 'claude');
+ if (systemPromptFile) {
+ args.push('--append-system-prompt-file', systemPromptFile);
+ }
+ if (effectiveModel) {
+ const injectedModel = resolveBedrockCliModel(effectiveModel, {
+ env: { ...process.env, ...settingsEnv, ...provider?.envVars },
+ providerId,
+ });
+ args.push('--model', injectedModel);
+ }
+ const command = provider?.command || process.env.CLAUDE_PATH || 'claude';
+ args.push(...buildEffortArgs(effort, { id: providerId, command }, args));
+ return { command, args, stdinMode: 'prompt', streamFormat: 'stream-json' };
+}
+
+const CLAUDE = {
+ id: 'claude',
+ idFragment: null, // never matched by id.includes() — it's the outside-the-loop default
+ inferredCommand: 'claude',
+ // The historical default: matches everything (no dedicated matchCliProvider
+ // — falls back to this same always-true matchCommand). MUST stay the last
+ // row so this doesn't short-circuit every other vendor's lookup.
+ matchCommand: () => true,
+ cliArgs: claudeCliArgs,
+ spawnArgs: claudeSpawnArgs,
+};
+
+/**
+ * One row per vendor, ordered to double as `inferTuiCommand`'s historical
+ * id-substring check order (codex, antigravity, cursor, gemini, kimi, grok,
+ * opencode — preserved in case a contrived id ever contained more than one
+ * vendor's fragment) with `claude` last. `claude` MUST stay last: its
+ * `matchCommand` returns true unconditionally (it's the historical default),
+ * so every `.find()` below would short-circuit on it if it came first. Order
+ * among the rest doesn't otherwise matter for the command/provider-based
+ * dispatchers — every `matchCommand`/`matchCliProvider` pair is mutually
+ * exclusive by construction (distinct binary basenames, or a provider-id
+ * check that doesn't overlap with a command-basename check).
+ */
+export const PROVIDER_VENDORS = [CODEX, ANTIGRAVITY, CURSOR, GEMINI_LEGACY, KIMI, GROK, OPENCODE, CLAUDE];
+
+/**
+ * A row's `matchCliProvider` may be absent when it's identical to
+ * `matchCommand(provider?.command)` (true for every vendor except codex,
+ * antigravity, and the legacy gemini-cli row, which match by provider id).
+ */
+function matchesProvider(vendor, provider) {
+ return vendor.matchCliProvider ? vendor.matchCliProvider(provider) : vendor.matchCommand(provider?.command);
+}
+
+/**
+ * `inferTuiCommand`'s id-substring walk (tuiHandshake.js) checks a DIFFERENT
+ * thing than every other dispatch site here — `provider.id` substrings, not
+ * `provider.command` basenames — so it can't reuse `matchCommand`/`.find()`.
+ * It still sources every returned command string from `PROVIDER_VENDORS`
+ * (via `idFragment`/`inferredCommand`) so it can't independently drift; only
+ * `claude` has no `idFragment` (it's the true fallback below, not matched by
+ * substring).
+ */
+export function inferTuiCommand(id) {
+ if (!id) return CLAUDE.inferredCommand;
+ for (const vendor of PROVIDER_VENDORS) {
+ if (vendor.idFragment && id.includes(vendor.idFragment)) return vendor.inferredCommand;
+ }
+ return CLAUDE.inferredCommand;
+}
+
+/** `applyCommandDefaults` (tuiHandshake.js): TUI posture-flag dispatch. */
+export function applyCommandDefaults(command, args) {
+ const vendor = PROVIDER_VENDORS.find((v) => v.tuiArgs && v.matchCommand(command));
+ return vendor ? vendor.tuiArgs(args) : args;
+}
+
+/**
+ * `prepareCliPrompt` (cliProviderArgs.js): spawn-time prompt delivery.
+ * `prepareGrokPromptFile` is the universal DEFAULT (not gated on grok, per its
+ * own doc comment — it's a no-op for any argv that isn't its own /dev/stdin
+ * sentinel, so calling it unconditionally as the fallback is safe and matches
+ * the original `prepareCliPrompt` body exactly).
+ */
+export function prepareCliPrompt(command, args, prompt) {
+ const vendor = PROVIDER_VENDORS.find((v) => v.preparePrompt && v.matchCommand(command));
+ return vendor ? vendor.preparePrompt(args, prompt) : prepareGrokPromptFile(args, prompt);
+}
+
+/** `buildCliArgs` (cliProviderArgs.js): headless one-shot argv per vendor. */
+export function buildVendorCliArgs(provider, baseArgs, { model, effort }) {
+ const vendor = PROVIDER_VENDORS.find((v) => v.cliArgs && matchesProvider(v, provider));
+ return vendor.cliArgs(baseArgs, { model, effort, provider });
+}
+
+/**
+ * `buildCliSpawnConfig` (agentCliSpawning.js): full `{ command, args,
+ * stdinMode, streamFormat? }` shape per vendor. Requires `spawnArgs` to be
+ * defined on the matched row — `gemini-legacy` deliberately has none, so a
+ * gemini-cli provider here falls through to `claude`'s row, exactly as it did
+ * before this registry existed (see file header).
+ */
+export function buildVendorSpawnConfig(provider, ctx) {
+ const vendor = PROVIDER_VENDORS.find((v) => v.spawnArgs && matchesProvider(v, provider));
+ return vendor.spawnArgs(provider, ctx);
+}
+
+/**
+ * Shared TUI model+effort injection — the piece that had ALREADY drifted once
+ * before #3618 was filed (an antigravity Bedrock exemption landed in
+ * `tuiHandshake.js#buildTuiInvocation` and was missed in
+ * `agentTuiSpawning.js#appendModelArgs`). Both call sites now call this one
+ * function instead of hand-duplicating the antigravity-vs-everyone-else split.
+ *
+ * `baseArgs` must already be the POST-`applyCommandDefaults` argv (posture
+ * flags applied) — this only handles `--model`/`--effort` injection.
+ */
+export function injectTuiModelAndEffort(command, baseArgs, provider, model, effort) {
+ if (isAntigravityCommand(command)) {
+ // agy validates the (model, effort) PAIR — resolved together against the
+ // provider's catalog (see antigravity.js).
+ const resolved = resolveAntigravityModelAndEffort(baseArgs, { model, effort, models: provider?.models });
+ const withModel = resolved.model ? [...baseArgs, '--model', resolved.model] : baseArgs;
+ return [...withModel, ...buildEffortArgs(resolved.effort, resolved.provider, withModel, resolved.base)];
+ }
+ const effectiveModel = resolveCliModel(model);
+ const shouldInject = !!effectiveModel && !hasModelFlag(baseArgs);
+ // Per-command model rewriting (OpenCode namespacing, Bedrock mapping) lives
+ // in resolveInjectedTuiModel, shared across both TUI spawn paths so they
+ // can't diverge again.
+ const withModel = shouldInject
+ ? [...baseArgs, '--model', resolveInjectedTuiModel(effectiveModel, provider, command)]
+ : baseArgs;
+ return [...withModel, ...buildEffortArgs(effort, { id: provider?.id, command }, withModel)];
+}
+
+// Every command a shipped vendor row resolves to, PLUS legacy/custom commands
+// with no corresponding PROVIDER_VENDORS row (no vendor file, no dispatch
+// special-casing — just historically allowlisted). allowedCommands.js derives
+// its Set from this so a new vendor row automatically becomes spawnable
+// without a second hand-maintained list.
+export const EXTRA_ALLOWED_COMMANDS = ['aider', 'copilot'];
diff --git a/server/lib/tuiHandshake.js b/server/lib/tuiHandshake.js
index afe3ca0b49..3a3f0b6a5a 100644
--- a/server/lib/tuiHandshake.js
+++ b/server/lib/tuiHandshake.js
@@ -12,11 +12,11 @@
* No cycle risk: this module imports nothing from either consumer.
*/
-import { resolveCliModel, hasModelFlag, resolveInjectedTuiModel, buildCodexStartupArgs, buildEffortArgs, commandBasename } from './providerModels.js';
-import { ensureAntigravityTuiArgs, isAntigravityCommand, resolveAntigravityModelAndEffort } from './antigravity.js';
-import { ensureGrokTuiArgs, isGrokCommand } from './grok.js';
-import { ensureKimiTuiArgs, isKimiCommand } from './kimi.js';
-import { CURSOR_COMMAND, ensureCursorTuiArgs, isCursorCommand } from './cursor.js';
+// inferTuiCommand / applyCommandDefaults are RE-EXPORTED below (not defined
+// here) — the per-vendor dispatch they used to hand-roll now lives in the
+// PROVIDER_VENDORS registry (#3618), consumed by every dispatch site that
+// used to duplicate its own vendor if-chain.
+import { inferTuiCommand, applyCommandDefaults, injectTuiModelAndEffort } from './providerVendors.js';
// ─── Paste handshake constants ────────────────────────────────────────────
@@ -860,20 +860,13 @@ export const RAW_SPOOL_MAX_BYTES = 256 * 1024 * 1024;
* asks "which command will actually be spawned?" before deciding whether the
* session can type `/do:pr` — so a missing signature here means a provider is
* told to run slash commands its real binary doesn't have.
+ *
+ * Defined in providerVendors.js (the PROVIDER_VENDORS registry, #3618);
+ * re-exported here for existing importers of this module.
* @param {string|null|undefined} id - provider id
* @returns {string}
*/
-export function inferTuiCommand(id) {
- if (!id) return 'claude';
- if (id.includes('codex')) return 'codex';
- if (id.includes('antigravity')) return 'agy';
- if (id.includes('cursor')) return CURSOR_COMMAND;
- if (id.includes('gemini')) return 'gemini';
- if (id.includes('kimi')) return 'kimi';
- if (id.includes('grok')) return 'grok';
- if (id.includes('opencode')) return 'opencode';
- return 'claude';
-}
+export { inferTuiCommand };
/**
* True when the given TUI command renders the elapsed working counter
@@ -896,63 +889,12 @@ export function rendersWorkCounter(commandName) {
return lower.includes('claude') || lower.includes('codex');
}
-// Codex TUI blocks on every tool approval AND sandboxes file/network writes
-// unless we run it fully bypassed. There's no human-at-keyboard for headless
-// calls (one-shot OR agent), so inject the full-yolo flag — the same posture
-// the CLI/exec path uses in `agentCliSpawning.js`. The bypass flag is mutually
-// exclusive with `--ask-for-approval` / `--sandbox`, so don't add it when the
-// provider config already pins an approval/sandbox/bypass policy of its own.
-// We ALSO disable codex's startup update check (see ensureCodexTuiArgs) —
-// independent of the approval posture, so it's injected even when a provider
-// pins its own policy. Match codex by BASENAME (`commandBasename`), not a strict
-// `=== 'codex'`: a provider commonly configures the absolute binary path
-// (`/opt/homebrew/bin/codex`, what `which codex` returns), and a strict match
-// would skip both the bypass flag and the update-check disable — leaving that
-// headless TUI to wedge on the update modal. A wrapper like `my-codex-wrapper`
-// has a non-`codex` basename and still (correctly) owns its own argv.
-export function applyCommandDefaults(command, args) {
- if (commandBasename(command) === 'codex') {
- return ensureCodexTuiArgs(args);
- }
- if (isAntigravityCommand(command)) {
- return ensureAntigravityTuiArgs(args);
- }
- if (isGrokCommand(command)) {
- return ensureGrokTuiArgs(args);
- }
- if (isKimiCommand(command)) {
- return ensureKimiTuiArgs(args);
- }
- if (isCursorCommand(command)) {
- return ensureCursorTuiArgs(args);
- }
- return args;
-}
-
-// Disable codex's startup update check (see buildCodexStartupArgs in
-// providerModels.js for the full "Update available!" modal failure mode) and
-// inject the full-yolo bypass. Both are prepended; the update-check disable is
-// independent of the approval posture (the modal is orthogonal to sandboxing),
-// so it rides even when a provider pins its own policy, while the bypass flag is
-// skipped when the argv already declares an approval/sandbox posture.
-function ensureCodexTuiArgs(args) {
- const prefix = [];
- if (!codexHasApprovalPolicy(args)) {
- prefix.push('--dangerously-bypass-approvals-and-sandbox');
- }
- prefix.push(...buildCodexStartupArgs(args));
- return prefix.length ? [...prefix, ...args] : args;
-}
-
-// True when the codex argv already declares an approval/sandbox posture, so
-// injecting `--dangerously-bypass-approvals-and-sandbox` would collide with it.
-function codexHasApprovalPolicy(args) {
- return args.some(arg =>
- arg === '--ask-for-approval' || arg === '-a' || arg.startsWith('-a=') || arg.startsWith('--ask-for-approval=') ||
- arg === '--sandbox' || arg === '-s' || arg.startsWith('-s=') || arg.startsWith('--sandbox=') ||
- arg === '--dangerously-bypass-approvals-and-sandbox' || arg === '--yolo'
- );
-}
+/**
+ * TUI posture-flag dispatch (approval/trust bypass per vendor). Defined in
+ * providerVendors.js (the PROVIDER_VENDORS registry, #3618); re-exported here
+ * for existing importers of this module.
+ */
+export { applyCommandDefaults };
/**
* Build the spawn args for a TUI invocation. When `provider.args` already
@@ -965,39 +907,18 @@ function codexHasApprovalPolicy(args) {
* the provider with it pinned, same as `defaultModel`) and becomes
* `--effort <level>` / codex's `-c model_reasoning_effort=<level>`. For agy an
* effort-suffixed model id is split so the base rides `--model` and its baked
- * tier becomes the `--effort` — see antigravity.js for why.
+ * tier becomes the `--effort` — see antigravity.js for why. The antigravity-
+ * vs-everyone-else split lives in providerVendors.js#injectTuiModelAndEffort,
+ * shared with agentTuiSpawning.js#buildTuiSpawnConfig so the two spawn paths
+ * can't diverge (they already had once, before #3618).
*/
export function buildTuiInvocation(provider, model) {
const command = provider?.command || inferTuiCommand(provider?.id);
const baseArgs = applyCommandDefaults(command, [...(provider?.args || [])]);
const effort = provider?.effort || null;
-
- // Antigravity pairs `--model` with `--effort` under its own rules (an
- // effort-suffixed id is split; agy validates the pair) — see antigravity.js.
- if (isAntigravityCommand(command)) {
- const resolved = resolveAntigravityModelAndEffort(baseArgs, {
- model,
- effort,
- models: provider?.models,
- });
- const withModel = resolved.model ? [...baseArgs, '--model', resolved.model] : baseArgs;
- return {
- command,
- args: [...withModel, ...buildEffortArgs(resolved.effort, resolved.provider, withModel, resolved.base)],
- };
- }
-
- const effectiveModel = resolveCliModel(model);
- const shouldInject = !!effectiveModel && !hasModelFlag(baseArgs);
- // Per-command model rewriting (OpenCode namespacing, cursor passthrough,
- // Bedrock mapping) lives in resolveInjectedTuiModel — shared with
- // agentTuiSpawning.js#appendModelArgs so the two spawn paths can't diverge.
- const withModel = shouldInject
- ? [...baseArgs, '--model', resolveInjectedTuiModel(effectiveModel, provider, command)]
- : baseArgs;
return {
command,
- args: [...withModel, ...buildEffortArgs(effort, { id: provider?.id, command }, withModel)],
+ args: injectTuiModelAndEffort(command, baseArgs, provider, model, effort),
};
}
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index 6897df1630..ba4fd065a2 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -27,12 +27,12 @@ import { safeJSONParse, PATHS } from '../lib/fileUtils.js';
import { createCodexStderrFormatter } from '../lib/codexCliOutput.js';
import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';
import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';
-import { ensureAntigravityPrintArgs, isAntigravityCliProvider } from '../lib/antigravity.js';
import { prepareCliPrompt } from '../lib/cliProviderArgs.js';
-import { CURSOR_COMMAND, isCursorCommand, ensureCursorHeadlessArgs } from '../lib/cursor.js';
-import { isGrokCommand, ensureGrokHeadlessArgs } from '../lib/grok.js';
-import { isKimiCommand, ensureKimiHeadlessArgs } from '../lib/kimi.js';
-import { resolveCliModel, buildEffortArgs, buildCodexStartupArgs, resolveBedrockCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand, applyLeanClaudeArgs, providerSuppliesGithubToken, isOllamaClaudeProvider } from '../lib/providerModels.js';
+// buildCliSpawnConfig's per-vendor argv construction dispatches through the
+// PROVIDER_VENDORS registry (#3618) instead of a hand-rolled per-vendor
+// if-chain — see providerVendors.js for the vendor rows.
+import { buildVendorSpawnConfig } from '../lib/providerVendors.js';
+import { resolveCliModel, providerSuppliesGithubToken, isOllamaClaudeProvider } from '../lib/providerModels.js';
import { resolveForgeTokenEnv } from './git.js';
import { prepareCliSpawn, killProcessTree } from '../lib/bufferedSpawn.js';
import { buildCliChildEnv } from '../lib/cliChildEnv.js';
@@ -252,175 +252,19 @@ export function createStreamJsonParser() {
* to the spawned child (see the spawn env below at the `claudeSettingsEnv`
* merge) — without it, a settings-only Bedrock box would map against an env
* missing the flag and still emit a bare, Bedrock-invalid `--model`.
+ *
+ * Per-vendor argv construction is dispatched through the PROVIDER_VENDORS
+ * registry (#3618) — see providerVendors.js for each vendor's `spawnArgs` row
+ * and the file header on the (preserved, not silently "fixed") asymmetries vs
+ * `buildCliArgs` (e.g. codex never forwards `provider.args` here, and there is
+ * no gemini-cli row so a legacy gemini-cli provider falls through to claude's
+ * default, exactly as before this registry existed).
*/
export function buildCliSpawnConfig(provider, model, settingsEnv = {}, { systemPromptFile = null, effort = null } = {}) {
- const providerId = provider?.id || 'claude-code';
// Configured-default sentinels (Codex / Antigravity / Grok Build) → null so
// the CLI uses its own default without a --model flag.
const effectiveModel = resolveCliModel(model);
-
- // Codex CLI uses different invocation pattern.
- // `--dangerously-bypass-approvals-and-sandbox` is the Codex equivalent of
- // Claude/Antigravity's `--dangerously-skip-permissions`: it skips all
- // approval prompts AND disables the sandbox. Without it, `codex exec` runs
- // under the default workspace-write sandbox (network blocked, so `gh pr create`
- // can't resolve api.github.com) and, in non-interactive `exec` mode, any
- // command that needs approval is silently cancelled — which is exactly how a
- // codex agent could push a branch over SSH yet fail to open the PR over HTTPS.
- // PortOS runs on a private, single-user, trusted machine (the "externally
- // sandboxed" context this flag documents), matching how we already spawn the
- // other CLIs unrestricted.
- if (providerId === 'codex') {
- // buildCodexStartupArgs disables codex's startup update check so a headless
- // exec run never spends startup time hitting GitHub / kicking off a brew
- // upgrade it can't complete unattended (the fatal interactive-modal variant
- // is documented on buildCodexStartupArgs in providerModels.js). Injected
- // UNCONDITIONALLY here (no provider.args passed): this branch builds codex's
- // argv from scratch and never forwards provider.args, and a headless CoS
- // agent can never dismiss the update modal — so the check must be off
- // regardless of any provider.args pin. (Passing provider.args would detect a
- // pin and skip injecting, but since the pin is never forwarded either, codex
- // would fall back to its check-ON default — the exact wedge this prevents.)
- const args = ['exec', '--dangerously-bypass-approvals-and-sandbox', ...buildCodexStartupArgs()];
- if (effectiveModel) {
- args.push('--model', effectiveModel);
- }
- args.push(...buildEffortArgs(effort, provider, args));
- return {
- command: provider?.command || 'codex',
- args,
- stdinMode: 'prompt' // codex exec reads prompt from stdin
- };
- }
-
- // Antigravity CLI (`agy`) replaces Gemini CLI. Use print mode for a
- // headless agent run; the prompt rides as the trailing `--print` value.
- // Per-task `--model` / `--effort` overrides are threaded in the same way as
- // claude/codex — agy documents both as session-scoped flags.
- if (isAntigravityCliProvider(provider)) {
- // `models` narrows the effort ladder to the tiers the chosen base model
- // actually offers — agy rejects `--model gemini-3.1-pro --effort medium`.
- const args = ensureAntigravityPrintArgs(provider?.args || [], {
- model: effectiveModel,
- effort,
- models: provider?.models,
- });
- return {
- command: provider?.command || 'agy',
- args,
- stdinMode: 'prompt'
- };
- }
-
- // OpenCode CLI (`opencode run`): headless agent invocation for a local Ollama
- // model. `opencode run` reads the prompt from stdin and auto-approves tools via
- // the `permission: "allow"` baked into OPENCODE_CONFIG_CONTENT (the equivalent
- // of claude's `--dangerously-skip-permissions` / codex's bypass — appropriate
- // for PortOS's single-user trusted box). The model is namespaced `ollama/<id>`
- // (prefixOpencodeModel). OpenCode emits plain text (no stream-json), so the
- // live-output handler falls through to its default text path.
- if (isOpencodeCommand(provider?.command)) {
- const baseArgs = provider?.args?.includes('run') ? [...provider.args] : ['run', ...(provider?.args || [])];
- const model = prefixOpencodeModel(provider, effectiveModel);
- // Respect a user-baked -m/--model pin (mirrors buildCliArgs) rather than
- // duplicating the flag — opencode takes the last, silently overriding it.
- if (model && !hasModelFlag(baseArgs)) {
- baseArgs.push('-m', model);
- }
- return {
- command: provider.command,
- args: baseArgs,
- stdinMode: 'prompt'
- };
- }
-
- // Grok Build CLI (`grok`): headless one-shot agent. Reads the combined
- // contract+task prompt from `--prompt-file /dev/stdin` (rewritten to a temp
- // file on Windows at the spawn site — via prepareCliPrompt), bypasses approval
- // prompts, and emits plain text (the live-output handler falls through to its
- // default text path, like OpenCode). grok is a non-Claude command, so
- // agentLifecycle keeps the operating contract in the stdin prompt (no
- // system-prompt-file split) — matching codex/antigravity/opencode.
- if (isGrokCommand(provider?.command)) {
- return {
- command: provider?.command || 'grok',
- args: ensureGrokHeadlessArgs(provider?.args || [], effectiveModel),
- stdinMode: 'prompt',
- };
- }
-
- // Kimi Code CLI (`kimi`): headless one-shot agent. `--print` runs non-
- // interactive print mode (implies `--afk`, so tool calls auto-approve). The
- // combined contract+task prompt is delivered as the `--prompt <value>` argv
- // (kimi does NOT read stdin in print mode) — spliced in at the spawn site via
- // prepareCliPrompt. Emits plain text (the live-output handler falls through to
- // its default text path, like grok/opencode). A non-Claude command, so
- // agentLifecycle keeps the operating contract in the prompt (no system-prompt-
- // file split) — matching codex/antigravity/grok/opencode.
- if (isKimiCommand(provider?.command)) {
- return {
- command: provider?.command || 'kimi',
- args: ensureKimiHeadlessArgs(provider?.args || [], effectiveModel),
- stdinMode: 'prompt',
- };
- }
-
- // Cursor Agent CLI (`cursor-agent`): headless one-shot. `--print` reads the
- // combined contract+task prompt from raw stdin (like claude/codex, unlike
- // grok/kimi). `--force` is load-bearing beyond approvals: without a trust
- // posture cursor-agent prints "Workspace Trust Required" and EXITS without
- // doing any work — in a fresh CoS worktree that is every run. Emits plain text
- // (the live-output handler falls through to its default text path, like
- // grok/kimi/opencode — see cursor.js on why stream-json isn't selected yet). A
- // non-Claude command, so agentLifecycle keeps the operating contract in the
- // stdin prompt (no system-prompt-file split), matching the other CLIs above.
- if (isCursorCommand(provider?.command)) {
- return {
- command: provider?.command || CURSOR_COMMAND,
- args: ensureCursorHeadlessArgs(provider?.args || [], effectiveModel),
- stdinMode: 'prompt',
- };
- }
-
- // Default: Claude Code CLI. applyLeanClaudeArgs adds `--bare
- // --strict-mcp-config` for Ollama-backed claude sessions (no-op otherwise,
- // idempotent against user-baked flags); the system-prompt contract file
- // rides via --append-system-prompt-file.
- const args = applyLeanClaudeArgs(provider, [
- '--dangerously-skip-permissions', // Unrestricted mode
- '--print', // Print output and exit
- '--output-format', 'stream-json', // Stream JSON events for live output
- '--verbose', // Required for stream-json
- '--include-partial-messages', // Include incremental text deltas
- ...(provider?.args || []), // User-configured provider args
- ], provider?.command || 'claude');
- if (systemPromptFile) {
- args.push('--append-system-prompt-file', systemPromptFile);
- }
- if (effectiveModel) {
- // Bedrock box: map a bare Claude id to its region-prefixed Bedrock form
- // just-in-time (no-op off Bedrock / for already-prefixed or non-Claude ids).
- // Env precedence mirrors the actual spawn env below: process.env <
- // settingsEnv (~/.claude/settings.json) < provider.envVars.
- const injectedModel = resolveBedrockCliModel(effectiveModel, {
- env: { ...process.env, ...settingsEnv, ...provider?.envVars },
- providerId,
- });
- args.push('--model', injectedModel);
- }
- // Per-task reasoning-effort override; a user-baked --effort in provider args
- // wins (buildEffortArgs mirrors the hasModelFlag rule). Keyed on the RESOLVED
- // launch command — not the raw provider — so a blank-command claude provider
- // still qualifies, matching the TUI builder's re-keying.
- const command = provider?.command || process.env.CLAUDE_PATH || 'claude';
- args.push(...buildEffortArgs(effort, { id: providerId, command }, args));
-
- return {
- command,
- args,
- stdinMode: 'prompt',
- streamFormat: 'stream-json'
- };
+ return buildVendorSpawnConfig(provider, { effectiveModel, effort, systemPromptFile, settingsEnv });
}
/**
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 862cb6bf63..e8cae01476 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -27,11 +27,11 @@ import * as git from './git.js';
import { resolveReviewLoopOptions } from './codeReview.js';
import { spawnTuiSessionViaRunner } from './cosRunnerClient.js';
import { shellQuote } from '../lib/shellQuote.js';
-import { resolveCliModel, buildEffortArgs, resolveInjectedTuiModel, hasModelFlag, isClaudeCommand, applyLeanClaudeArgs, providerSuppliesGithubToken } from '../lib/providerModels.js';
+import { isClaudeCommand, applyLeanClaudeArgs, providerSuppliesGithubToken } from '../lib/providerModels.js';
import { createStreamingAnsiStripper, stripAnsi } from '../lib/ansiStrip.js';
import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';
import { isMachineOnline } from '../lib/connectivity.js';
-import { isAntigravityCommand, resolveAntigravityModelAndEffort } from '../lib/antigravity.js';
+import { isAntigravityCommand } from '../lib/antigravity.js';
import {
DEFAULT_TUI_PROMPT_DELAY_MS,
DEFAULT_TUI_IDLE_TIMEOUT_MS,
@@ -67,6 +67,7 @@ import {
extractVerifiablePromptPrefix,
isPasteConfirmed,
} from '../lib/tuiHandshake.js';
+import { injectTuiModelAndEffort } from '../lib/providerVendors.js';
import { agentGuardEnv } from '../lib/agentGuard/index.js';
import { composeProviderEnv } from '../lib/cliChildEnv.js';
import { execFile } from 'child_process';
@@ -222,43 +223,14 @@ function shellHasLiveChild(shellPid) {
});
}
-function appendModelArgs(args, model, command, provider) {
- const effectiveModel = resolveCliModel(model);
- if (!effectiveModel) return args;
- // Respect a user-baked --model/-m pin for EVERY command rather than appending
- // a second flag that overrides it — the same gate `buildTuiInvocation` and
- // `buildCliArgs` apply, and the documented convention repo-wide ("a baked pin
- // wins"). This used to be scoped to opencode alone, so a pinned claude/codex —
- // and now cursor — provider spawned `--model <pin> --model <ui-choice>`, where
- // last-flag-wins silently discarded the user's pin (or the CLI rejected the
- // duplicate outright).
- if (hasModelFlag(args)) return args;
- // Antigravity never reaches here: buildTuiSpawnConfig resolves its model and
- // effort together up front (agy validates the pair) — see antigravity.js.
-
- // Which id to actually pass (OpenCode namespacing / cursor passthrough /
- // Bedrock mapping) is shared with tuiHandshake.js#buildTuiInvocation, so the
- // two spawn paths can't drift — they already had, on cursor.
- return [...args, '--model', resolveInjectedTuiModel(effectiveModel, provider, command)];
-}
-
export function buildTuiSpawnConfig(provider, model, { systemPromptFile = null, effort = null } = {}) {
const command = provider?.command || inferTuiCommand(provider?.id);
const baseArgs = applyCommandDefaults(command, [...(provider?.args || [])]);
- let args;
- if (isAntigravityCommand(command)) {
- // agy validates the (model, effort) PAIR — `gemini-3.1-pro` has no `medium`
- // tier — and a legacy suffixed id carries its own effort, so the two are
- // resolved together against the provider's catalog (see antigravity.js).
- const resolved = resolveAntigravityModelAndEffort(baseArgs, { model, effort, models: provider?.models });
- args = resolved.model ? [...baseArgs, '--model', resolved.model] : baseArgs;
- args = [...args, ...buildEffortArgs(resolved.effort, resolved.provider, args, resolved.base)];
- } else {
- args = appendModelArgs(baseArgs, model, command, provider);
- // Reasoning-effort override — the provider is re-keyed on the RESOLVED launch
- // command so an inferred command (blank provider.command) still qualifies.
- args = [...args, ...buildEffortArgs(effort, { id: provider?.id, command }, args)];
- }
+ // Model+effort injection (including the antigravity-validates-the-pair special
+ // case) is shared with tuiHandshake.js#buildTuiInvocation via
+ // providerVendors.js#injectTuiModelAndEffort, so the two spawn paths can't
+ // drift — they already had once, on cursor, before #3618.
+ let args = injectTuiModelAndEffort(command, baseArgs, provider, model, effort);
// Lean mode for Ollama-backed claude sessions (no-op otherwise) — must come
// before the system-prompt flag so `--bare` is present when the contract
// file rides along.