UNPKG

@bitkyc08/opencodex

Version:

Universal provider proxy for OpenAI Codex & Claude Code — use any LLM with Codex CLI/App/SDK and Claude Code

1,859 lines • 86.8 kB
/**
 * Client-neutral config export core.
 *
 * One pure function per client, one shared input type. Every export surface (CLI,
 * management API, GUI) consumes this module so the bytes a user copies, downloads, or
 * curls can never drift between surfaces.
 *
 * Two invariants carried over from `ocx opencode` (src/cli/opencode.ts), which owned the
 * OpenCode serializer before it moved here:
 *
 * - **No secret is ever serialized.** Configs carry only the client's documented env
 *   reference (`{env:VAR}` for OpenCode, `$VAR` for Pi); the real admission key travels
 *   through the environment. AGENTS.md treats token serialization as a release blocker.
 * - **No metadata is guessed.** A model with no authoritative context window ships
 *   without context/output fields, and the client applies its own defaults. Pi's `cost`
 *   is omitted entirely rather than zero-filled, because zeros would assert "free",
 *   which is false for routed providers.
 *
 * This module never writes a file. `destination` names the canonical path for a human;
 * targeting it is the caller's explicit act.
 */
import { homedir } from "node:os";
import { gentleShellPaths } from "./gentle-shell-path";
import { absoluteClientPath, ClientPathError, isAbsoluteClientPath, piAgentDir } from "./client-path";
export { ClientPathError, piAgentDir } from "./client-path";
import { existsSync, lstatSync, readFileSync, realpathSync, statSync } from "node:fs";
import { basename, dirname, join, resolve } from "node:path";
import { shouldInjectApiAuthHeader, standaloneCodexRoutingTarget } from "../codex/inject";
import { FORMAT_MEDIA_TYPE, serializeDocument, type ConfigFormat } from "../integrations/serialize";
import { fileIO } from "../integrations/config-io";
import { canonicalizeReasoningEfforts } from "../reasoning-effort";
import { selectNestedSelectors } from "./config-export/nested-selectors";
import { providerCodexAccountMode } from "../providers/registry";
import { expandFastExportModels } from "./config-export/fast-models";
import { namedExportContext } from "./config-export/alias-selectors";
import { probeHostname } from "../server/proxy-liveness";
import type { OcxConfig } from "../types";

export type { ConfigFormat } from "../integrations/serialize";
export type { ManagedFragment, ManagedContribution, BuildContribution, OpencodeLaunchEnv, OpencodeCatalogModel, ExportModel, ExportContext, ExportClientId, ExportClientSpec, PiModelEntry, DroidReasoningDefaults } from "./config-export/contracts";
export { OPENCODE_PROVIDER_ID, OPENCODE_CONFIG_SCHEMA, OPENCODE_API_KEY_ENV, OPENCODE_API_KEY_ENV_REF, KILO_API_KEY_ENV, KILO_API_KEY_ENV_REF, KILO_CONFIG_SCHEMA, HERMES_API_KEY_ENV, HERMES_API_KEY_ENV_REF, OPENCLAW_API_KEY_ENV, OPENCLAW_API_KEY_ENV_REF, LOOPBACK_API_KEY_PLACEHOLDER, GAJAE_API_KEY_ENV, SCHEMA_REQUIRED_OUTPUT_BUDGET, OPENCODE_PROVIDER_BLOCK_DEFAULT_CONFIG } from "./config-export/constants";
export { normalizeExportModels } from "./config-export/model-metadata";
export type { OmpModelEntry, OmpProviderBlock, OmpGeneratedConfig } from "./config-export/omp";
export type { ZcodeModelEntry, ZcodeProviderBlock, ZcodeGeneratedConfig } from "./config-export/zcode";
export type { ZcodeStoreProviderRule, ZcodeStoreModelRule } from "./config-export/zcode-store";
export {
  ZCODE_STORE_SCHEMA_VERSION,
  ZCODE_STORE_PROVIDER_GROUP,
  ZCODE_STORE_API_TYPE,
  ZCODE_STORE_PROVIDER_NAME,
  ZCODE_STORE_PROVIDER_RULES_PATH,
  ZCODE_STORE_MODEL_RULES_PATH,
  buildZcodeStoreProviderRule,
  buildZcodeStoreContribution,
  zcodeStoreSchemaEstablished,
} from "./config-export/zcode-store";
export type { DshReasoningEffort, DshWireReasoningEffort, DshModelEntry, DshProviderBlock, DshGeneratedConfig } from "./config-export/dsh";
export { DSH_PROFILE_PROVIDER_PATH, dshProfilePatchEstablished, buildDshProfilePatchContribution } from "./config-export/dsh";
export type { McodeProviderBlock, McodeModelEntry, McodeGeneratedConfig } from "./config-export/mcode";
export type { RaycastAbility, RaycastAbilityName, RaycastModelEntry, RaycastProviderEntry, RaycastGeneratedConfig } from "./config-export/raycast";
export { buildRaycastClientConfig, summarizeRaycast, buildRaycastContribution } from "./config-export/raycast";
export { droidHomeDir, droidConfigPath, buildDroidClientConfig, summarizeDroid, buildDroidContribution, droidReasoningModels, droidDefaultsFromOwnedRows, validateDroidReasoningDefaults } from "./config-export/droid";
export type { DroidModelEntry, DroidGeneratedConfig } from "./config-export/droid";

import type { ExportModel, OpencodeLaunchEnv, OpencodeCatalogModel, ExportContext, PiModelEntry, ManagedContribution, ManagedFragment, ExportClientId, ExportClientSpec } from "./config-export/contracts";
import { OPENCODE_API_KEY_ENV_REF, OPENCODE_PROVIDER_BLOCK_DEFAULT_CONFIG, OPENCODE_CONFIG_SCHEMA, OPENCODE_PROVIDER_ID, PI_API_DIALECT, LOOPBACK_API_KEY_PLACEHOLDER, HERMES_API_KEY_ENV_REF, OPENCLAW_API_KEY_ENV_REF, OPENCODE_API_KEY_ENV, HERMES_API_KEY_ENV, OPENCLAW_API_KEY_ENV, KILO_API_KEY_ENV } from "./config-export/constants";
import { exportModelLabel, authoritativeContextWindow, outputBudgetFor, inputBudgetFor, normalizeExportModels, inputModalitiesForClient, opencodeModelCapabilities, proxyAdmissionHeaders, singleFragment } from "./config-export/model-metadata";
import { exportReasoningEfforts, exportDefaultReasoningEffort, legacyReasoningMetadata, type LegacyEffortVariant } from "./config-export/reasoning-metadata";
import { opencodeModelUsesChat } from "./config-export/opencode-wire";
import { buildOmpClientConfig, summarizeOmp, buildOmpContribution } from "./config-export/omp";
import { buildDshClientConfig, summarizeDsh, buildDshContribution, DSH_DESKTOP_PROFILE } from "./config-export/dsh";
import { buildMcodeClientConfig, summarizeMcode, buildMcodeContribution } from "./config-export/mcode";
import { buildZcodeClientConfig, summarizeZcode, buildZcodeContribution } from "./config-export/zcode";
import { buildClineClientConfig, summarizeCline, buildClineContribution } from "./config-export/cline";
import { buildRaycastClientConfig, summarizeRaycast, buildRaycastContribution } from "./config-export/raycast";
import { buildKiloClientConfig, summarizeKilo, buildKiloContribution, kiloConfigPath } from "./config-export/kilo";
export { kiloConfigPath, kiloHomeDir, kiloCandidatePath, KILO_CONFIG_CANDIDATES } from "./config-export/kilo";
export type { KiloGeneratedConfig, KiloProviderBlock, KiloModelEntry } from "./config-export/kilo";
import { droidConfigPath, buildDroidClientConfig, summarizeDroid, buildDroidContribution } from "./config-export/droid";
import {
  buildCommandCodeClientConfig,
  summarizeCommandCode,
  buildCommandCodeContribution,
  commandCodeProviderRoot,
  type CommandCodeGeneratedConfig,
  type CommandCodeModelEntry,
  type CommandCodeProviderBlock,
} from "./config-export/commandcode";

export type { CommandCodeGeneratedConfig, CommandCodeModelEntry, CommandCodeProviderBlock };
export { buildCommandCodeClientConfig, summarizeCommandCode, buildCommandCodeContribution, commandCodeProviderRoot };
import { agentConfigPath, buildQoderCnClientConfig, buildQoderCnContribution, buildWorkbuddyClientConfig, buildWorkbuddyContribution, summarizeWorkbuddy, workbuddyApplyRefusal } from "./config-export/agent-clients";
import { buildQoderClientConfig, summarizeQoder, buildQoderContribution, qoderConfigPath } from "./config-export/qoder";
export { buildQoderClientConfig, qoderConfigPath, qoderHomeDir, type QoderGeneratedConfig } from "./config-export/qoder";
import { buildT3CodeClientConfig, summarizeT3Code, buildT3CodeContribution, t3codeApplyRefusal, t3codeConfigPath } from "./config-export/t3code";
export { buildT3CodeClientConfig, t3codeConfigPath, t3codeHomeDir, type T3CodeGeneratedConfig } from "./config-export/t3code";



export interface OpencodeModelEntry {
  name: string;
  provider?: { npm: typeof OPENCODE_CHAT_NPM };
  limit?: { context: number; input?: number; output: number };
  /**
   * opencode's own capability fields, derived from the catalog row's declared input
   * modalities. Written only when the row declares at least one — an entry without them is
   * what opencode already treats as text-only, and omitting them keeps an undeclared model
   * byte-identical to what shipped before.
   */
  attachment?: boolean;
  modalities?: { input: string[]; output: string[] };
  tool_call?: boolean;
  reasoning?: boolean;
  interleaved?: { field: "reasoning_content" };
  options?: { reasoningEffort: string };
  variants?: Record<string, LegacyEffortVariant>;
}

/**
 * One selectable reasoning effort.
 *
 * Native V2 variants use settings; legacy clients receive a separate options map.
 */
export interface OpencodeModelVariant {
  id: string;
  settings: { reasoningEffort: string };
}

export interface OpencodeV2ModelEntry {
  name: string;
  package?: typeof OPENCODE_CHAT_PACKAGE;
  limit?: { context: number; input?: number; output: number };
  capabilities?: { tools: boolean; input?: string[]; output?: string[] };
  compatibility?: { reasoningField: "reasoning_content" };
  settings?: { reasoningEffort: string };
  variants: OpencodeModelVariant[];
}

/** Endpoint and admission, spelled once and shared by both block generations. */
export interface OpencodeProviderConnection {
  baseURL: string;
  apiKey?: string;
  headers?: Record<string, string>;
  /**
   * opencode's own client-side wait for the proxy's first response header, in ms, or `false`
   * to disable it. Emitted only when `opencodeClientExport.headerTimeoutMs` is set. opencode's
   * default is 300000 (5 min); a slow local model's prompt prefill behind a non-streaming turn
   * can exceed it, so the proxy sends no bytes and opencode's header wait fires ("Timed out
   * waiting for response headers").
   */
  headerTimeout?: number | false;
  /** opencode's wait between streamed response chunks (ms) or `false`; emitted from `chunkTimeoutMs`. */
  chunkTimeout?: number | false;
  /** opencode's whole-request bound (ms) or `false`; emitted from `timeoutMs`. opencode has no default. */
  timeout?: number | false;
}

