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

68.1 KB
Raw Blame
/**
 * `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). That is load-bearing, not cosmetic: reaching into
 * opencodeConfig.js for the OpenCode public-review agent name pulled ports.js
 * in behind it and broke a suite that partially mocks it — which is why that
 * constant lives in providerModels.js beside its siblings.
 */

import { isProcessProvider } from './providerTypes.js';
import {
  resolveCliModel,
  resolveCliEffort,
  foldCursorEffortIntoModel,
  isCursorProvider,
  isClaudeCommand,
  hasModelFlag,
  argvHasFlag,
  resolveInjectedTuiModel,
  resolveClaudeCliModel,
  buildCodexStartupArgs,
  buildCodexAgentThreadArgs,
  buildEffortArgs,
  isOpencodeCommand,
  ensureLeadingSubcommand,
  prefixOpencodeModel,
  localRuntimeNamespace,
  opencodeProviderIsLocalOnly,
  OPENCODE_PUBLIC_REVIEW_AGENT,
  OPENCODE_BUILD_AGENT,
  applyLeanClaudeArgs,
  CODEX_WORKSPACE_NETWORK_KEY,
  CODEX_WORKSPACE_WRITABLE_ROOTS_KEY,
  CODEX_PLUGINS_FEATURE_KEY,
  CODEX_APPS_FEATURE_KEY,
  CODEX_HOOKS_FEATURE_KEY,
} from './providerModels.js';
import {
  isCodexCommand,
  ensureCodexTuiArgs,
  CODEX_COMMAND,
  CODEX_CLI_ID,
  buildCodexOssArgs,
  buildCodexAuthModeArgs,
} 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';
import { PI_COMMAND, isPiCommand, ensurePiTuiArgs, ensurePiHeadlessArgs, preparePiPrompt } from './pi.js';
import { KILO_COMMAND, KILO_COMMAND_ALIASES, isKiloCommand, ensureKiloTuiArgs, ensureKiloHeadlessArgs } from './kilo.js';
import {
  OPENCHAMBER_COMMAND,
  isOpenchamberCommand,
  ensureOpenchamberHeadlessArgs,
  prepareOpenchamberPrompt,
} from './openchamber.js';
import { PROVIDER_TYPES } from './aiToolkit/constants.js';
import {
  publicReviewPostureForProfile,
  PUBLIC_REVIEW_EXECUTION_PROFILE,
  PUBLIC_REVIEW_GATE_EXECUTION_PROFILE,
  PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE,
  PUBLIC_REVIEW_NO_TOOL_POSTURE,
  PUBLIC_REVIEW_ACTIONS_POSTURE,
  PUBLIC_REVIEW_POSTURES,
} from './agentExecutionProfiles.js';

export {
  isPublicReviewNoToolProfile,
  publicReviewPostureForProfile,
  PUBLIC_REVIEW_EXECUTION_PROFILE,
  PUBLIC_REVIEW_GATE_EXECUTION_PROFILE,
  PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE,
  PUBLIC_REVIEW_NO_TOOL_POSTURE,
  PUBLIC_REVIEW_ACTIONS_POSTURE,
  PUBLIC_REVIEW_POSTURES,
} from './agentExecutionProfiles.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',
  });
}

// ─── tool-free one-shot argv (#9008) ───────────────────────────────────────

// Approval/permission-bypass switches, in every vendor's spelling. A one-shot
// text call (Ask, AI app detection) hands the model caller-supplied text, so it
// must never carry one: with it, the CLI is an agent that runs shell commands
// with the PortOS user's privileges. Boolean flags; a `--flag=value` spelling is
// dropped too. Short aliases are vendor-specific (`-f` is not a bypass
// everywhere), so they live on the vendor rows as `bypassAliases`.
const APPROVAL_BYPASS_FLAGS = [
  '--dangerously-skip-permissions', // claude, agy
  '--allow-dangerously-skip-permissions', // claude
  '--dangerously-bypass-approvals-and-sandbox', // codex
  '--full-auto', // codex
  '--yolo', // codex, cursor, kimi
  '--auto', // kilo, kimi
  '--approve', // pi
  '--force', // cursor
  '--auto-review', // cursor
  '--always-approve', // grok
  '--yes-always', // aider
  '--allow-all-tools', // copilot
];
// Valued options whose VALUE is the bypass (`--permission-mode bypassPermissions`
// for claude and grok, codex's unsandboxed mode).
const APPROVAL_BYPASS_VALUES = new Map([
  ['--permission-mode', 'bypassPermissions'],
  ['--sandbox', 'danger-full-access'],
  ['-s', 'danger-full-access'],
]);

const flagMatches = (arg, flag) => arg === flag || arg.startsWith(`${flag}=`);

/**
 * Remove each option in `flags` together with its value(s): the joined
 * `--flag=value` spelling, or the separate tokens that follow it. `variadic`
 * options consume every following token up to the next flag (Claude's
 * `--tools <tools...>`); the others consume exactly one.
 */
function dropOptions(args, flags, { variadic = false } = {}) {
  const out = [];
  for (let i = 0; i < args.length; i += 1) {
    const arg = args[i];
    const flag = typeof arg === 'string' && flags.find((f) => flagMatches(arg, f));
    if (!flag) {
      out.push(arg);
      continue;
    }
    if (arg !== flag) continue; // joined form carries its own value
    if (!variadic) {
      i += 1;
      continue;
    }
    while (i + 1 < args.length && !(typeof args[i + 1] === 'string' && args[i + 1].startsWith('-'))) i += 1;
  }
  return out;
}

/** Strip every approval-bypass switch. `removed` says whether one was present. */
function stripApprovalBypassArgs(args, aliases = []) {
  const booleans = [...APPROVAL_BYPASS_FLAGS, ...aliases];
  const out = [];
  for (let i = 0; i < args.length; i += 1) {
    const arg = args[i];
    if (typeof arg !== 'string') { out.push(arg); continue; }
    if (booleans.some((f) => flagMatches(arg, f))) continue;
    const valued = [...APPROVAL_BYPASS_VALUES].find(([flag]) => flagMatches(arg, flag));
    if (valued) {
      const [flag, bypass] = valued;
      if (arg === `${flag}=${bypass}`) continue;
      if (arg === flag && args[i + 1] === bypass) { i += 1; continue; }
    }
    out.push(arg);
  }
  return { args: out, removed: out.length !== args.length };
}

// Claude Code: no built-in tools, no MCP servers (a project `.mcp.json` would
// otherwise start processes), and only the USER's settings — a project or local
// `.claude/settings*.json` in the working directory can declare hooks, which
// run shell commands without any tool call, and print mode skips the trust
// dialog that would otherwise gate them. `--restricted` is not used: it also
// drops user settings, where a Bedrock or gateway install keeps its env.
const CLAUDE_TOOL_FREE_ARGS = [
  '--tools', '',
  '--strict-mcp-config',
  '--mcp-config', '{"mcpServers":{}}',
  '--setting-sources', 'user',
];
function claudeToolFreeArgs(args) {
  const cleared = dropOptions(
    dropOptions(args, ['--tools', '--allowedTools', '--allowed-tools', '--mcp-config'], { variadic: true }),
    ['--setting-sources'],
  ).filter((arg) => arg !== '--strict-mcp-config');
  return [...cleared, ...CLAUDE_TOOL_FREE_ARGS];
}

