Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

90.3 KB
Raw Blame
/**
 * `.project_config.toml` read/write (single hidden config file).
 *
 * Doesn't reuse core's loadProjectConfig/saveProjectConfig (they only keep known
 * fields): reads and writes the complete object directly via smol-toml, preserving
 * extension fields like `name`. credential (api_key / base_url / created_at) is
 * **inlined on the model entry** — there's no longer a supplementary section or
 * secrets file; since the file contains secrets, it's always written with mode
 * 0600. Plaintext only ever hits disk, and is always masked in responses.
 *
 * Model references are **fully split into separate fields**: an entry is
 * stored as two independent fields, `provider` and `model_id`; the `(provider,
 * model_id)` pair is the entry's unique key. `model_id` is the upstream request id,
 * sent to AgentHub verbatim — string concatenation like `<provider>/<id>` is
 * forbidden everywhere in the pipeline. `default_model` / `vision_model` are `{
 * provider, model_id }` paired references (TOML tables).
 *
 * Reads are memoized on the file's mtime (see readTable): every consumer of this
 * service — scheduler model-ref validation, the models/schedules routes, usage
 * pricing — shares one parsed table per on-disk version instead of re-reading and
 * re-parsing the TOML per call. The service's own writes all funnel through
 * `writeRaw`, which invalidates synchronously; external edits (CLI, hand edits) are
 * caught by the stat. The cached table is shared between callers and must be treated
 * as immutable — every mutating method here copies before changing.
 */
import fs from "node:fs/promises";
import path from "node:path";
import { parse as parseToml } from "smol-toml";
import {
  CHAT_APPROVAL_MODES,
  atomicWriteFile,
  DEFAULT_CHAT_THINKING_LEVELS,
  DEFAULT_COMMAND_POLICY_RULES,
  effectiveCommandPolicyRules,
  parseCommandPolicy,
  parsePluginTables,
  pluginTablesToToml,
  GenerativeModel,
  canonicalClientType,
  listEndpointModels as coreListEndpointModels,
  MODELSCOPE_PROVIDER_ID,
  catalogEntryFor,
  defaultProjectConfig,
  imageUrlMessage,
  metaMaxTokens,
  offPeakAt,
  presetPromotions,
  projectConfigFromTable,
  projectConfigPath,
  renderProjectConfigToml,
  modelEnvFallback,
  modelEnvPreviewKey,
  resolveModelCredential,
  userText,
} from "@adelie/core";
import {
  VENDOR_ENDPOINTS,
  providerInfo,
  unaddableModel,
  unroutableVendorModel,
} from "@adelie/core/model-catalog";
import type {
  PluginTables,
  CommandPolicyRule,
  GenerativeModelConfig,
  LLMOutcome,
  ModelRequestContext,
  ModelRef,
  OmniMessage,
  ProjectConfig,
} from "@adelie/core";
import type {
  ChatDefaultsDto,
  CommandPolicyDto,
  CommandPolicyRuleDto,
  EndpointModelListRequest,
  EndpointModelListResponse,
  ModelInfo,
  ModelPricingDto,
  ModelProtocolDetectRequest,
  ModelProtocolDetectResponse,
  ModelRefDto,
  ModelsResponse,
  ModelsUpdateRequest,
  ModelUpdateEntry,
  ModelTestRequest,
  ModelTestResponse,
  ModelVisionDetectRequest,
  ModelVisionDetectResponse,
} from "../api/types.js";
import { badRequest } from "../http/validate.js";
import { HttpError } from "../http/errors.js";
import { cacheable } from "../internal/mtime-gate.js";
import type {
  PlatformCatalogPricing,
  PlatformModelApplyResult,
  PlatformModelCatalog,
} from "./platform-auth-types.js";
import { detectModelProtocol } from "./protocol-detect.js";
import {
  VISION_PROBE_IMAGE,
  VISION_PROBE_MAX_TOKENS,
  VISION_PROBE_PROMPT,
  VISION_PROBE_TIMEOUT_MS,
  classifyVisionProbe,
  classifyVisionProbeError,
} from "./vision-detect.js";
import type { PricingRates } from "./usage-service.js";
import { Component, Use } from "@adelie/core/kernel";
import type { Config, Paths } from "../hmr/capabilities.js";
import type {
  ModelPromotion,
  ModelProviderAuthToken,
  ModelProviderAuthTokens,
  ModelPromotions,
  ProjectConfigStore,
} from "../mechanisms/projects.js";

export type RawTable = Record<string, unknown>;

/**
 * API key masking: length <=12 -> `***`, otherwise `first4…last4`; plaintext is
 * never sent to the client. The 12-char threshold: `first4…last4` exposes 8
 * characters, which for a 9-12 character short secret would leak more than half of
 * it, so those are masked in full instead.
 */
export function maskApiKey(key: string): string {
  if (key.length <= 12) return "***";
  return `${key.slice(0, 4)}…${key.slice(-4)}`;
}

function asTable(v: unknown): RawTable {
  return v !== null && typeof v === "object" && !Array.isArray(v) ? (v as RawTable) : {};
}

function asArray(v: unknown): RawTable[] {
  return Array.isArray(v) ? v.map(asTable) : [];
}

function optNum(v: unknown): number | undefined {
  return typeof v === "number" && Number.isFinite(v) ? v : undefined;
}

function platformPricingTable(pricing: PlatformCatalogPricing): RawTable {
  return {
    unit: pricing.unit,
    cache_read: pricing.cacheRead,
    cache_write: pricing.cacheWrite,
    output: pricing.output,
  };
}

function platformPricingMatches(value: unknown, pricing: PlatformCatalogPricing): boolean {
  const stored = asTable(value);
  return (
    stored.unit === pricing.unit &&
    stored.cache_read === pricing.cacheRead &&
    stored.cache_write === pricing.cacheWrite &&
    stored.output === pricing.output
  );
}

/**
 * A stored `pricing` table as the three buckets, or undefined when it holds none: one present
 * bucket is a price, and a missing one reads as 0.
 */
function pricingDtoOf(value: unknown): ModelPricingDto | undefined {
  const pricing = asTable(value);
  const cacheRead = optNum(pricing.cache_read);
  const cacheWrite = optNum(pricing.cache_write);
  const output = optNum(pricing.output);
  if (cacheRead === undefined && cacheWrite === undefined && output === undefined) {
    return undefined;
  }
  return { cacheRead: cacheRead ?? 0, cacheWrite: cacheWrite ?? 0, output: output ?? 0 };
}

/** The same three numbers, or both absent. */
function samePricing(a: ModelPricingDto | undefined, b: ModelPricingDto | undefined): boolean {
  if (a === undefined || b === undefined) return a === b;
  return a.cacheRead === b.cacheRead && a.cacheWrite === b.cacheWrite && a.output === b.output;
}

/** A promotion's fraction off every bucket, rounded to six decimals the way `tieredRates` rounds. */
function promotedRates(rates: PricingRates, discount: number): PricingRates {
  const off = (v: number): number => Math.round(v * (1 - discount) * 1e6) / 1e6;
  return {
    cacheRead: off(rates.cacheRead),
    cacheWrite: off(rates.cacheWrite),
    output: off(rates.output),
  };
}

/**
 * A price read from a Project's config, at the instant it is billed.
 *
 * A scheduled row stores its PEAK price — the one number that is true whatever hour it is
 * written — and the reduced tier is derived here, from the instant the Request completed or the
 * record ran. The two differ only while the stored price is still exactly the catalog's peak:
 * once the user has typed their own number, nothing here knows whether it is a peak rate, and
 * halving it would invent a discount. The models page's badge bails on the same condition, so
 * the card and the bill always agree about what this row costs.
 */
function scheduledRateAt(
  provider: string,
  modelId: string,
  rates: PricingRates,
  at: Date,
): PricingRates {
  const entry = catalogEntryFor(provider, modelId);
  const schedule = entry?.offPeakDiscount;
  if (schedule === undefined || entry?.pricing === undefined || Number.isNaN(at.getTime())) {
    return rates;
  }
  const peak = entry.pricing;
  const untouched =
    rates.cacheRead === peak.cache_read &&
    rates.cacheWrite === peak.cache_write &&
    rates.output === peak.output;
  if (!untouched || !offPeakAt(schedule, at)) return rates;
  return promotedRates(rates, schedule.rate);
}

function optStr(v: unknown): string | undefined {
  return typeof v === "string" && v !== "" ? v : undefined;
}

/** One row a keyless entry may borrow a key from: its group and the endpoint it speaks to. */
interface KeyPoolRow {
  provider: string;
  baseUrl: string | undefined;
  apiKey: string | undefined;
}

/**
 * The key a keyless row may borrow from the rows beside it: the single `api_key` the pool
 * holds for the same provider **and the same base URL**, or undefined when there is none or
 * when those rows disagree about it.
 *
 * "Sync presets" adds a catalog entry with no credential. That is right for a model nobody has
 * reached yet, and wrong for the fourteenth row of a gateway group: TokenDance — like every
 * other gateway — is one endpoint behind one key, so a preset the catalog carries later is the
 * same login as the rows beside it. Left keyless it reads "no key configured" and fails its own
 * speed test next to twelve rows that work, and the only cure the user has is pasting the same
 * key a thirteenth time. Borrowing it is what makes the sync finish the job they started when
 * they pasted it once.
 *
 * Borrowing stays inside an unambiguous group. Two different keys under one provider and one
 * base URL are two accounts (or a deliberate split), and picking one of them for a new row
 * would be a guess; a different base URL is a different service, where a shared provider id
 * says nothing about the credential. Both cases leave the row keyless, exactly as it was before
 * this rule existed.
 */
function groupApiKey(
  pool: readonly KeyPoolRow[],
  provider: string,
  baseUrl: string | undefined,
): string | undefined {
  const target = baseUrl ?? "";
  const keys = new Set<string>();
  for (const row of pool) {
    if (row.provider !== provider) continue;
    if ((row.baseUrl ?? "") !== target) continue;
    if (row.apiKey !== undefined) keys.add(row.apiKey);
  }
  return keys.size === 1 ? [...keys][0] : undefined;
}

/** Command-policy rules as DTOs: per-rule `enabled` made explicit (stored absence = on). */
function toCommandPolicyRuleDtos(rules: readonly CommandPolicyRule[]): CommandPolicyRuleDto[] {
  return rules.map((r) => ({
    name: r.name,
    pattern: r.pattern,
    ...(r.description !== undefined ? { description: r.description } : {}),
    enabled: r.enabled !== false,
  }));
}

