Skip to content

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io

13.4 KB
Raw Blame
import type { OpenCodeModel, OpenCodeProviderConfig } from "@/types";
import { PI_THINKING_LEVELS } from "@/config/piThinkingProfiles";
import { isPlainObject } from "@/lib/requestOverrides";

// ── Default configs ──────────────────────────────────────────────────

export const CLAUDE_DEFAULT_CONFIG = JSON.stringify({ env: {} }, null, 2);
export const CODEX_DEFAULT_CONFIG = JSON.stringify(
  { auth: {}, config: "" },
  null,
  2,
);
export const GEMINI_DEFAULT_CONFIG = JSON.stringify(
  {
    env: {
      GOOGLE_GEMINI_BASE_URL: "",
      GEMINI_API_KEY: "",
      GEMINI_MODEL: "gemini-3.6-flash",
    },
  },
  null,
  2,
);

export const OPENCODE_DEFAULT_NPM = "@ai-sdk/openai-compatible";
export const OPENCODE_DEFAULT_CONFIG = JSON.stringify(
  {
    npm: OPENCODE_DEFAULT_NPM,
    options: {
      baseURL: "",
      apiKey: "",
      setCacheKey: true,
    },
    models: {},
  },
  null,
  2,
);
export const OPENCODE_KNOWN_OPTION_KEYS = [
  "baseURL",
  "apiKey",
  "headers",
] as const;

// Contains ":", which is not valid in an HTTP field name, so it cannot
// collide with a legitimate custom header from an existing configuration.
export { REQUEST_HEADER_DRAFT_PREFIX as OPENCODE_HEADER_DRAFT_PREFIX } from "./requestHeaders";
export const OPENCODE_EXTRA_OPTION_DRAFT_PREFIX = "draft-option:";

export const OPENCLAW_DEFAULT_CONFIG = JSON.stringify(
  {
    baseUrl: "",
    apiKey: "",
    api: "openai-completions",
    models: [],
  },
  null,
  2,
);

// ── Pure functions ───────────────────────────────────────────────────

// Keys only a V1 declaration has, and keys only a native one has. Mirrors
// provider_format in src-tauri/src/opencode_config.rs.
const OPENCODE_LEGACY_ONLY_KEYS = ["npm", "options", "api"];
const OPENCODE_NATIVE_ONLY_KEYS = [
  "package",
  "settings",
  "headers",
  "body",
  "canonical",
];

function parseJson(json: string): unknown {
  try {
    return JSON.parse(json);
  } catch {
    return undefined;
  }
}

/** Keep native declarations out of the V1 structured editor. Source metadata
 * disambiguates built-in overrides containing only models (or an empty object).
 * A pasted full config holding `providers` counts as native too.
 */
export function isNativeOpencodeConfig(
  json: string,
  source?: "v1" | "v2",
): boolean {
  if (source) return source === "v2";
  const value = parseJson(json);
  if (!isPlainObject(value)) return false;
  if (OPENCODE_LEGACY_ONLY_KEYS.some((key) => key in value)) return false;
  return [...OPENCODE_NATIVE_ONLY_KEYS, "providers"].some(
    (key) => key in value,
  );
}

/** A declaration that does not rely on a built-in definition: it names a
 * package (`npm` for V1, `package` for native) and at least one model.
 */
export function hasOpencodeDefinition(
  declaration: unknown,
  packageKey: "npm" | "package",
): boolean {
  if (!isPlainObject(declaration)) return false;
  const pkg = declaration[packageKey];
  const { models } = declaration;
  return (
    typeof pkg === "string" &&
    pkg.trim() !== "" &&
    isPlainObject(models) &&
    Object.keys(models).length > 0
  );
}

/** The native form's check: a pasted full config holds the declaration under
 * `providers.<id>`, where the backend also takes it from.
 */
export function hasNativeOpencodeDefinition(
  json: string,
  providerId: string,
): boolean {
  const value = parseJson(json);
  const providers = isPlainObject(value) ? value.providers : undefined;
  const declaration = isPlainObject(providers)
    ? (providers[providerId] ?? value)
    : value;
  return hasOpencodeDefinition(declaration, "package");
}

/** Models a stored provider declares, read from the fragment the backend
 * writes: settings may hold a full config with the declaration under
 * `providers.<id>` / `provider.<id>`.
 */
export function getOpencodeDeclaredModels(
  providerId: string,
  settingsConfig: unknown,
): { id: string; name?: string }[] {
  let declaration = settingsConfig;
  if (
    isPlainObject(settingsConfig) &&
    ["$schema", "provider", "providers"].some((key) => key in settingsConfig)
  ) {
    const pick = (key: string) => {
      const section = settingsConfig[key];
      return isPlainObject(section) ? section[providerId] : undefined;
    };
    declaration = pick("providers") ?? pick("provider") ?? settingsConfig;
  }
  const models = isPlainObject(declaration) ? declaration.models : undefined;
  if (!isPlainObject(models)) return [];
  return (
    Object.entries(models)
      // 原生声明可以 `disabled: true` 关掉某个模型,不能拿它当默认
      .filter(
        ([id, model]) =>
          id.trim() && !(isPlainObject(model) && model.disabled === true),
      )
      .map(([id, model]) => ({
        id,
        name:
          isPlainObject(model) && typeof model.name === "string"
            ? model.name
            : undefined,
      }))
  );
}