// Grok's read-only permission mode plus an empty built-in tool allowlist — the
// same pair its no-tool public-review recipe enforces.
function grokToolFreeArgs(args) {
  return [...dropOptions(args, ['--permission-mode', '--tools']), '--permission-mode', 'plan', '--tools', ''];
}

// Pi: `--no-builtin-tools` alone leaves extension tools enabled, so extensions
// and skills go too (the no-tool public-review recipe's rule).
const PI_TOOL_FREE_ARGS = ['--no-approve', '--no-tools', '--no-builtin-tools', '--no-extensions', '--no-skills'];
function piToolFreeArgs(args) {
  return [...args.filter((arg) => !PI_TOOL_FREE_ARGS.includes(arg)), ...PI_TOOL_FREE_ARGS];
}

// ─── codex ──────────────────────────────────────────────────────────────────

// Codex has no tool-disable switch, so a one-shot is never `toolFree`. It can
// still be confined: OS-level read-only sandbox (no writes, no mutating
// commands), no session persisted, no user config re-routing the run. Callers
// that only need that bound (music-video code authoring over the user's own
// brief) accept it through `isReadOnlySandboxOneShotProvider`; the Ask/app-detect
// host-control guard keeps treating codex as non-tool-free.
const CODEX_READ_ONLY_ONE_SHOT_ARGS = ['--sandbox', 'read-only', '--skip-git-repo-check', '--ephemeral', '--ignore-user-config'];
function codexReadOnlyOneShotArgs(args) {
  const cleared = dropOptions(args, ['--sandbox', '-s']).filter((arg) => !CODEX_READ_ONLY_ONE_SHOT_ARGS.includes(arg));
  // Options precede the stdin-prompt marker, which stays last.
  const tail = cleared.at(-1) === '-' ? ['-'] : [];
  return [...cleared.slice(0, cleared.length - tail.length), ...CODEX_READ_ONLY_ONE_SHOT_ARGS, ...tail];
}

// The opt-in that pins a Codex run to the account PortOS believes it is using.
// A third-party bridge re-points Codex by writing top-level routing keys into
// `~/.codex/config.toml`, and codex honors that file on every invocation — so
// without this flag PortOS's runs, reviewer rounds and autofixer repairs route
// wherever that file says while the provider card reports a ChatGPT account.
// Default OFF (an absent flag is today's behavior); the AI Providers page badges
// the override and offers the toggle. Same flag the public-review recipes
// already pass, so no new Codex surface is introduced here.
const codexIgnoreUserConfigArgs = (provider, existingArgs = []) => (
  provider?.ignoreUserConfig === true && !existingArgs.includes('--ignore-user-config')
    ? ['--ignore-user-config']
    : []
);

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(...codexIgnoreUserConfigArgs(provider, args));
  args.push(...buildCodexAuthModeArgs(provider, baseArgs));
  args.push(...buildCodexStartupArgs(baseArgs));
  // The local-model backing, when the record carries a runtime marker codex can
  // serve. Emitted from the marker rather than from provider args so a wrapper
  // stays declarative — see buildCodexOssArgs in codex.js.
  args.push(...buildCodexOssArgs(provider, baseArgs));
  if (model) {
    args.push('--model', model);
  }
  args.push(...buildEffortArgs(effort, provider, args, model));
  args.push('-'); // stdin marker
  return args;
}

function codexSpawnArgs(provider, { effectiveModel, effort, maxConcurrentThreads }) {
  // 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',
    ...codexIgnoreUserConfigArgs(provider),
    ...buildCodexAuthModeArgs(provider),
    ...buildCodexStartupArgs(),
    ...buildCodexOssArgs(provider),
    ...buildCodexAgentThreadArgs(maxConcurrentThreads),
  ];
  if (effectiveModel) {
    args.push('--model', effectiveModel);
  }
  args.push(...buildEffortArgs(effort, provider, args, effectiveModel));
  return { command: provider?.command || CODEX_COMMAND, args, stdinMode: 'prompt' };
}

// Codex's own sandbox modes are the enforcement here, not the prompt. Both
// public-review recipes build argv from scratch and never forward
// `provider.args`: a saved `--dangerously-bypass-approvals-and-sandbox` in a
// user's provider config would otherwise turn a screened review into an
// unrestricted session.
function codexPublicReviewActionsSpawnArgs(provider, { effectiveModel, effort, maxConcurrentThreads }) {
  // `workspace-write` is intentionally the narrowest Codex sandbox that can
  // apply a supplied patch and run local tests; `--approve-for-me` only
  // suppresses interactive confirmations inside that sandbox. Never replace
  // these with the unrestricted bypass used by the ordinary coding-agent path.
  return codexPublicReviewArgs(provider, { effectiveModel, effort, maxConcurrentThreads }, [
    '--sandbox', 'workspace-write',
    '--approve-for-me',
  ]);
}

// Code-review reader: Codex's OS-level read-only sandbox may inspect files but
// never write or run a mutating command. It still exposes read tools, so it is
// the read-only code-review tier, not the no-tool posture. Claim reviews run in
// an isolated non-repository scratch cwd with the diff inlined, which codex
// refuses ("Not inside a trusted directory") unless the repo check is skipped;
// the read-only sandbox, not the repo check, is the safety boundary here.
function codexReadOnlyReviewSpawnArgs(provider, ctx) {
  return codexPublicReviewArgs(provider, ctx, ['--sandbox', 'read-only', '--skip-git-repo-check']);
}

function codexPublicReviewArgs(provider, { effectiveModel, effort, maxConcurrentThreads }, postureArgs) {
  const args = [
    'exec',
    ...postureArgs,
    '--ephemeral',
    '--ignore-user-config',
    ...buildCodexStartupArgs(),
    // The backing is orthogonal to the posture: a local-backed record reviews
    // untrusted public code under the SAME sandbox ladder, with the tokens
    // generated on-box. `--ignore-user-config` does not strip it — the pair is
    // argv, not config.
    ...buildCodexOssArgs(provider),
    ...buildCodexAgentThreadArgs(maxConcurrentThreads),
  ];
  if (effectiveModel) {
    args.push('--model', effectiveModel);
  }
  args.push(...buildEffortArgs(effort, provider, args, effectiveModel));
  return { command: provider?.command || CODEX_COMMAND, args, stdinMode: 'prompt' };
}

// Antigravity's `--sandbox` is its maintained terminal-restriction posture and
// `--mode` picks what the session may do inside it: `plan` cannot edit at all,
// `accept-edits` may apply the screened patch and run tests. Provider args are
// intentionally not copied: saved args could turn a safe profile back into an
// unrestricted session. `--print` carries the prompt as its VALUE (see
// antigravity.js) — `prepareAntigravityPrompt` relocates it to the end of the
// argv at spawn time, which is why it is safe to append flags after it here.
function antigravityPublicReviewActionsSpawnArgs(provider, ctx) {
  return antigravityPublicReviewArgs(provider, ctx, 'accept-edits');
}

function antigravityPublicReviewArgs(provider, { effectiveModel, effort } = {}, mode) {
  const args = [
    '--sandbox',
    '--mode', mode,
    '--disable-slash-commands',
    '--print',
  ];
  if (effectiveModel) args.push('--model', effectiveModel);
  args.push(...buildEffortArgs(effort, provider, args, effectiveModel));
  return { command: provider?.command || ANTIGRAVITY_COMMAND, args, stdinMode: 'prompt' };
}