/** Leniently reads a paired reference table (default_model / vision_model); returns undefined on a shape mismatch (including the old string format). */
function optRef(v: unknown): ModelRef | undefined {
  const t = asTable(v);
  const provider = optStr(t.provider);
  const modelId = optStr(t.model_id);
  return provider !== undefined && modelId !== undefined
    ? { provider, model_id: modelId }
    : undefined;
}

/** Whether an entry matches a paired reference (the entry's provider / model_id fields must be strings). */
function entryMatches(m: RawTable, provider: string, modelId: string): boolean {
  return m.provider === provider && m.model_id === modelId;
}

/** In-process Map/Set key for a paired reference (\0-separated to avoid concatenation ambiguity; never persisted, not an id format). */
function refKey(provider: string, modelId: string): string {
  return `${provider}\0${modelId}`;
}

/** Display form of a paired reference (for error messages; display only, not a storage format). */
function showRef(provider: string, modelId: string): string {
  return `(provider=${provider}, model_id=${modelId})`;
}

/**
 * Connectivity probe prompt: asks for one word, so the whole exchange fits in a
 * single-digit output budget. The wording discourages reasoning and the trailing empty
 * <think></think> makes many reasoning models treat their thinking phase as already
 * closed - keeping the probe's tiny budget on actual output instead of burning it on
 * thinking.
 */
const PROBE_PROMPT =
  'ping - reply with the single word "pong" and nothing else. Do not think or explain.\n<think></think>';

/**
 * Endpoint model-listing bound: the SDK paginates `/models` under the hood, so one slow
 * or endless gateway must not pin the add-group dialog — 20s matches the connectivity
 * test's request timeout.
 */
const LIST_MODELS_TIMEOUT_MS = 20_000;

/**
 * Speed probe prompt: a one-word answer can't be timed (a compliant model emits 1-3
 * tokens, and the window is then dominated by the final usage chunk's round trip), so
 * speed mode asks for something long enough to run into its raised cap. Counting to 50 is
 * deterministic and needs no knowledge, so every model produces the same token stream at
 * its own decoding rate. Carries the same anti-thinking hint as the connectivity prompt.
 */
const SPEED_PROBE_PROMPT =
  "Count from 1 to 50 as a comma-separated list, and nothing else. Do not think or explain.\n<think></think>";

/**
 * Bounds for a one-off utility completion (see completeOnce). The budget is core's own
 * meta-request budget, the one `createBareLLM` sizes session titles and vision descriptions
 * with, tightened by the entry's pinned per-model cap: an identifier is a handful of tokens,
 * but on a reasoning model the thinking is spent out of the same cap, and a budget cut to the
 * size of the answer leaves the answer itself with nothing (`finish_reason=length` before a
 * single text token — the failure the connectivity probe's `probeVerdict` tolerates by name).
 * The caller is a dialog waiting on the answer, so the wait stays short.
 */
const UTILITY_COMPLETION_BUDGET = 300;
const UTILITY_COMPLETION_TIMEOUT_MS = 15_000;
/**
 * How many free models one utility ask may actually be sent to, and how long the whole walk may
 * take. A naming dialog is waiting on the answer, so a run of dead or throttled free endpoints
 * must not add up to a stall: each attempt gets what is left of the budget, up to the single
 * attempt timeout above, and candidates that cannot be built at all (no credential, no
 * routable id) cost neither an attempt nor a wait.
 */
const UTILITY_COMPLETION_ATTEMPTS = 4;
const UTILITY_COMPLETION_WALK_BUDGET_MS = 30_000;

/**
 * What one utility completion produced: the model's text, or why there is none. A bare null
 * would say "no answer" and nothing else — and every one of these failures (no model
 * configured, a missing credential, a provider rejection, a timeout, an answer that was all
 * thinking) is one the user can act on, so the reason travels to the caller, which records it.
 */
export type UtilityCompletion =
  | { ok: true; text: string }
  | {
      ok: false;
      /** `no_model`: the Project names no default model, or names one it has no entry for — nothing was asked. `failed`: the model was asked and produced no text. */
      cause: "no_model" | "failed";
      error: string;
    };

/** How much of a failure detail is kept for display; the error recorder truncates again at its own bound. */
const MAX_FAILURE_DETAIL = 300;

/**
 * What a request that did not complete has to say: the provider's own message when the outcome
 * carries one, and the bare status (`aborted`, a `retryable` idle timeout) when it does not.
 */
function outcomeDetail(outcome: LLMOutcome): string {
  const detail = outcome.errorMessage ? outcome.errorMessage : outcome.status;
  return String(detail).slice(0, MAX_FAILURE_DETAIL);
}

/**
 * The model config one utility completion runs with, built from a Project's model entry.
 * Exported because two of its fields decide whether an answer arrives at all, and reading them
 * here costs no network:
 *
 * - `thinkingLevel: "none"`, the level core's own out-of-band requests use. Every provider the
 *   product ships works with it; a level that leaves thinking on spends the budget below on
 *   reasoning nobody reads.
 * - `maxTokens`: the shared meta budget, tightened by the entry's pinned per-model cap — never
 *   a budget cut to the size of an identifier. A reasoning model spends its thinking out of the
 *   same cap, so a budget that small ends the request at `finish_reason=length` with the answer
 *   never started (see `probeVerdict`, which tolerates exactly that ending for the probe).
 *
 * `requestTimeoutMs` defaults to the single attempt timeout; the walk in `completeOnce` passes
 * what is left of its budget, so the last candidate of a slow run cannot overshoot it.
 */
export function utilityCompletionConfig(
  modelId: string,
  entry: Record<string, unknown>,
  requestTimeoutMs: number = UTILITY_COMPLETION_TIMEOUT_MS,
): GenerativeModelConfig {
  const clientType = canonicalClientType(optStr(entry.client_type));
  // The same credential rule as every other client the harness builds (see core's
  // resolveModelCredential): a keyless entry pointed away from its vendor throws here, which
  // completeOnce reports as the failure it is.
  const credential = resolveModelCredential({
    provider: optStr(entry.provider) ?? "",
    modelId,
    clientType,
    baseUrl: optStr(entry.base_url),
    apiKey: optStr(entry.api_key),
  });
  return {
    modelId,
    ...credential,
    ...(clientType ? { clientType } : {}),
    tools: [],
    thinkingLevel: "none",
    maxTokens: metaMaxTokens(UTILITY_COMPLETION_BUDGET, optNum(entry.max_tokens)),
    requestTimeoutMs,
  };
}

/**
 * A Project's free model entries, in the order its config lists them: what a utility ask is
 * allowed to spend. "Free" is the same reading the models page badges with — a `pricing` table
 * that is present and says 0 on all three buckets. An entry with no pricing at all is unpriced
 * rather than free, and a self-hosted row that bills nobody through a rate the catalog cannot
 * know is deliberately not counted here: this is about not spending, not about who pays.
 *
 * Pure, so the walk's own ordering and filtering are unit tested without a config file.
 */
export function freeModelEntries(
  raw: RawTable,
): Array<{ provider: string; modelId: string; entry: RawTable }> {
  const out: Array<{ provider: string; modelId: string; entry: RawTable }> = [];
  const seen = new Set<string>();
  for (const entry of asArray(raw.models)) {
    const provider = optStr(entry.provider);
    const modelId = optStr(entry.model_id);
    if (provider === undefined || modelId === undefined) continue;
    const pricing = pricingDtoOf(entry.pricing);
    if (pricing === undefined) continue;
    if (pricing.cacheRead !== 0 || pricing.cacheWrite !== 0 || pricing.output !== 0) continue;
    // One entry per reference: a duplicated row in a hand-edited file must not be asked twice.
    const key = `${provider}\u0000${modelId}`;
    if (seen.has(key)) continue;
    seen.add(key);
    out.push({ provider, modelId, entry });
  }
  return out;
}

/**
 * Drains a model stream into the answer's text, or the reason there is none.
 *
 * Complete `text` messages only. Every partial fragment is backfilled into one complete `text`
 * message when the stream ends — on a normal finish and on an interrupted one alike (the
 * translator's `finish` and `finishInterrupted` both flush the text buffer) — so counting both
 * would return the answer twice, and counting only the partials would drop nothing but gain
 * nothing either. A stream that carried only thinking leaves the buffer empty, and the
 * terminal outcome is then what has something to say about why.
 */
export async function collectUtilityCompletion(
  stream: AsyncGenerator<OmniMessage, LLMOutcome>,
): Promise<UtilityCompletion> {
  let text = "";
  for (;;) {
    const step = await stream.next();
    if (step.done) {
      if (text.trim() !== "") return { ok: true, text };
      return { ok: false, cause: "failed", error: outcomeDetail(step.value) };
    }
    const p = step.value.payload as { type?: string; text?: string };
    if (p.type === "text" && typeof p.text === "string") text += p.text;
  }
}

@Component()
export class ProjectConfigService implements ProjectConfigStore {
  /**
   * Parsed-table cache, one entry per Project, keyed by the config file's mtime as
   * recorded at read time (a fresh mtime is stored as a never-matching sentinel, see
   * mtime-gate). A repeat read while the stat still matches costs one stat and zero
   * parses; a mismatch (external edit) or a service write (writeRaw deletes the
   * entry) falls back to a full read.
   */
  private readonly cache = new Map<string, { mtimeMs: number; table: RawTable }>();
  private readonly providerCredentialLocks = new Map<string, Promise<unknown>>();
  private modelApiKeyResolver:
    ((context: ModelRequestContext) => Promise<string | undefined>) | undefined;

  @Use() private readonly paths!: Paths;
  /** Optional for narrow service tests; the production Projects module always provides it. */
  @Use() private readonly promotions?: ModelPromotions;
  /** Optional for narrow service tests; OAuth refresh metadata lives in web.db, not TOML. */
  @Use() private readonly providerAuthTokens?: ModelProviderAuthTokens;
  private get root(): string {
    return this.paths.root;
  }

  private filePath(projectId: string): string {
    return projectConfigPath(this.root, projectId);
  }

  setModelApiKeyResolver(
    resolver: (context: ModelRequestContext) => Promise<string | undefined>,
  ): void {
    this.modelApiKeyResolver = resolver;
  }

  private requestApiKeyResolver(
    projectId: string,
    provider: string,
    modelId: string,
    enabled = true,
  ): Pick<GenerativeModelConfig, "resolveApiKey"> | Record<string, never> {
    if (!enabled || this.modelApiKeyResolver === undefined) return {};
    return {
      resolveApiKey: () => this.modelApiKeyResolver!({ projectId, provider, modelId }),
    };
  }

