Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 78 additions & 8 deletions packages/core/src/models-dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,31 @@ export const Event = {

declare const OPENCODE_MODELS_DEV: Record<string, Provider> | undefined

// altimate_change start — a bundled catalogue the host process hands over at runtime
// A build that already ships the catalogue in its own module passes a loader for it here rather than defining
// OPENCODE_MODELS_DEV, which would embed a second copy of it in every bundle of the binary.
type SnapshotLoader = () => Promise<Record<string, Provider> | undefined>
let hostSnapshot: SnapshotLoader | undefined
export function provideSnapshot(load: SnapshotLoader | undefined) {
hostSnapshot = load
}
// altimate_change end

// altimate_change start — only a catalogue is served or cached
// A proxy or captive portal can answer 200 with JSON that isn't one (`{"error": ...}`). Served, or read back
// from the cache on every start, it failed plugin boot, which reads `id`, `env` and `models` on each provider.
// The provider entries shaped that way, or undefined when there are none (the fork's loader keeps the same rule).
function catalogOf(value: unknown): Record<string, Provider> | undefined {
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined
const entries = Object.entries(value).filter(([, entry]) => {
if (!entry || typeof entry !== "object" || Array.isArray(entry)) return false
const { id, env, models } = entry as Record<string, unknown>
return typeof id === "string" && Array.isArray(env) && !!models && typeof models === "object" && !Array.isArray(models)
Comment thread
ralphstodomingo marked this conversation as resolved.
Resolved
})
return entries.length > 0 ? (Object.fromEntries(entries) as Record<string, Provider>) : undefined
}
// altimate_change end

export interface Interface {
readonly get: () => Effect.Effect<Record<string, Provider>>
readonly refresh: (force?: boolean) => Effect.Effect<void>
Expand Down Expand Up @@ -174,15 +199,40 @@ export const layer = Layer.effect(
}
return Effect.succeed(undefined)
}),
Effect.map((v) => v as Record<string, Provider> | undefined),
// altimate_change start — a cache that isn't a catalogue is dropped like a corrupt one
Effect.flatMap((v) => {
if (v === undefined) return Effect.succeed(undefined)
const catalogue = catalogOf(v)
if (catalogue || Flag.OPENCODE_MODELS_PATH !== undefined) return Effect.succeed(catalogue)
return fs.remove(filepath, { force: true }).pipe(Effect.ignore, Effect.as(undefined))
}),
// altimate_change end
)

const loadSnapshot = Effect.sync(() =>
typeof OPENCODE_MODELS_DEV === "undefined" ? undefined : OPENCODE_MODELS_DEV,
)
// altimate_change start — with no build-time snapshot, the host's (provideSnapshot)
const loadSnapshot = Effect.promise(async () => {
if (typeof OPENCODE_MODELS_DEV !== "undefined") return OPENCODE_MODELS_DEV
if (!hostSnapshot) return undefined
// A loader that throws, synchronously or not, counts as no snapshot.
try {
return await hostSnapshot()
} catch {
return undefined
}
})
// altimate_change end

const fetchAndWrite = Effect.fn("ModelsDev.fetchAndWrite")(function* () {
// altimate_change start — fetch and check, then write, as separate steps
// Only a catalogue (`catalogOf`) is written to the cache. A failed write is logged and the catalogue still
// returned, so `populate` serves it and `refresh` still invalidates (the next load fetches it again).
const fetchCatalogue = Effect.fn("ModelsDev.fetchCatalogue")(function* () {
const text = yield* fetchApi()
const catalogue = catalogOf(yield* Effect.try({ try: () => JSON.parse(text) as unknown, catch: (error) => error }))
if (!catalogue) return yield* Effect.fail(new Error("models.dev answered with JSON that is not a catalogue"))
return { text, catalogue }
})

const writeCache = Effect.fn("ModelsDev.writeCache")(function* (text: string) {
const tempfile = `${filepath}.${process.pid}.${Date.now()}.tmp`
yield* fs.writeWithDirs(tempfile, text).pipe(
Effect.andThen(fs.rename(tempfile, filepath)),
Expand All @@ -193,23 +243,43 @@ export const layer = Layer.effect(
}),
),
)
return text
})