// Grok exposes both halves of the contract as first-class flags:
// `--permission-mode plan` is its read-only mode, `--tools ''` empties the
// built-in tool allowlist, and `--sandbox <profile>` applies its own
// filesystem/network sandbox (`workspace` is grok's built-in profile). The
// safety flags are seeded as the BASE args so `ensureGrokHeadlessArgs` sees a
// permission posture already pinned and does not append its usual
// `--permission-mode bypassPermissions`.
function grokPublicReviewSpawnArgs(provider, ctx) {
  return grokPublicReviewArgs(provider, ctx, ['--permission-mode', 'plan', '--tools', '']);
}

function grokPublicReviewActionsSpawnArgs(provider, ctx) {
  return grokPublicReviewArgs(provider, ctx, ['--sandbox', 'workspace', '--permission-mode', 'acceptEdits']);
}

function grokPublicReviewArgs(provider, { effectiveModel, effort } = {}, postureArgs) {
  const args = ensureGrokHeadlessArgs([
    ...postureArgs,
    '--no-subagents',
    '--disable-web-search',
  ], effectiveModel);
  args.push(...buildEffortArgs(effort, provider, args, effectiveModel));
  // `ensureGrokHeadlessArgs` appends the GROK_STDIN_PROMPT_PATH prompt-file
  // sentinel that `prepareGrokPromptFile` rewrites on Windows; keep it present.
  return { command: provider?.command || 'grok', args, stdinMode: 'prompt' };
}

const matchCodexProcess = (provider) => isProcessProvider(provider) && isCodexCommand(provider?.command);

const CODEX = {
  id: 'codex',
  idFragment: 'codex',
  inferredCommand: CODEX_COMMAND,
  matchCommand: isCodexCommand,
  // Id OR command: the shipped `codex` record is not the only one that must
  // build codex argv any more — a local-backed wrapper (`codex-ollama`) carries
  // its own id, and an id-only match would drop it through to `claude`'s
  // fallback row and spawn `claude --print` against the codex binary.
  matchCliProvider: (provider) => provider?.id === CODEX_CLI_ID || isCodexCommand(provider?.command),
  tuiArgs: ensureCodexTuiArgs,
  cliArgs: codexCliArgs,
  spawnArgs: codexSpawnArgs,
  toolFreeOneShot: { matchCommand: isCodexCommand, sandboxArgs: codexReadOnlyOneShotArgs },
  publicReview: {
    // The CLI id and the TUI id share one binary, so both reach the same
    // enforced recipe when a stage selects them.
    // Read-only filesystem access still exposes tools; it is not no-tool.
    [PUBLIC_REVIEW_ACTIONS_POSTURE]: {
      spawnArgs: codexPublicReviewActionsSpawnArgs,
      matchProvider: matchCodexProcess,
    },
  },
  readOnlyReview: {
    spawnArgs: codexReadOnlyReviewSpawnArgs,
    matchProvider: matchCodexProcess,
  },
};

// ─── antigravity ────────────────────────────────────────────────────────────

function antigravityCliArgs(baseArgs, { model, effort, provider }) {
  return ensureAntigravityPrintArgs(baseArgs, { model, effort, models: provider?.models });
}

const ANTIGRAVITY = {
  id: 'antigravity',
  // `isAntigravityCommand` has always accepted this spelling beside `agy`; the
  // allowlist did not, so such a record 400'd at /spawn-tui.
  commandAliases: ['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),
  publicReview: {
    // Plan mode is not an explicit empty-tool contract.
    [PUBLIC_REVIEW_ACTIONS_POSTURE]: {
      spawnArgs: antigravityPublicReviewActionsSpawnArgs,
      matchProvider: (provider) => isProcessProvider(provider) && isAntigravityCommand(provider?.command),
    },
  },
};

// ─── opencode ───────────────────────────────────────────────────────────────

/** Append the namespaced `-m` unless the argv already pins a model. */
function appendOpencodeModel(args, provider, model) {
  const resolvedModel = prefixOpencodeModel(provider, model);
  if (resolvedModel && !hasModelFlag(args)) args.push('-m', resolvedModel);
  return args;
}

const opencodeSpawnConfig = (provider, args) => ({ command: provider?.command || 'opencode', args, stdinMode: 'prompt' });

/**
 * Pin OpenCode's tool-enabled `build` agent unless the argv already selects one.
 *
 * Unlike every other vendor here, OpenCode's ROLE — not just its permissions —
 * is argv state, and the seeded records ship `args: []` (TUI) / `args: ["run"]`
 * (headless). A bare invocation therefore opens in whatever agent that install
 * defaults to, which is how a completion run came up as a read-only specialist
 * and refused to write its own sentinel (#7405 — the contract it could not
 * reconcile is `SENTINEL_WRITE_PERMISSION_NOTE` in promptSections/completion.js).
 * Argv, not `OPENCODE_CONFIG_CONTENT`: that env var is stripped for a
 * gateway-backed wrapper (`cliChildEnv.js`), and a `data.reference` seed edit
 * would never reach an install's already-stored record.
 *
 * Idempotent on `--agent`, which is what lets the public-review recipes keep
 * their `--agent plan` while sharing these builders.
 *
 * @param {string[]} args
 * @returns {string[]}
 */
const ensureOpencodeAgent = (args) =>
  argvHasFlag(args, ['--agent']) ? args : [...args, '--agent', OPENCODE_BUILD_AGENT];

function opencodeCliArgs(baseArgs, { model, provider }) {
  const args = ensureLeadingSubcommand(baseArgs, 'run');
  return ensureOpencodeAgent(appendOpencodeModel(args, provider, model));
}

/** `applyCommandDefaults` arm — both TUI spawn paths share it, so they can't drift. */
const ensureOpencodeTuiArgs = (args = []) => ensureOpencodeAgent([...args]);

/**
 * An OpenCode wrapper this install can actually run the tool-free gate on.
 * Three conditions, each closing a different way the stage would otherwise be
 * offered and then fail — or, worse, appear to succeed:
 *
 *   - **an Ollama or LM Studio namespace.** Private assessments verify installed
 *     weights on either runtime. Public-review model validation independently
 *     keeps its stricter Ollama-only capability probe. Other local runtimes
 *     have no maintained assessment recipe.
 *   - **only local endpoints.** The enforcement rides in
 *     `OPENCODE_CONFIG_CONTENT`, which `cliChildEnv.js` keeps through the
 *     public-review env allowlist under the SAME `opencodeConfigIsLocalOnly`
 *     rule. A provider carrying `ollamaBacked` but a relocated off-box
 *     `baseURL` would pass a marker-only check here, then have its hardened
 *     config stripped there — and OpenCode falls back to the user's own
 *     `~/.config/opencode`, tools and MCP servers intact, while the gate still
 *     reports as enforced. Sharing one predicate is what makes that
 *     unrepresentable.
 *   - **a spawnable binary**, as for every other vendor.
 */
const matchOpencodeBinary = (provider) => isProcessProvider(provider) && isOpencodeCommand(provider?.command);

const isLocalOpencodeProvider = (provider) => matchOpencodeBinary(provider)
  && ['ollama', 'lmstudio'].includes(localRuntimeNamespace(provider))
  && opencodeProviderIsLocalOnly(provider);

/**
 * OpenCode is the natural harness for a local Ollama model — but unlike every
 * other vendor here it has NO read-only argv flag: its tool posture, permission
 * block and per-model `tool_call` advertisement all live in the config. So this
 * recipe is only half the enforcement; the other half is
 * `hardenOpencodeConfigForNoTool` in `opencodeConfig.js`, which the same
 * `safetyProfile` applies to `OPENCODE_CONFIG_CONTENT`.
 *
 * The argv is the ordinary headless one seeded with the read-only agent (the
 * shape grok's recipe uses), so `run`/`-m` namespacing cannot drift from the
 * normal path. Provider args are deliberately not forwarded: a saved
 * `--agent build` would select the tool-enabled agent. There is no effort flag
 * to add — `opencode run` has none; the level rides
 * `agent.<name>.reasoningEffort` in the config, which the harden step copies
 * onto this agent (see `hardenOpencodeConfigForNoTool`).
 */
function opencodePublicReviewSpawnArgs(provider, { effectiveModel } = {}) {
  return opencodeSpawnConfig(provider, opencodeCliArgs(['--agent', OPENCODE_PUBLIC_REVIEW_AGENT], { model: effectiveModel, provider }));
}

/**
 * The ATTACHABLE `sandboxed-actions` invocation (#6238). OpenCode's headless
 * argv is a one-shot `opencode run …`, which cannot become an interactive
 * session by dropping flags the way Claude's recipe does — in a PTY it neither
 * accepts a pasted prompt nor renders. Its real interactive entry point is the
 * BARE binary, which takes the same `--agent`/`-m` flags and reads the prompt
 * the spawner pastes into every TUI (`agentTuiSpawning.js`). The tool-enabled
 * agent is pinned on the argv and provider args are not forwarded (same rule as
 * `buildTuiSpawnConfig`): a saved `--agent plan` would hand the session to a
 * human nobody has to be. Permissions are the config's, on both paths — every
 * tool allowed, the interactive gates denied (`buildOpencodeEnvVars`) — for as
 * long as `OPENCODE_CONFIG_CONTENT` survives the actions env allowlist, i.e. a
 * local-only endpoint (`cliChildEnv.js`); a gateway-backed wrapper runs on the
 * operator's own `~/.config/opencode` instead, exactly as its headless run
 * already did.
 *
 * The row supplies ONLY this builder: a headless actions run keeps falling
 * through to the ordinary `run` argv, and with no headless `spawnArgs` the row
 * is not an enforcement (OpenCode ships no sandbox; the disposable worktree is
 * the isolation), so the schedule UI keeps reporting it as worktree-only.
 */
function opencodePublicReviewActionsTuiSpawnArgs(provider, { effectiveModel } = {}) {
  return opencodeSpawnConfig(provider, appendOpencodeModel(['--agent', OPENCODE_BUILD_AGENT], provider, effectiveModel));
}

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).
  tuiArgs: ensureOpencodeTuiArgs,
  cliArgs: opencodeCliArgs,
  spawnArgs: defaultSpawnArgs(opencodeCliArgs, 'opencode'),
  publicReview: {
    [PUBLIC_REVIEW_NO_TOOL_POSTURE]: {
      spawnArgs: opencodePublicReviewSpawnArgs,
      matchProvider: isLocalOpencodeProvider,
    },
    [PUBLIC_REVIEW_ACTIONS_POSTURE]: {
      // No `spawnArgs` here — see the builder's docstring above: OpenCode
      // ships no sandbox, so this row is never an enforcement and the
      // attachable builder below is unreachable through the posture gate
      // (`enforcesPublicReviewPosture` requires `spawnArgs`).
      tuiSpawnArgs: opencodePublicReviewActionsTuiSpawnArgs,
      matchProvider: matchOpencodeBinary,
    },
  },
};