  private async withProviderCredentialLock<T>(
    projectId: string,
    provider: string,
    task: () => Promise<T>,
  ): Promise<T> {
    const key = `${projectId}\0${provider}`;
    const previous = this.providerCredentialLocks.get(key) ?? Promise.resolve();
    let release!: () => void;
    const gate = new Promise<void>((resolve) => (release = resolve));
    const current = previous.catch(() => undefined).then(() => gate);
    this.providerCredentialLocks.set(key, current);
    await previous.catch(() => undefined);
    try {
      return await task();
    } finally {
      release();
      if (this.providerCredentialLocks.get(key) === current)
        this.providerCredentialLocks.delete(key);
    }
  }

  /**
   * When the Project config (models/credentials) last changed: the config file's mtime as
   * ISO — an honest persistent source that survives server restarts (every models update
   * rewrites the file). undefined when the file doesn't exist yet.
   */
  private async configUpdatedAt(projectId: string): Promise<string | undefined> {
    try {
      const st = await fs.stat(this.filePath(projectId));
      return st.mtime.toISOString();
    } catch {
      return undefined;
    }
  }

  /** Reads the raw TOML object; returns an empty object if the file doesn't exist (does not write to disk). */
  async readRaw(projectId: string): Promise<RawTable> {
    return (await this.readTable(projectId)) ?? {};
  }

  /**
   * mtime-gated read of the parsed table; null when the file doesn't exist (readRaw
   * flattens that to `{}`, loadConfig to the preset default config — the two
   * pre-existing missing-file behaviors). Serving the shared cached object is safe
   * because no consumer mutates it (see the class header).
   */
  private async readTable(projectId: string): Promise<RawTable | null> {
    const file = this.filePath(projectId);
    let mtimeMs: number;
    try {
      mtimeMs = (await fs.stat(file)).mtimeMs;
    } catch (err) {
      if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
      this.cache.delete(projectId); // Config deleted (or the whole Project): drop the stale entry.
      return null;
    }
    const cached = this.cache.get(projectId);
    if (cached && cached.mtimeMs === mtimeMs) return cached.table;
    let raw: string;
    try {
      raw = await fs.readFile(file, "utf8");
    } catch (err) {
      if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
      this.cache.delete(projectId); // Vanished between stat and read: same as never existing.
      return null;
    }
    const table = asTable(parseToml(raw));
    this.cache.set(projectId, { mtimeMs: cacheable(mtimeMs), table });
    return table;
  }

  /**
   * Typed view of the same cached table — byte-for-byte the semantics of core's
   * `loadProjectConfig` (missing file → preset default config; legacy format → the
   * same error, via core's shared narrowing) without its per-call readFile + parse.
   * Serves the scheduler's model-ref validation (see schedule-store).
   */
  async loadConfig(projectId: string): Promise<ProjectConfig> {
    const table = await this.readTable(projectId);
    if (table === null) return defaultProjectConfig();
    return projectConfigFromTable(this.filePath(projectId), table);
  }

  /**
   * Writes the whole object to disk: the file inlines secrets like api_key, always
   * written with mode 0600, and replaced atomically so a crash mid-write cannot
   * truncate it — matching core's saveProjectConfig behavior.
   */
  async writeRaw(projectId: string, data: RawTable): Promise<void> {
    const file = this.filePath(projectId);
    await fs.mkdir(path.dirname(file), { recursive: true });
    // Rendering goes through core's single writer: paired references become inline
    // tables, models is placed last — matching the CLI's output format exactly
    // (the same file should never have two formats).
    await atomicWriteFile(file, renderProjectConfigToml(data), {
      mode: 0o600,
      followSymlinks: true,
    });
    // Every service write funnels through here: invalidate synchronously so the next
    // read re-parses (external writers are caught by readTable's stat instead).
    this.cache.delete(projectId);
  }

  /**
   * Initial config for a newly created Project: display name + preset built-in
   * model catalog (the default model and all preset entries, sourced from the same
   * core defaultProjectConfig; a gateway model's base_url is already inlined on the
   * entry, with no key); users only need to fill in an API key as needed (leave it
   * blank to fall back to the provider's environment variable).
   */
  async writeInitialConfig(projectId: string, name: string): Promise<void> {
    const preset = defaultProjectConfig();
    await this.writeRaw(projectId, {
      name,
      ...(preset.default_model !== undefined ? { default_model: preset.default_model } : {}),
      // The factory command-policy rules are seeded exactly like the model presets:
      // copied in at creation, owned by the project from then on.
      ...(preset.command_policy !== undefined ? { command_policy: preset.command_policy } : {}),
      models: preset.models,
    });
  }

  /**
   * Backfills preset models (for onboarding an existing Project, e.g. the
   * `default_project` shared with the CLI when the first user is onboarded — its
   * directory already existed and never went through `writeInitialConfig`, so it
   * previously had no models and no default model).
   *
   * **Only backfills when there are no models at all**: a Project that already has
   * models configured (via the CLI or edited by the user) is left as-is, and its
   * other fields (name, etc.) are preserved too — existing config is never
   * overwritten. Returns whether it wrote the presets, which is when their promotions
   * are to be seeded too (seedPresetPromotions).
   */
  async ensurePresetModels(projectId: string): Promise<boolean> {
    const raw = await this.readRaw(projectId);
    if (asArray(raw.models).length > 0) return false;
    const preset = defaultProjectConfig();
    await this.writeRaw(projectId, {
      ...raw,
      // Also reset to the preset default_model if the existing one points at a now-deleted model, to keep the default model valid.
      ...(preset.default_model !== undefined ? { default_model: preset.default_model } : {}),
      models: preset.models,
    });
    return true;
  }

  /**
   * Stores the built-in catalog's flat promotions for a Project just seeded with the preset
   * models: the file carries their list prices, and these fractions are the rest of what the
   * presets bill. The rows reference the Project's `projects` row (foreign keys are enforced),
   * so this runs once that row exists.
   */
  async seedPresetPromotions(projectId: string): Promise<void> {
    this.promotions?.replaceAll(projectId, presetPromotions());
  }

  /** Project display name (the toml's name; returns undefined if unset, the frontend falls back to displaying the id). */
  async getName(projectId: string): Promise<string | undefined> {
    const raw = await this.readRaw(projectId);
    return typeof raw.name === "string" ? raw.name : undefined;
  }

  /**
   * Backfills a display name for a Project that was **adopted** rather than created through
   * `writeInitialConfig` — the shared `default_project` (see provisionInitialProject and
   * Startup's boot sweep): its directory predates the Web onboarding, so it carries no name and
   * every surface fell back to showing the raw id. Only writes when no name is stored (an empty
   * one counts as none): a name the operator or an older CLI set is left alone, exactly like
   * ensurePresetModels leaves configured models alone. A Project with **no config file at all**
   * is left untouched too — this never brings a Project into existence.
   */
  async ensureDisplayName(projectId: string, name: string): Promise<void> {
    const table = await this.readTable(projectId);
    if (table === null) return;
    if (typeof table.name === "string" && table.name !== "") return;
    await this.writeRaw(projectId, { ...table, name });
  }

  /**
   * Rewrites the display name, preserving every other field (models, credentials, default
   * model): read-modify-write of the same toml, like ensurePresetModels. The id itself is
   * immutable — only this label changes.
   */
  async setName(projectId: string, name: string): Promise<void> {
    const raw = await this.readRaw(projectId);
    await this.writeRaw(projectId, { ...raw, name });
  }

  /** Paired reference of the default Model; returns undefined if unconfigured (or in the old string format). */
  async getDefaultModelRef(projectId: string): Promise<ModelRef | undefined> {
    const raw = await this.readRaw(projectId);
    return optRef(raw.default_model);
  }

  /**
   * Sets the default Model to an already-configured entry (the narrow
   * PUT /models/default route): rewrites only the top-level `default_model` — the SAME key
   * the models page's whole-table PUT maintains, so the two surfaces stay single-sourced —
   * preserving every other field via read-modify-write. The pair must name an entry in
   * `models` (the identical rule updateModels applies to `defaultModel`); a reference
   * outside the config is a 400, since createSession would error on it immediately. No
   * runtime invalidation: existing Sessions pin their model at creation, and this route
   * never touches credentials.
   */
  async setDefaultModelRef(projectId: string, ref: ModelRefDto): Promise<ModelRefDto> {
    const raw = await this.readRaw(projectId);
    if (!asArray(raw.models).some((m) => entryMatches(m, ref.provider, ref.modelId))) {
      throw badRequest(
        `defaultModel must be included in models: ${showRef(ref.provider, ref.modelId)}.`,
      );
    }
    await this.writeRaw(projectId, {
      ...raw,
      default_model: { provider: ref.provider, model_id: ref.modelId },
    });
    return { provider: ref.provider, modelId: ref.modelId };
  }

  /**
   * New-chat defaults (`[default_chat]`): read leniently — same tolerance as core's
   * loadProjectConfig (an invalid value drops that key; a missing/malformed block reads as
   * empty). Members may read; only the fields present in the file appear in the DTO.
   */
  async getChatDefaults(projectId: string): Promise<ChatDefaultsDto> {
    const raw = await this.readRaw(projectId);
    const t = asTable(raw.default_chat);
    const agentId = optStr(t.agent_id);
    const workspace = optStr(t.workspace);
    const approval = optStr(t.approval_mode);
    const thinking = optStr(t.thinking_level);
    return {
      ...(agentId !== undefined ? { agentId } : {}),
      ...(workspace !== undefined ? { workspace } : {}),
      ...(approval !== undefined && (CHAT_APPROVAL_MODES as readonly string[]).includes(approval)
        ? { approvalMode: approval as ChatDefaultsDto["approvalMode"] }
        : {}),
      ...(thinking !== undefined &&
      (DEFAULT_CHAT_THINKING_LEVELS as readonly string[]).includes(thinking)
        ? { thinkingLevel: thinking as ChatDefaultsDto["thinkingLevel"] }
        : {}),
    };
  }

  /**
   * Replaces the whole `[default_chat]` block (declarative PUT: an omitted key clears it;
   * an empty request removes the block entirely, restoring the pre-existing behavior).
   * Field validation (enums / agent existence) happens at the route; this is a
   * read-modify-write like setName — every other field (models, credentials, name, the
   * default model) is preserved. Returns the stored block as re-read from disk.
   */
  async setChatDefaults(projectId: string, req: ChatDefaultsDto): Promise<ChatDefaultsDto> {
    const raw = await this.readRaw(projectId);
    const block: RawTable = {
      ...(req.agentId !== undefined ? { agent_id: req.agentId } : {}),
      ...(req.workspace !== undefined ? { workspace: req.workspace } : {}),
      ...(req.approvalMode !== undefined ? { approval_mode: req.approvalMode } : {}),
      ...(req.thinkingLevel !== undefined ? { thinking_level: req.thinkingLevel } : {}),
    };
    const next: RawTable = { ...raw };
    if (Object.keys(block).length > 0) next.default_chat = block;
    else delete next.default_chat;
    await this.writeRaw(projectId, next);
    return this.getChatDefaults(projectId);
  }