export function isKnownOpencodeOptionKey(key: string): boolean {
  return OPENCODE_KNOWN_OPTION_KEYS.includes(
    key as (typeof OPENCODE_KNOWN_OPTION_KEYS)[number],
  );
}

export function parseOpencodeConfig(
  settingsConfig?: Record<string, unknown>,
): OpenCodeProviderConfig {
  const normalize = (
    parsed: Partial<OpenCodeProviderConfig>,
  ): OpenCodeProviderConfig => ({
    npm: parsed.npm ?? (settingsConfig ? "" : OPENCODE_DEFAULT_NPM),
    options:
      parsed.options && typeof parsed.options === "object"
        ? (parsed.options as OpenCodeProviderConfig["options"])
        : {},
    models:
      parsed.models && typeof parsed.models === "object"
        ? (parsed.models as Record<string, OpenCodeModel>)
        : {},
  });

  try {
    const parsed = JSON.parse(
      settingsConfig ? JSON.stringify(settingsConfig) : OPENCODE_DEFAULT_CONFIG,
    ) as Partial<OpenCodeProviderConfig>;
    return normalize(parsed);
  } catch {
    return {
      npm: OPENCODE_DEFAULT_NPM,
      options: {},
      models: {},
    };
  }
}

export function parseOpencodeConfigStrict(
  settingsConfig?: Record<string, unknown>,
): OpenCodeProviderConfig {
  const parsed = JSON.parse(
    settingsConfig ? JSON.stringify(settingsConfig) : OPENCODE_DEFAULT_CONFIG,
  ) as Partial<OpenCodeProviderConfig>;
  return {
    npm: parsed.npm ?? (settingsConfig ? "" : OPENCODE_DEFAULT_NPM),
    options:
      parsed.options && typeof parsed.options === "object"
        ? (parsed.options as OpenCodeProviderConfig["options"])
        : {},
    models:
      parsed.models && typeof parsed.models === "object"
        ? (parsed.models as Record<string, OpenCodeModel>)
        : {},
  };
}

export const OPENCODE_KNOWN_MODEL_KEYS = ["name", "limit", "options"] as const;

export function isKnownModelKey(key: string): boolean {
  return OPENCODE_KNOWN_MODEL_KEYS.includes(
    key as (typeof OPENCODE_KNOWN_MODEL_KEYS)[number],
  );
}

/**
 * 模型字段的方言:OpenCode 和 MiniMax Code 用 OpenCode 的模型结构;DeepSeek Harness
 * 走 pi-ai 适配器,多认 `reasoningEfforts`(档位 → 上游值)和 `compat`。
 */
export type OpenCodeModelDialect = "opencode" | "dsh";

type Modalities = { input: string[]; output?: string[] };

function isStringList(value: unknown): value is string[] {
  return (
    Array.isArray(value) && value.every((item) => typeof item === "string")
  );
}

function isModalities(value: unknown): value is Modalities {
  return (
    isPlainObject(value) &&
    isStringList(value.input) &&
    (value.output === undefined || isStringList(value.output))
  );
}

const REASONING_EFFORT_LEVEL_SET = new Set<string>(PI_THINKING_LEVELS);

export function isReasoningEffortMap(
  value: unknown,
): value is Record<string, string | null> {
  if (!isPlainObject(value)) return false;
  const entries = Object.entries(value);
  return (
    entries.length > 0 &&
    entries.every(
      ([key, item]) =>
        REASONING_EFFORT_LEVEL_SET.has(key) &&
        (item === null || typeof item === "string"),
    )
  );
}

/** 展开区有专门控件的字段不在「模型属性」里重复;形状认不出的照旧留在那里,免得藏起来改不了。 */
function hasDedicatedControl(
  key: string,
  value: unknown,
  dialect: OpenCodeModelDialect,
): boolean {
  switch (key) {
    case "reasoning":
      return typeof value === "boolean";
    case "modalities":
      return isModalities(value);
    case "reasoningEfforts":
      return (
        dialect === "dsh" && (value === false || isReasoningEffortMap(value))
      );
    case "compat":
      return dialect === "dsh" && isPlainObject(value);
    default:
      return false;
  }
}

export function modelSupportsReasoning(
  model: OpenCodeModel,
  dialect: OpenCodeModelDialect,
): boolean {
  if (typeof model.reasoning === "boolean") return model.reasoning;
  return dialect === "dsh" && isReasoningEffortMap(model.reasoningEfforts);
}