// ─── kilo ───────────────────────────────────────────────────────────────────

function kiloCliArgs(baseArgs, { model }) {
  return ensureKiloHeadlessArgs(baseArgs, model);
}

const KILO = {
  id: 'kilo',
  idFragment: 'kilo',
  inferredCommand: KILO_COMMAND,
  // `@kilocode/cli` installs two bin names for one program, and `isKiloCommand`
  // accepts both — so the runner's allowlist has to as well, or a provider
  // configured as `kilocode` is classified everywhere and spawnable nowhere.
  commandAliases: KILO_COMMAND_ALIASES,
  matchCommand: isKiloCommand,
  // No dedicated matchCliProvider — matches by command, same as matchCommand.
  tuiArgs: ensureKiloTuiArgs,
  cliArgs: kiloCliArgs,
  spawnArgs: defaultSpawnArgs(kiloCliArgs, KILO_COMMAND),
  // No publicReview recipe: Kilo is an OpenCode fork whose tool posture lives in
  // its config rather than argv, and PortOS writes no Kilo config (see
  // providerHarnesses.js) — so there is nothing here that could ENFORCE a
  // tool-free stage, and declaring one would make the gate decorative.
};

// ─── openchamber ────────────────────────────────────────────────────────────

function openchamberCliArgs(baseArgs, { model }) {
  return ensureOpenchamberHeadlessArgs(baseArgs, model);
}

const OPENCHAMBER = {
  id: 'openchamber',
  idFragment: 'openchamber',
  inferredCommand: OPENCHAMBER_COMMAND,
  matchCommand: isOpenchamberCommand,
  // No dedicated matchCliProvider — matches by command, same as matchCommand.
  // No `tuiArgs`: OpenChamber's interactive surface is a web app, and the bare
  // binary starts its SERVER — there is nothing for a PTY to attach to, and an
  // argv builder here would exist only to be misused (see openchamber.js).
  cliArgs: openchamberCliArgs,
  preparePrompt: prepareOpenchamberPrompt,
  spawnArgs: defaultSpawnArgs(openchamberCliArgs, OPENCHAMBER_COMMAND),
};

// ─── grok ───────────────────────────────────────────────────────────────────

function grokCliArgs(baseArgs, { model, toolFree }) {
  return ensureGrokHeadlessArgs(baseArgs, model, { toolFree });
}

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'),
  toolFreeOneShot: { matchCommand: isGrokCommand, toolFreeArgs: grokToolFreeArgs },
  publicReview: {
    [PUBLIC_REVIEW_NO_TOOL_POSTURE]: {
      spawnArgs: grokPublicReviewSpawnArgs,
      matchProvider: (provider) => isProcessProvider(provider) && isGrokCommand(provider?.command),
    },
    [PUBLIC_REVIEW_ACTIONS_POSTURE]: {
      spawnArgs: grokPublicReviewActionsSpawnArgs,
      matchProvider: (provider) => isProcessProvider(provider) && isGrokCommand(provider?.command),
    },
  },
};

// ─── 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'),
  // No tool-disable switch: only the bypass alias is stripped.
  toolFreeOneShot: { matchCommand: isKimiCommand, bypassAliases: ['-y'] },
};

// ─── cursor ─────────────────────────────────────────────────────────────────

function cursorCliArgs(baseArgs, { model, effort }) {
  // cursor-agent has no `--effort` flag (it exits non-zero on one), so the level
  // is folded into the model id instead — resolved through cursor's ladder first
  // so an out-of-range value clamps the way every other CLI's does. Resolved
  // against the CLI this row IS, not `provider`, so a provider that reaches this
  // row by id alone still gets its level applied.
  return ensureCursorHeadlessArgs(baseArgs, model, resolveCliEffort(effort, { command: CURSOR_COMMAND }));
}

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),
  // No tool-disable switch. `--force` also clears cursor's workspace-trust
  // gate, so when a bypass is stripped the narrow `--trust` (which approves
  // nothing) keeps the headless run from exiting on the trust block.
  toolFreeOneShot: {
    matchCommand: isCursorCommand,
    bypassAliases: ['-f'],
    afterStrip: (args) => (argvHasFlag(args, ['--trust']) ? args : [...args, '--trust']),
  },
};