  /**
   * Sandbox command policy (`[command_policy]`): read leniently, mirroring core's
   * loadProjectConfig tolerance — a non-boolean `enabled` reads as true (the default), a
   * rule missing name or pattern is dropped, and an absent (or non-array) `rules` value
   * serves the factory set: a project from before the block was seeded behaves as the
   * defaults until its first saved edit materializes them. The factory set also rides
   * along as `defaultRules` for the settings UI's "restore defaults".
   */
  async getCommandPolicy(projectId: string): Promise<CommandPolicyDto> {
    const raw = await this.readRaw(projectId);
    // Core's shared narrowing + the single "absent = factory set" fallback: this GET can
    // never disagree with what the Environment snapshot will enforce.
    const policy = parseCommandPolicy(raw.command_policy);
    return {
      enabled: policy?.enabled !== false,
      rules: toCommandPolicyRuleDtos(effectiveCommandPolicyRules(policy)),
      defaultRules: toCommandPolicyRuleDtos(DEFAULT_COMMAND_POLICY_RULES),
    };
  }

  /**
   * Replaces the `[command_policy]` block (declarative PUT, validated at the route). A PUT
   * always materializes the full rule list into the file — model-presets style: once
   * written, later factory changes never rewrite it — storing per field only what departs
   * from the defaults (`enabled = false`, a rule's `enabled = false`, a non-empty
   * description). Read-modify-write like setChatDefaults, preserving every other key.
   * Returns the block as re-read.
   */
  async setCommandPolicy(
    projectId: string,
    req: {
      enabled?: boolean;
      rules: { name: string; pattern: string; description?: string; enabled?: boolean }[];
    },
  ): Promise<CommandPolicyDto> {
    const raw = await this.readRaw(projectId);
    const block: RawTable = {};
    if (req.enabled === false) block.enabled = false;
    block.rules = req.rules.map((r) => ({
      name: r.name,
      pattern: r.pattern,
      ...(r.description !== undefined && r.description !== ""
        ? { description: r.description }
        : {}),
      ...(r.enabled === false ? { enabled: false } : {}),
    }));
    await this.writeRaw(projectId, { ...raw, command_policy: block });
    return this.getCommandPolicy(projectId);
  }

  /**
   * The `[plugins]` key this Project writes: the shared table and each machine's own, in the
   * file's order; both empty when it asks for none.
   */
  async getPluginTables(projectId: string): Promise<PluginTables> {
    return parsePluginTables((await this.readRaw(projectId)).plugins) ?? { all: {}, machines: {} };
  }

  /**
   * Replaces this Project's plugin tables (a declarative PUT, validated at the route).
   * Read-modify-write like setCommandPolicy, so every other key survives. An empty table is
   * written as an empty table rather than removed: "this Project asks for none" is a
   * decision, and a reader cannot tell it from "never configured" if the key vanishes.
   */
  async setPluginTables(projectId: string, tables: PluginTables): Promise<PluginTables> {
    const raw = await this.readRaw(projectId);
    await this.writeRaw(projectId, { ...raw, plugins: pluginTablesToToml(tables) });
    return this.getPluginTables(projectId);
  }

  /**
   * The price a Request on this paired reference is billed at, completing at `at`, or undefined
   * when the Project stores no price for it (-> the record's cost is NULL). The file holds the
   * list price and the row's promotion its fraction; both are folded here, at the tier `at` falls
   * in, so the recorder fixes a Request's cost with the one figure in force when it completed and
   * the Trace page can ask the same question at a past Request's own timestamp.
   */
  async getPricing(
    projectId: string,
    provider: string,
    modelId: string,
    at: Date,
  ): Promise<PricingRates | undefined> {
    const raw = await this.readRaw(projectId);
    const entry = asArray(raw.models).find((m) => entryMatches(m, provider, modelId));
    const rates = pricingDtoOf(entry?.pricing);
    if (rates === undefined) return undefined;
    const scheduled = scheduledRateAt(provider, modelId, rates, at);
    const discount = this.promotions?.get(projectId, provider, modelId);
    return discount === undefined ? scheduled : promotedRates(scheduled, discount);
  }

  /**
   * Model connectivity test: the model reference `(provider, modelId)` is submitted
   * as a pair in the request body; sends one minimal request using that model's
   * config (optionally overridden with an unsaved apiKey / baseUrl) — no tools, no
   * system prompt, thinking at the lowest level, a tiny output cap, 20s timeout —
   * just to see whether the endpoint answers. The model id sent to AgentHub is
   * `modelId` itself (the upstream id verbatim; client_type inference follows it).
   *
   * A reasoning-heavy model can spend the whole tiny output cap on thinking
   * (finish_reason=length with no text — AgentHub raises EmptyResponseError,
   * collapsed to a malformed outcome): the endpoint demonstrably streamed model
   * output, which is everything a connectivity test proves, so that case counts as
   * ok too (see probeVerdict).
   *
   * Never throws: the LLM layer collapses auth/parameter/network errors into an
   * `LLMOutcome`, which is translated here into ok / message. Consumes very few
   * Tokens (single-digit output; speed mode spends up to its 64-token cap to have a
   * window worth timing), and writes no Trace and records no usage.
   */
  /**
   * Vision capability probe: sends one 1x1 PNG plus a one-word prompt and reports whether
   * the model took it (see services/vision-detect.ts for the verdict rules and why this
   * one costs real money, unlike the protocol probes).
   *
   * Credential resolution is the connectivity test's, verbatim — the request's key, else
   * the stored one, unless "clear" is checked, else the environment where core's
   * resolveModelCredential allows it (the vendor's own endpoint; never a gateway's). Nothing
   * secret is returned; the failure message is the provider's own text, truncated.
   */
  async detectVision(
    projectId: string,
    req: ModelVisionDetectRequest,
  ): Promise<ModelVisionDetectResponse> {
    const raw = await this.readRaw(projectId);
    // Probeable before the entry exists, so a custom model can be checked while adding it.
    const entry = asArray(raw.models).find((m) => entryMatches(m, req.provider, req.modelId)) ?? {};
    const savedBaseUrl = optStr(entry.base_url);
    const baseUrl = req.baseUrl === null ? undefined : (req.baseUrl ?? savedBaseUrl);
    const clientType = canonicalClientType(req.clientType ?? optStr(entry.client_type));
    const draftKey = req.clearApiKey ? undefined : (req.apiKey ?? optStr(entry.api_key));
    try {
      // Inside the try for the same reason as testModel: both the credential rule's refusal
      // and the SDK's own missing-credential throw at construction must read as "probe
      // failed", not a 500.
      const credential = resolveModelCredential({
        provider: req.provider,
        modelId: req.modelId,
        clientType,
        baseUrl,
        apiKey: draftKey,
      });
      const llm = new GenerativeModel({
        modelId: req.modelId,
        ...credential,
        ...this.requestApiKeyResolver(
          projectId,
          req.provider,
          req.modelId,
          req.apiKey === undefined && req.clearApiKey !== true,
        ),
        ...(clientType ? { clientType } : {}),
        tools: [],
        // The lowest real level, not "none": several reasoning endpoints reject a request
        // that disables thinking outright, and a probe must not fail on the knob it sends.
        thinkingLevel: "low",
        maxTokens: VISION_PROBE_MAX_TOKENS,
        requestTimeoutMs: VISION_PROBE_TIMEOUT_MS,
      });
      // Both parts must carry role "user" — a mixed-role batch is rejected before it is
      // sent (see generative-model's UniMessage merge).
      const gen = llm.streamGenerate({
        newMessages: [userText(VISION_PROBE_PROMPT), imageUrlMessage(VISION_PROBE_IMAGE)],
      });
      let sawContent = false;
      for (;;) {
        const step = await gen.next();
        if (step.done) {
          const outcome = classifyVisionProbe(step.value, sawContent);
          if (outcome !== "failed") return { outcome };
          return { outcome, message: outcomeDetail(step.value) };
        }
        if (isProbeContent(step.value)) sawContent = true;
      }
    } catch (err) {
      const outcome = classifyVisionProbeError(err);
      if (outcome !== "failed") return { outcome };
      return {
        outcome,
        message: (err instanceof Error ? err.message : String(err)).slice(0, 300),
      };
    }
  }

  /**
   * One short completion on a **free** model of the Project, for utility asks that belong to
   * no Session — today the English identifier a display name is translated into. A free model
   * is walked first, and several of them: free endpoints are throttled, delisted and retired
   * routinely, one dead endpoint says nothing about the next, and the ask must not cost
   * anything, so the Project's default model is deliberately not among the candidates. What
   * the caller gets when none of them answers is the reason, and its own fallback.
   *
   * The walk is bounded twice over: at most `UTILITY_COMPLETION_ATTEMPTS` requests are sent,
   * and together they get `UTILITY_COMPLETION_WALK_BUDGET_MS`. A candidate that cannot be built
   * at all — no credential, no routable id — costs neither an attempt nor a wait, so a config
   * full of unusable free rows does not eat the budget of the ones that work. Nothing throws:
   * no free entry, an entry with no credential, a refusal, a timeout, or an answer with no text
   * all come back as `{ ok: false }` carrying the reason, which the caller records so the
   * errors panel can say why the ask produced nothing. Callers must still have a result that
   * works without it. The request is not metered — it carries no Session to attribute it to.
   *
   * Thinking is off and the budget is the shared meta budget, for the same reason core's own
   * out-of-band requests set them that way: a reasoning model spends thinking out of
   * `maxTokens`, so a budget the size of the answer ends the request at `finish_reason=length`
   * with no text at all.
   */
  async completeOnce(projectId: string, prompt: string): Promise<UtilityCompletion> {
    const raw = await this.readRaw(projectId);
    const candidates = freeModelEntries(raw);
    const deadline = Date.now() + UTILITY_COMPLETION_WALK_BUDGET_MS;
    // The last thing that went wrong, whether it was a build that threw or a request that
    // produced nothing: the caller records one line, and the most recent dead end is the one
    // worth naming.
    let failure: Extract<UtilityCompletion, { ok: false }> | undefined;
    let sent = 0;
    for (const candidate of candidates) {
      if (sent >= UTILITY_COMPLETION_ATTEMPTS) break;
      const remaining = deadline - Date.now();
      if (remaining < 1000) break;
      let llm: GenerativeModel;
      try {
        // Inside the try for the same reason as the probes: the SDK throws during
        // construction when a credential is missing or the id cannot be routed, and that must
        // read as one candidate being unusable rather than an exception out of a dialog's
        // helper. Such a candidate is skipped without being asked.
        llm = new GenerativeModel({
          ...utilityCompletionConfig(
            candidate.modelId,
            candidate.entry,
            Math.min(UTILITY_COMPLETION_TIMEOUT_MS, remaining),
          ),
          ...this.requestApiKeyResolver(projectId, candidate.provider, candidate.modelId),
        });
      } catch (err) {
        failure = {
          ok: false,
          cause: "failed",
          error: (err instanceof Error ? err.message : String(err)).slice(0, MAX_FAILURE_DETAIL),
        };
        continue;
      }
      sent += 1;
      const res = await collectUtilityCompletion(
        llm.streamGenerate({ newMessages: [userText(prompt)] }),
      );
      if (res.ok) return res;
      failure = res;
    }
    if (sent === 0) {
      // Nothing was ever asked, so "no model" is the honest reading rather than a model that
      // failed: the Project either lists no free entry or has no credential for any of them.
      return {
        ok: false,
        cause: "no_model",
        error: failure?.error ?? "the Project has no free ($0-priced) model that can be run",
      };
    }
    return {
      ok: false,
      cause: "failed",
      error: failure?.error ?? "every free model of the Project gave no answer",
    };
  }