/** opencode V1 provider block: `npm` + `options`. */
export interface OpencodeProviderBlock {
  npm: string;
  name: string;
  options: OpencodeProviderConnection;
  models: Record<string, OpencodeModelEntry>;
}

/** opencode V2 provider block: `package` + `settings` and native variant arrays. */
export interface OpencodeV2ProviderBlock {
  package: string;
  name: string;
  settings: Omit<OpencodeProviderConnection, "headers">;
  headers?: Record<string, string>;
  models: Record<string, OpencodeV2ModelEntry>;
}

/**
 * Both generations, always built together: they are one document's two fragments and must
 * agree on the model set, the names, and the connection. Building them in one pass is what
 * makes that a fact rather than a convention.
 */
export interface OpencodeProviderBlocks {
  v1: OpencodeProviderBlock;
  v2: OpencodeV2ProviderBlock;
}

export interface OpencodeGeneratedConfig {
  $schema: string;
  /** Legacy block. Kept so opencode V1 installs keep working; V2 merges both and this one loses. */
  provider: Record<string, OpencodeProviderBlock>;
  /** opencode V2 block. */
  providers: Record<string, OpencodeV2ProviderBlock>;
}

const OPENCODE_CHAT_NPM = "@ai-sdk/openai-compatible";
const OPENCODE_CHAT_PACKAGE = "@opencode/ai/providers/openai-compatible";
const OPENCODE_RESPONSES_NPM = "@ai-sdk/openai";
const OPENCODE_RESPONSES_PACKAGE = "@opencode/ai/providers/openai-compatible-responses";

/** Display name for the provider block, identical in both generations. */
const OPENCODE_PROVIDER_NAME = "OpenCodex";

/**
 * Resolve the user's global opencode config path. opencode uses the XDG layout on every
 * platform (including Windows, where it is %USERPROFILE%\.config\opencode).
 */
export function opencodeGlobalConfigPath(
  env: OpencodeLaunchEnv = process.env,
  home: string = homedir(),
): string {
  const xdg = env.XDG_CONFIG_HOME && env.XDG_CONFIG_HOME.length > 0 ? env.XDG_CONFIG_HOME : join(home, ".config");
  return join(xdg, "opencode", "opencode.json");
}

const OMP_PROFILE_NAME_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/;
const OMP_WINDOWS_RESERVED_PROFILE_RE = /^(?:CON|PRN|AUX|NUL|COM[0-9]|LPT[0-9])(?:\..*)?$/i;

function ompProfileName(env: OpencodeLaunchEnv): string | undefined {
  // OMP_PROFILE wins by presence, even when explicitly empty; PI_PROFILE is
  // only the legacy fallback when the canonical variable is undefined.
  const raw = env.OMP_PROFILE !== undefined ? env.OMP_PROFILE : env.PI_PROFILE;
  const profile = raw?.trim();
  if (!profile || profile === "default") return undefined;
  if (
    profile === "."
    || profile === ".."
    || profile.endsWith(".")
    || !OMP_PROFILE_NAME_RE.test(profile)
    || OMP_WINDOWS_RESERVED_PROFILE_RE.test(profile)
  ) {
    throw new ClientPathError(`Invalid OMP profile "${raw}"`);
  }
  return profile;
}


/** Pi's canonical custom-provider catalog. */
export function piConfigPath(env: OpencodeLaunchEnv = process.env, home: string = homedir()): string {
  return join(piAgentDir(env, home), "models.json");
}

/** Resolve the global Oh My Pi agent directory using OMP's own env precedence. */
export function ompAgentDir(env: OpencodeLaunchEnv = process.env, home: string = homedir()): string {
  const profile = ompProfileName(env);
  if (!profile) {
    const override = env.PI_CODING_AGENT_DIR?.trim();
    if (override) return absoluteClientPath(override, home, "PI_CODING_AGENT_DIR");
  }
  // OMP treats PI_CONFIG_DIR as a directory name relative to the user's home,
  // even when the value starts with `/` or `~`. Mirror that path.join contract
  // exactly instead of assigning those values different filesystem semantics.
  const root = join(home, env.PI_CONFIG_DIR || ".omp");
  return profile ? join(root, "profiles", profile, "agent") : join(root, "agent");
}

/** OMP's canonical custom-provider catalog. */
export function ompModelsConfigPath(env: OpencodeLaunchEnv = process.env, home: string = homedir()): string {
  const agentDir = ompAgentDir(env, home);
  const yamlFallback = join(agentDir, "models.yaml");
  const canonical = join(agentDir, "models.yml");
  return !existsSync(canonical) && existsSync(yamlFallback) ? yamlFallback : canonical;
}

/** Compose the OpenAI-compatible proxy base URL from a live probe result. */
export function opencodeProxyBaseUrl(
  port: number,
  hostname?: string,
  config?: Pick<OcxConfig, "unauthenticatedLoopbackListener">,
): string {
  if (config?.unauthenticatedLoopbackListener?.enabled) {
    return standaloneCodexRoutingTarget(port, {
      hostname,
      unauthenticatedLoopbackListener: config.unauthenticatedLoopbackListener,
    }).baseUrl;
  }
  return `http://${probeHostname(hostname)}:${port}/v1`;
}

/**
 * Hermes resolves its home the way cc-switch's writer does: an explicit
 * `HERMES_HOME`, then Windows `%LOCALAPPDATA%\hermes`, then `~/.hermes`.
 */
export function hermesHomeDir(env: OpencodeLaunchEnv = process.env, home: string = homedir()): string {
  const override = env.HERMES_HOME?.trim();
  if (override) return override;
  if (process.platform === "win32") {
    const local = env.LOCALAPPDATA?.trim();
    return join(local && local.length > 0 ? local : join(home, "AppData", "Local"), "hermes");
  }
  return join(home, ".hermes");
}

export function hermesConfigPath(env: OpencodeLaunchEnv = process.env, home: string = homedir()): string {
  return join(hermesHomeDir(env, home), "config.yaml");
}

/**
 * OpenClaw's EFFECTIVE home: `OPENCLAW_HOME` outranks the OS home.
 *
 * Everything below derives from this, which is why it is separate: a profile
 * directory and the default state directory both hang off the effective home,
 * not off `homedir()`.
 */
function openclawEffectiveHome(env: OpencodeLaunchEnv, home: string): string {
  const override = env.OPENCLAW_HOME?.trim();
  return override ? absoluteClientPath(override, home, "OPENCLAW_HOME") : home;
}

/**
 * OpenClaw's state directory, in the gateway's own precedence order:
 *
 * 1. `OPENCLAW_STATE_DIR` — an explicit relocation wins outright.
 * 2. `OPENCLAW_PROFILE` — a named profile is `.openclaw-<profile>` under the
 *    effective home. `default` is the unnamed profile, so it stays
 *    `.openclaw`.
 * 3. `.openclaw` under the effective home (`OPENCLAW_HOME` or the OS home).
 *
 * This is also what "is it installed?" detection looks at, so it has to follow
 * the same selectors the gateway does — otherwise an operator running a
 * profile reads as not installed while their gateway runs fine. We honor the
 * ENVIRONMENT selectors only: a `--profile` flag passed to some other process
 * is not something we can observe, and guessing it would be worse than
 * following the same environment the user gave us.
 */
export function openclawHomeDir(env: OpencodeLaunchEnv = process.env, home: string = homedir()): string {
  const stateDir = env.OPENCLAW_STATE_DIR?.trim();
  const effectiveHome = openclawEffectiveHome(env, home);
  if (stateDir) return absoluteClientPath(stateDir, effectiveHome, "OPENCLAW_STATE_DIR");
  const profile = env.OPENCLAW_PROFILE?.trim();
  // OpenClaw compares the profile name case-insensitively, so `DEFAULT` is
  // still the unnamed profile rather than a `.openclaw-DEFAULT` directory.
  if (profile && profile.toLowerCase() !== "default") return join(effectiveHome, `.openclaw-${profile}`);
  /*
   * `.clawdbot` is not migration debris — OpenClaw still treats it as an
   * active runtime candidate, preferring the modern directory when it exists
   * and otherwise selecting the legacy one. Mirroring that order is not
   * guessing: an install that has not migrated is one this integration would
   * otherwise report as "not installed" while its gateway runs fine.
   */
  const modern = join(effectiveHome, ".openclaw");
  if (existsSync(modern)) return modern;
  const legacy = join(effectiveHome, ".clawdbot");
  if (existsSync(legacy)) return legacy;
  return modern;
}

/**
 * The config file OpenClaw actually reads.
 *
 * An explicit `OPENCLAW_CONFIG_PATH` wins outright — it is a file selector, so
 * it does NOT relocate the state directory that detection looks at. Otherwise
 * `openclaw.json` under the resolved state directory.
 *
 * Ignoring these selectors meant the toggle could report success after writing
 * `~/.openclaw/openclaw.json` while the running gateway read somewhere else —
 * and snapshot the wrong file, so the rollback promise pointed at a file
 * nobody loads.
 */
export function openclawConfigPath(env: OpencodeLaunchEnv = process.env, home: string = homedir()): string {
  const explicit = env.OPENCLAW_CONFIG_PATH?.trim();
  if (explicit) return absoluteClientPath(explicit, openclawEffectiveHome(env, home), "OPENCLAW_CONFIG_PATH");
  /*
   * OpenClaw searches FILE candidates, not directories: a `.openclaw`
   * directory that exists but holds no config does not beat an actual
   * `.clawdbot/clawdbot.json`. Checking the directory first picked an
   * absent modern file over a real legacy one and wrote where nothing reads.
   *
   * An explicit state dir still scopes the search to that directory, because
   * the operator named it.
   */
  const stateOverride = env.OPENCLAW_STATE_DIR?.trim();
  const effectiveHome = openclawEffectiveHome(env, home);
  const profile = env.OPENCLAW_PROFILE?.trim();
  const scoped = stateOverride !== undefined && stateOverride !== ""
    || (profile !== undefined && profile !== "" && profile.toLowerCase() !== "default");
  const stateDir = openclawHomeDir(env, home);
  const candidates = scoped
    ? [join(stateDir, "openclaw.json"), join(stateDir, "clawdbot.json")]
    : [
      join(effectiveHome, ".openclaw", "openclaw.json"),
      join(effectiveHome, ".openclaw", "clawdbot.json"),
      join(effectiveHome, ".clawdbot", "openclaw.json"),
      join(effectiveHome, ".clawdbot", "clawdbot.json"),
    ];
  for (const candidate of candidates) {
    if (existsSync(candidate)) return candidate;
  }
  return candidates[0]!;
}

export function kimiHomeDir(env: OpencodeLaunchEnv = process.env, home: string = homedir()): string {
  const override = env.KIMI_CODE_HOME?.trim();
  return override && override.length > 0 ? override : join(home, ".kimi-code");
}

export function kimiConfigPath(env: OpencodeLaunchEnv = process.env, home: string = homedir()): string {
  return join(kimiHomeDir(env, home), "config.toml");
}

export function gajaeHomeDir(_env: OpencodeLaunchEnv = process.env, home: string = homedir()): string {
  return join(home, ".gjc");
}

