Files
kilocode/packages/opencode/src/provider/models.ts
T
Johnny Eric Amancio 7ea50aac14 OpenCode v1.3.3 (#8790)
* tweak: use theme tokens for debug bar surface

* chore: update nix node_modules hashes

* feat(tui): add heap snapshot functionality for TUI and server (#19028)

* ci

* change model for changelog

* release: v1.3.2

* fix(opencode): skip typechecking generated models snapshot (#19018)

* Revert "fix(app): more startup efficiency (#18985)"

This reverts commit 98b3340cee.

* Revert "fix(app): startup efficiency (#18854)"

This reverts commit 546748a461.

* effectify Worktree service (#18679)

* fix: increase operations-per-run to 1000 and pin stale action to v10.2.0

The stale-issues workflow was hitting the default 30 operations limit,
preventing it from processing all 2900+ issues/PRs. Increased to 1000
to handle the full backlog. Also pinned to exact v10.2.0 for reproducibility.

* Add close-issues script and GitHub Action

- Create script/github/close-issues.ts to close stale issues after 60 days
- Add GitHub Action workflow to run daily at 2 AM
- Remove old stale-issues workflow to avoid conflicts

* Fix close-issues workflow permissions

- Add contents: read permission for checkout
- Use github.token instead of secrets.GITHUB_TOKEN

* Process issues sequentially to avoid rate limits

* Change issue close reason from not_planned to completed

* fix(opencode): avoid snapshotting files over 2MB (#19043)

* fix: provide merge context to beta conflict resolver (#19055)

* tweak: only spawn lsp servers for files in current instance (or cwd if instance is global) (#19058)

* fix: beta resolver typecheck + build smoke check (#19060)

* fix: unblock beta conflict recovery (#19068)

* electron: add createDirectory to open directory picker (#19071)

* electron: remove file extension from electron-store wrapper (#19082)

* app: pre-warm project globalSync state when navigate project via keybind (#19088)

* fix(app): move message navigation off cmd+arrow (#18728)

* Reapply "fix(app): startup efficiency (#18854)"

This reverts commit a379eb3867.

* Reapply "fix(app): more startup efficiency (#18985)"

This reverts commit cbe1337f24.

* fix(app): hash inline script for csp

* Revert "fix(app): startup efficiency"

* Reapply "fix(app): startup efficiency"

This reverts commit 898456a25c.

* fix(app): opencode web server url

* chore(app): markdown playground in storyboard

* chore(app): markdown playground in storyboard

* feat(core): initial implementation of syncing (#17814)

* chore: generate

* chore: bump modelcontextprotocol/sdk to 1.27.1 (#19064)

* chore: storybook tweaks

* feat: restore git-backed review modes with effectful git service (#18900)

* chore: generate

* chore: update nix node_modules hashes

* chore: cleanup

* chore: remove dead code for todoread tool (#19128)

* chore: storybook tweaks

* fix(opencode): classify ZlibError from Bun fetch as retryable instead of unknown (#19104)

Co-authored-by: Aiden Cline <63023139+rekram1-node@users.noreply.github.com>

* fix(task): respect agent permission config for todowrite tool (#19125)

* fix(app): agent normalization (#19169)

* fix: Windows e2e stability (CrossSpawnSpawner, snapshot isolation, session race guards) (#19163)

* fix+refactor(mcp): lifecycle tests, cancelPending fix, Effect migration (#19042)

* effectify Bus service: migrate to Effect PubSub + InstanceState (#18579)

* file: use Effect.cached for scan deduplication (#19164)

* ignore: update disavowed list (#19184)

* skill: use Effect.cached for load deduplication (#19165)

* chore: generate

* fix: bump gitlab-ai-provider to 5.3.3 for DWS tool approval support (#19185)

* test: restore 5 workers on Windows e2e (#19188)

* fix(opencode): image paste on Windows Terminal 1.25+ with kitty keyboard (#17674)

* chore: update nix node_modules hashes

* wip: zen

* wip: zen

* go: do not respect disabled zen models

* fix: ensure enterprise url is set properly during auth flow (#19212)

* revert: roll back git-backed review modes (#19295)

* chore: generate

* tui: bypass local SSE event streaming in worker (#19183)

* feat: embed WebUI in binary with proxy flags (#19299)

Co-authored-by: BlankParticle <blankparticle@gmail.com>

* release: v1.3.3

* refactor: kilo compat for v1.3.3

* fix: Typecheck issues

* fix(build): normalize backslashes in web UI bundle import paths

Replace backslashes with forward slashes in embedded web UI file import
paths to ensure correct module resolution on Windows.

* fix: Add mcp reconnect error handling

* chore(script): use forward slashes in web UI bundle export keys

Ensure embedded file map keys use POSIX-style paths so lookups are
consistent across platforms.

* chore: regenerate source links

---------

Co-authored-by: Jay V <air@live.ca>
Co-authored-by: opencode-agent[bot] <opencode-agent[bot]@users.noreply.github.com>
Co-authored-by: Dax <mail@thdxr.com>
Co-authored-by: Dax Raad <d@ironbay.co>
Co-authored-by: opencode <opencode@sst.dev>
Co-authored-by: Kit Langton <kit.langton@gmail.com>
Co-authored-by: Adam <2363879+adamdotdevin@users.noreply.github.com>
Co-authored-by: Luke Parker <10430890+Hona@users.noreply.github.com>
Co-authored-by: Aiden Cline <63023139+rekram1-node@users.noreply.github.com>
Co-authored-by: Brendan Allan <brendonovich@outlook.com>
Co-authored-by: Shoubhit Dash <shoubhit2005@gmail.com>
Co-authored-by: James Long <longster@gmail.com>
Co-authored-by: André Cruz <acruz@cloudflare.com>
Co-authored-by: Ariane Emory <97994360+ariane-emory@users.noreply.github.com>
Co-authored-by: Vladimir Glafirov <vglafirov@gitlab.com>
Co-authored-by: Frank <frank@anoma.ly>
Co-authored-by: BlankParticle <blankparticle@gmail.com>
Co-authored-by: Imanol Maiztegui <imanol.mzd@gmail.com>
2026-04-12 01:00:50 +02:00

255 lines
8.8 KiB
TypeScript

import { Global } from "../global"
import { Log } from "../util/log"
import path from "path"
import z from "zod"
import { Installation } from "../installation"
import { Flag } from "../flag/flag"
import { lazy } from "@/util/lazy"
import { Config } from "../config/config" // kilocode_change
import { ModelCache } from "./model-cache" // kilocode_change
import { Auth } from "../auth" // kilocode_change
import { AI_SDK_PROVIDERS, KILO_OPENROUTER_BASE, PROMPTS } from "@kilocode/kilo-gateway" // kilocode_change
import { Filesystem } from "../util/filesystem"
// Try to import bundled snapshot (generated at build time)
// Falls back to undefined in dev mode when snapshot doesn't exist
/* @ts-ignore */
// kilocode_change start
const normalizeKiloBaseURL = (baseURL: string | undefined, orgId: string | undefined): string | undefined => {
if (!baseURL) return undefined
const trimmed = baseURL.replace(/\/+$/, "")
if (orgId) {
if (trimmed.includes("/api/organizations/")) return trimmed
if (trimmed.endsWith("/api")) return `${trimmed}/organizations/${orgId}`
return `${trimmed}/api/organizations/${orgId}`
}
if (trimmed.includes("/openrouter")) return trimmed
if (trimmed.endsWith("/api")) return `${trimmed}/openrouter`
return `${trimmed}/api/openrouter`
}
export const Prompt = z.enum(PROMPTS)
export const AiSdkProvider = z.enum(AI_SDK_PROVIDERS)
// kilocode_change end
export namespace ModelsDev {
const log = Log.create({ service: "models.dev" })
const filepath = path.join(Global.Path.cache, "models.json")
export const Model = z.object({
id: z.string(),
name: z.string(),
family: z.string().optional(),
release_date: z.string(),
attachment: z.boolean(),
reasoning: z.boolean(),
temperature: z.boolean(),
tool_call: z.boolean(),
interleaved: z
.union([
z.literal(true),
z
.object({
field: z.enum(["reasoning_content", "reasoning_details"]),
})
.strict(),
])
.optional(),
cost: z
.object({
input: z.number(),
output: z.number(),
cache_read: z.number().optional(),
cache_write: z.number().optional(),
context_over_200k: z
.object({
input: z.number(),
output: z.number(),
cache_read: z.number().optional(),
cache_write: z.number().optional(),
})
.optional(),
})
.optional(),
limit: z.object({
context: z.number(),
input: z.number().optional(),
output: z.number(),
}),
modalities: z
.object({
input: z.array(z.enum(["text", "audio", "image", "video", "pdf"])),
output: z.array(z.enum(["text", "audio", "image", "video", "pdf"])),
})
.optional(),
// kilocode_change start
recommendedIndex: z.number().optional(),
prompt: Prompt.optional().catch(undefined),
isFree: z.boolean().optional(),
ai_sdk_provider: AiSdkProvider.optional().catch(undefined),
// kilocode_change end
experimental: z.boolean().optional(),
status: z.enum(["alpha", "beta", "deprecated"]).optional(),
options: z.record(z.string(), z.any()),
headers: z.record(z.string(), z.string()).optional(),
provider: z.object({ npm: z.string().optional(), api: z.string().optional() }).optional(),
variants: z.record(z.string(), z.record(z.string(), z.any())).optional(),
})
export type Model = z.infer<typeof Model>
export const Provider = z.object({
api: z.string().optional(),
name: z.string(),
env: z.array(z.string()),
id: z.string(),
npm: z.string().optional(),
models: z.record(z.string(), Model),
})
export type Provider = z.infer<typeof Provider>
function url() {
return Flag.KILO_MODELS_URL || "https://models.dev"
}
export const Data = lazy(async () => {
const result = await Filesystem.readJson(Flag.KILO_MODELS_PATH ?? filepath).catch(() => {})
if (result) return result
// @ts-ignore
const snapshot = await import("./models-snapshot.js")
.then((m) => m.snapshot as Record<string, unknown>)
.catch(() => undefined)
if (snapshot) return snapshot
if (Flag.KILO_DISABLE_MODELS_FETCH) return {}
const json = await fetch(`${url()}/api.json`).then((x) => x.text())
return JSON.parse(json)
})
export async function get() {
const result = await Data()
// kilocode_change start
const providers = result as Record<string, Provider>
if (providers["kilo"]) {
delete providers["kilo"]
}
// Inject kilo provider with dynamic model fetching
// Skip injection entirely when enabled_providers is set and doesn't include "kilo",
// or when "kilo" is in disabled_providers. This prevents unnecessary network calls
// to the Kilo API for teams using only their own providers (e.g. LiteLLM).
const config = await Config.get()
const disabled = new Set(config.disabled_providers ?? [])
const enabled = config.enabled_providers ? new Set(config.enabled_providers) : null
const kiloAllowed = (!enabled || enabled.has("kilo")) && !disabled.has("kilo")
if (kiloAllowed && !providers["kilo"]) {
const kiloOptions = config.provider?.kilo?.options
// resolve org ID from auth (OAuth accountId) not just config
const kiloAuth = await Auth.get("kilo")
const kiloOrgId =
kiloOptions?.kilocodeOrganizationId ?? (kiloAuth?.type === "oauth" ? kiloAuth.accountId : undefined)
const normalizedBaseURL = normalizeKiloBaseURL(kiloOptions?.baseURL, kiloOrgId)
const kiloFetchOptions = {
...(normalizedBaseURL ? { baseURL: normalizedBaseURL } : {}),
...(kiloOrgId ? { kilocodeOrganizationId: kiloOrgId } : {}),
}
const defaultBaseURL = kiloOrgId
? `https://api.kilo.ai/api/organizations/${kiloOrgId}`
: "https://api.kilo.ai/api/openrouter"
const providerBaseURL = normalizedBaseURL ?? defaultBaseURL
const ensureTrailingSlash = (value: string): string => (value.endsWith("/") ? value : `${value}/`)
const apertisConfig = config.provider?.apertis?.options
const apertisBaseURL = apertisConfig?.baseURL ?? "https://api.apertis.ai/v1"
const apertisFetchOptions = {
...(apertisConfig?.baseURL ? { baseURL: apertisConfig.baseURL } : {}),
}
const [kiloModels, apertisModels] = await Promise.all([
ModelCache.fetch("kilo", kiloFetchOptions).catch(() => ({})),
!providers["apertis"]
? ModelCache.fetch("apertis", apertisFetchOptions).catch(() => ({}))
: Promise.resolve(null),
])
providers["kilo"] = {
id: "kilo",
name: "Kilo Gateway",
env: ["KILO_API_KEY"],
api: ensureTrailingSlash(KILO_OPENROUTER_BASE),
npm: "@kilocode/kilo-gateway",
models: kiloModels,
}
if (Object.keys(kiloModels).length === 0) {
ModelCache.refresh("kilo", kiloFetchOptions).catch(() => {})
}
if (!providers["apertis"] && apertisModels !== null) {
providers["apertis"] = {
id: "apertis",
name: "Apertis",
env: ["APERTIS_API_KEY"],
api: apertisBaseURL,
npm: "@ai-sdk/openai-compatible",
models: apertisModels,
}
if (Object.keys(apertisModels).length === 0) {
ModelCache.refresh("apertis", apertisFetchOptions).catch(() => {})
}
}
} else if (!providers["apertis"]) {
const apertisConfig = config.provider?.apertis?.options
const apertisBaseURL = apertisConfig?.baseURL ?? "https://api.apertis.ai/v1"
const apertisFetchOptions = {
...(apertisConfig?.baseURL ? { baseURL: apertisConfig.baseURL } : {}),
}
const apertisModels = await ModelCache.fetch("apertis", apertisFetchOptions).catch(() => ({}))
providers["apertis"] = {
id: "apertis",
name: "Apertis",
env: ["APERTIS_API_KEY"],
api: apertisBaseURL,
npm: "@ai-sdk/openai-compatible",
models: apertisModels,
}
if (Object.keys(apertisModels).length === 0) {
ModelCache.refresh("apertis", apertisFetchOptions).catch(() => {})
}
}
return providers
// kilocode_change end
}
export async function refresh() {
const result = await fetch(`${url()}/api.json`, {
headers: {
"User-Agent": Installation.USER_AGENT,
},
signal: AbortSignal.timeout(10 * 1000),
}).catch((e) => {
log.error("Failed to fetch models.dev", {
error: e,
})
})
if (result && result.ok) {
await Filesystem.write(filepath, await result.text())
ModelsDev.Data.reset()
}
}
}
if (!Flag.KILO_DISABLE_MODELS_FETCH && !process.argv.includes("--get-yargs-completions")) {
ModelsDev.refresh()
setInterval(
async () => {
await ModelsDev.refresh()
},
60 * 1000 * 60,
).unref()
}