  async testModel(projectId: string, req: ModelTestRequest): Promise<ModelTestResponse> {
    const raw = await this.readRaw(projectId);
    // Testable even if the model isn't in the config yet (validate before saving when adding a custom model): in that case all parameters come from the request body.
    const entry = asArray(raw.models).find((m) => entryMatches(m, req.provider, req.modelId)) ?? {};
    // Always tests against the **current form draft**: checking "clear" means the saved key is not fallen back to; an explicit null base URL is treated as cleared.
    const savedBaseUrl = optStr(entry.base_url);
    const baseUrl = req.baseUrl === null ? undefined : (req.baseUrl ?? savedBaseUrl);
    // The pre-0.4.2 "openai" spelling (request or stored entry) is normalized to the
    // canonical "openai-chat" (deprecated upstream alias; see canonicalClientType).
    const clientType = canonicalClientType(req.clientType ?? optStr(entry.client_type));
    const draftKey = req.clearApiKey ? undefined : (req.apiKey ?? optStr(entry.api_key));
    // Fast mode follows the form draft like baseUrl (the frontend always sends the current
    // toggle), falling back to the stored annotation: the probe then exercises exactly the
    // serving tier sessions would use, so a model rejecting fast_mode fails the test with
    // the actionable message before the config is saved.
    const fastMode = req.fastMode ?? entry.fast_mode === true;

    const startedAt = Date.now();
    try {
      // Credential resolution and construction must both be inside the try block: core's
      // credential rule refuses a keyless entry pointed away from its vendor (a gateway row
      // never borrows OPENAI_API_KEY / ANTHROPIC_API_KEY from the server environment — the
      // group speed test runs through here too), and the provider SDK can throw during
      // **client construction** itself when a credential is missing. The whole point of a
      // connectivity test is to collapse that kind of failure into `{ ok:false }`; outside
      // the try, a missing-key test would bubble up as a 500.
      const credential = resolveModelCredential({
        provider: req.provider,
        modelId: req.modelId,
        clientType,
        baseUrl,
        apiKey: draftKey,
      });
      const llm = new GenerativeModel({
        modelId: req.modelId,
        ...credential,
        ...this.requestApiKeyResolver(
          projectId,
          req.provider,
          req.modelId,
          req.apiKey === undefined && req.clearApiKey !== true,
        ),
        ...(clientType ? { clientType } : {}),
        ...(fastMode ? { fastMode: true } : {}),
        tools: [],
        // The lowest real level, not "none": several reasoning endpoints reject a request
        // that disables thinking outright, and a probe must not fail on the knob it sends.
        thinkingLevel: "low",
        // Speed mode pairs a raised cap with a prompt that keeps generating (see
        // SPEED_PROBE_PROMPT), so the stream lasts long enough for TTFT/TPS to describe
        // decoding rather than one round trip; the plain connectivity test keeps the
        // single-digit-token budget.
        maxTokens: req.speed ? 64 : 16,
        requestTimeoutMs: 20_000,
      });
      const gen = llm.streamGenerate({
        newMessages: [userText(req.speed ? SPEED_PROBE_PROMPT : PROBE_PROMPT)],
      });
      let sawContent = false;
      let firstContentAt: number | null = null;
      let outputTokens = 0;
      for (;;) {
        const step = await gen.next();
        if (step.done) {
          const verdict = probeVerdict(step.value, sawContent);
          if (!verdict.ok) return verdict;
          const res: ModelTestResponse = { ok: true, latencyMs: Date.now() - startedAt };
          if (firstContentAt !== null) {
            res.ttftMs = firstContentAt - startedAt;
            // Output rate over the streaming window (first content -> stream end), dropped
            // when the sample is too small to mean anything (see probeTps): usage is only
            // reported on completed streams, so thinking-only malformed endings carry TTFT
            // but no rate, and so does a model that answers in a couple of tokens.
            const tps = probeTps(outputTokens, Date.now() - firstContentAt);
            if (tps !== undefined) res.tps = tps;
          }
          return res;
        }
        if (isProbeContent(step.value)) {
          sawContent = true;
          if (firstContentAt === null) firstContentAt = Date.now();
        }
        const p = step.value.payload as { type?: string; request?: { output?: number } };
        if (p.type === "token_usage" && typeof p.request?.output === "number") {
          outputTokens = p.request.output;
        }
      }
    } catch (err) {
      // Defensive: an unexpected exception during construction/iteration (the LLM layer promises not to throw; this is a fallback).
      return {
        ok: false,
        message: (err instanceof Error ? err.message : String(err)).slice(0, 300),
      };
    }
  }

  /**
   * Protocol detection for a custom base URL (see services/protocol-detect.ts for the
   * probe order and classification). Credential resolution has three layers, in order:
   *   1. the request body's key (what the user just typed in the dialog);
   *   2. otherwise, when the optional paired reference names a stored entry and "clear"
   *      isn't checked, that entry's saved key (the frontend only ever sees the mask);
   *   3. otherwise the environment: a provider-scoped variable (the Penguin Go relay's
   *      PENGUIN_GO_API_KEY) resolved here for the group's rows, and otherwise the variable
   *      of whichever protocol each probe speaks, resolved inside detectModelProtocol
   *      because the protocol is the thing being determined — and only for a URL that is
   *      the vendor's own (see core's endpointEnvApiKey), never for a gateway or a private
   *      server.
   * Layers 2 and 3 are read server-side only and never travel back to the browser.
   * Detection still runs with no credential at all: a protocol-shaped 401/403 proves the
   * route. Never throws on probe failures — every outcome is reported per probe.
   */
  async detectProtocol(
    projectId: string,
    req: ModelProtocolDetectRequest,
  ): Promise<ModelProtocolDetectResponse> {
    let apiKey = req.apiKey;
    let savedClientType: string | undefined;
    if (apiKey === undefined && !req.clearApiKey && req.provider && req.modelId) {
      const raw = await this.readRaw(projectId);
      const entry = asArray(raw.models).find((m) =>
        entryMatches(m, req.provider as string, req.modelId as string),
      );
      apiKey = entry !== undefined ? optStr(entry.api_key) : undefined;
      savedClientType = entry === undefined ? undefined : optStr(entry.client_type);
    }
    if (apiKey === undefined && req.provider && req.modelId) {
      // A provider-scoped pair (the relay's) is the harness's to read, for any URL in that
      // group; a vendor pair is left to the per-probe rule in detectModelProtocol. Without a
      // relay key, anonymous probing is still safe and can identify a route from its 401.
      const fallback = modelEnvFallback({
        provider: req.provider,
        modelId: req.modelId,
        clientType: savedClientType,
      });
      if (fallback !== undefined && !fallback.readByClient) {
        apiKey = process.env[fallback.envKey]?.trim() || undefined;
      }
    }
    return detectModelProtocol({
      baseUrl: req.baseUrl,
      ...(apiKey ? { apiKey } : {}),
    });
  }

  /**
   * Endpoint model listing for the add-group import (see EndpointModelListRequest). All
   * parameters come from the request — a group being created has no stored entry to fall
   * back to; an omitted key is lent the protocol's environment variable only when the URL is
   * that vendor's own (core's endpointEnvApiKey), and refused otherwise. Never throws: SDK
   * construction
   * and request failures collapse into `{ ok:false, message }`, an AgentHub
   * UnsupportedOperationError additionally sets `unsupported` so the dialog can point at
   * the manual path, and a listing that outlives LIST_MODELS_TIMEOUT_MS is reported as
   * timed out. Nothing cancels the request behind it: the race only stops waiting, and a
   * later rejection is already handled by the race itself. The listing is returned
   * verbatim; dedup against the config is the caller's policy, exactly like the probe
   * routes never write anything either.
   */
  async listEndpointModels(
    req: EndpointModelListRequest,
    listImpl: typeof coreListEndpointModels = coreListEndpointModels,
    timeoutMs: number = LIST_MODELS_TIMEOUT_MS,
  ): Promise<EndpointModelListResponse> {
    const clientType = canonicalClientType(req.clientType) ?? req.clientType;
    let timer: ReturnType<typeof setTimeout> | undefined;
    try {
      const listing = listImpl({
        clientType,
        baseUrl: req.baseUrl,
        ...(req.apiKey ? { apiKey: req.apiKey } : {}),
      });
      const timeout = new Promise<never>((_, reject) => {
        timer = setTimeout(() => reject(new Error("model listing timed out")), timeoutMs);
        timer.unref?.();
      });
      const models = await Promise.race([listing, timeout]);
      return { ok: true, models };
    } catch (err) {
      const unsupported = err instanceof Error && err.name === "UnsupportedOperationError";
      return {
        ok: false,
        ...(unsupported ? { unsupported: true } : {}),
        message: (err instanceof Error ? err.message : String(err)).slice(0, 300),
      };
    } finally {
      if (timer !== undefined) clearTimeout(timer);
    }
  }