export function gajaeConfigPath(env: OpencodeLaunchEnv = process.env, home: string = homedir()): string {
  return join(gajaeHomeDir(env, home), "agent", "models.yml");
}

/** DSH_HOME uses the raw nonblank value; trimming it would name a different path. */
export function dshHomeDir(env: OpencodeLaunchEnv = process.env, home: string = homedir()): string {
  const raw = env.DSH_HOME;
  if (raw === undefined || raw.trim().length === 0) return join(home, ".dsh");
  if (raw === "~") return home;
  if (raw.startsWith("~/") || raw.startsWith("~\\")) return join(home, raw.slice(2));
  if (!isAbsoluteClientPath(raw)) {
    throw new ClientPathError(
      `DSH_HOME must be an absolute path or start with ~; "${raw}" depends on the working directory, `
      + "so opencodex and DSH would disagree about which settings file it names. Use a drive letter or UNC share on Windows.",
    );
  }
  // DSH calls node:path.resolve after tilde expansion. Preserve the raw value
  // for the decision above, then normalize the absolute spelling the same way
  // so both processes bind ownership and locks to one path string.
  return resolve(raw);
}

export function dshConfigPath(env: OpencodeLaunchEnv = process.env, home: string = homedir()): string {
  return join(dshHomeDir(env, home), "settings.yaml");
}

/** The Desktop profile's patch, where DSH 0.1.7+ reads provider routes (see `DSH_PROFILE_PROVIDER_PATH`). */
export function dshProfilePatchPath(env: OpencodeLaunchEnv = process.env, home: string = homedir()): string {
  return join(dshHomeDir(env, home), "profiles", DSH_DESKTOP_PROFILE, "cordis.patch.yml");
}

/**
 * MiniMax Code stores runtime state under `MINIMAX_DATA_DIR`, then the legacy
 * `MAVIS_DATA_DIR`, and finally `~/.minimax`. Relative overrides are refused
 * because a background proxy and a foreground client can have different CWDs.
 */
export function mcodeHomeDir(env: OpencodeLaunchEnv = process.env, home: string = homedir()): string {
  const primary = env.MINIMAX_DATA_DIR?.trim();
  if (primary) return absoluteClientPath(primary, home, "MINIMAX_DATA_DIR");
  const legacy = env.MAVIS_DATA_DIR?.trim();
  if (legacy) return absoluteClientPath(legacy, home, "MAVIS_DATA_DIR");
  return join(home, ".minimax");
}

export function mcodeConfigPath(env: OpencodeLaunchEnv = process.env, home: string = homedir()): string {
  return join(mcodeHomeDir(env, home), "config.yaml");
}

/** Bootstrap settings always stay at the default home, even after relocation. */
export type ZcodePathIO = {
  readText: (path: string) => { kind: "text"; text: string } | { kind: "missing" } | { kind: "failed"; code?: string };
};
const zcodePathIO: ZcodePathIO = {
  /** Shares the integration reader's four-MiB limit and regular-file-only bootstrap contract. */
  readText: path => fileIO().readText(path),
};
export class ZcodeSettingsPathError extends ClientPathError {}

export function zcodeBootstrapSettingsPath(home: string = homedir()): string {
  return join(home, ".zcode", "v2", "setting.json");
}

/** The pre-relocation path is retained solely to recognize historical ownership. */
export function zcodeLegacyHomeDir(env: OpencodeLaunchEnv = process.env, home: string = homedir()): string {
  const override = env.ZCODE_DATA_DIR?.trim();
  return override ? absoluteClientPath(override, home, "ZCODE_DATA_DIR") : join(home, ".zcode");
}

/** ZCODE_DATA_DIR names the .zcode root; dataBaseDir names its parent. */
export function zcodeHomeDir(env: OpencodeLaunchEnv = process.env, home: string = homedir(), io: ZcodePathIO = zcodePathIO): string {
  if (env.ZCODE_DATA_DIR?.trim()) return zcodeLegacyHomeDir(env, home);
  const bootstrap = zcodeBootstrapSettingsPath(home);
  const read = io.readText(bootstrap);
  if (read.kind === "missing") return join(home, ".zcode");
  const unknown = () => new ZcodeSettingsPathError(
    `ZCode's active data root is unknown: ${bootstrap} must be readable JSON with an absolute dataBaseDir (or no dataBaseDir). Repair the bootstrap setting before enabling or refreshing; no legacy provider will be applied.`,
  );
  if (read.kind !== "text") throw unknown();
  let settings: unknown;
  try { settings = JSON.parse(read.text); } catch { throw unknown(); }
  if (settings === null || typeof settings !== "object" || Array.isArray(settings)) throw unknown();
  const base = (settings as Record<string, unknown>).dataBaseDir;
  if (base === undefined) return join(home, ".zcode");
  // Match the native path's value, without cwd or tilde expansion. The native
  // ZCODE_DATA_BASE_DIR selector is not an alias for our ZCODE_DATA_DIR.
  if (typeof base !== "string" || !isAbsoluteClientPath(base) || base.includes("\0")) throw unknown();
  return join(base, ".zcode");
}

export function zcodeConfigPath(env: OpencodeLaunchEnv = process.env, home: string = homedir(), io?: ZcodePathIO): string {
  return join(zcodeHomeDir(env, home, io), "v2", "config.json");
}

/**
 * The home directory Command Code itself resolves: `env.HOME ?? env.USERPROFILE`
 * (`homeDir15` in the published `command-code@1.66.0` bundle).
 *
 * On POSIX `os.homedir()` already reads `$HOME`, so the two agree and `home` is
 * returned as is. On Windows `os.homedir()` reads `%USERPROFILE%` and ignores
 * `HOME`, which Git for Windows, MSYS2 and Cygwin set, so a user whose `HOME` differs
 * would get a provider block in a store Command Code never opens. Only the OS-default
 * home is replaced: a caller that injects a different root (a test, the writer's
 * `input.home`) keeps it, and a blank or relative value falls back to `home`.
 */
export function commandCodeUserHome(env: OpencodeLaunchEnv = process.env, home: string = homedir(), platform: NodeJS.Platform = process.platform): string {
  if (platform !== "win32" || home !== homedir()) return home;
  const value = env.HOME ?? env.USERPROFILE;
  return typeof value === "string" && value.trim() && isAbsoluteClientPath(value, platform) ? value : home;
}

/**
 * Command Code's provider store directory — `.commandcode` under the home the client
 * resolves (see {@link commandCodeUserHome}), with no override.
 *
 * There is deliberately no `COMMANDCODE_HOME` here, unlike the other clients in this
 * file: `grep -c COMMANDCODE_HOME` over the shipped `dist/cli.mjs` and
 * `dist/index.mjs` returns 0. An override we honour but the client ignores is worse
 * than none: `enable` would report success and write a provider block at a path no
 * Command Code process ever opens, and the user would see an empty model list with no
 * error anywhere. An apply against a relocated home is instead refused by `detectDir`
 * not existing.
 */
export function commandCodeHomeDir(env: OpencodeLaunchEnv = process.env, home: string = homedir(), platform: NodeJS.Platform = process.platform): string {
  return join(commandCodeUserHome(env, home, platform), ".commandcode");
}

export function commandCodeConfigPath(env: OpencodeLaunchEnv = process.env, home: string = homedir(), platform: NodeJS.Platform = process.platform): string {
  return join(commandCodeHomeDir(env, home, platform), "providers.json");
}

/**
 * Command Code's credential store, next to the provider file.
 *
 * Only the DESKTOP app reads this before it will show a workspace; the published
 * CLI is content with `apiKey: false` in `providers.json`. It is the vendor's file,
 * shared with real logins and other providers' tokens, so this integration NEVER
 * writes it: the desktop user signs in themselves. Exported so callers and tests
 * can name the path they must leave alone.
 */
export function commandCodeAuthPath(env: OpencodeLaunchEnv = process.env, home: string = homedir(), platform: NodeJS.Platform = process.platform): string {
  return join(commandCodeHomeDir(env, home, platform), "auth.json");
}

/**
 * The provider store a current ZCode reads, which is NOT the file above.
 *
 * ZCode 3.14 moved custom providers to `v2/provider_config.json` and left
 * `v2/config.json` reachable only through a one-shot import that runs when the
 * new file is missing. The client creates the new file on first launch, so on
 * an install that has ever run, the import has already happened and never runs
 * again — every later write to `v2/config.json` is read by nobody (#5348).
 *
 * The integration writes this store through its existing schema-aware writer. The env override is
 * ZCode's own (`ZCODE_PERSONAL_PROVIDER_CONFIG_FILE`), so an operator who
 * relocated the store is measured against the file their client actually opens
 * rather than the default location. A relative override is refused for the same
 * reason `ZCODE_DATA_DIR` refuses one: we and the client would disagree about
 * which file it names, and here that disagreement decides whether an apply is
 * reported as effective.
 */
export function zcodeProviderStorePath(env: OpencodeLaunchEnv = process.env, home: string = homedir(), io?: ZcodePathIO): string {
  const override = env.ZCODE_PERSONAL_PROVIDER_CONFIG_FILE?.trim();
  if (override) return absoluteClientPath(override, home, "ZCODE_PERSONAL_PROVIDER_CONFIG_FILE");
  return join(zcodeHomeDir(env, home, io), "v2", "provider_config.json");
}

/**
 * Prime Agent resolves its agent directory from `PRIME_AGENT_CODING_AGENT_DIR`
 * — the brand-derived spelling of the `PI_CODING_AGENT_DIR` that `ompAgentDir`
 * already honors, because the agent builds that variable name from its own
 * `piConfig.name` — and otherwise falls back to `~/.prime/agent`. Relative
 * overrides are refused for the same reason as MCode's and ZCode's: a
 * background proxy and a foreground client can have different working
 * directories.
 */
export function primeAgentDir(env: OpencodeLaunchEnv = process.env, home: string = homedir()): string {
  const override = env.PRIME_AGENT_CODING_AGENT_DIR?.trim();
  if (override) return absoluteClientPath(override, home, "PRIME_AGENT_CODING_AGENT_DIR");
  return join(home, ".prime", "agent");
}

/** Prime Agent's canonical custom-provider catalog. */
export function primeConfigPath(env: OpencodeLaunchEnv = process.env, home: string = homedir()): string {
  return join(primeAgentDir(env, home), "models.json");
}