const fetchAndWrite = Effect.fn("ModelsDev.fetchAndWrite")(function* () {
const { text, catalogue } = yield* fetchCatalogue()
yield* writeCache(text).pipe(
Effect.catch((error) => Effect.logWarning("Failed to write the models cache; using the catalogue anyway", { error })),
)
return catalogue
Comment thread
ralphstodomingo marked this conversation as resolved.
Resolved
})
// altimate_change end

const populate = Effect.gen(function* () {
const fromDisk = yield* loadFromDisk
if (fromDisk) return fromDisk
const snapshot = yield* loadSnapshot
if (snapshot) return snapshot
if (Flag.OPENCODE_DISABLE_MODELS_FETCH) return {}
// Flock is cross-process: concurrent opencode CLIs can race on this cache file.
const text = yield* Effect.scoped(
// altimate_change start — a failed first load serves an empty catalogue instead of dying
// Plugin boot waits on this load, and agent state and every prompt wait on plugin boot, so
// dying here failed all of them on a machine with no cache that could not reach models.dev.
// The empty catalogue lasts until a refresh succeeds: `refresh` invalidates it and publishes
// `Refreshed`, and the models-dev plugin reloads.
const loaded = yield* Effect.scoped(
Effect.gen(function* () {
yield* Flock.effect(lockKey)
return yield* fetchAndWrite()
}),
).pipe(
Effect.catch((error) =>
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
Effect.logError("Failed to load models.dev; serving an empty catalogue until a refresh succeeds", {
error,
}).pipe(Effect.as(undefined)),
),
)
return JSON.parse(text) as Record<string, Provider>
return loaded ?? {}
Comment thread
ralphstodomingo marked this conversation as resolved.
Resolved
// altimate_change end
}).pipe(Effect.withSpan("ModelsDev.populate"), Effect.orDie)

const [cachedGet, invalidate] = yield* Effect.cachedInvalidateWithTTL(populate, Duration.infinity)
Expand Down
194 changes: 183 additions & 11 deletions packages/core/test/models.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { Global } from "@opencode-ai/core/global"
import { ModelsDev } from "@opencode-ai/core/models-dev"
import { EventV2 } from "@opencode-ai/core/event"
import { it } from "./lib/effect"
import { readFile, rm, writeFile, utimes, mkdir } from "fs/promises"
import { chmod, readFile, rm, stat, writeFile, utimes, mkdir } from "fs/promises"
import path from "path"

// test/preload.ts pins OPENCODE_MODELS_PATH to a fixture so other tests can
Expand Down Expand Up @@ -153,28 +153,200 @@ describe("ModelsDev Service", () => {
}),
)

// Fetching is on only inside `eff`. `provided` builds the layer before that, with fetching off, so the
// layer's eager background refresh never starts and every request a test sees is the one under test.
const withFetch = <A, E, R>(eff: Effect.Effect<A, E, R>) =>
Comment thread
ralphstodomingo marked this conversation as resolved.
Resolved
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
Effect.acquireUseRelease(
Effect.sync(() => {
Flag.OPENCODE_DISABLE_MODELS_FETCH = false
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
}),
() => eff,
// Back to this suite's value (beforeAll); afterAll restores the original.
() =>
Effect.sync(() => {
Flag.OPENCODE_DISABLE_MODELS_FETCH = true
}),
)
const getWithFetch = (state: Ref.Ref<MockState>) =>
provided(state, withFetch(ModelsDev.Service.use((s) => s.get())))
const cacheText = Effect.promise(() => readFile(cacheFile, "utf8").catch(() => "absent"))
const withHostSnapshot = <A, E, R>(load: Parameters<typeof ModelsDev.provideSnapshot>[0], eff: Effect.Effect<A, E, R>) =>
Effect.acquireUseRelease(
Effect.sync(() => ModelsDev.provideSnapshot(load)),
() => eff,
() => Effect.sync(() => ModelsDev.provideSnapshot(undefined)),
)

it.live("get() recovers from a corrupted cache file by fetching a fresh catalog", () =>
Effect.gen(function* () {
yield* writeCacheText("{")
const state = yield* Ref.make({ ...initialState, body: JSON.stringify(fixture2) })
expect(yield* getWithFetch(state)).toEqual(fixture2)
expect(yield* cacheText).toBe(JSON.stringify(fixture2))
expect((yield* Ref.get(state)).calls.length).toBe(1)
}),
)