  /**
   * GET models view: masks credential (inline fields), flags the default Model;
   * the group is the entry's `provider` field, looked up in the built-in catalog by
   * the `(provider, model_id)` pair to fill in displayName / envKey (entries outside
   * the catalog are treated as custom models: envKey only has a fallback for the
   * openai protocol). vision follows the TOML annotation when present, otherwise
   * falls back to the catalog annotation (if neither exists, the field is omitted =
   * supported by default). `pricing` is the file's list price, and a row with a stored
   * promotion reports its fraction as `discount`.
   */
  async getModels(projectId: string): Promise<ModelsResponse> {
    const raw = await this.readRaw(projectId);
    const defaultRef = optRef(raw.default_model);
    const visionRef = optRef(raw.vision_model);
    const discounts = new Map(
      (this.promotions?.list(projectId) ?? []).map((p) => [
        refKey(p.provider, p.modelId),
        p.discount,
      ]),
    );
    const models: ModelInfo[] = asArray(raw.models)
      // An entry is valid only if both provider and model_id are strings (an entry in the old concatenated format lacks provider and is ignored).
      .filter((m) => typeof m.provider === "string" && typeof m.model_id === "string")
      .map((m) => {
        const provider = m.provider as string;
        const modelId = m.model_id as string;
        const pricingDto = pricingDtoOf(m.pricing);
        const discount = discounts.get(refKey(provider, modelId));
        // Normalized on read: entries stored before AgentHub 0.4.2's openai -> openai-chat
        // rename report the canonical spelling without a disk rewrite (the next models PUT
        // persists it).
        const clientType = canonicalClientType(optStr(m.client_type));
        const cat = catalogEntryFor(provider, modelId);
        const credBaseUrl = optStr(m.base_url);
        // The env fallback the entry is actually allowed (core's modelEnvFallback): the
        // variable AgentHub's routed client reads — an explicit client_type takes priority,
        // otherwise the id auto-routes — but only while the entry's endpoint is the vendor's
        // own. A gateway, custom or vLLM row with its own endpoint gets no envKey at all:
        // reporting a name there would promise a fallback the harness refuses.
        const fallback = modelEnvFallback({ provider, modelId, clientType, baseUrl: credBaseUrl });
        const envKey = fallback?.envKey;
        const vision = typeof m.vision === "boolean" ? m.vision : cat?.supportsVision;
        // Video input: the annotation when one is stored, otherwise the catalog — read through
        // the catalog exactly as core's `catalogSupportsVideo` does it, so the composer's
        // decision (inline video, or a file the model opens by path) is the same one the
        // server's own routes make for the same Session.
        const video = m.video === true || cat?.supportsVideo === true ? true : undefined;
        // Output cap: TOML annotation only (user-owned; the built-in catalog never presets it).
        const maxTokens = optNum(m.max_tokens);
        // Fast mode: TOML annotation only (user-owned); only `true` is reported — absent = off.
        const fastMode = m.fast_mode === true ? true : undefined;
        // Display name: the explicit TOML field (user-edited) takes priority, then the built-in
        // catalog. An empty string is not the same as an absent field — absent means "inherit
        // whatever the catalog calls this model", empty means the user cleared the name on a
        // model the catalog does name, and inheriting there would hand the name straight back.
        // The distinction is reported rather than flattened, because the whole table comes back
        // on the next PUT: a cleared name that arrived as "no name" would be written back as
        // "inherit" and undo itself. Clients render the empty string as the model id.
        const displayName =
          m.display_name === "" ? "" : (optStr(m.display_name) ?? cat?.displayName);
        // credential is inlined on the entry: a credential block is emitted if either api_key or base_url is present.
        const apiKey = optStr(m.api_key);
        const createdAt = optStr(m.created_at);
        // Masked env-fallback preview, for the entries the UI may present as covered (core's
        // modelEnvPreviewKey — the dialog's hint reads the same function): a row on a vendor
        // endpoint, or a keyless row in a group whose defaults are the vendor's. A vLLM preset
        // or a custom row with no base URL does fall back under the rule, but is not shown as
        // configured. Presence is implied by the field, the plaintext never leaves the server,
        // and an empty variable counts as absent — it would not authenticate either. Read from
        // this process's env, which on the desktop already includes the imported login-shell
        // variables.
        const previewKey = modelEnvPreviewKey({
          provider,
          modelId,
          clientType,
          baseUrl: credBaseUrl,
        });
        const envValue = previewKey !== undefined ? (process.env[previewKey] ?? "") : "";
        const envKeyMasked = envValue !== "" ? maskApiKey(envValue) : undefined;
        const info: ModelInfo = {
          provider,
          modelId,
          ...(displayName !== undefined ? { displayName } : {}),
          isDefault:
            defaultRef !== undefined &&
            defaultRef.provider === provider &&
            defaultRef.model_id === modelId,
          ...(optNum(m.context_window) !== undefined
            ? { contextWindow: optNum(m.context_window)! }
            : {}),
          ...(clientType ? { clientType } : {}),
          ...(vision !== undefined ? { vision } : {}),
          ...(video !== undefined ? { video } : {}),
          ...(maxTokens !== undefined ? { maxTokens } : {}),
          ...(fastMode !== undefined ? { fastMode } : {}),
          ...(envKey ? { envKey } : {}),
          ...(envKeyMasked !== undefined ? { envKeyMasked } : {}),
          ...(pricingDto ? { pricing: pricingDto } : {}),
          ...(discount !== undefined ? { discount } : {}),
          ...(apiKey !== undefined || credBaseUrl !== undefined
            ? {
                credential: {
                  ...(apiKey !== undefined ? { apiKeyMasked: maskApiKey(apiKey) } : {}),
                  ...(credBaseUrl !== undefined ? { baseUrl: credBaseUrl } : {}),
                  ...(createdAt !== undefined ? { createdAt } : {}),
                },
              }
            : {}),
        };
        return info;
      });
    const toDto = (ref: ModelRef): ModelRefDto => ({
      provider: ref.provider,
      modelId: ref.model_id,
    });
    const updatedAt = await this.configUpdatedAt(projectId);
    return {
      ...(defaultRef !== undefined ? { defaultModel: toDto(defaultRef) } : {}),
      ...(visionRef !== undefined ? { visionModel: toDto(visionRef) } : {}),
      ...(updatedAt !== undefined ? { updatedAt } : {}),
      models,
    };
  }

  /**
   * PUT replaces the whole models table: key =
   * `(provider, modelId)`; model entries that no longer appear are deleted along
   * with their inline credential; omitting apiKey keeps the existing value,
   * providing one overwrites it and records created_at, clearApiKey clears it;
   * baseUrl null clears it / omitted keeps it. A key change (either the group or
   * the upstream id changes) is migrated as a pair via `renamedFrom`: credential and
   * unknown fields migrate along with the base entry, and default/vision pointers
   * follow. Other extension fields in the toml (name, etc.) are preserved.
   *
   * Promotions (web.db) follow the new table once the file is written: a declared
   * `discount` is stored (null clears it); an omitted one keeps the stored promotion unless
   * the entry renames the row or changes its pricing; a row left out of the table takes its
   * promotion with it. A `discount` outside (0, 1) rejects the request before any write.
   *
   * An entry the request adds to a first-party vendor group under a model id AgentHub cannot
   * route is rejected as well (`model_not_routable`), and so is one it adds to any built-in
   * group but custom and vLLM when it is not one of that group's presets
   * (`model_not_addable`); one already stored under that key is written as it stands. See
   * the loops below for why the two differ.
   */
  async updateModels(projectId: string, req: ModelsUpdateRequest): Promise<ModelsResponse> {
    return this.withProviderCredentialLock(projectId, MODELSCOPE_PROVIDER_ID, () =>
      this.updateModelsUnlocked(projectId, req),
    );
  }