/**
 * omo resolves its agent directory from THREE variables, in its own order:
 * `OMO_CODING_AGENT_DIR`, then `SENPI_CODING_AGENT_DIR`, then
 * `PI_CODING_AGENT_DIR`, falling back to `~/.omo/agent`. That is not an
 * inference from the family resemblance — `bin/lib/agent-dir.js` publishes the
 * list as `AGENT_DIR_ENV_NAMES` and the launcher pins the first two to whatever
 * it resolves before spawning senpi, so the engine can never disagree with it.
 *
 * The order is load-bearing rather than cosmetic. A user with both
 * `PI_CODING_AGENT_DIR` and `OMO_CODING_AGENT_DIR` set runs omo out of the omo
 * one; checking Pi's first would have us write a catalog omo never reads.
 *
 * Each variable reports under its OWN name, because telling someone that
 * `PI_CODING_AGENT_DIR` is relative when they set `OMO_CODING_AGENT_DIR` sends
 * them to the wrong line of their shell profile. An empty or whitespace value
 * falls through to the next name, which is what omo's own `.trim()`-then-test
 * loop does.
 *
 * One divergence is deliberate: omo `resolve()`s a relative override against its
 * own cwd and does not expand `~`. We refuse the relative form and do expand
 * `~`, exactly as Pi, Prime, MCode and ZCode already do, because a background
 * proxy and a foreground client have different working directories and would
 * otherwise disagree about which file is named.
 *
 * Consequence worth knowing: a user who sets only `PI_CODING_AGENT_DIR` has Pi
 * and omo reading ONE `models.json`. Both clients emit the same provider block
 * through the same builder so the bytes agree; what cannot be shared is the
 * ownership record, since two enabled clients would claim one file. That is
 * omo's contract, not ours to paper over.
 */
export function omoAgentDir(env: OpencodeLaunchEnv = process.env, home: string = homedir()): string {
  const omo = env.OMO_CODING_AGENT_DIR?.trim();
  if (omo) return absoluteClientPath(omo, home, "OMO_CODING_AGENT_DIR");
  const senpi = env.SENPI_CODING_AGENT_DIR?.trim();
  if (senpi) return absoluteClientPath(senpi, home, "SENPI_CODING_AGENT_DIR");
  const pi = env.PI_CODING_AGENT_DIR?.trim();
  if (pi) return absoluteClientPath(pi, home, "PI_CODING_AGENT_DIR");
  return join(home, ".omo", "agent");
}

/** omo's canonical custom-provider catalog, read by the senpi engine it wraps. */
export function omoConfigPath(env: OpencodeLaunchEnv = process.env, home: string = homedir()): string {
  return join(omoAgentDir(env, home), "models.json");
}

/**
 * Aside's state root. Unlike every other client here, Aside ships NO variable
 * that relocates it: its CLI carries `ASIDE_DAEMON_BASE_URL`,
 * `ASIDE_PRODUCT_VARIANT` and similar, and the only `.aside` path baked into the
 * binary is its own update-check file under `~/.aside/cli`. So there is no
 * client-owned override to mirror, and this registry does not invent one.
 */
export function asideHomeDir(_env: OpencodeLaunchEnv = process.env, home: string = homedir()): string {
  const root = join(home, ".aside");
  // A user who relocated Aside (for example to an external volume) leaves ~/.aside as a
  // symlink, and Aside itself follows it (issue 5648). Canonicalize only that top-level
  // alias, once, and only onto a directory: every boundary below the root (u/, account
  // directories, models.json) keeps refusing links against the canonical path.
  try {
    if (lstatSync(root).isSymbolicLink() && statSync(root).isDirectory()) return realpathSync.native(root);
  } catch {
    // Missing or unreadable: the literal path lets the profile reader report it.
  }
  return root;
}

/**
 * Which account's catalog we write.
 *
 * Aside is per-ACCOUNT: state lives under `~/.aside/u/<id>/` and the id comes
 * from `accounts.json`, which Aside maintains. That makes this the only path
 * resolver here that parses file CONTENTS rather than probing existence — the
 * module already does the latter at four sites.
 *
 * It throws rather than defaulting. A machine can hold several accounts (both
 * `u/0` and `u/1` existed on the machine this was developed against), so
 * guessing `0` when the manifest cannot be read would name a real config file
 * belonging to a DIFFERENT account, pass the installed-directory check, and
 * write into somebody else's catalog. An unresolvable account is reported the
 * same way an unresolvable `DSH_HOME` is.
 *
 * Callers that need BOTH the config path and the detect directory must derive
 * them from ONE call to `asideAccountDir` rather than calling the two exported
 * helpers in sequence: `resolveIntegrationPaths` in the integration registry is
 * that seam. Caching here cannot substitute for it — a cache keyed on the
 * manifest's mtime re-reads exactly when the manifest changes, which is the
 * case the consistency is needed for.
 */
function asideCurrentAccountId(root: string): number {
  const manifest = join(root, "accounts.json");
  let raw: string;
  try {
    raw = readFileSync(manifest, "utf8");
  } catch {
    throw new ClientPathError(
      `Aside's account manifest is missing or unreadable at ${manifest}, so opencodex cannot tell which `
      + "account's model catalog to write. Launch Aside once to create it.",
    );
  }
  let parsed: unknown;
  try {
    parsed = JSON.parse(raw);
  } catch {
    throw new ClientPathError(
      `Aside's account manifest at ${manifest} is not readable JSON, so the account it names cannot be `
      + "trusted. Writing a guessed account would target a different account's catalog.",
    );
  }
  const id = (parsed as { currentAccountId?: unknown } | null)?.currentAccountId;
  if (typeof id !== "number" || !Number.isInteger(id) || id < 0) {
    throw new ClientPathError(
      `Aside's account manifest at ${manifest} declares no usable currentAccountId, so opencodex cannot `
      + "tell which account is current.",
    );
  }
  return id;
}

/**
 * The signed-in account's directory. This is also the install signal: the CLI
 * creates `~/.aside/cli` for its own update check before any account exists, so
 * the OUTER directory can be present on a machine that never signed in.
 */
export function asideAccountDir(env: OpencodeLaunchEnv = process.env, home: string = homedir()): string {
  const root = asideHomeDir(env, home);
  return join(root, "u", String(asideCurrentAccountId(root)));
}

/** Aside's custom-provider catalog for the current account. */
export function asideConfigPath(env: OpencodeLaunchEnv = process.env, home: string = homedir()): string {
  return join(asideAccountDir(env, home), "models.json");
}

/**
 * Raycast's Custom Providers directory. Raycast hard-codes
 * `~/.config/raycast/ai` on macOS AND Windows: it neither honors
 * `XDG_CONFIG_HOME` nor ships a variable of its own that relocates the file, so
 * unlike `opencodeGlobalConfigPath` there is no override to mirror and the env
 * parameter exists only to keep the resolver signature uniform with the rest.
 */
export function raycastAiDir(_env: OpencodeLaunchEnv = process.env, home: string = homedir()): string {
  return join(home, ".config", "raycast", "ai");
}

/** The providers file Raycast watches (manual.raycast.com/ai/custom-providers). */
export function raycastConfigPath(env: OpencodeLaunchEnv = process.env, home: string = homedir()): string {
  return join(raycastAiDir(env, home), "providers.yaml");
}

/** Same endpoint and credentials, with the admission header serialized by generation. */
function opencodeProviderConnection(baseURL: string, config: OcxConfig): OpencodeProviderConnection {
  const options: OpencodeProviderConnection = { baseURL };
  // Opt-in opencode-side timeout overrides. Omitted by default so opencode keeps its native
  // header/chunk waits for every upstream routed through the proxy (current V2 defaults the
  // header wait to 5 min and the longer chunk wait to 15 min, but this repo pins no opencode
  // release); a user fronting a slow local model sets these to extend or disable the wait that
  // otherwise cuts a long prefill.
  const timeouts = config.opencodeClientExport;
  if (timeouts) {
    if (timeouts.headerTimeoutMs !== undefined) options.headerTimeout = timeouts.headerTimeoutMs;
    if (timeouts.chunkTimeoutMs !== undefined) options.chunkTimeout = timeouts.chunkTimeoutMs;
    if (timeouts.timeoutMs !== undefined) options.timeout = timeouts.timeoutMs;
  }
  // Non-loopback binds accept proxy admission only via x-opencodex-api-key so Authorization
  // stays free for Codex Direct upstream credentials when applicable.
  if (shouldInjectApiAuthHeader(config)) {
    options.headers = { "x-opencodex-api-key": OPENCODE_API_KEY_ENV_REF };
    // The OpenAI SDK requires a key even when the proxy's admission uses its own header.
    options.apiKey = LOOPBACK_API_KEY_PLACEHOLDER;
    return options;
  }
  options.apiKey = OPENCODE_API_KEY_ENV_REF;
  return options;
}

/**
 * Exact declared choices. An empty array is intentional: omitting variants lets OpenCode
 * synthesize low/medium/high, even for a model whose upstream declares no adjustable effort.
 */
function opencodeEffortVariants(model: OpencodeCatalogModel): OpencodeModelVariant[] {
  return (exportReasoningEfforts(model) ?? []).map(effort => ({ id: effort, settings: { reasoningEffort: effort } }));
}

/**
 * Both provider generations for one resolved base URL.
 *
 * `limit.context` is emitted ONLY from an authoritative context window — never guessed.
 * When none is available the whole `limit` block is dropped and opencode keeps its own
 * defaults; when one is present, `limit.output` rides along (opencode's schema requires
 * the pair) clamped to the context window.
 *
 * Two blocks instead of one because opencode V2 reads the `providers` map and V1 reads
 * `provider`, with native arrays versus legacy maps for variants. Emitting both keeps V1 installs
 * working: V2 merges them by provider id and model id, so a model listed in both blocks
 * appears once, with the V2 entry's name, connection, and variants.
 */
export function opencodeProviderBlocks(
  baseURL: string,
  catalogModels: readonly OpencodeCatalogModel[],
  config: OcxConfig,
): OpencodeProviderBlocks {
  const v1Models: Record<string, OpencodeModelEntry> = {};
  const v2Models: Record<string, OpencodeV2ModelEntry> = {};
  for (const model of expandFastExportModels(catalogModels)) {
    const key = model.namespaced;
    const usesChat = opencodeModelUsesChat(model, config);
    const { interleaved, ...reasoning } = legacyReasoningMetadata(model);
    const entry: OpencodeModelEntry = {
      name: exportModelLabel(model),
      ...reasoning,
      ...(usesChat ? { provider: { npm: OPENCODE_CHAT_NPM }, ...(interleaved ? { interleaved } : {}) } : {}),
    };
    const context = authoritativeContextWindow(model.contextWindow);
    if (context !== undefined) {
      entry.limit = { context, output: outputBudgetFor(context, model) };
      const input = inputBudgetFor(context, model);
      if (input !== undefined) entry.limit.input = input;
    }
    // Native V2 decoders ignore legacy attachment/modalities fields. Emit each generation's
    // actual capability shape rather than relying on migration of the other provider block.
    const capabilities = opencodeModelCapabilities(model.inputModalities);
    if (capabilities) {
      entry.attachment = capabilities.attachment;
      entry.modalities = capabilities.modalities;
    }
    if (typeof model.supportsTools === "boolean") entry.tool_call = model.supportsTools;
    v1Models[key] = entry;
    const defaultEffort = exportDefaultReasoningEffort(model);
    // V2 requires tools whenever capabilities exists. A partial object discards the entire
    // native block, losing explicit variants. Unknown tools use the legacy modality migration
    // rather than inventing a tools flag to make the native schema accept the declaration.
    const v2Capabilities: OpencodeV2ModelEntry["capabilities"] = typeof model.supportsTools === "boolean" ? {
      tools: model.supportsTools,
      ...(capabilities ? { input: [...capabilities.modalities.input], output: [...capabilities.modalities.output] } : {}),
    } : undefined;
    v2Models[key] = {
      name: entry.name,
      ...(entry.limit ? { limit: { ...entry.limit } } : {}),
      ...(v2Capabilities ? { capabilities: v2Capabilities } : {}),
      ...(usesChat ? { package: OPENCODE_CHAT_PACKAGE } : {}),
      ...(usesChat && interleaved ? { compatibility: { reasoningField: interleaved.field } } : {}),
      ...(defaultEffort !== undefined ? { settings: { reasoningEffort: defaultEffort } } : {}),
      variants: opencodeEffortVariants(model),
    };
  }
  const connection = opencodeProviderConnection(baseURL, config);
  const { headers, ...settings } = connection;
  return {
    v1: {
      npm: OPENCODE_RESPONSES_NPM,
      name: OPENCODE_PROVIDER_NAME,
      options: connection,
      models: v1Models,
    },
    v2: {
      package: OPENCODE_RESPONSES_PACKAGE,
      name: OPENCODE_PROVIDER_NAME,
      settings,
      ...(headers ? { headers } : {}),
      models: v2Models,
    },
  };
}

