mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-06 15:52:22 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Agent setup, environment testing, and managed AI connections pass
provider API keys into the OpenCode adapter and Paperclip Runner
> - OpenCode setup failed with `Secret not found` when a user supplied a
direct Gemini API key alongside a stale or auto-selected secret binding,
and the OpenCode runtime reported `GOOGLE_GENERATIVE_AI_API_KEY` missing
because Paperclip only passed `GEMINI_API_KEY` and limited OpenCode to
OpenRouter credentials
> - Users need reliable direct provider API keys and Google/Antigravity
API-key connectors across legacy OpenCode, native Paperclip Runner, and
Plugin Runner environments without exposing raw keys to child tool
shells
> - This pull request strips probe-overridden secret references
(including symmetric Google key aliases) before secret resolution,
prioritizes pasted API keys in setup, routes direct OpenCode provider
credentials through a runner-owned loopback proxy, and enables API-key
AI connections (including the Google / Antigravity connector) for
`opencode_local`
> - The benefit is that OpenCode agents test and run reliably with
direct provider keys or connected Google/Antigravity API keys without
false `Secret not found`, missing `GOOGLE_GENERATIVE_AI_API_KEY` errors,
or raw key leaks into child environments
## Linked Issues or Issue Description
- Fixes: #23359
- Refs #23370 (related community fix by @dev-787 for the initial Gemini
API key issue)
## What Changed
- **Server test-environment secret stripping and inheritance
(`server/src/routes/agents.ts`)**: Strip any credential key supplied in
`testCredentials` (including the symmetric `GEMINI_API_KEY` /
`GOOGLE_GENERATIVE_AI_API_KEY` pair and `hermes_gateway` `apiKey`) from
both `adapterConfig` and resolved environment `envVars` before secret
persistence normalization and runtime resolution. Scope `opencode_local`
inheritable credential groups from `@paperclipai/shared`
(`OPENCODE_PROVIDER_CREDENTIAL_ENV_KEYS`), skip inheritance when the
child supplies any OpenCode credential, and isolate multi-provider
parents to one matching provider group.
- **UI setup credential precedence (`ui/src/lib/provider-credential.ts`,
`ui/src/components/new-agent/NewAgentSetup.tsx`)**: Prefer an explicitly
entered raw API key over an auto-selected organization or personal
secret, and clear stale provider secret bindings and Google alias keys
when switching credentials or providers.
- **OpenCode direct provider keys and Gemini aliasing
(`packages/adapters/opencode-local/`, `packages/adapter-utils/`)**:
Mirror non-empty `GEMINI_API_KEY` into `GOOGLE_GENERATIVE_AI_API_KEY`
during OpenCode runtime config preparation and model discovery while
preserving blank managed isolation. Register `google`, `xai`, `groq`,
and `opencode` API key names in `api-billing-type`.
- **Runner-owned loopback credential proxy and allowlist parity
(`packages/paperclip-runner/`, `packages/plugins/sdk/`,
`packages/shared/`)**: Export canonical
`OPENCODE_PROVIDER_CREDENTIAL_ENV_KEYS` and
`OPENCODE_CREDENTIAL_ENV_KEYS` from `@paperclipai/shared`. Route direct
OpenCode provider API keys (`google`, `anthropic`, `openai`, `xai`,
`groq`, `opencode`) through a runner-owned loopback proxy
(`packages/paperclip-runner/src/drivers/opencode/provider-proxy.ts`)
with per-session bearer tokens, model-pinned endpoint allowlists, native
upstream auth header injection, request secret redaction, and redirect
refusal so raw keys never enter `opencode serve` child environments or
`opencode.json`. Allow direct provider keys across TypeScript, Rust, and
Plugin SDK allowlists, reserve `GOOGLE_API_KEY` and `GROK_API_KEY` in
TS/Rust configured-environment projections, strip ambient provider keys
(including `OPENROUTER_API_KEY`) from sanitized OpenCode runner
environments unless explicitly supplied, and redact provider keys in
output custody.
- **Antigravity / multi-provider API-key AI connections for OpenCode
(`packages/shared/`, `server/src/services/`,
`ui/src/components/ai-connections/`)**: Enable `api_key` AI connections
for `google` (Antigravity catalog slug), `anthropic`, `openai`, and
`xai` on `opencode_local` (keeping OAuth `subscription` methods
excluded), enforce provider-to-model prefix compatibility, mirror
`GEMINI_API_KEY` to `GOOGLE_GENERATIVE_AI_API_KEY` in
`prepareManagedAiRuntime`, isolate project config with
`OPENCODE_DISABLE_PROJECT_CONFIG=true`, and scope child-auth override
detection in `agent-ai-connection-default.ts` to non-empty OpenCode
credentials (supporting plain values, `secret_ref.secretId`, and
`user_secret_ref.key`).
- **Tests and pinned input registry**: Added unit, route, cross-layer
allowlist parity, and pinned `opencode@1.18.34` `bash`-tool credential
isolation tests across `adapter-utils`, `adapter-opencode-local`,
`paperclip-runner`, `server`, and `ui`, and synchronized
`tests/runner-e2e/source-sdk-public-inputs.json`.
## Verification
- `@paperclipai/adapter-utils`: `src/api-billing-type.test.ts` (17/17
tests), `typecheck`, `build` — passed
- `@paperclipai/adapter-opencode-local`:
`src/server/runtime-config.test.ts`, `src/server/models.test.ts`,
`typecheck`, `build` — passed
- `@paperclipai/shared`: full suite (123/123 files, 1426/1426 tests),
`typecheck`, `build` — passed
- `@paperclipai/paperclip-runner`: `typecheck:typescript`,
`build:typescript`, `check:package-boundaries`,
`opencode-server-driver.test.ts` (101/101 including pinned
`opencode@1.18.34` `bash`-tool test), `output-custody.test.ts` (13/13),
`configured-environment.test.ts` (35/35),
`antigravity-credentials.test.ts` (11/11), and
`durable-prp-control-plane.test.ts` — passed
- `@paperclipai/server`: `typecheck` and targeted suites
(`ai-connections.test.ts` 170/170, `agent-hire-ai-connections.test.ts`
84/84, `agent-test-environment-routes.test.ts` 72/72,
`agent-hire-auth-inheritance-routes.test.ts` 29/29,
`plugin-runner-credentials.test.ts` 43/43,
`plugin-runner-credential-names.test.ts` 6/6 cross-layer TS/Rust parity,
`opencode-local-adapter-environment.test.ts` 4/4,
`ai-auth-failure.test.ts` 32/32, `ai-provider-routing.test.ts` 21/21,
`antigravity-runner-credentials.test.ts`) — passed
- `@paperclipai/ui`: `typecheck`, `provider-credential.test.ts`,
`AiConnectionSelect.test.tsx` (20/20 tests) — passed
- `@paperclipai/plugin-sdk`: `build`, `environment-tasks.test.ts`,
`environment-task-release-resume.test.ts` (104/104) — passed on
`03dc341957`
- `@paperclipai/paperclip-runner`: `provider-traffic.test.ts` &
`provider-traffic-proxy.test.ts` alongside OpenCode/Antigravity/custody
suites (169/169) — passed on `03dc341957`
- `node tests/runner-e2e/source-sdk-public-inputs.mjs
03dc341957 --check` — passed (`changed:
false`, 602 inputs)
- GitHub CI on `03dc341957`: all 95 checks green (`MERGEABLE` / `CLEAN`)
— `ci / verify` ([run
47315344108](https://github.com/paperclipai/paperclip/actions/runs/47315344108)),
`ci / e2e`, `Verify Paperclip Runner` (static checks, Rust, Vitest
package & native server suites), `Runner Windows` ([run
47315343800](https://github.com/paperclipai/paperclip/actions/runs/47315343800)),
`Runner image` (`amd64` + `arm64`, [run
47315343840](https://github.com/paperclipai/paperclip/actions/runs/47315343840)),
`macOS OpenCode SSH runtime` ([run
47315343817](https://github.com/paperclipai/paperclip/actions/runs/47315343817)),
`Verify serialized server suites` (1/9–9/9), `Superagent Security Scan`,
`Greptile Review` (5/5), `Paperclip Review` (5/5), `Socket Security`,
and `security/snyk` passed.
- Local verification gap: `cargo` is not installed in this container;
Rust checks (`typecheck:rust` / `test:rust`) ran and passed in GitHub CI
(`verify_paperclip_runner`).
## Risks
- Low to moderate risk. No database schema or migration changes are
included.
- Touches provider credential allowlists in both TypeScript and Rust
(`codex_provider.rs`, `configured_environment.rs`), the runner-owned
loopback proxy for direct OpenCode providers, and secret-stripping logic
in `POST /companies/:companyId/adapters/:type/test-environment`. Parity
between TypeScript and Rust allowlists is enforced by
`plugin-runner-credential-names.test.ts`, and Rust build/test checks
pass in CI.
- `opencode_local` AI connection compatibility enforces that the
selected model prefix matches the connected provider (for example,
`google/...` for a Google/Antigravity API-key connection). Existing
`openrouter/...` connections remain compatible.
## Model Used
- Google Gemini (Antigravity agent runtime) with reasoning, repository
code navigation, shell execution, and automated test verification.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip <noreply@paperclip.ing>
374 lines
12 KiB
TypeScript
374 lines
12 KiB
TypeScript
import { createHash } from "node:crypto";
|
|
import os from "node:os";
|
|
import type { AdapterModel } from "@paperclipai/adapter-utils";
|
|
import {
|
|
asString,
|
|
ensurePathInEnv,
|
|
runChildProcess,
|
|
} from "@paperclipai/adapter-utils/server-utils";
|
|
import { isValidOpenCodeModelId } from "../index.js";
|
|
import { applyOpenCodeProviderEnvAliases } from "./runtime-config.js";
|
|
|
|
const MODELS_CACHE_TTL_MS = 60_000;
|
|
const MODELS_DISCOVERY_TIMEOUT_MS = 20_000;
|
|
// `opencode models` is a lightweight metadata call, but on a shared ollama
|
|
// daemon it can queue behind an in-flight `opencode run` generation on the
|
|
// same host and either time out or fail with an opaque error. Retry a few
|
|
// times with backoff before surfacing a hard failure (SAG-6326/SAG-6336).
|
|
const MODELS_DISCOVERY_RETRY_DELAYS_MS = [2_000, 4_000];
|
|
|
|
function sleep(ms: number): Promise<void> {
|
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
}
|
|
|
|
function resolveOpenCodeCommand(input: unknown): string {
|
|
const envOverride =
|
|
typeof process.env.PAPERCLIP_OPENCODE_COMMAND === "string" &&
|
|
process.env.PAPERCLIP_OPENCODE_COMMAND.trim().length > 0
|
|
? process.env.PAPERCLIP_OPENCODE_COMMAND.trim()
|
|
: "opencode";
|
|
return asString(input, envOverride);
|
|
}
|
|
|
|
const discoveryCache = new Map<
|
|
string,
|
|
{ expiresAt: number; models: AdapterModel[] }
|
|
>();
|
|
const VOLATILE_ENV_KEY_PREFIXES = ["PAPERCLIP_", "npm_", "NPM_"] as const;
|
|
const VOLATILE_ENV_KEY_EXACT = new Set([
|
|
"PWD",
|
|
"OLDPWD",
|
|
"SHLVL",
|
|
"_",
|
|
"TERM_SESSION_ID",
|
|
"HOME",
|
|
]);
|
|
|
|
export function requireOpenCodeModelId(input: unknown): string {
|
|
const model = asString(input, "").trim();
|
|
if (!isValidOpenCodeModelId(model)) {
|
|
throw new Error(
|
|
"OpenCode requires `adapterConfig.model` in provider/model format.",
|
|
);
|
|
}
|
|
return model;
|
|
}
|
|
|
|
function dedupeModels(models: AdapterModel[]): AdapterModel[] {
|
|
const seen = new Set<string>();
|
|
const deduped: AdapterModel[] = [];
|
|
for (const model of models) {
|
|
const id = model.id.trim();
|
|
if (!id || seen.has(id)) continue;
|
|
seen.add(id);
|
|
deduped.push({ id, label: model.label.trim() || id });
|
|
}
|
|
return deduped;
|
|
}
|
|
|
|
function sortModels(models: AdapterModel[]): AdapterModel[] {
|
|
return [...models].sort((a, b) =>
|
|
a.id.localeCompare(b.id, "en", { numeric: true, sensitivity: "base" }),
|
|
);
|
|
}
|
|
|
|
function firstNonEmptyLine(text: string): string {
|
|
return (
|
|
text
|
|
.split(/\r?\n/)
|
|
.map((line) => line.trim())
|
|
.find(Boolean) ?? ""
|
|
);
|
|
}
|
|
|
|
export function parseOpenCodeModelsOutput(stdout: string): AdapterModel[] {
|
|
const parsed: AdapterModel[] = [];
|
|
for (const raw of stdout.split(/\r?\n/)) {
|
|
const line = raw.trim();
|
|
if (!line) continue;
|
|
const firstToken = line.split(/\s+/)[0]?.trim() ?? "";
|
|
if (!firstToken.includes("/")) continue;
|
|
const provider = firstToken.slice(0, firstToken.indexOf("/")).trim();
|
|
const model = firstToken.slice(firstToken.indexOf("/") + 1).trim();
|
|
if (!provider || !model) continue;
|
|
parsed.push({ id: `${provider}/${model}`, label: `${provider}/${model}` });
|
|
}
|
|
return dedupeModels(parsed);
|
|
}
|
|
|
|
function normalizeEnv(input: unknown): Record<string, string> {
|
|
const envInput =
|
|
typeof input === "object" && input !== null && !Array.isArray(input)
|
|
? (input as Record<string, unknown>)
|
|
: {};
|
|
const env: Record<string, string> = {};
|
|
for (const [key, value] of Object.entries(envInput)) {
|
|
if (typeof value === "string") env[key] = value;
|
|
}
|
|
return env;
|
|
}
|
|
|
|
function isVolatileEnvKey(key: string): boolean {
|
|
if (VOLATILE_ENV_KEY_EXACT.has(key)) return true;
|
|
return VOLATILE_ENV_KEY_PREFIXES.some((prefix) => key.startsWith(prefix));
|
|
}
|
|
|
|
function hashValue(value: string): string {
|
|
return createHash("sha256").update(value).digest("hex");
|
|
}
|
|
|
|
function discoveryCacheKey(
|
|
command: string,
|
|
cwd: string,
|
|
env: Record<string, string>,
|
|
) {
|
|
const envKey = Object.entries(env)
|
|
.filter(([key]) => !isVolatileEnvKey(key))
|
|
.sort(([a], [b]) => a.localeCompare(b))
|
|
.map(([key, value]) => `${key}=${hashValue(value)}`)
|
|
.join("\n");
|
|
return `${command}\n${cwd}\n${envKey}`;
|
|
}
|
|
|
|
function pruneExpiredDiscoveryCache(now: number) {
|
|
for (const [key, value] of discoveryCache.entries()) {
|
|
if (value.expiresAt <= now) discoveryCache.delete(key);
|
|
}
|
|
}
|
|
|
|
export async function discoverOpenCodeModels(
|
|
input: {
|
|
command?: unknown;
|
|
cwd?: unknown;
|
|
env?: unknown;
|
|
refresh?: boolean;
|
|
} = {},
|
|
): Promise<AdapterModel[]> {
|
|
const command = resolveOpenCodeCommand(input.command);
|
|
const cwd = asString(input.cwd, process.cwd());
|
|
const env = normalizeEnv(input.env);
|
|
// Ensure HOME points to the actual running user's home directory.
|
|
// When the server is started via `runuser -u <user>`, HOME may still
|
|
// reflect the parent process (e.g. /root), causing OpenCode to miss
|
|
// provider auth credentials stored under the target user's home.
|
|
let resolvedHome: string | undefined;
|
|
try {
|
|
resolvedHome = os.userInfo().homedir || undefined;
|
|
} catch {
|
|
// os.userInfo() throws a SystemError when the current UID has no
|
|
// /etc/passwd entry (e.g. `docker run --user 1234` with a minimal
|
|
// image). Fall back to process.env.HOME.
|
|
}
|
|
// Prevent OpenCode from writing an opencode.json into the working directory.
|
|
// Apply Google alias independently to host and explicit envs before merging so
|
|
// an explicit blank GOOGLE_GENERATIVE_AI_API_KEY cannot be repopulated by an
|
|
// ambient host GEMINI_API_KEY, while an explicit GEMINI_API_KEY still overrides
|
|
// an ambient host GOOGLE_GENERATIVE_AI_API_KEY.
|
|
const aliasedHostEnv = applyOpenCodeProviderEnvAliases(normalizeEnv(process.env));
|
|
const aliasedExplicitEnv = applyOpenCodeProviderEnvAliases(env);
|
|
const runtimeEnv = normalizeEnv(
|
|
ensurePathInEnv({
|
|
...aliasedHostEnv,
|
|
...aliasedExplicitEnv,
|
|
...(resolvedHome ? { HOME: resolvedHome } : {}),
|
|
OPENCODE_DISABLE_PROJECT_CONFIG: "true",
|
|
}),
|
|
);
|
|
|
|
const maxAttempts = MODELS_DISCOVERY_RETRY_DELAYS_MS.length + 1;
|
|
let lastError: Error | undefined;
|
|
|
|
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
const result = await runChildProcess(
|
|
`opencode-models-${Date.now()}-${Math.random().toString(16).slice(2)}`,
|
|
command,
|
|
["models", ...(input.refresh ? ["--refresh"] : [])],
|
|
{
|
|
cwd,
|
|
env: runtimeEnv,
|
|
timeoutSec: MODELS_DISCOVERY_TIMEOUT_MS / 1000,
|
|
graceSec: 3,
|
|
onLog: async () => {},
|
|
},
|
|
);
|
|
|
|
if (result.timedOut) {
|
|
lastError = new Error(
|
|
`\`opencode models\` timed out after ${MODELS_DISCOVERY_TIMEOUT_MS / 1000}s.`,
|
|
);
|
|
} else if ((result.exitCode ?? 1) !== 0) {
|
|
const detail =
|
|
firstNonEmptyLine(result.stderr) || firstNonEmptyLine(result.stdout);
|
|
lastError = new Error(
|
|
detail
|
|
? `\`opencode models\` failed: ${detail}`
|
|
: "`opencode models` failed.",
|
|
);
|
|
} else {
|
|
return sortModels(parseOpenCodeModelsOutput(result.stdout));
|
|
}
|
|
|
|
const delayMs = MODELS_DISCOVERY_RETRY_DELAYS_MS[attempt - 1];
|
|
if (delayMs === undefined) break;
|
|
await sleep(delayMs);
|
|
}
|
|
|
|
throw lastError ?? new Error("`opencode models` failed.");
|
|
}
|
|
|
|
export async function discoverOpenCodeModelsCached(
|
|
input: {
|
|
command?: unknown;
|
|
cwd?: unknown;
|
|
env?: unknown;
|
|
} = {},
|
|
): Promise<AdapterModel[]> {
|
|
const command = resolveOpenCodeCommand(input.command);
|
|
const cwd = asString(input.cwd, process.cwd());
|
|
const env = normalizeEnv(input.env);
|
|
const key = discoveryCacheKey(command, cwd, env);
|
|
const now = Date.now();
|
|
pruneExpiredDiscoveryCache(now);
|
|
const cached = discoveryCache.get(key);
|
|
if (cached && cached.expiresAt > now) return cached.models;
|
|
|
|
const models = await discoverOpenCodeModels({ command, cwd, env });
|
|
discoveryCache.set(key, { expiresAt: now + MODELS_CACHE_TTL_MS, models });
|
|
return models;
|
|
}
|
|
|
|
async function refreshOpenCodeModelsCached(input: {
|
|
command?: unknown;
|
|
cwd?: unknown;
|
|
env?: unknown;
|
|
}): Promise<AdapterModel[]> {
|
|
const command = resolveOpenCodeCommand(input.command);
|
|
const cwd = asString(input.cwd, process.cwd());
|
|
const env = normalizeEnv(input.env);
|
|
// OpenCode 1.18.17 uses `models --refresh` only to update its on-disk
|
|
// models.dev cache. Its stdout is a confirmation message, not the refreshed
|
|
// catalog, so enumerate once more after the refresh under the exact same
|
|
// command/cwd/env before deciding whether the configured model exists.
|
|
await discoverOpenCodeModels({
|
|
command,
|
|
cwd,
|
|
env,
|
|
refresh: true,
|
|
});
|
|
const models = await discoverOpenCodeModels({ command, cwd, env });
|
|
if (models.length > 0) {
|
|
discoveryCache.set(discoveryCacheKey(command, cwd, env), {
|
|
expiresAt: Date.now() + MODELS_CACHE_TTL_MS,
|
|
models,
|
|
});
|
|
}
|
|
return models;
|
|
}
|
|
|
|
export function isTruthyEnvFlag(value: string | undefined): boolean {
|
|
if (value === undefined) return false;
|
|
const v = value.trim().toLowerCase();
|
|
return v === "true" || v === "1" || v === "yes";
|
|
}
|
|
|
|
export async function ensureOpenCodeModelConfiguredAndAvailable(input: {
|
|
model?: unknown;
|
|
command?: unknown;
|
|
cwd?: unknown;
|
|
env?: unknown;
|
|
}): Promise<AdapterModel[]> {
|
|
const model = requireOpenCodeModelId(input.model);
|
|
|
|
// When the caller opts into OPENCODE_ALLOW_ALL_MODELS, OpenCode accepts any
|
|
// provider/model at run time (e.g. gateway-routed models that never appear in
|
|
// `opencode models` output). Honour that by skipping the availability probe;
|
|
// we still enforce the provider/model format above and do not second-guess
|
|
// the configured model. Prefer the explicit run env, then the process env.
|
|
const env = normalizeEnv(input.env);
|
|
if (
|
|
isTruthyEnvFlag(
|
|
env.OPENCODE_ALLOW_ALL_MODELS ?? process.env.OPENCODE_ALLOW_ALL_MODELS,
|
|
)
|
|
) {
|
|
return [{ id: model, label: model }];
|
|
}
|
|
|
|
let models: AdapterModel[];
|
|
try {
|
|
models = await discoverOpenCodeModelsCached({
|
|
command: input.command,
|
|
cwd: input.cwd,
|
|
env: input.env,
|
|
});
|
|
} catch (err) {
|
|
// The availability probe is a best-effort pre-flight guard, not a gate. If
|
|
// `opencode models` itself cannot run — a transient CLI error, a timeout, a
|
|
// provider hiccup — do NOT abort the run. The real invocation is
|
|
// authoritative, so a probe that can't execute must never be fatal.
|
|
// (Previously this threw and crashed runs mid-flight, discarding the agent's
|
|
// completed work and its terminal disposition, which then reopened the issue.)
|
|
console.warn(
|
|
`[opencode-local] Model availability probe could not run for "${model}" (${
|
|
err instanceof Error ? err.message : String(err)
|
|
}); proceeding with the configured model.`,
|
|
);
|
|
return [{ id: model, label: model }];
|
|
}
|
|
|
|
if (models.length === 0) {
|
|
// The probe ran but returned nothing (e.g. a transient provider-auth blip).
|
|
// Same reasoning as above: warn, don't block the run.
|
|
console.warn(
|
|
`[opencode-local] \`opencode models\` returned no models; proceeding with the configured model "${model}".`,
|
|
);
|
|
return [{ id: model, label: model }];
|
|
}
|
|
|
|
if (!models.some((entry) => entry.id === model)) {
|
|
// `opencode models` reads a persistent models.dev cache. Long-lived runner
|
|
// hosts can therefore report a stale non-empty catalog even while the
|
|
// configured provider serves the model. Refresh once before treating a
|
|
// cached miss as authoritative; a successful refresh that still omits the
|
|
// model retains the strict availability rejection below.
|
|
try {
|
|
const refreshedModels = await refreshOpenCodeModelsCached({
|
|
command: input.command,
|
|
cwd: input.cwd,
|
|
env: input.env,
|
|
});
|
|
if (refreshedModels.some((entry) => entry.id === model)) {
|
|
return refreshedModels;
|
|
}
|
|
if (refreshedModels.length > 0) models = refreshedModels;
|
|
} catch (err) {
|
|
console.warn(
|
|
`[opencode-local] Model availability refresh failed for "${model}" (${
|
|
err instanceof Error ? err.message : String(err)
|
|
}); preserving the cached availability rejection.`,
|
|
);
|
|
}
|
|
|
|
const sample = models
|
|
.slice(0, 12)
|
|
.map((entry) => entry.id)
|
|
.join(", ");
|
|
throw new Error(
|
|
`Configured OpenCode model is unavailable: ${model}. Available models: ${sample}${models.length > 12 ? ", ..." : ""}`,
|
|
);
|
|
}
|
|
|
|
return models;
|
|
}
|
|
|
|
export async function listOpenCodeModels(): Promise<AdapterModel[]> {
|
|
try {
|
|
return await discoverOpenCodeModelsCached();
|
|
} catch {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
export function resetOpenCodeModelsCacheForTests() {
|
|
discoveryCache.clear();
|
|
}
|