  private async updateModelsUnlocked(
    projectId: string,
    req: ModelsUpdateRequest,
  ): Promise<ModelsResponse> {
    req.models.forEach((entry, i) => {
      const { discount } = entry;
      if (discount === undefined || discount === null) return;
      if (!(Number.isFinite(discount) && discount > 0 && discount < 1)) {
        throw badRequest(`models[${i}].discount must be null or a number above 0 and below 1.`);
      }
    });
    const raw = await this.readRaw(projectId);
    const prevModels = asArray(raw.models);
    const hadModelScopeGroup = prevModels.some(
      (model) => model.provider === MODELSCOPE_PROVIDER_ID,
    );
    // Where a keyless preset row may borrow a key from (see groupApiKey): the stored table plus
    // the rows this request itself brings a key for. Both halves are needed, because the models
    // page writes the whole table — the row that carries the key and the preset that needs it
    // arrive together, in an order the page chooses, and borrowing from the stored table alone
    // would make the outcome depend on that order. The endpoint is resolved the way the write
    // below resolves it, so a row is judged under the base URL it is about to have.
    const baseUrlOf = (entry: ModelUpdateEntry): string | undefined => {
      if (entry.baseUrl === null) return undefined;
      if (entry.baseUrl !== undefined) return entry.baseUrl;
      const ref = entry.renamedFrom ?? { provider: entry.provider, modelId: entry.modelId };
      return optStr(prevModels.find((m) => entryMatches(m, ref.provider, ref.modelId))?.base_url);
    };
    const keyPool: KeyPoolRow[] = [
      ...prevModels.map((m) => ({
        provider: optStr(m.provider) ?? "",
        baseUrl: optStr(m.base_url),
        apiKey: optStr(m.api_key),
      })),
      ...req.models
        .filter((entry) => !entry.clearApiKey && entry.apiKey !== undefined)
        .map((entry) => ({
          provider: entry.provider,
          baseUrl: baseUrlOf(entry),
          apiKey: entry.apiKey,
        })),
    ];

    // A vendor group carries the built-in catalog and nothing else: its entries persist no
    // client_type, so AgentHub places each one by the spelling of the model id alone, and an
    // id it cannot place fails at request time with a sentence listing client types the user
    // never chose. Refused here, while the request can still be sent somewhere that works.
    //
    // Only an entry this request introduces is judged. The models page replaces the whole
    // table on every save, so an id written before this rule existed would otherwise block
    // every later edit of every other row; such a row is left exactly as it is, and the page
    // marks it. A key change is a different entry — moving a model into a vendor group, or
    // renaming one inside it, is the act of writing it there — so it is judged like a new one.
    for (const entry of req.models) {
      if (!unroutableVendorModel(entry.provider, entry.modelId, entry.clientType)) continue;
      if (prevModels.some((m) => entryMatches(m, entry.provider, entry.modelId))) continue;
      throw new HttpError(
        400,
        "model_not_routable",
        `Model ${showRef(entry.provider, entry.modelId)} cannot be routed: a vendor group carries built-in models only. Add it under a custom group, where its protocol can be picked or detected.`,
      );
    }

    // Only custom, vLLM and user-defined groups take models added by hand; every other
    // built-in group, gateways included, carries its catalog presets and the rows it already
    // stores. The same grandfathering as above: a stored row is written as it stands, hand-added
    // ones from before this rule included, and so is a row renamed inside its own group. A row
    // moved in from another group is being added here, and a preset is always welcome back
    // (the preset sync writes a deleted one again).
    for (const entry of req.models) {
      if (!unaddableModel(entry.provider, entry.modelId)) continue;
      if (prevModels.some((m) => entryMatches(m, entry.provider, entry.modelId))) continue;
      const from = entry.renamedFrom;
      if (
        from !== undefined &&
        from.provider === entry.provider &&
        prevModels.some((m) => entryMatches(m, from.provider, from.modelId))
      ) {
        continue;
      }
      const group = providerInfo(entry.provider)?.label ?? entry.provider;
      throw new HttpError(
        400,
        "model_not_addable",
        `Model ${showRef(entry.provider, entry.modelId)} cannot be added: the ${group} group carries its built-in models only. Add it under a custom group.`,
      );
    }

    const seen = new Set<string>();
    const nextModels: RawTable[] = [];
    let keepModelScopeGroup = false;
    let clearModelScopeProviderAuthToken = false;
    // Rename mapping (old reference key -> new reference): default model / vision model pointers follow a key change instead of being lost on a full table replacement.
    const renamed = new Map<string, ModelRefDto>();
    // Each row's promotion, settled against the stored set once the file is written.
    const promotionPlan: Array<{
      provider: string;
      modelId: string;
      declared: number | null | undefined;
      keep: boolean;
    }> = [];
    for (const entry of req.models) {
      const key = refKey(entry.provider, entry.modelId);
      if (seen.has(key)) {
        throw badRequest(
          `models contains a duplicate model reference: ${showRef(entry.provider, entry.modelId)}.`,
        );
      }
      seen.add(key);
      const renamedFrom =
        entry.renamedFrom !== undefined &&
        !(
          entry.renamedFrom.provider === entry.provider &&
          entry.renamedFrom.modelId === entry.modelId
        )
          ? entry.renamedFrom
          : undefined;
      if (renamedFrom !== undefined) {
        renamed.set(refKey(renamedFrom.provider, renamedFrom.modelId), {
          provider: entry.provider,
          modelId: entry.modelId,
        });
      }

      // Model entry: uses the old entry (the entry for the original reference when
      // the key changed) as the base, preserving unknown fields and inline
      // credential; known fields are replaced wholesale per the request (omitted
      // means removed).
      const prevRef = entry.renamedFrom ?? { provider: entry.provider, modelId: entry.modelId };
      const prev = prevModels.find((m) => entryMatches(m, prevRef.provider, prevRef.modelId)) ?? {};
      // An omitted promotion survives only on the row it was taken off, at the price it was
      // taken off: a renamed row is another row, and a changed price is not that price.
      promotionPlan.push({
        provider: entry.provider,
        modelId: entry.modelId,
        declared: entry.discount,
        keep:
          entry.discount === undefined &&
          renamedFrom === undefined &&
          samePricing(entry.pricing, pricingDtoOf(prev.pricing)),
      });
      const next: RawTable = { ...prev, provider: entry.provider, model_id: entry.modelId };
      delete next.context_window;
      delete next.client_type;
      delete next.vision;
      delete next.max_tokens;
      delete next.fast_mode;
      delete next.pricing;
      delete next.display_name;
      // Leftover key from the old concatenated format (request_model_id): defensively stripped, never written to disk again.
      delete next.request_model_id;

      // Display name: **only written to disk when it differs from the built-in
      // catalog (looked up by the paired reference)** — preset models keep the
      // config clean, only user-edited ones (including those not found in the
      // catalog) get written into the TOML.
      //
      // An ABSENT name and an EMPTY one are different requests, and a client that confuses
      // them destroys a name it never meant to touch: absent means "inherit whatever the
      // catalog calls this model" (nothing is written, so the read path falls back to the
      // catalog), empty means "the user cleared it".
      const catNew = catalogEntryFor(entry.provider, entry.modelId);
      if (entry.displayName && entry.displayName !== catNew?.displayName) {
        next.display_name = entry.displayName;
      } else if (entry.displayName === "" && catNew?.displayName !== undefined) {
        // Cleared on a model the catalog names. Writing nothing would leave the field absent,
        // which reads as "inherit" — so the name the user just deleted would come back on the
        // next load. The empty string is what records the deletion. Only reached for a catalog
        // model: a custom one has no name to inherit, so absence already says it.
        next.display_name = "";
      }
      if (entry.contextWindow !== undefined) next.context_window = entry.contextWindow;
      // Stored canonically: a client sending the deprecated "openai" alias persists
      // "openai-chat" (see canonicalClientType).
      if (entry.clientType) next.client_type = canonicalClientType(entry.clientType);
      // Treated as supported by default: only written to disk when explicitly annotated (both true/false are kept; false drives a frontend blocking hint).
      if (entry.vision !== undefined) next.vision = entry.vision;
      // Inherit-the-Agent-value by default: only written to disk when explicitly annotated (omitted on a full-table PUT = the annotation is cleared).
      if (entry.maxTokens !== undefined) next.max_tokens = entry.maxTokens;
      // Off by default: only `true` is written to disk (absent = off); omitted or false clears the annotation.
      if (entry.fastMode === true) next.fast_mode = true;
      if (entry.pricing !== undefined) {
        next.pricing = {
          unit: "usd_per_mtok",
          cache_read: entry.pricing.cacheRead,
          cache_write: entry.pricing.cacheWrite,
          output: entry.pricing.output,
        };
      }
      // credential is inlined on the entry; added/removed on top of the old value per the request (migrates automatically with the base entry when the key changes).
      if (entry.clearApiKey) {
        delete next.api_key;
        delete next.created_at;
        if (entry.provider === MODELSCOPE_PROVIDER_ID) clearModelScopeProviderAuthToken = true;
      }
      if (entry.apiKey !== undefined) {
        next.api_key = entry.apiKey;
        next.created_at = new Date().toISOString();
        if (entry.provider === MODELSCOPE_PROVIDER_ID) clearModelScopeProviderAuthToken = true;
      } else if (
        !entry.clearApiKey &&
        next.api_key === undefined &&
        catalogEntryFor(entry.provider, entry.modelId) !== undefined
      ) {
        // A preset row this request leaves keyless borrows its group's key when the table holds
        // exactly one for that provider + base URL (see groupApiKey). "Sync presets" is what puts
        // a catalog entry here without a credential, and a preset the catalog has carried since
        // before this rule reached the table is still keyless — saving the page is what fills it
        // in. Only the catalog's own rows borrow: a row added by hand is the user's own entry,
        // where replacing it without its key has always meant the credential does not migrate.
        const borrowed = groupApiKey(keyPool, entry.provider, baseUrlOf(entry));
        if (borrowed !== undefined) {
          next.api_key = borrowed;
          next.created_at = new Date().toISOString();
          if (entry.provider === MODELSCOPE_PROVIDER_ID) clearModelScopeProviderAuthToken = true;
        }
      }
      if (entry.baseUrl === null) delete next.base_url;
      else if (entry.baseUrl !== undefined) next.base_url = entry.baseUrl;
      if (entry.provider === MODELSCOPE_PROVIDER_ID) keepModelScopeGroup = true;
      nextModels.push(next);
    }
    if (hadModelScopeGroup && !keepModelScopeGroup) clearModelScopeProviderAuthToken = true;

    // default_model: when provided it must be present in models; when omitted the previous value is kept (the pointer follows a key rename; if it was deleted, it's removed).
    let defaultModel: ModelRefDto | undefined;
    if (req.defaultModel !== undefined) {
      if (!seen.has(refKey(req.defaultModel.provider, req.defaultModel.modelId))) {
        throw badRequest(
          `defaultModel must be included in models: ${showRef(req.defaultModel.provider, req.defaultModel.modelId)}.`,
        );
      }
      defaultModel = req.defaultModel;
    } else {
      const prevRef = optRef(raw.default_model);
      if (prevRef !== undefined) {
        const prevKey = refKey(prevRef.provider, prevRef.model_id);
        const followed = renamed.get(prevKey) ?? {
          provider: prevRef.provider,
          modelId: prevRef.model_id,
        };
        if (seen.has(refKey(followed.provider, followed.modelId))) defaultModel = followed;
      }
    }

    // vision_model: same semantics as default_model; additionally must not be annotated vision=false (can't proxy-read images if unsupported).
    const targetOf = (ref: ModelRefDto) =>
      req.models.find((m) => m.provider === ref.provider && m.modelId === ref.modelId);
    let visionModel: ModelRefDto | undefined;
    if (req.visionModel !== undefined) {
      if (!seen.has(refKey(req.visionModel.provider, req.visionModel.modelId))) {
        throw badRequest(
          `visionModel must be included in models: ${showRef(req.visionModel.provider, req.visionModel.modelId)}.`,
        );
      }
      if (targetOf(req.visionModel)?.vision === false) {
        throw badRequest(
          `visionModel must not point to a model annotated as not supporting images: ${showRef(req.visionModel.provider, req.visionModel.modelId)}.`,
        );
      }
      visionModel = req.visionModel;
    } else {
      const prevRef = optRef(raw.vision_model);
      if (prevRef !== undefined) {
        const prevKey = refKey(prevRef.provider, prevRef.model_id);
        const followed = renamed.get(prevKey) ?? {
          provider: prevRef.provider,
          modelId: prevRef.model_id,
        };
        if (seen.has(refKey(followed.provider, followed.modelId))) {
          // The former vision model is now annotated as not supporting images: the annotation takes priority, and the pointer is dropped as invalid.
          if (targetOf(followed)?.vision !== false) visionModel = followed;
        }
      }
    }

    const toRaw = (ref: ModelRefDto): RawTable => ({
      provider: ref.provider,
      model_id: ref.modelId,
    });
    const next: RawTable = { ...raw, models: nextModels };
    if (defaultModel !== undefined) next.default_model = toRaw(defaultModel);
    else delete next.default_model;
    if (visionModel !== undefined) next.vision_model = toRaw(visionModel);
    else delete next.vision_model;
    const commit = async (): Promise<ModelsResponse> => {
      await this.writeRaw(projectId, next);
      if (this.promotions !== undefined) {
        const stored = new Map(
          this.promotions.list(projectId).map((p) => [refKey(p.provider, p.modelId), p.discount]),
        );
        const rows: ModelPromotion[] = [];
        for (const { provider, modelId, declared, keep } of promotionPlan) {
          const discount = keep ? stored.get(refKey(provider, modelId)) : declared;
          if (discount !== undefined && discount !== null)
            rows.push({ provider, modelId, discount });
        }
        // Built from the new table alone, so a dropped row's promotion is gone with it.
        this.promotions.replaceAll(projectId, rows);
      }
      if (clearModelScopeProviderAuthToken) {
        this.providerAuthTokens?.delete(projectId, MODELSCOPE_PROVIDER_ID);
      }
      return this.getModels(projectId);
    };
    return commit();
  }