/** `opencodex` provider block for a resolved base URL (opencode V1 shape). */
function opencodeProviderBlock(
  baseURL: string,
  catalogModels: readonly OpencodeCatalogModel[],
  config: OcxConfig,
): OpencodeProviderBlock {
  return opencodeProviderBlocks(baseURL, catalogModels, config).v1;
}

/** `opencodex` provider block for a resolved base URL (opencode V2 shape, carries variants). */
export function opencodeV2ProviderBlock(
  baseURL: string,
  catalogModels: readonly OpencodeCatalogModel[],
  config: OcxConfig = OPENCODE_PROVIDER_BLOCK_DEFAULT_CONFIG,
): OpencodeV2ProviderBlock {
  return opencodeProviderBlocks(baseURL, catalogModels, config).v2;
}

/**
 * Build the `opencodex` provider block from proxy catalog rows keyed by each row's
 * canonical `namespaced` selector. Used by the `ocx opencode` launcher, which injects
 * the block through OpenCode's inline runtime layer rather than any file.
 */
export function buildOpencodeProviderBlockFromCatalog(
  port: number,
  catalogModels: readonly OpencodeCatalogModel[],
  hostname?: string,
  config: OcxConfig = OPENCODE_PROVIDER_BLOCK_DEFAULT_CONFIG,
): OpencodeProviderBlock {
  return opencodeProviderBlock(opencodeProxyBaseUrl(port, hostname), catalogModels, config);
}

/**
 * OpenCode document: both provider generations plus `$schema`, and nothing else.
 *
 * The order below fixes the order of the emitted keys and nothing else: the two blocks are
 * disjoint top-level keys, and which generation opencode prefers when it merges them is
 * opencode's decision, not a consequence of where we write it. Both blocks are generated in
 * one pass so they cannot disagree about the model set, the names, or the connection.
 */
function buildOpencodeClientConfig(ctx: ExportContext): OpencodeGeneratedConfig {
  const models = normalizeExportModels(ctx.models);
  const config = ctx.config ?? OPENCODE_PROVIDER_BLOCK_DEFAULT_CONFIG;
  const blocks = opencodeProviderBlocks(ctx.baseUrl, models, config);
  return {
    $schema: OPENCODE_CONFIG_SCHEMA,
    provider: { [OPENCODE_PROVIDER_ID]: blocks.v1 },
    providers: { [OPENCODE_PROVIDER_ID]: blocks.v2 },
  };
}

export interface PiProviderBlock {
  baseUrl: string;
  api: string;
  apiKey: string;
  compat?: PiProviderCompat;
  models: PiModelEntry[];
}

/**
 * The subset of Pi's per-provider `compat` block this export writes. Both keys are part of
 * Pi's own model-config schema; an unknown key there would empty the whole config, so nothing
 * outside this set is ever emitted.
 */
export interface PiProviderCompat {
  sendSessionAffinityHeaders?: boolean;
  supportsDeveloperRole?: boolean;
}

interface PiExportOptions {
  sendSessionAffinityHeaders?: boolean;
  /**
   * Drop native OpenAI rows when the serving proxy runs Codex Direct (`codexAccountMode: direct`).
   * Direct mode forwards the caller's own bearer, and Pi sends the loopback placeholder key, so a
   * native row would only ever answer 401. The CLI-built Pi export omitted them before the export
   * moved onto the serving proxy's roster (#8172); this keeps that behaviour.
   */
  omitNativeInCodexDirect?: boolean;
  /**
   * Use the raw nested upstream selector the serving proxy proved for a row (#8172). A row
   * without that proof keeps its canonical key.
   */
  rawNestedModelIds?: boolean;
  /**
   * Tell Pi to send its system prompt as `system` rather than `developer` (#5664).
   *
   * Pi sends `developer` for reasoning models by default. On `/v1/chat/completions` the proxy
   * forwards the caller's roles verbatim unless a destination has recorded
   * `foldDeveloperRoleToSystem`, and many OpenAI-compatible upstreams reject `developer` with a
   * 400. `system` is accepted by every destination behind this one provider block, so the export
   * states it rather than leaving each user to hand-edit a block the next export rewrites.
   */
  foldDeveloperRole?: boolean;
  /** Provider dialect; omitted writes `PI_API_DIALECT`. */
  api?: "openai-completions" | "openai-responses";
}

export interface PiGeneratedConfig {
  providers: Record<string, PiProviderBlock>;
}

/**
 * Hermes `~/.hermes/config.yaml`. We emit ONLY the provider entry — never
 * `model.default` — because hijacking the user's main model is not what a
 * connect action asks for.
 */
export interface HermesProviderBlock {
  api: string;
  api_key: string;
  api_mode: "chat_completions";
  /** Header name only; Hermes supplies a dynamic per-conversation value. */
  session_affinity_header: "session-id";
  /** We supply the list, so skip their live `/models` probe. */
  discover_models: false;
  models: Record<string, HermesModelEntry>;
  extra_headers?: Record<string, string>;
}

/** Capability metadata Hermes cannot discover for a custom local provider. */
export interface HermesModelEntry {
  supports_vision?: boolean;
}

export interface HermesGeneratedConfig {
  providers: Record<string, HermesProviderBlock>;
}

export interface OpenclawModelEntry {
  id: string;
  name: string;
  contextWindow?: number;
  input?: string[];
}

export interface OpenclawProviderBlock {
  baseUrl: string;
  apiKey: string;
  api: "openai-completions";
  models: OpenclawModelEntry[];
  headers?: Record<string, string>;
}

/** `mode: "merge"` keeps OpenClaw's bundled catalog alongside ours. */
export interface OpenclawGeneratedConfig {
  models: {
    mode: "merge";
    providers: Record<string, OpenclawProviderBlock>;
  };
}

export interface KimiProviderBlock {
  type: "openai";
  base_url: string;
  api_key: string;
}

/**
 * `max_context_size` is mandatory and must be positive, so a model with no
 * authoritative context window is omitted from the document entirely rather
 * than guessed at. Catalog image input becomes `image_in`; other capabilities
 * are not inferred from routed model names.
 * A declared effort ladder becomes `support_efforts` (limited to Kimi Code's
 * documented levels) plus the `thinking` capability, and a declared default in
 * that ladder becomes `default_effort` (#8095).
 */
export interface KimiModelBlock {
  provider: string;
  model: string;
  max_context_size: number;
  display_name?: string;
  capabilities?: Array<"thinking" | "image_in">;
  support_efforts?: KimiEffort[];
  default_effort?: KimiEffort;
}

/** Kimi Code's thinking efforts, in its documented order; anything else fails its config validation. */
const KIMI_EFFORT_ORDER = ["low", "medium", "high", "xhigh", "max"] as const;
type KimiEffort = typeof KIMI_EFFORT_ORDER[number];

function kimiEfforts(model: ExportModel): { support_efforts?: KimiEffort[]; default_effort?: KimiEffort } {
  // An explicit "no reasoning" declaration outranks any ladder that reached the exporter.
  if (model.supportsReasoning === false || model.supportsReasoningEffort === false) return {};
  const offered = new Set((model.reasoningEfforts ?? [])
    .filter((effort): effort is string => typeof effort === "string")
    .map(effort => effort.trim().toLowerCase()));
  const support = KIMI_EFFORT_ORDER.filter(effort => offered.has(effort));
  if (support.length === 0) return {};
  const declared = typeof model.defaultReasoningEffort === "string"
    ? model.defaultReasoningEffort.trim().toLowerCase() : undefined;
  const fallback = support.find(effort => effort === declared);
  return { support_efforts: support, ...(fallback ? { default_effort: fallback } : {}) };
}

export interface KimiGeneratedConfig {
  providers: Record<string, KimiProviderBlock>;
  models: Record<string, KimiModelBlock>;
}

export interface GajaeModelEntry {
  id: string;
  name: string;
  input: string[];
  contextWindow?: number;
  maxTokens?: number;
  /** Advertised only when the catalog declares at least one wire-selectable effort. */
  reasoning?: true;
  /** GJC's per-model reasoning-effort capability declaration. */
  thinking?: {
    mode: "effort";
    minLevel: string;
    maxLevel: string;
    levels: string[];
  };
  /** Tells GJC to pass the selected level as OpenAI-compatible reasoning_effort. */
  compat?: { supportsReasoningEffort: true };
}

/** Gajae validates strictly: an unknown field fails the whole config. */
export interface GajaeProviderBlock {
  baseUrl: string;
  apiKey: string;
  api: "openai-completions";
  models: GajaeModelEntry[];
}

export interface GajaeGeneratedConfig {
  providers: Record<string, GajaeProviderBlock>;
}

/**
 * Pi's `~/.pi/agent/models.json` shape. `models` is an ARRAY (identity lives in `id`),
 * unlike OpenCode's keyed object.
 *
 * Two fields were deliberately absent once. `cost` still is: it requires all four price
 * fields and we have no price data at all, so emitting zeros would assert every routed
 * model is free. `reasoning` used to be omitted because Pi's boolean and the catalog's
 * effort ladder did not obviously map — but a NON-EMPTY ladder is the catalog's own
 * statement that the model accepts reasoning parameters (adapters honor `reasoning_effort`),
 * and an empty or absent ladder is the statement that it does not. Emitting `reasoning:
 * true` exactly for rows with a ladder is therefore not a guess; it is what makes Pi's
 * effort control appear for routed models at all. The export also emits a `thinkingLevelMap`
 * that hides every pi level outside the declared ladder, so pi never offers (and sends) an
 * effort the ladder does not contain — custom-row ladders are catalog advertisement only
 * and get no wire clamp, so this map is what keeps pi honest for those. Users who need a
 * different mapping can still hand-tune `thinkingLevelMap` afterwards.
 *
 * Pi's input enum IS verified: its documented model configuration accepts only
 * `text` and `image`, and a validation failure yields an EMPTY model config
 * rather than dropping the offending entry — one bad value costs every routed
 * model. The rest of this contract (omitting `cost`) is still ours rather than
 * a claim about Pi's acceptance.
 */