// ─── 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.
};

// Pi public review discards configured args and disables every tool/resource
// discovery surface. --no-builtin-tools alone leaves extension tools enabled.
const piCliArgs = (args, { model, effort }) => ensurePiHeadlessArgs(args, model, effort);
const PI = {
  id: 'pi',
  idFragment: 'pi-',
  matchId: (id) => /^pi(?:-|$)/.test(id),
  inferredCommand: PI_COMMAND,
  matchCommand: isPiCommand,
  tuiArgs: ensurePiTuiArgs,
  cliArgs: piCliArgs,
  preparePrompt: preparePiPrompt,
  spawnArgs: defaultSpawnArgs(piCliArgs, PI_COMMAND),
  toolFreeOneShot: { matchCommand: isPiCommand, bypassAliases: ['-a'], toolFreeArgs: piToolFreeArgs },
  publicReview: {
    [PUBLIC_REVIEW_NO_TOOL_POSTURE]: {
      matchProvider: (provider) => isProcessProvider(provider) && isPiCommand(provider?.command),
      spawnArgs: (provider, { effectiveModel, effort } = {}) => ({
        command: provider.command,
        args: ensurePiHeadlessArgs([
          '--no-approve', '--no-tools', '--no-builtin-tools', '--no-extensions',
          '--no-skills', '--no-prompt-templates', '--no-themes', '--no-context-files', '--no-session',
        ], effectiveModel, effort),
        stdinMode: 'prompt',
      }),
    },
  },
};

// ─── claude (default fallback — MUST stay last) ────────────────────────────

function claudeCliArgs(baseArgs, { model, effort, provider }) {
  const args = [...baseArgs, '-p', '-'];
  if (model && !hasModelFlag(baseArgs)) {
    const resolvedModel = resolveClaudeCliModel(model, {
      env: { ...process.env, ...provider?.envVars },
      providerId: provider?.id || '',
    });
    args.push('--model', resolvedModel);
  }
  args.push(...buildEffortArgs(effort, provider, args));
  return args;
}

const CLAUDE_PERMISSION_POSTURE_FLAGS = [
  '--permission-mode', '--dangerously-skip-permissions', '--allow-dangerously-skip-permissions',
];