// 与后端给「开了思考、没写档位」的模型补的默认档位一致(dsh_config.rs)
const DSH_DEFAULT_REASONING_EFFORTS = {
  off: null,
  low: "low",
  medium: "medium",
  high: "high",
};

export function withModelReasoning(
  model: OpenCodeModel,
  enabled: boolean,
  dialect: OpenCodeModelDialect,
): OpenCodeModel {
  const next = { ...model };
  if (dialect === "dsh") {
    // DSH 只看 reasoningEfforts:false 表示不思考,对象是提供的档位
    next.reasoning = enabled;
    next.reasoningEfforts = enabled
      ? isReasoningEffortMap(model.reasoningEfforts)
        ? model.reasoningEfforts
        : { ...DSH_DEFAULT_REASONING_EFFORTS }
      : false;
  } else if (enabled) {
    next.reasoning = true;
  } else {
    // 不写 false:OpenCode 里 false 会盖住 models.dev 同名条目
    delete next.reasoning;
  }
  return next;
}

export function modelSupportsImageInput(model: OpenCodeModel): boolean {
  return (
    isModalities(model.modalities) && model.modalities.input.includes("image")
  );
}

export function withModelImageInput(
  model: OpenCodeModel,
  enabled: boolean,
): OpenCodeModel {
  const current = isModalities(model.modalities) ? model.modalities : null;
  const input = (current?.input ?? ["text"]).filter((item) => item !== "image");
  return {
    ...model,
    modalities: {
      ...current,
      input: enabled ? [...input, "image"] : input,
      output: current?.output ?? ["text"],
    },
  };
}

export function getModelExtraFields(
  model: OpenCodeModel,
  dialect: OpenCodeModelDialect = "opencode",
): Record<string, string> {
  const extra: Record<string, string> = {};
  for (const [k, v] of Object.entries(model)) {
    if (!isKnownModelKey(k) && !hasDedicatedControl(k, v, dialect)) {
      extra[k] = typeof v === "string" ? v : JSON.stringify(v);
    }
  }
  return extra;
}

export function formatOpencodeExtraOptionValue(value: unknown): string {
  return typeof value === "string" ? value : JSON.stringify(value);
}

export function toOpencodeExtraOptions(
  options: OpenCodeProviderConfig["options"],
): Record<string, string> {
  const extra: Record<string, string> = {};
  for (const [k, v] of Object.entries(options || {})) {
    if (!isKnownOpencodeOptionKey(k)) {
      extra[k] = formatOpencodeExtraOptionValue(v);
    }
  }
  return extra;
}

/**
 * Reconciles the extra-option row editor's string map into the stored
 * `options` object in place. Rows whose text still matches the stored
 * value's display form were not touched by the user, so their stored
 * values (types included) are kept as-is; a renamed row carries its old
 * display text under the new key, so its stored value is re-homed from
 * the key that vanished from the rows. Only added, edited and removed
 * rows are rewritten.
 */
export function mergeOpencodeExtraOptionRows(
  options: Record<string, unknown>,
  rows: Record<string, string>,
): void {
  const nextRows: Record<string, string> = {};
  for (const [k, v] of Object.entries(rows)) {
    const trimmedKey = k.trim();
    if (trimmedKey && !k.startsWith(OPENCODE_EXTRA_OPTION_DRAFT_PREFIX)) {
      nextRows[trimmedKey] = v;
    }
  }

  // Keys that vanished from the rows were deleted or renamed away. Keep
  // their stored values around: a renamed row's untouched display text is
  // matched against them below to re-home the value with its type.
  const renamedAway: Array<[string, unknown]> = [];
  for (const k of Object.keys(options)) {
    // Own-property check: `k in nextRows` would also match inherited
    // Object.prototype keys such as "constructor" or "toString", keeping
    // rows the user deleted.
    if (
      !isKnownOpencodeOptionKey(k) &&
      !Object.prototype.hasOwnProperty.call(nextRows, k)
    ) {
      renamedAway.push([k, options[k]]);
      delete options[k];
    }
  }

  for (const [k, v] of Object.entries(nextRows)) {
    const existing = options[k];
    if (
      existing !== undefined &&
      formatOpencodeExtraOptionValue(existing) === v
    ) {
      continue;
    }
    // A key unknown to `options` can still be an untouched row, namely a
    // rename: the editor moves the display text to the new key verbatim.
    // Inherit the vanished key's stored value instead of re-parsing the
    // text; same-text vanished keys render identically, so any match has
    // the same display form and usually the same type.
    const source = renamedAway.find(
      ([, stored]) => formatOpencodeExtraOptionValue(stored) === v,
    );
    if (source) {
      options[k] = source[1];
      continue;
    }
    try {
      options[k] = JSON.parse(v);
    } catch {
      options[k] = v;
    }
  }
}