function buildPiClientConfig(ctx: ExportContext, options: PiExportOptions = {}): PiGeneratedConfig {
  const models: PiModelEntry[] = [];
  const roster = options.rawNestedModelIds ? selectNestedSelectors(ctx.models) : ctx.models;
  const omitNative = options.omitNativeInCodexDirect === true
    && providerCodexAccountMode("openai", ctx.config?.providers?.openai) === "direct";
  for (const model of normalizeExportModels(roster)) {
    if (omitNative && model.native === true) continue;
    // Text is the one modality every routed model supports; anything richer must come
    // from the catalog rather than an assumption — and must still be inside the enum
    // Pi accepts, because one rejected value empties the whole config.
    const input = inputModalitiesForClient("pi", model.inputModalities);
    // An audio-only model has no honest representation here; claiming `text`
    // would fail at call time instead, so the row is dropped.
    if (input === null) continue;
    const entry: PiModelEntry = {
      id: model.namespaced,
      name: exportModelLabel(model),
      input,
    };
    if (Array.isArray(model.reasoningEfforts) && model.reasoningEfforts.length > 0) {
      entry.reasoning = true;
      const efforts = model.reasoningEfforts;
      entry.thinkingLevelMap = {
        // pi's off level maps to the declared `none` sentinel (the proxy omits the
        // reasoning parameter for it); hidden when the ladder does not declare none.
        off: efforts.includes("none") ? "none" : null,
        minimal: efforts.includes("minimal") ? "minimal" : null,
        low: efforts.includes("low") ? "low" : null,
        medium: efforts.includes("medium") ? "medium" : null,
        high: efforts.includes("high") ? "high" : null,
        xhigh: efforts.includes("xhigh") ? "xhigh" : null,
        max: efforts.includes("max") ? "max" : efforts.includes("ultra") ? "ultra" : null,
      };
    }
    const context = authoritativeContextWindow(model.contextWindow);
    if (context !== undefined) {
      entry.contextWindow = context;
      entry.maxTokens = outputBudgetFor(context, model);
    }
    models.push(entry);
  }
  const compat: PiProviderCompat = {
    ...(options.sendSessionAffinityHeaders ? { sendSessionAffinityHeaders: true } : {}),
    ...(options.foldDeveloperRole ? { supportsDeveloperRole: false } : {}),
  };
  return {
    providers: {
      [OPENCODE_PROVIDER_ID]: {
        baseUrl: ctx.baseUrl,
        api: options.api ?? PI_API_DIALECT,
        apiKey: LOOPBACK_API_KEY_PLACEHOLDER,
        ...(Object.keys(compat).length > 0 ? { compat } : {}),
        models,
      },
    },
  };
}

/**
 * Pi's export options, shared by `ocx export --client pi` and the managed contribution so the two
 * never drift apart at the first refresh. omo uses the same options: senpi documents both keys in
 * its models.json `compat` block (docs/models.md, docs/custom-provider.md).
 */
const PI_EXPORT_OPTIONS: PiExportOptions = { sendSessionAffinityHeaders: true, foldDeveloperRole: true };
const PI_NATIVE_SELECTOR_OPTIONS: PiExportOptions = { ...PI_EXPORT_OPTIONS, rawNestedModelIds: true, omitNativeInCodexDirect: true };
/**
 * Prime and Aside run the Pi runtime and read the same models.json, so they need Pi's developer-role
 * statement (#8864): without it they send their system prompt as `developer`, which DashScope and
 * Moonshot reject with a 400. Session affinity stays Pi's alone (eb8cc9ab73).
 */
const PI_DEVELOPER_ROLE_OPTIONS: PiExportOptions = { foldDeveloperRole: true };

/** Do not let provider-controlled catalog text become an environment lookup. */
function containsEnvInterpolation(value: string): boolean {
  return value.includes("${");
}

function buildHermesClientConfig(ctx: ExportContext): HermesGeneratedConfig {
  const models: Record<string, HermesModelEntry> = {};
  for (const model of normalizeExportModels(ctx.models)) {
    if (containsEnvInterpolation(model.namespaced)) continue;
    const declared = model.inputModalities;
    models[model.namespaced] = declared && declared.length > 0
      ? { supports_vision: declared.includes("image") }
      : {};
  }
  const headers = proxyAdmissionHeaders(ctx.config, HERMES_API_KEY_ENV_REF);
  return {
    providers: {
      [OPENCODE_PROVIDER_ID]: {
        api: ctx.baseUrl,
        api_key: HERMES_API_KEY_ENV_REF,
        api_mode: "chat_completions",
        session_affinity_header: "session-id",
        discover_models: false,
        models,
        ...(headers ? { extra_headers: headers } : {}),
      },
    },
  };
}

function buildOpenclawClientConfig(ctx: ExportContext): OpenclawGeneratedConfig {
  const models: OpenclawModelEntry[] = normalizeExportModels(ctx.models).flatMap(model => {
    const name = exportModelLabel(model);
    if (containsEnvInterpolation(model.namespaced) || containsEnvInterpolation(name)) return [];
    const context = authoritativeContextWindow(model.contextWindow);
    const input = [...new Set(model.inputModalities?.filter(value => ["text", "image", "video", "audio"].includes(value)))];
    return [{
      id: model.namespaced,
      name,
      ...(context !== undefined ? { contextWindow: context } : {}),
      ...(input.length > 0 ? { input } : {}),
    }];
  });
  const headers = proxyAdmissionHeaders(ctx.config, OPENCLAW_API_KEY_ENV_REF);
  return {
    models: {
      mode: "merge",
      providers: {
        [OPENCODE_PROVIDER_ID]: {
          baseUrl: ctx.baseUrl,
          apiKey: OPENCLAW_API_KEY_ENV_REF,
          api: "openai-completions",
          models,
          ...(headers ? { headers } : {}),
        },
      },
    },
  };
}

/** Kimi's model alias: one key per model, namespaced under our provider id. */
export function kimiModelAlias(namespaced: string): string {
  return `${OPENCODE_PROVIDER_ID}/${namespaced}`;
}

function buildKimiClientConfig(ctx: ExportContext): KimiGeneratedConfig {
  const models: Record<string, KimiModelBlock> = {};
  for (const model of normalizeExportModels(ctx.models)) {
    const context = authoritativeContextWindow(model.contextWindow);
    // `max_context_size` is mandatory and must be positive. We do not guess it,
    // so a model without an authoritative window is left out rather than
    // shipped with a number we invented.
    if (context === undefined) continue;
    const efforts = kimiEfforts(model);
    const capabilities: Array<"thinking" | "image_in"> = [
      ...(efforts.support_efforts ? ["thinking" as const] : []),
      ...(model.inputModalities?.includes("image") ? ["image_in" as const] : []),
    ];
    models[kimiModelAlias(model.namespaced)] = {
      provider: OPENCODE_PROVIDER_ID,
      model: model.namespaced,
      max_context_size: context,
      ...(model.displayName ? { display_name: model.displayName } : {}),
      ...(capabilities.length > 0 ? { capabilities } : {}),
      ...efforts,
    };
  }
  return {
    providers: {
      [OPENCODE_PROVIDER_ID]: {
        type: "openai",
        base_url: ctx.baseUrl,
        api_key: LOOPBACK_API_KEY_PLACEHOLDER,
      },
    },
    models,
  };
}

function buildGajaeClientConfig(ctx: ExportContext): GajaeGeneratedConfig {
  const models: GajaeModelEntry[] = [];
  for (const model of normalizeExportModels(ctx.models)) {
    // Gajae's enum is text|image and it rejects the whole file over one bad
    // value, naming the offending index in the error.
    const input = inputModalitiesForClient("gajae", model.inputModalities);
    if (input === null) continue;
    const entry: GajaeModelEntry = {
      id: model.namespaced,
      name: exportModelLabel(model),
      input,
    };
    const context = authoritativeContextWindow(model.contextWindow);
    if (context !== undefined) {
      entry.contextWindow = context;
      entry.maxTokens = outputBudgetFor(context, model);
    }
    // GJC accepts the OpenAI-compatible effort ladder in model metadata. `none` means
    // no parameter and `ultra` is an OCX orchestration level that folds to `max` on the
    // wire, so neither can be offered as a GJC model-level effort.
    const declaredEfforts = model.reasoningEfforts
      // Native Codex rows do not repeat their built-in ladder in the catalog. They still
      // accept the standard effort field, so omitting this fallback hides GJC's thinking
      // control for the models most likely to need it.
      ?? (model.native && model.provider === "openai"
        ? ["low", "medium", "high", "xhigh", "max"]
        : []);
    const efforts = canonicalizeReasoningEfforts(declaredEfforts)
      .filter(effort => effort !== "none" && effort !== "ultra");
    if (efforts.length > 0) {
      entry.reasoning = true;
      entry.thinking = {
        mode: "effort",
        minLevel: efforts[0]!,
        maxLevel: efforts.at(-1)!,
        levels: efforts,
      };
      entry.compat = { supportsReasoningEffort: true };
    }
    models.push(entry);
  }
  return {
    providers: {
      [OPENCODE_PROVIDER_ID]: {
        baseUrl: ctx.baseUrl,
        apiKey: LOOPBACK_API_KEY_PLACEHOLDER,
        api: "openai-completions",
        models,
      },
    },
  };
}

/**
 * Per-client model counts, read back off the SERIALIZED document rather than
 * recomputed from the input rows: `modelsWithoutLimits` drives a GUI line about
 * the bytes the user actually receives, so a parallel reimplementation of the
 * "authoritative context window" rule would be free to drift from it.
 */
function summarizeOpencode(document: unknown): { modelCount: number; modelsWithoutLimits: number } {
  const models = Object.values((document as OpencodeGeneratedConfig | undefined)?.provider?.[OPENCODE_PROVIDER_ID]?.models ?? {});
  return { modelCount: models.length, modelsWithoutLimits: models.filter(model => !model.limit).length };
}

function summarizePi(document: unknown): { modelCount: number; modelsWithoutLimits: number } {
  const models = (document as PiGeneratedConfig | undefined)?.providers?.[OPENCODE_PROVIDER_ID]?.models ?? [];
  return { modelCount: models.length, modelsWithoutLimits: models.filter(model => model.contextWindow === undefined).length };
}

function summarizeHermes(document: unknown): { modelCount: number; modelsWithoutLimits: number } {
  const models = (document as HermesGeneratedConfig | undefined)?.providers?.[OPENCODE_PROVIDER_ID]?.models ?? {};
  // Hermes carries capability metadata but no per-model limit to be missing.
  return { modelCount: Object.keys(models).length, modelsWithoutLimits: 0 };
}

function summarizeOpenclaw(document: unknown): { modelCount: number; modelsWithoutLimits: number } {
  const models = (document as OpenclawGeneratedConfig | undefined)?.models?.providers?.[OPENCODE_PROVIDER_ID]?.models ?? [];
  return { modelCount: models.length, modelsWithoutLimits: models.filter(model => model.contextWindow === undefined).length };
}

function summarizeKimi(document: unknown): { modelCount: number; modelsWithoutLimits: number } {
  const models = Object.values((document as KimiGeneratedConfig | undefined)?.models ?? {});
  // A model with no authoritative window is omitted entirely, so every model
  // present carries max_context_size by construction.
  return { modelCount: models.length, modelsWithoutLimits: 0 };
}