function claudeSpawnArgs(provider, { effectiveModel, effort, systemPromptFile, settingsEnv }) {
  const providerId = provider?.id || 'claude-code';
  const providerArgs = provider?.args || [];
  // A provider that pins its own permission posture (e.g. `--permission-mode auto`)
  // must not also receive the default bypass, which would override it (#10419).
  const hasPosture = argvHasFlag(providerArgs, CLAUDE_PERMISSION_POSTURE_FLAGS);
  const args = applyLeanClaudeArgs(provider, [
    ...(hasPosture ? [] : ['--dangerously-skip-permissions']),
    '--print',
    '--output-format', 'stream-json',
    '--verbose',
    '--include-partial-messages',
    ...providerArgs,
  ], provider?.command || 'claude');
  if (systemPromptFile) {
    args.push('--append-system-prompt-file', systemPromptFile);
  }
  if (effectiveModel) {
    const injectedModel = resolveClaudeCliModel(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' };
}

// Shared by both Claude postures: no MCP servers, no browser bridge, no
// persisted session, no slash commands. `--bare` is NOT here: it also disables
// OAuth/keychain auth, so it would break a subscription-authenticated cloud
// Claude — `applyLeanClaudeArgs` adds it for the local Ollama wrapper only.
const CLAUDE_PUBLIC_REVIEW_COMMON_ARGS = [
  '--strict-mcp-config',
  '--mcp-config', '{"mcpServers":{}}',
  '--no-chrome',
  '--no-session-persistence',
  '--disable-slash-commands',
];

const CLAUDE_PUBLIC_REVIEW_NO_TOOL_ARGS = [
  '--permission-mode', 'plan',
  // The code-review model gets the cleared PR material in its prompt. Keep
  // both controls: `--restricted` removes the command/network-capable built-in
  // tools, while the explicit empty set prevents Claude Code from advertising
  // any tool schema to a local model that does not support tool calls.
  '--restricted',
  '--tools', '',
  ...CLAUDE_PUBLIC_REVIEW_COMMON_ARGS,
];

// Claude Code's OS-level sandbox (seatbelt on macOS, bubblewrap on Linux) is a
// settings switch rather than a flag; `--settings` accepts inline JSON. Inside
// it, Bash runs without prompting but filesystem writes stay inside the working
// tree and the empty domain allowlist denies every network request — in
// `--print` mode a denied request is simply not executed, there is nobody to
// approve it. The web tools are denied outright for the same reason.
//
// `sandbox.filesystem.allowWrite` (a real, current setting) does NOT reach a
// PR that edits `.claude/skills`, `.claude/agents`, `.claude/commands`,
// `.claude/hooks`, `.claude/workflows`, or `.mcp.json` — Claude Code's docs
// state plainly that these are "protected paths" and "there is no way to
// exempt one of them: an allowWrite entry ... doesn't lift the protection."
// (docs.claude.com/en/docs/claude-code/sandboxing, "Protected paths"). The
// only way to lift it is `sandbox.filesystem.disabled`, which turns off
// filesystem isolation for every path — defeating the point of sandboxing an
// untrusted PR's patch. So the Stage 3 review prompt (`pr-reviewer-review` in
// taskPromptDefaults/prompts.js) is taught the `git apply --cached` +
// index-verification fallback instead (#5963).
const CLAUDE_SANDBOX_SETTINGS = JSON.stringify({
  sandbox: { enabled: true, autoAllowBashIfSandboxed: true, network: { allowedDomains: [] } },
});
const CLAUDE_PUBLIC_REVIEW_ACTIONS_ARGS = [
  '--permission-mode', 'acceptEdits',
  '--settings', CLAUDE_SANDBOX_SETTINGS,
  '--disallowedTools', 'WebFetch,WebSearch',
  ...CLAUDE_PUBLIC_REVIEW_COMMON_ARGS,
];

// Flags Claude Code accepts ONLY alongside `--print`, mapped to whether they
// consume the following argv entry as their value. The posture arrays above are
// written for the headless launch, so the attachable `tuiSpawnArgs` recipe has to
// drop them — the CLI refuses to start at all otherwise:
//
//   Error: --no-session-persistence can only be used with --print mode.
//
// That is a 3-second exit(1) before the prompt is ever pasted, and it burned all
// three retries of a Stage 3 pr-reviewer run. Worse, the only thing in the PTY
// transcript by then was the shell's echo of the argv, so the failure analyzer
// classified the run off `--mcp-config '{"mcpServers":{}}'` and filed "MCP server
// error" for what was a flag-compatibility bug (agent-a12b1837).
//
// Filtered rather than conditionally spread so a print-only flag added to ANY
// posture set is dropped for the attachable recipe automatically.
const CLAUDE_PRINT_ONLY_ARGS = new Map([
  ['--no-session-persistence', false],
  ['--output-format', true],
]);

function dropPrintOnlyArgs(args) {
  const kept = [];
  for (let i = 0; i < args.length; i += 1) {
    if (!CLAUDE_PRINT_ONLY_ARGS.has(args[i])) {
      kept.push(args[i]);
      continue;
    }
    if (CLAUDE_PRINT_ONLY_ARGS.get(args[i])) i += 1; // also skip its value
  }
  return kept;
}

const claudePublicReviewSpawnArgsFor = (postureArgs) => (provider, ctx) => claudePublicReviewArgs(postureArgs, provider, ctx);

function claudePublicReviewArgs(postureArgs, provider, {
  effectiveModel,
  effort,
  systemPromptFile,
  tui = false,
} = {}) {
  const providerId = provider?.id || 'claude-code';
  const args = [
    ...(tui ? dropPrintOnlyArgs(postureArgs) : postureArgs),
    ...(tui ? [] : ['--print', '--output-format', 'stream-json', '--verbose', '--include-partial-messages']),
  ];
  if (systemPromptFile) args.push('--append-system-prompt-file', systemPromptFile);
  if (effectiveModel) {
    // Pass the stage's model id through VERBATIM. Do not consult the host's
    // Bedrock settings or ambient environment while constructing it: this
    // profile is reachable from an Ollama-backed Claude wrapper, and a server
    // started in Bedrock mode must not turn a local model into a cloud one.
    args.push('--model', effectiveModel);
  }
  const safeArgs = applyLeanClaudeArgs(provider, args, provider?.command || 'claude');
  safeArgs.push(...buildEffortArgs(effort, { id: providerId, command: provider?.command || 'claude' }, safeArgs));
  return {
    command: provider?.command || 'claude',
    args: safeArgs,
    stdinMode: 'prompt',
    streamFormat: 'stream-json',
  };
}

const matchClaudeBinary = (provider) => isProcessProvider(provider) && isClaudeCommand(provider?.command);

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,
  // Positive binary match: the row's always-true `matchCommand` must never
  // hand an unknown command claude's flags or a tool-free verdict.
  toolFreeOneShot: { matchCommand: isClaudeCommand, toolFreeArgs: claudeToolFreeArgs },
  publicReview: {
    // Claude is the historical always-true fallback row, so its posture
    // matcher must positively identify the binary — an unknown command must
    // never inherit claude's flag set.
    [PUBLIC_REVIEW_NO_TOOL_POSTURE]: {
      spawnArgs: claudePublicReviewSpawnArgsFor(CLAUDE_PUBLIC_REVIEW_NO_TOOL_ARGS),
      matchProvider: matchClaudeBinary,
    },
    [PUBLIC_REVIEW_ACTIONS_POSTURE]: {
      spawnArgs: claudePublicReviewSpawnArgsFor(CLAUDE_PUBLIC_REVIEW_ACTIONS_ARGS),
      matchProvider: matchClaudeBinary,
      // One of two posture/vendor pairings that may run as an ATTACHABLE session
      // (OpenCode is the other — see its row).
      // `claudePublicReviewArgs` drops only the flags that REQUIRE `--print`
      // (the headless output set plus CLAUDE_PRINT_ONLY_ARGS) for
      // `tui: true`; every enforcement flag above (`--permission-mode
      // acceptEdits`, the `--settings` sandbox JSON, `--disallowedTools`, and
      // the shared no-MCP/no-chrome/no-slash-command set) is still emitted, so
      // an operator who drops into the PTY inherits the same boundary the
      // headless run had. Nothing inside the session can widen it: the only
      // lever that lifts Claude Code's filesystem protection is
      // `sandbox.filesystem.disabled`, which this recipe never emits, and
      // `--disable-slash-commands` removes the in-session settings surface.
      tuiSpawnArgs: claudePublicReviewSpawnArgsFor(CLAUDE_PUBLIC_REVIEW_ACTIONS_ARGS),
    },
  },
};

/**
 * 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, KILO, OPENCHAMBER, PI, 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);
}

/**
 * The vendor recipe enforcing `posture` for `provider`, or null when this
 * install has no maintained recipe for that pairing.
 *
 * Eligibility is DECLARED by the vendor row, never named by the caller: a
 * pipeline stage asks for a posture and every enabled provider whose vendor
 * declares it is a legal choice. That is what lets an install with only grok
 * (or only a local Claude wrapper) configure the same stages an install with
 * codex configures. A row's matcher must positively identify the binary —
 * claude's `matchCommand` is unconditionally true (it is the historical
 * fallback row), so an unknown command must never inherit its argv.
 */
export function publicReviewRecipe(provider, posture) {
  if (!PUBLIC_REVIEW_POSTURES.includes(posture)) return null;
  for (const vendor of PROVIDER_VENDORS) {
    const recipe = vendor.publicReview?.[posture];
    if ((recipe?.spawnArgs || recipe?.tuiSpawnArgs) && recipe.matchProvider(provider)) return recipe;
  }
  return null;
}

/**
 * `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.matchId ? vendor.matchId(id) : vendor.idFragment && id.includes(vendor.idFragment)) return vendor.inferredCommand;
  }
  return CLAUDE.inferredCommand;
}

/**
 * `applyCommandDefaults` (tuiHandshake.js): interactive-session flag dispatch.
 * Public-review stages never reach this — headless OR attachable, their argv
 * comes from `buildVendorSpawnConfig`, which is where a posture is enforced.
 * (That is load-bearing for the attachable case: `ensureAntigravityTuiArgs` and
 * friends append `--dangerously-skip-permissions`-class defaults, which would
 * undo the recipe.)
 *
 * `provider` carries the record-level facts a command name cannot — the codex
 * `ignoreUserConfig` pin and its local-runtime backing. Passing it here keeps
 * BOTH TUI spawn paths on one injection point, which is the whole reason this
 * dispatcher exists (see the `injectTuiModelAndEffort` note below for what
 * happened the last time an argv rule lived in only one of them).
 */
export function applyCommandDefaults(command, args, provider = null) {
  const vendor = PROVIDER_VENDORS.find((v) => v.tuiArgs && v.matchCommand(command));
  if (!vendor) return args;
  // `provider` is optional and only some vendors read it (codex, for the
  // `ignoreUserConfig` pin and the local-runtime backing) — a vendor that
  // ignores the second argument keeps behaving exactly as before.
  return vendor.tuiArgs(args, provider);
}

/**
 * `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).
 *
 * `options` carries the spawn facts an argv BUILDER cannot know because they
 * are decided per run rather than per provider — today just `cwd`, which
 * OpenChamber needs as the `--dir` its control plane cannot infer (see
 * openchamber.js). Every other vendor ignores it.
 */
export function prepareCliPrompt(command, args, prompt, options = {}) {
  const vendor = PROVIDER_VENDORS.find((v) => v.preparePrompt && v.matchCommand(command));
  return vendor ? vendor.preparePrompt(args, prompt, options) : prepareGrokPromptFile(args, prompt);
}

/** `buildCliArgs` (cliProviderArgs.js): headless one-shot argv per vendor. */
export function buildVendorCliArgs(provider, baseArgs, { model, effort, toolFree = false }) {
  const vendor = PROVIDER_VENDORS.find((v) => v.cliArgs && matchesProvider(v, provider));
  return vendor.cliArgs(baseArgs, { model, effort, provider, toolFree });
}

/**
 * Make a built one-shot CLI argv tool-free (#9008), for callers that hand the
 * model text they do not control — Ask and AI app detection. Run it on the
 * FINAL argv (after the vendor builder, before prompt delivery), because
 * several builders append their vendor's bypass flag themselves.
 *
 * Every approval-bypass switch is removed for every vendor. A vendor with a
 * maintained tool-disable switch (claude, grok, pi) then gets it appended and
 * reports `toolFree: true`; every other CLI — including agy, codex, opencode,
 * kilo and cursor, whose tool posture has no argv off switch — reports
 * `toolFree: false`, which callers treat as host control. An API provider runs
 * no process, so its argv is returned unchanged with `toolFree: true`.
 *
 * @param {object} provider - provider record (type, command)
 * @param {string[]} [args] - the built argv
 * @returns {{ args: string[], toolFree: boolean }}
 */
export function toolFreeOneShotArgs(provider, args = []) {
  if (provider?.type === PROVIDER_TYPES.API) return { args: [...args], toolFree: true };
  const spec = PROVIDER_VENDORS.find((v) => v.toolFreeOneShot?.matchCommand(provider?.command))?.toolFreeOneShot;
  const { args: stripped, removed } = stripApprovalBypassArgs(args, spec?.bypassAliases);
  if (spec?.toolFreeArgs) return { args: spec.toolFreeArgs(stripped), toolFree: true };
  if (spec?.sandboxArgs) return { args: spec.sandboxArgs(stripped), toolFree: false, readOnlySandbox: true };
  return { args: removed && spec?.afterStrip ? spec.afterStrip(stripped) : stripped, toolFree: false };
}

// Autofixer repair posture (#12487). Claude keeps file Read/Edit/Write only:
// acceptEdits auto-approves edits inside the working directory and nothing
// else, and neither project MCP servers nor project settings (hooks) load.
const CLAUDE_REPAIR_ARGS = [
  '--restricted', '--safe-mode',
  '--permission-mode', 'acceptEdits',
  '--tools', 'Read,Edit,Write,Grep,Glob',
  '--strict-mcp-config', '--mcp-config', '{"mcpServers":{}}',
  '--no-chrome', '--disable-slash-commands',
  '--disallowedTools', 'Bash', 'WebFetch', 'WebSearch',
];
// Codex's OS sandbox confines its shell commands to the working directory
// with network off. MCP servers, plugins and apps run outside that sandbox
// (computer-use, node_repl), and an `mcp_servers` override cannot clear them,
// so the user's config.toml is not loaded at all (auth still is) and the
// plugin/app surfaces are disabled.
const CODEX_REPAIR_ARGS = [
  '--sandbox', 'workspace-write', '--ignore-user-config', '--ignore-rules',
  '-c', `${CODEX_WORKSPACE_NETWORK_KEY}=false`, '-c', `${CODEX_WORKSPACE_WRITABLE_ROOTS_KEY}=[]`,
  '-c', `${CODEX_PLUGINS_FEATURE_KEY}=false`, '-c', `${CODEX_APPS_FEATURE_KEY}=false`,
  '-c', `${CODEX_HOOKS_FEATURE_KEY}=false`,
];

/**
 * Saved provider argv for a file-editing repair driven by untrusted input
 * (autofixer crash logs), or null when the vendor has no enforced restricted
 * mode. Build from the fixed recipe: arbitrary saved options can restore MCP,
 * plugins, hooks or writable roots even after a sandbox flag is overridden.
 * Model and effort still come from the provider's fields in the vendor builder.
 * The result replaces `provider.args`; the vendor builder adds `-p -` / `-`.
 *
 * @param {object} provider - provider record (command, args)
 * @returns {{ mode: 'claude-disallowed-tools'|'codex-workspace-write', args: string[] } | null}
 */
export function restrictedRepairArgs(provider) {
  const command = provider?.command;
  if (!command) return null;
  if (isClaudeCommand(command)) {
    return { mode: 'claude-disallowed-tools', args: [...CLAUDE_REPAIR_ARGS] };
  }
  if (isCodexCommand(command)) {
    return { mode: 'codex-workspace-write', args: ['exec', ...CODEX_REPAIR_ARGS] };
  }
  return null;
}

/**
 * Whether a one-shot call on `provider` can run without host authority: an API
 * provider, or a headless CLI whose vendor has a tool-disable switch. A TUI
 * record is never tool-free — its interactive argv comes from the TUI spawn
 * path, which this module does not make tool-free.
 */
export function isToolFreeOneShotProvider(provider) {
  if (provider?.type === PROVIDER_TYPES.API) return true;
  return provider?.type === PROVIDER_TYPES.CLI && toolFreeOneShotArgs(provider).toolFree;
}

/**
 * Whether a headless CLI one-shot is held to an OS read-only sandbox (codex)
 * though it cannot disable its tools. Weaker than tool-free: read tools remain.
 */
function isReadOnlySandboxOneShotProvider(provider) {
  return provider?.type === PROVIDER_TYPES.CLI && toolFreeOneShotArgs(provider).readOnlySandbox === true;
}

/** Providers music-video code authoring may use: tool-free, or read-only sandboxed. */
export function isAuthoringOneShotProvider(provider) {
  return isToolFreeOneShotProvider(provider) || isReadOnlySandboxOneShotProvider(provider);
}

/**
 * The refusal for a one-shot over caller text whose provider cannot be made
 * tool-free and whose caller lacks host control, or null when it may run.
 * A plain `{ status, code, message }` so this module stays free of the server's
 * error classes; callers wrap it in a `ServerError`.
 *
 * @param {object} provider
 * @param {boolean} hasHostControl - the caller's server-derived authority
 */
export function toolFreeOneShotRefusal(provider, hasHostControl) {
  if (hasHostControl === true || isToolFreeOneShotProvider(provider)) return null;
  return {
    status: 403,
    code: 'HOST_CONTROL_FORBIDDEN',
    message: `Provider '${providerLabel(provider)}' cannot run without tools, so using it here requires host control: an operator session, or a local connection when no password is set. Choose an API provider or a tool-free CLI instead.`,
  };
}

/** How a provider names itself in an error a user has to act on. */
function providerLabel(provider) {
  return provider?.id || provider?.command || 'unknown';
}

/**
 * `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 posture = publicReviewPostureForProfile(ctx?.safetyProfile);
  if (posture) {
    const recipe = publicReviewRecipe(provider, posture);
    if (!supportsPublicReviewPosture(provider, posture)) {
      throw new Error(`Provider '${providerLabel(provider)}' has no enforced ${posture} public-review posture`);
    }
    // An interactive spawn has no headless fallback tier: the ordinary
    // `spawnArgs` of a vendor without a TUI-capable recipe emits that vendor's
    // HEADLESS argv (`--print`, `exec`, `run`), which in a PTY neither accepts
    // a pasted prompt nor enforces anything. Fail closed rather than open a
    // session whose posture is decorative. Callers decide TUI-vs-headless from
    // `supportsTuiPublicReviewPosture`, so reaching this is a routing bug.
    if (ctx?.tui) {
      if (!recipe?.tuiSpawnArgs) {
        throw new Error(`Provider '${providerLabel(provider)}' has no attachable ${posture} public-review recipe`);
      }
      return recipe.tuiSpawnArgs(provider, ctx);
    }
    return recipe.spawnArgs(provider, ctx);
  }
  const vendor = PROVIDER_VENDORS.find((v) => v.spawnArgs && matchesProvider(v, provider));
  return vendor.spawnArgs(provider, ctx);
}

/**
 * Every public-review posture this provider can actually be configured for,
 * in `PUBLIC_REVIEW_POSTURES` order. This is the value the schedule UI reads to
 * offer a stage's eligible providers, so it must stay derived from the vendor
 * rows rather than from a hardcoded list of vendor names.
 *
 * API/custom providers have no maintained recipe: a generic read-only prompt
 * is not enforcement, so they fail closed. A TUI record IS eligible — the
 * stage spawns its binary through the vendor's enforced recipe, headless unless
 * that recipe also supplies `tuiSpawnArgs` (see `isProcessProvider` and
 * `supportsTuiPublicReviewPosture`).
 */
export function publicReviewPosturesForProvider(provider) {
  return PUBLIC_REVIEW_POSTURES.filter((posture) => supportsPublicReviewPosture(provider, posture));
}

/**
 * The subset of `publicReviewPosturesForProvider` backed by a vendor-enforced
 * recipe; the schedule UI uses the difference to say which actions-stage
 * choices are OS-sandboxed and which rely on the worktree alone.
 */
export function enforcedPublicReviewPosturesForProvider(provider) {
  return PUBLIC_REVIEW_POSTURES.filter((posture) => enforcesPublicReviewPosture(provider, posture));
}

// A row that supplies the HEADLESS argv is an enforcement; one that supplies
// only an attachable invocation (OpenCode's actions row) is not — the stage
// still falls through to the vendor's ordinary argv and the schedule UI keeps
// reporting that choice as worktree-only rather than OS-sandboxed.
const enforcesPublicReviewPosture = (provider, posture) => (
  isProcessProvider(provider) && Boolean(publicReviewRecipe(provider, posture)?.spawnArgs)
);

/**
 * Vendor ids that declare a maintained recipe for `posture`, for naming what a
 * user could install when nothing on their machine qualifies. Derived from the
 * rows so the suggestion cannot go stale when a vendor gains or loses a recipe.
 */
export function publicReviewCapableVendorIds(posture) {
  return PROVIDER_VENDORS.filter((vendor) => vendor.publicReview?.[posture]?.spawnArgs).map((vendor) => vendor.id);
}

/**
 * Whether `provider` may run a stage with this posture.
 *
 * The no-tool gate requires a maintained recipe: only an enforced argv can
 * hold a model tool-free. Actions require a maintained enforcement recipe too:
 * a disposable worktree cannot stop malware reading host files or networking.
 * API providers have no binary to spawn and fail closed for these CLI profiles.
 */
export function supportsPublicReviewPosture(provider, posture) {
  return enforcesPublicReviewPosture(provider, posture);
}

/**
 * The spawn-time gate for a public-content stage, as a block or `null`.
 *
 * Takes the POSTURE (what the stage requires), not a boolean, because the
 * caller's posture is `null` for every ordinary task — and `null` has no
 * recipe, so asking `supportsPublicReviewPosture` about it answers "false"
 * for work that was never public-content at all. Deciding here keeps the
 * "no posture requested" case explicit instead of a caller-side `&&` that a
 * refactor can drop (it was, in #5830: every ordinary agent task blocked with
 * "has no enforced null public-content review mode").
 *
 * @returns {{ reason: string, category: string }|null}
 */
export function publicReviewProviderBlock(provider, posture) {
  if (!posture) return null;
  if (supportsPublicReviewPosture(provider, posture)) return null;
  return {
    reason: `Provider '${providerLabel(provider)}' has no enforced ${posture} public-content review mode`,
    category: posture === PUBLIC_REVIEW_ACTIONS_POSTURE
      ? 'public-review-actions-provider-unsupported'
      : 'public-review-provider-unsupported',
  };
}

/** Whether a provider can run a tool-free public-content stage. */
export function supportsPublicReviewProvider(provider) {
  return supportsPublicReviewPosture(provider, PUBLIC_REVIEW_NO_TOOL_POSTURE);
}

/**
 * How a CLI code reviewer is held to reading, strongest first — or null when
 * the vendor maintains no enforced reviewer mode:
 *
 * - `no-tool`   — the vendor's no-tool public-review recipe (claude, grok, …).
 * - `read-only` — an enforced mode that may read but never write (codex's
 *                 OS-level read-only sandbox).
 *
 * Only code review consults the read-only tier; a no-tool pipeline stage still
 * requires the no-tool recipe. Antigravity has neither: live runs showed both
 * its `--mode plan` and its terminal `--sandbox` still write files, so it
 * must not be listed here as read-only.
 */
export function codeReviewTier(provider) {
  if (supportsPublicReviewProvider(provider)) return PUBLIC_REVIEW_NO_TOOL_POSTURE;
  return readOnlyReviewRecipe(provider) ? 'read-only' : null;
}

function readOnlyReviewRecipe(provider) {
  if (!isProcessProvider(provider)) return null;
  return PROVIDER_VENDORS.find((vendor) => vendor.readOnlyReview?.matchProvider(provider))?.readOnlyReview || null;
}

/**
 * Headless argv for the tier `codeReviewTier` names (`ctx` as for
 * `buildVendorSpawnConfig`), or null when the vendor has no enforced reviewer
 * mode and the caller must fall back to its ordinary argv.
 */
export function buildCodeReviewSpawnConfig(provider, ctx) {
  if (supportsPublicReviewProvider(provider)) return buildVendorSpawnConfig(provider, ctx);
  return readOnlyReviewRecipe(provider)?.spawnArgs(provider, ctx) || null;
}

/** Whether a provider can run the sandboxed final public-review stage. */
export function supportsPublicReviewActionsProvider(provider) {
  return supportsPublicReviewPosture(provider, PUBLIC_REVIEW_ACTIONS_POSTURE);
}

/**
 * Whether `provider` may run a `posture` stage as an ATTACHABLE PTY session
 * rather than headless.
 *
 * Deliberately much narrower than `supportsPublicReviewPosture`: that one lets
 * the actions stage fall through to a vendor's ordinary headless recipe when it
 * declares none, which is fine for a `--print` child and useless in a PTY. An
 * interactive session requires a recipe that has been reviewed for it and
 * supplies `tuiSpawnArgs` — the argv a PTY can drive (for Claude the headless
 * argv minus the flags that only work under `--print`; for OpenCode a
 * different entry point entirely).
 *
 * `no-tool` is structurally excluded: an interactive session for a reasoner
 * with no tools buys nothing and widens the boundary for free, so no row
 * declares it and this returns false for that posture by construction.
 */
export function supportsTuiPublicReviewPosture(provider, posture) {
  return enforcesPublicReviewPosture(provider, posture) && Boolean(publicReviewRecipe(provider, posture)?.tuiSpawnArgs);
}

/** Whether the sandboxed final public-review stage can attach a PTY here. */
export function supportsTuiPublicReviewActionsProvider(provider) {
  return supportsTuiPublicReviewPosture(provider, PUBLIC_REVIEW_ACTIONS_POSTURE);
}

/**
 * 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)];
  }
  if (isCursorProvider({ id: provider?.id, command })) {
    // Cursor's effort is a model-variant parameter, not a flag — fold it in so
    // the TUI honors a pinned level instead of dropping it (buildEffortArgs
    // emits nothing for cursor by design).
    const cursorModel = foldCursorEffortIntoModel(
      resolveCliModel(model),
      resolveCliEffort(effort, { id: provider?.id, command })
    );
    return (cursorModel && !hasModelFlag(baseArgs)) ? [...baseArgs, '--model', cursorModel] : baseArgs;
  }
  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,
    effectiveModel,
  )];
}

// 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'];