it.live("get() serves an empty catalogue when the first fetch fails", () =>
Effect.gen(function* () {
const state = yield* Ref.make({ ...initialState, status: 503, body: "unavailable" })
expect(yield* getWithFetch(state)).toEqual({})
expect((yield* Ref.get(state)).calls.length).toBeGreaterThanOrEqual(1)
expect(yield* cacheText).toBe("absent")
}),
)

it.live("get() serves an empty catalogue when models.dev answers with a body that is not JSON", () =>
Effect.gen(function* () {
const state = yield* Ref.make({ ...initialState, body: "<html>sign in to this network</html>" })
expect(yield* getWithFetch(state)).toEqual({})
expect(yield* cacheText).toBe("absent")
}),
)

it.live("JSON that isn't a catalogue is neither served nor cached", () =>
Effect.gen(function* () {
const state = yield* Ref.make({ ...initialState, body: JSON.stringify({ error: "blocked by proxy" }) })
expect(yield* getWithFetch(state)).toEqual({})
expect(yield* cacheText).toBe("absent")
}),
)

it.live("a cache file that is JSON but not a catalogue is dropped, not served", () =>
Effect.gen(function* () {
yield* writeCache({ error: "blocked by proxy" })
const state = yield* Ref.make(initialState)
const result = yield* provided(
state,
ModelsDev.Service.use((s) => s.get()),
)
expect(result).toEqual({}) // fetching is off here, and there is no snapshot
expect(yield* cacheText).toBe("absent")
}),
)

it.live("a refresh that answers with something other than a catalogue leaves the cache as it was", () =>
Effect.gen(function* () {
yield* writeCache(fixture)
const state = yield* Ref.make({ ...initialState, body: JSON.stringify({ error: "blocked by proxy" }) })
const result = yield* provided(
state,
Effect.gen(function* () {
const svc = yield* ModelsDev.Service
yield* svc.refresh(true)
return yield* svc.get()
}),
)
expect(result).toEqual(fixture)
expect(yield* cacheText).toBe(JSON.stringify(fixture))
}),
)

it.live("provider entries not shaped like one are left out", () =>
Effect.gen(function* () {
yield* writeCache({ ...fixture, broken: { id: "broken", name: "Broken" }, note: "not a provider" })
const state = yield* Ref.make(initialState)
const result = yield* provided(
state,
ModelsDev.Service.use((s) => s.get()),
)
expect(result).toEqual(fixture)
}),
)