function summarizeGajae(document: unknown): { modelCount: number; modelsWithoutLimits: number } {
  const models = (document as GajaeGeneratedConfig | undefined)?.providers?.[OPENCODE_PROVIDER_ID]?.models ?? [];
  return { modelCount: models.length, modelsWithoutLimits: models.filter(model => model.contextWindow === undefined).length };
}

function buildOpencodeContribution(ctx: ExportContext): ManagedContribution {
  const doc = buildOpencodeClientConfig(ctx);
  return {
    clientId: "opencode",
    fragments: [
      // Legacy block first, so the emitted JSON reads the way a config migration does.
      // opencode V1 reads only `provider`, V2 reads both, and the generation that wins the
      // merge is decided by opencode — what we control is that both name the same models.
      { path: ["provider", OPENCODE_PROVIDER_ID], value: doc.provider[OPENCODE_PROVIDER_ID] },
      { path: ["providers", OPENCODE_PROVIDER_ID], value: doc.providers[OPENCODE_PROVIDER_ID] },
    ],
  };
}

function buildPiContribution(ctx: ExportContext): ManagedContribution {
  const doc = buildPiClientConfig(ctx, PI_NATIVE_SELECTOR_OPTIONS);
  return singleFragment("pi", ["providers", OPENCODE_PROVIDER_ID], doc.providers[OPENCODE_PROVIDER_ID]);
}

function buildHermesContribution(ctx: ExportContext): ManagedContribution {
  const doc = buildHermesClientConfig(ctx);
  return singleFragment("hermes", ["providers", OPENCODE_PROVIDER_ID], doc.providers[OPENCODE_PROVIDER_ID]);
}

function buildOpenclawContribution(ctx: ExportContext): ManagedContribution {
  const doc = buildOpenclawClientConfig(ctx);
  return singleFragment("openclaw", ["models", "providers", OPENCODE_PROVIDER_ID], doc.models.providers[OPENCODE_PROVIDER_ID]);
}

/**
 * Kimi is why a contribution is a LIST: it owns the provider block AND one
 * `models` entry per model. A writer that only knew about the provider would
 * strand every model entry on disable.
 */
function buildKimiContribution(ctx: ExportContext): ManagedContribution {
  const doc = buildKimiClientConfig(ctx);
  const fragments: ManagedFragment[] = [
    { path: ["providers", OPENCODE_PROVIDER_ID], value: doc.providers[OPENCODE_PROVIDER_ID] },
  ];
  for (const [alias, block] of Object.entries(doc.models)) {
    fragments.push({ path: ["models", alias], value: block });
  }
  return { clientId: "kimi", fragments };
}

function buildGajaeContribution(ctx: ExportContext): ManagedContribution {
  const doc = buildGajaeClientConfig(ctx);
  return singleFragment("gajae", ["providers", OPENCODE_PROVIDER_ID], doc.providers[OPENCODE_PROVIDER_ID]);
}

/**
 * Prime Agent (PrimeIntellect) is the pi coding agent shipped under a different
 * brand rather than a lookalike: its package declares a `piConfig` block, and
 * the agent derives its config directory (`.prime/agent`) and env prefix from
 * that block alone. `models.json` is therefore the SAME contract Pi reads, so
 * this client reuses Pi's builder and summarizer verbatim. Restating the shape
 * here would create a second copy of one fact, which is exactly how the
 * "anything that is not OpenCode must be Pi" summarizer bug happened.
 *
 * The one thing that could still differ is the path we own, and it does not:
 * Prime keeps our entries under the same `providers.<id>` key. So the only new
 * code is stamping the right client id on the ownership record.
 */
function buildPrimeContribution(ctx: ExportContext): ManagedContribution {
  const doc = buildPiClientConfig(ctx, PI_DEVELOPER_ROLE_OPTIONS);
  return singleFragment("prime", ["providers", OPENCODE_PROVIDER_ID], doc.providers[OPENCODE_PROVIDER_ID]);
}

/**
 * Aside is the strongest case yet for reusing Pi's builder, because the
 * evidence is a live file rather than a package manifest.
 *
 * The machine this landed on already had opencodex wired into Aside BY HAND:
 * `~/.aside/u/0/models.json` carried a `providers.opencodex` block with the same
 * four keys, the same `openai-completions` dialect, the same
 * `opencodex-loopback` placeholder, and 24 models using the same
 * `thinkingLevelMap` levels this builder emits. A user reproduced Pi's document
 * from scratch because that is what Aside reads.
 *
 * Key ORDER differs (the hand-written file has `apiKey` before `api`), which is
 * why the devlog claims compatibility rather than byte equality: JSON key order
 * is not semantic and Aside parses this file rather than diffing it.
 *
 * As with prime, only the ownership stamp is Aside's own, so a disable removes
 * the fragment this client recorded and not one another client wrote.
 */
function buildAsideContribution(ctx: ExportContext): ManagedContribution {
  const doc = buildPiClientConfig(ctx, PI_DEVELOPER_ROLE_OPTIONS);
  return singleFragment("aside", ["providers", OPENCODE_PROVIDER_ID], doc.providers[OPENCODE_PROVIDER_ID]);
}

/**
 * omo is the Pi document again, and this time the engine was checked rather
 * than inferred: `omo-ai@beta` is a launcher around `@code-yeongyu/senpi`, and
 * senpi's compiled validator accepts what `buildPiClientConfig` emits verbatim —
 * the keyed `providers`, the `models` ARRAY whose identity is `id`, the
 * `openai-completions` dialect, the loopback placeholder, and the
 * `thinkingLevelMap` levels. Evidence:
 * `devlog/_fin/260912_omo_client_integration/001_omo_contract.md`.
 *
 * The flag is passed HERE as well as in the spec's `build`, the same rule Prime
 * and Aside follow with their own options; passing it on only one would make `ocx export --client omo`
 * emit a `compat` block while enable and refresh wrote a file without it, and
 * the two would drift apart at the first refresh.
 *
 * The same rule covers the opt-in `omoClientExport.api` dialect (#7431): both paths read it from
 * the live config, so a refresh keeps the Responses dialect instead of reverting it to Chat.
 */
function buildOmoContribution(ctx: ExportContext): ManagedContribution {
  const doc = buildPiClientConfig(ctx, omoExportOptions(ctx));
  return singleFragment("omo", ["providers", OPENCODE_PROVIDER_ID], doc.providers[OPENCODE_PROVIDER_ID]);
}

function omoExportOptions(ctx: ExportContext): PiExportOptions {
  return ctx.config?.omoClientExport?.api === "openai-responses"
    ? { ...PI_EXPORT_OPTIONS, api: "openai-responses" }
    : PI_EXPORT_OPTIONS;
}

/** Cline's shared SDK store; command-local --config must be mirrored by the env override. */
export function clineConfigPath(env: OpencodeLaunchEnv = process.env, home: string = homedir()): string {
  const explicit = env.CLINE_PROVIDER_SETTINGS_PATH?.trim();
  const data = env.CLINE_DATA_DIR?.trim();
  const root = env.CLINE_DIR?.trim();
  const path = explicit ? absoluteClientPath(explicit, home, "CLINE_PROVIDER_SETTINGS_PATH")
    : join(data ? absoluteClientPath(data, home, "CLINE_DATA_DIR")
      : join(root ? absoluteClientPath(root, home, "CLINE_DIR") : join(home, ".cline"), "data"), "settings", "providers.json");
  if (basename(path).toLowerCase() === "models.json") {
    throw new ClientPathError("CLINE_PROVIDER_SETTINGS_PATH must differ from the sibling models.json catalog");
  }
  return path;
}

export function clineSettingsDir(env: OpencodeLaunchEnv = process.env, home: string = homedir()): string {
  return dirname(clineConfigPath(env, home));
}