  /**
   * Writes one API key onto every model of a provider group — the credential half of the
   * bulk group-key action, performing the same `api_key` + `created_at` write `updateModels`
   * performs on the entries it rewrites. No other field is read or replaced, so a caller
   * that never saw the rest of the table cannot flatten it.
   *
   * Returns how many entries were written; an empty group writes nothing and returns 0.
   */
  async setGroupApiKey(projectId: string, provider: string, apiKey: string): Promise<number> {
    if (provider === MODELSCOPE_PROVIDER_ID) {
      return this.withProviderCredentialLock(projectId, provider, async () => {
        const applied = await this.setGroupApiKeyUnlocked(projectId, provider, apiKey);
        if (applied > 0) this.providerAuthTokens?.delete(projectId, MODELSCOPE_PROVIDER_ID);
        return applied;
      });
    }
    return this.setGroupApiKeyUnlocked(projectId, provider, apiKey);
  }

  async setGroupApiKeyWithProviderAuthToken(
    projectId: string,
    provider: string,
    apiKey: string,
    token: Omit<ModelProviderAuthToken, "provider" | "updatedAt">,
    options: { expectedRefreshToken?: string } = {},
  ): Promise<number> {
    return this.withProviderCredentialLock(projectId, provider, async () => {
      if (options.expectedRefreshToken !== undefined) {
        const current = this.providerAuthTokens?.get(projectId, provider);
        if (current?.refreshToken !== options.expectedRefreshToken) return 0;
      }
      const applied = await this.setGroupApiKeyUnlocked(projectId, provider, apiKey);
      if (applied > 0) {
        this.providerAuthTokens?.upsert(projectId, {
          provider,
          refreshToken: token.refreshToken,
          accessTokenExpiresAt: token.accessTokenExpiresAt,
        });
      }
      return applied;
    });
  }

  private async setGroupApiKeyUnlocked(
    projectId: string,
    provider: string,
    apiKey: string,
  ): Promise<number> {
    const raw = await this.readRaw(projectId);
    const createdAt = new Date().toISOString();
    let applied = 0;
    const nextModels = asArray(raw.models).map((m) => {
      if (m.provider !== provider) return m;
      applied += 1;
      return { ...m, api_key: apiKey, created_at: createdAt };
    });
    if (applied === 0) return 0;
    await this.writeRaw(projectId, { ...raw, models: nextModels });
    return applied;
  }

  /** Returns one persisted group key without exposing it through an HTTP response. */
  async getGroupApiKey(projectId: string, provider: string): Promise<string | undefined> {
    const raw = await this.readRaw(projectId);
    for (const model of asArray(raw.models)) {
      if (model.provider !== provider) continue;
      const apiKey = optStr(model.api_key);
      if (apiKey !== undefined) return apiKey;
    }
    return undefined;
  }

  /**
   * The key a group's account balance is read with (the catalog's `balance` descriptor names
   * the endpoint). The stored group key comes first. Without one, the environment key a
   * Session on one of the group's rows would use: core's modelEnvFallback decides, the rule
   * resolveModelCredential applies, and its variable is read from this process's env as the
   * routed client itself would read it. One more condition, because the balance request is
   * the server's own rather than the routed client's: the variable's official endpoint must
   * be the balance endpoint's host, so a vendor key never reaches another vendor. A DeepSeek
   * row keyed by DEEPSEEK_API_KEY qualifies; a gateway's rows (TokenDance) get no fallback at
   * all. Never returned to the browser.
   */
  async getGroupBalanceKey(projectId: string, provider: string): Promise<string | undefined> {
    const stored = await this.getGroupApiKey(projectId, provider);
    if (stored !== undefined) return stored;
    const balanceUrl = providerInfo(provider)?.balance?.url;
    if (balanceUrl === undefined) return undefined;
    const origin = (url: string): string | undefined => {
      try {
        return new URL(url).origin;
      } catch {
        return undefined;
      }
    };
    const balanceOrigin = origin(balanceUrl);
    const raw = await this.readRaw(projectId);
    for (const model of asArray(raw.models)) {
      if (model.provider !== provider) continue;
      const modelId = optStr(model.model_id);
      if (modelId === undefined) continue;
      const fallback = modelEnvFallback({
        provider,
        modelId,
        clientType: canonicalClientType(optStr(model.client_type)),
        baseUrl: optStr(model.base_url),
      });
      if (fallback === undefined) continue;
      const endpoints = VENDOR_ENDPOINTS[fallback.envKey] ?? [];
      if (!endpoints.some((own) => origin(own) === balanceOrigin)) continue;
      const value = process.env[fallback.envKey]?.trim();
      if (value) return value;
    }
    return undefined;
  }

  /**
   * Adds newly advertised models and refreshes platform-owned routing and list price on
   * existing rows, then replaces this group's promotions (web.db) with the platform's. Project
   * TOML stays in the same shape as every other model group, list price included. Other
   * annotations remain Project-owned and are never overwritten. Authorization additionally
   * applies the freshly delivered key to the whole group.
   */
  async mergePlatformModels(
    projectId: string,
    provider: string,
    catalog: PlatformModelCatalog,
    apiKey: string,
    applyKeyToExisting: boolean,
  ): Promise<PlatformModelApplyResult> {
    const raw = await this.readRaw(projectId);
    const current = asArray(raw.models);
    const catalogById = new Map(catalog.models.map((model) => [model.modelId, model]));
    const storedPromotions = new Map(
      (this.promotions?.list(projectId) ?? [])
        .filter((promotion) => promotion.provider === provider)
        .map((promotion) => [promotion.modelId, promotion.discount]),
    );
    const known = new Set<string>();
    const createdAt = new Date().toISOString();
    let added = 0;
    let updated = 0;
    let applied = 0;
    let configChanged = false;
    const nextModels = current.map((model): RawTable => {
      if (model.provider !== provider || typeof model.model_id !== "string") return model;
      const modelId = String(model.model_id);
      known.add(modelId);
      const catalogModel = catalogById.get(modelId);
      const remotePricing = catalogModel?.pricing;
      const pricingChanged =
        remotePricing !== undefined && !platformPricingMatches(model.pricing, remotePricing);
      const clientTypeChanged =
        catalogModel !== undefined && model.client_type !== catalogModel.clientType;
      // A row the platform no longer lists loses its promotion below, which is a change too.
      const promotionChanged =
        this.promotions !== undefined && storedPromotions.get(modelId) !== catalogModel?.discount;
      if (pricingChanged || clientTypeChanged || promotionChanged) updated += 1;
      if (applyKeyToExisting) applied += 1;
      if (!pricingChanged && !clientTypeChanged && !applyKeyToExisting) return model;
      configChanged = true;
      return {
        ...model,
        ...(pricingChanged && remotePricing !== undefined
          ? { pricing: platformPricingTable(remotePricing) }
          : {}),
        ...(clientTypeChanged && catalogModel !== undefined
          ? { client_type: catalogModel.clientType }
          : {}),
        ...(applyKeyToExisting ? { api_key: apiKey, created_at: createdAt } : {}),
      };
    });

    for (const model of catalog.models) {
      if (known.has(model.modelId)) continue;
      known.add(model.modelId);
      added += 1;
      applied += 1;
      configChanged = true;
      nextModels.push({
        provider,
        model_id: model.modelId,
        display_name: model.displayName,
        context_window: model.contextWindow,
        vision: model.supportsVision,
        pricing: platformPricingTable(model.pricing),
        client_type: model.clientType,
        base_url: model.baseUrl,
        api_key: apiKey,
        created_at: createdAt,
      });
    }

    if (configChanged) {
      await this.writeRaw(projectId, { ...raw, models: nextModels });
    }
    // After the file write, so a promotion never lands for a row the file failed to take; a
    // failure here leaves the group's previous promotions until the next authorization or Sync.
    this.promotions?.replaceProvider(
      projectId,
      provider,
      catalog.models.flatMap((model) =>
        model.discount !== undefined && known.has(model.modelId)
          ? [{ provider, modelId: model.modelId, discount: model.discount }]
          : [],
      ),
    );
    return { added, updated, applied };
  }
}

/**
 * Whether a streamed message carries genuine model content (thinking or text, partial delta
 * or complete backfill) — the probe's "the endpoint really answered" signal. Tool calls and
 * event messages don't count (the probe declares no tools).
 */
export function isProbeContent(msg: OmniMessage): boolean {
  const p = msg.payload as { type?: string; thinking?: string; text?: string };
  if (p.type === "partial_thinking" || p.type === "thinking") return Boolean(p.thinking);
  if (p.type === "partial_text" || p.type === "text") return Boolean(p.text);
  return false;
}

/**
 * Probe verdict from the terminal LLM outcome. `completed` always passes. A `malformed`
 * ending after genuine streamed content also passes: the typical case is a reasoning-heavy
 * model that spends the probe's tiny max_tokens entirely on thinking (finish_reason=length ->
 * AgentHub's EmptyResponseError, a `retryable` outcome that still streamed content) — the
 * endpoint, credential, and model id all demonstrably work, which is what a connectivity
 * test measures. Everything else (fatal rejections, and retryable failures with nothing
 * received) fails with the outcome's message.
 */
export function probeVerdict(
  outcome: LLMOutcome,
  sawContent: boolean,
): { ok: true } | { ok: false; message: string } {
  if (outcome.status === "completed") return { ok: true };
  if (outcome.status === "retryable" && sawContent) return { ok: true };
  return { ok: false, message: outcomeDetail(outcome) };
}

/**
 * Sample floors below which the streaming window says nothing about decoding rate. The
 * speed probe's 64-token cap clears both by a wide margin, so hitting a floor means the
 * model didn't really stream (a one-word answer, or usage that never arrived).
 */
const PROBE_TPS_MIN_TOKENS = 16;
const PROBE_TPS_MIN_WINDOW_MS = 100;

/**
 * Output rate (tokens/s) over the probe's streaming window (first content -> stream end),
 * rounded to 1dp; undefined when the sample is too small to be meaningful. A stream's
 * closing usage chunk costs a round trip on its own, so a two-token answer measures network
 * jitter and nothing else — 2 tokens in 30ms reads as 66.7 tok/s and the same model 30ms
 * later reads as 33.3, which the card badges would paint green vs yellow. Callers report
 * TTFT alone rather than a fabricated rate; a malformed ending carries no usage at all and
 * lands here as 0 tokens.
 */
export function probeTps(outputTokens: number, windowMs: number): number | undefined {
  if (outputTokens < PROBE_TPS_MIN_TOKENS || windowMs <= PROBE_TPS_MIN_WINDOW_MS) return undefined;
  return Math.round((outputTokens / (windowMs / 1000)) * 10) / 10;
}