// A read-only folder blocks the write only where its mode is enforced: not on Windows, and not for root.
const modeBlocksWrites = process.platform !== "win32" && process.getuid?.() !== 0
;(modeBlocksWrites ? it.live : it.live.skip)("a fetched catalogue is served even when the cache can't be written", () =>
Effect.gen(function* () {
const state = yield* Ref.make(initialState)
const result = yield* Effect.acquireUseRelease(
Effect.sync(() => {
Flag.OPENCODE_DISABLE_MODELS_FETCH = false
Effect.promise(async () => {
await mkdir(Global.Path.cache, { recursive: true })
const { mode } = await stat(Global.Path.cache)
await chmod(Global.Path.cache, 0o555)
Comment thread
ralphstodomingo marked this conversation as resolved.
Resolved
Comment thread
ralphstodomingo marked this conversation as resolved.
Resolved
return mode
}),
() => getWithFetch(state),
(mode) => Effect.promise(() => chmod(Global.Path.cache, mode)),
)
expect(result).toEqual(fixture)
expect(yield* cacheText).toBe("absent")
}),
)

;(modeBlocksWrites ? it.live : it.live.skip)("a refresh fills the empty catalogue even when the cache can't be written", () =>
Effect.gen(function* () {
const state = yield* Ref.make({ ...initialState, status: 503, body: "unavailable" })
const result = yield* Effect.acquireUseRelease(
Effect.promise(async () => {
Comment thread
ralphstodomingo marked this conversation as resolved.
Resolved
await mkdir(Global.Path.cache, { recursive: true })
const { mode } = await stat(Global.Path.cache)
await chmod(Global.Path.cache, 0o555)
return mode
}),
() =>
provided(
state,
ModelsDev.Service.use((s) => s.get()),
withFetch(
Effect.gen(function* () {
const svc = yield* ModelsDev.Service
const before = yield* svc.get()
yield* Ref.update(state, (s) => ({ ...s, status: 200, body: JSON.stringify(fixture) }))
yield* svc.refresh(true)
return { before, after: yield* svc.get() }
}),
),
),
() =>
Effect.sync(() => {
Flag.OPENCODE_DISABLE_MODELS_FETCH = true
(mode) => Effect.promise(() => chmod(Global.Path.cache, mode)),
)
expect(result.before).toEqual({})
expect(result.after).toEqual(fixture)
expect(yield* cacheText).toBe("absent")
}),
)

it.live("a refresh that succeeds replaces the empty catalogue served after a failed fetch", () =>
Effect.gen(function* () {
const state = yield* Ref.make({ ...initialState, status: 503, body: "unavailable" })
const result = yield* provided(
state,
withFetch(
Effect.gen(function* () {
const svc = yield* ModelsDev.Service
const before = yield* svc.get()
yield* Ref.update(state, (s) => ({ ...s, status: 200, body: JSON.stringify(fixture) }))
yield* svc.refresh(true)
const after = yield* svc.get()
return { before, after }
}),
),
)
expect(result).toEqual(fixture2)
expect(yield* Effect.promise(() => readFile(cacheFile, "utf8"))).toBe(JSON.stringify(fixture2))
const final = yield* Ref.get(state)
expect(final.calls.length).toBe(1)
expect(result.before).toEqual({})
expect(result.after).toEqual(fixture)
}),
)

it.live("with no cache, get() serves the host's catalogue (provideSnapshot) without a fetch", () =>
Effect.gen(function* () {
const state = yield* Ref.make({ ...initialState, status: 503, body: "unavailable" })
expect(yield* withHostSnapshot(async () => fixture2, getWithFetch(state))).toEqual(fixture2)
expect((yield* Ref.get(state)).calls).toEqual([])
}),
)

it.live("a host catalogue that fails to load, or whose loader throws, counts as none: get() fetches", () =>
Effect.gen(function* () {
for (const load of [
() => Promise.reject(new Error("no snapshot module")),
() => {
throw new Error("no snapshot module")
},
]) {
yield* Effect.promise(() => rm(cacheFile, { force: true }))
const state = yield* Ref.make(initialState)
expect(yield* withHostSnapshot(load, getWithFetch(state))).toEqual(fixture)
expect((yield* Ref.get(state)).calls.length).toBe(1)
}
}),
)

Expand Down
13 changes: 13 additions & 0 deletions packages/opencode/src/altimate/models-snapshot-host.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// altimate_change - new file
//
// Hands core's models loader (packages/core/src/models-dev.ts) the catalogue this build already ships for the
// fork's loader (src/provider/models-snapshot.ts, regenerated by script/build.ts). Without it, core has no
// bundled catalogue, and a machine with no models cache that can't reach models.dev fails every request.
// Reusing the module keeps one copy of the catalogue per bundle; a build-time define would add another.
// Imported first by each entry point that runs the server (src/index.ts, src/cli/tui/worker.ts).
import { ModelsDev } from "@opencode-ai/core/models-dev"

ModelsDev.provideSnapshot(() =>
// @ts-ignore — the generated module's literal type is too large to check; the fork's loader imports it the same way
import("../provider/models-snapshot.js").then((m) => m.snapshot as unknown as Record<string, ModelsDev.Provider>),
)
3 changes: 3 additions & 0 deletions packages/opencode/src/cli/tui/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
// rationale (this is the systemic fix for the log-flood class that regresses on every upstream merge).
import "./worker-console-guard"
// altimate_change end
// altimate_change start — core's models loader reads the catalogue this build already ships
import "@/altimate/models-snapshot-host"
// altimate_change end
import { Server } from "@/server/server"
import { InstanceRuntime } from "@/project/instance-runtime"
import { Rpc } from "@/util/rpc"
Expand Down
3 changes: 3 additions & 0 deletions packages/opencode/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ import { hideBin } from "yargs/helpers"
// altimate_change start - stdin tool arguments
import { foldStdinArgs } from "./altimate/tool-cli/argv"
// altimate_change end
// altimate_change start — core's models loader reads the catalogue this build already ships
import "./altimate/models-snapshot-host"
// altimate_change end
import { RunCommand } from "./cli/cmd/run"
import { GenerateCommand } from "./cli/cmd/generate"
import { ConsoleCommand } from "./cli/cmd/account"
Expand Down
Loading
Loading