export const EXPORT_CLIENTS: Record<ExportClientId, ExportClientSpec> = {
  qoder: {
    id: "qoder",
    filename: "qoder-settings.json",
    destination: env => qoderConfigPath(env),
    apiKeyEnv: "",
    exportHint: "Qoder reads a non-secret placeholder from settings.json; loopback needs no key.",
    build: buildQoderClientConfig,
    format: "json",
    summarize: summarizeQoder,
    buildContribution: buildQoderContribution,
    loopbackOnly: true,
  },
  "qoder-cn": {
    id: "qoder-cn", filename: "qoder-cn-settings.json", destination: env => agentConfigPath("qoder-cn", env),
    apiKeyEnv: "", exportHint: "Qoder CN uses a non-secret loopback placeholder.", format: "json",
    build: buildQoderCnClientConfig, summarize: summarizeQoder, buildContribution: buildQoderCnContribution, loopbackOnly: true,
  },
  ...Object.fromEntries((["workbuddy", "workbuddy-ai"] as const).map(id => [id, {
    id, filename: `${id}-models.json`, destination: (env: NodeJS.ProcessEnv) => agentConfigPath(id, env),
    apiKeyEnv: "", exportHint: "WorkBuddy uses a non-secret loopback placeholder.", format: "json" as const,
    build: buildWorkbuddyClientConfig, summarize: summarizeWorkbuddy, validateApply: workbuddyApplyRefusal,
    buildContribution: (ctx: ExportContext) => buildWorkbuddyContribution(id, ctx), loopbackOnly: true,
  }])) as Record<"workbuddy" | "workbuddy-ai", ExportClientSpec>,
  opencode: {
    id: "opencode",
    filename: "opencode.json",
    destination: env => opencodeGlobalConfigPath(env),
    apiKeyEnv: OPENCODE_API_KEY_ENV,
    exportHint: `export ${OPENCODE_API_KEY_ENV}=<your key>`,
    build: buildOpencodeClientConfig,
    format: "json",
    summarize: summarizeOpencode,
    buildContribution: buildOpencodeContribution,
    // carries the dedicated header in provider options
    loopbackOnly: false,
  },
  pi: {
    id: "pi",
    filename: "pi-models.json",
    destination: env => piConfigPath(env),
    apiKeyEnv: "",
    exportHint: "Pi reads a non-secret placeholder from models.json; loopback needs no key.",
    build: ctx => buildPiClientConfig(ctx, PI_NATIVE_SELECTOR_OPTIONS),
    format: "json",
    summarize: summarizePi,
    buildContribution: buildPiContribution,
    // No header field in Pi's provider block, so there is nowhere to put the
    // dedicated admission header a remote bind requires.
    loopbackOnly: true,
  },
  omp: {
    id: "omp",
    filename: "omp-models.yaml",
    destination: env => ompModelsConfigPath(env),
    apiKeyEnv: "",
    exportHint: "OMP reads a non-secret placeholder from models.yml; loopback needs no key.",
    build: buildOmpClientConfig,
    format: "yaml",
    summarize: summarizeOmp,
    buildContribution: buildOmpContribution,
    // OMP supports provider-level headers, but remote credential wiring is
    // intentionally deferred from this initial loopback-only integration.
    loopbackOnly: true,
  },
  hermes: {
    id: "hermes",
    filename: "hermes-config.yaml",
    destination: env => hermesConfigPath(env),
    apiKeyEnv: HERMES_API_KEY_ENV,
    exportHint: `export ${HERMES_API_KEY_ENV}=<your key>`,
    build: buildHermesClientConfig,
    format: "yaml",
    summarize: summarizeHermes,
    buildContribution: buildHermesContribution,
    // extra_headers carries the dedicated header
    loopbackOnly: false,
  },
  openclaw: {
    id: "openclaw",
    filename: "openclaw.json5",
    destination: env => openclawConfigPath(env),
    apiKeyEnv: OPENCLAW_API_KEY_ENV,
    exportHint: `export ${OPENCLAW_API_KEY_ENV}=<your key>`,
    build: buildOpenclawClientConfig,
    format: "json5",
    summarize: summarizeOpenclaw,
    buildContribution: buildOpenclawContribution,
    // headers carries the dedicated header
    loopbackOnly: false,
  },
  kimi: {
    id: "kimi",
    filename: "kimi-config.toml",
    destination: env => kimiConfigPath(env),
    // Kimi reads credentials only from its own file, so there is no env var to
    // export: a loopback bind uses the placeholder, and a remote bind is
    // refused rather than handed the user's real key.
    apiKeyEnv: "",
    exportHint: "Kimi Code reads credentials from its config file; loopback needs no key.",
    build: buildKimiClientConfig,
    format: "toml",
    summarize: summarizeKimi,
    buildContribution: buildKimiContribution,
    // no header field, and credentials come only from this file
    loopbackOnly: true,
  },
  gajae: {
    id: "gajae",
    filename: "gajae-models.yaml",
    destination: env => gajaeConfigPath(env),
    apiKeyEnv: "",
    exportHint: "No environment variable is needed for the loopback provider.",
    build: buildGajaeClientConfig,
    format: "yaml",
    summarize: summarizeGajae,
    buildContribution: buildGajaeContribution,
    // strict schema with no header field, so the dedicated header has nowhere to go
    loopbackOnly: true,
  },
  dsh: {
    id: "dsh",
    filename: "settings.yaml",
    destination: env => dshConfigPath(env),
    apiKeyEnv: "",
    exportHint: "DSH uses a non-secret loopback bearer placeholder in settings.yaml; loopback needs no key.",
    build: buildDshClientConfig,
    format: "yaml",
    summarize: summarizeDsh,
    buildContribution: buildDshContribution,
    loopbackOnly: true,
  },
  mcode: {
    id: "mcode",
    filename: "mcode-config.yaml",
    destination: env => mcodeConfigPath(env),
    apiKeyEnv: "",
    exportHint: "MiniMax Code reads a non-secret placeholder from config.yaml; loopback needs no key.",
    build: buildMcodeClientConfig,
    format: "yaml",
    summarize: summarizeMcode,
    buildContribution: buildMcodeContribution,
    // MCode persists this credential and exposes no dedicated proxy-admission
    // header field, so real keys are never serialized and remote binds refuse.
    loopbackOnly: true,
  },
  zcode: {
    id: "zcode",
    filename: "config.json",
    destination: env => zcodeConfigPath(env),
    apiKeyEnv: "",
    exportHint: "ZCode reads a non-secret placeholder from v2/config.json; loopback needs no key.",
    build: buildZcodeClientConfig,
    format: "json",
    summarize: summarizeZcode,
    buildContribution: buildZcodeContribution,
    // ZCode persists the credential in its own file and has no dedicated
    // proxy-admission header field, so real keys are never serialized and
    // remote binds refuse — same reasoning as MCode.
    loopbackOnly: true,
  },
  commandcode: {
    id: "commandcode",
    filename: "providers.json",
    destination: env => commandCodeConfigPath(env),
    // No env var exists behind this integration: buildCommandCodeClientConfig
    // writes `apiKey: false`, the documented keyless form for a loopback endpoint.
    apiKeyEnv: "",
    exportHint: "The provider is written with `apiKey: false`, the keyless form the CLI accepts. The desktop app needs its own Command Code sign-in; opencodex never writes `~/.commandcode/auth.json`.",
    build: buildCommandCodeClientConfig,
    format: "json",
    summarize: summarizeCommandCode,
    buildContribution: buildCommandCodeContribution,
    loopbackOnly: true,
  },
  prime: {
    id: "prime",
    filename: "prime-models.json",
    destination: env => primeConfigPath(env),
    apiKeyEnv: "",
    exportHint: "Prime Agent reads a non-secret placeholder from models.json; loopback needs no key.",
    build: ctx => buildPiClientConfig(ctx, PI_DEVELOPER_ROLE_OPTIONS),
    format: "json",
    summarize: summarizePi,
    buildContribution: buildPrimeContribution,
    // Prime's provider block does accept `headers`, so a dedicated admission
    // header has somewhere to live, but remote credential wiring is deferred
    // from this initial loopback-only integration — same stance as OMP's.
    loopbackOnly: true,
  },
  aside: {
    id: "aside",
    // Not a bare `models.json`: a download lands in the user's Downloads folder,
    // where pi's and prime's files would collide with it. Prime set this
    // precedent with `prime-models.json`.
    filename: "aside-models.json",
    destination: env => asideConfigPath(env),
    apiKeyEnv: "",
    exportHint: "Aside reads a non-secret placeholder from models.json; loopback needs no key.",
    build: ctx => buildPiClientConfig(ctx, PI_DEVELOPER_ROLE_OPTIONS),
    format: "json",
    summarize: summarizePi,
    buildContribution: buildAsideContribution,
    // The observed provider block has exactly four keys and none is `headers`,
    // so the dedicated admission header has nowhere to live and a non-loopback
    // bind would generate a config that 401s.
    loopbackOnly: true,
  },
  raycast: {
    id: "raycast",
    // Not a bare `providers.yaml`: same Downloads-folder collision argument as
    // `aside-models.json`.
    filename: "raycast-providers.yaml",
    destination: env => raycastConfigPath(env),
    apiKeyEnv: "",
    exportHint: "Raycast reads providers.yaml with no api_keys entry; loopback needs no key.",
    build: buildRaycastClientConfig,
    format: "yaml",
    summarize: summarizeRaycast,
    buildContribution: buildRaycastContribution,
    // Raycast's provider entry has no header field, and its `api_keys` value
    // is read literally (no env interpolation), so the only way to admit a
    // remote bind would be a plaintext secret on disk. Refuse instead.
    loopbackOnly: true,
  },
  /*
   * The shared client roster preserves public landing order, not family grouping.
   * Keep this registry in the same order so its iteration agrees with the roster.
   */
  omo: {
    id: "omo",
    // Not a bare `models.json`: same Downloads-folder collision argument as
    // `prime-models.json` and `aside-models.json`.
    filename: "omo-models.json",
    destination: env => omoConfigPath(env),
    apiKeyEnv: "",
    exportHint: "omo reads a non-secret placeholder from models.json; loopback needs no key.",
    build: ctx => buildPiClientConfig(ctx, omoExportOptions(ctx)),
    format: "json",
    summarize: summarizePi,
    buildContribution: buildOmoContribution,
    /*
     * Loopback-only for OMP's and Prime's reason, NOT Pi's and Aside's. senpi's
     * provider block does accept a `headers` map and does interpolate `$ENV` in
     * its values, so unlike Aside there is somewhere the dedicated admission
     * header could live. What does not exist is a builder that emits one:
     * `buildPiClientConfig` writes no headers at all, which is why `pi` is
     * loopback-only too. Teaching the shared builder to emit them would change
     * four clients at once, so remote wiring is deferred and a non-loopback bind
     * refuses rather than generating a config that 401s.
     */
    loopbackOnly: true,
  },
  cline: {
    id: "cline",
    filename: "cline-config-bundle.json",
    destination: env => clineConfigPath(env),
    apiKeyEnv: "",
    exportHint: "Cline CLI bundle: settings goes in providers.json, catalog in sibling models.json. Stop Cline before enabling/syncing/restoring, then restart. Select --provider opencodex; the default provider stays unchanged. Loopback only.",
    build: buildClineClientConfig,
    format: "json",
    summarize: summarizeCline,
    buildContribution: buildClineContribution,
    loopbackOnly: true,
  },
  kilo: {
    id: "kilo",
    filename: "kilo.jsonc",
    destination: env => kiloConfigPath(env),
    apiKeyEnv: KILO_API_KEY_ENV,
    exportHint: `export ${KILO_API_KEY_ENV}=<your key>`,
    build: buildKiloClientConfig,
    format: "json",
    summarize: summarizeKilo,
    buildContribution: buildKiloContribution,
    loopbackOnly: false,
    jsonc: true,
  },
  droid: {
    id: "droid",
    filename: "factory-settings.json",
    destination: env => droidConfigPath(env),
    apiKeyEnv: "",
    exportHint: "Factory Droid reads keyless loopback custom models from settings.json. Select one with /model.",
    build: buildDroidClientConfig,
    format: "json",
    summarize: summarizeDroid,
    buildContribution: buildDroidContribution,
    loopbackOnly: true,
  },
  "gentle-shell": {
    id: "gentle-shell",
    filename: "gentle-shell-models.json",
    destination: env => gentleShellPaths(env).configPath,
    apiKeyEnv: "",
    exportHint: "Gentle Shell uses its persistent selected home; restart the shell to load the catalog. Link/shared homes use the Pi integration.",
    build: ctx => buildPiClientConfig(ctx, PI_EXPORT_OPTIONS),
    format: "json",
    summarize: summarizePi,
    buildContribution: ctx => {
      const doc = buildPiClientConfig(ctx, PI_EXPORT_OPTIONS);
      return singleFragment("gentle-shell", ["providers", OPENCODE_PROVIDER_ID], doc.providers[OPENCODE_PROVIDER_ID]);
    },
    loopbackOnly: true,
  },
  t3code: {
    id: "t3code",
    filename: "t3code-settings.json",
    destination: env => t3codeConfigPath(env),
    apiKeyEnv: "",
    exportHint: "Merge providerInstances.opencodex into T3 Code's settings.json; it reloads the file. Loopback needs no key.",
    build: buildT3CodeClientConfig,
    format: "json",
    summarize: summarizeT3Code,
    validateApply: t3codeApplyRefusal,
    buildContribution: buildT3CodeContribution,
    loopbackOnly: true,
  },
};

export { EXPORT_CLIENT_IDS } from "./client-ids";

export function isExportClientId(value: string): value is ExportClientId {
  return Object.prototype.hasOwnProperty.call(EXPORT_CLIENTS, value);
}

/** Single entry point every export surface calls. */
export function buildClientConfig(client: ExportClientId, ctx: ExportContext): unknown {
  return EXPORT_CLIENTS[client].build(namedExportContext(client, ctx));
}

/**
 * The bytes a user actually receives, plus what they are. One place turns a
 * client id into text so the CLI, the API and the GUI cannot disagree about
 * format or media type — and so no consumer has to infer either from a
 * filename.
 */
export function buildClientConfigText(
  client: ExportClientId,
  ctx: ExportContext,
): { document: unknown; text: string; format: ConfigFormat; mediaType: string } {
  const spec = EXPORT_CLIENTS[client];
  const document = spec.build(namedExportContext(client, ctx));
  return {
    document,
    text: serializeDocument(document, spec.format),
    format: spec.format,
    mediaType: FORMAT_MEDIA_TYPE[spec.format],
  };
}

/** The fragments opencodex owns in a client's config (writer-side). */
export function buildClientContribution(client: ExportClientId, ctx: ExportContext): ManagedContribution {
  return EXPORT_CLIENTS[client].buildContribution(namedExportContext(client, ctx));
}