mirror of
https://github.com/anomalyco/opencode.git
synced 2026-08-17 12:58:34 -04:00
Compare commits
19 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| edebe43a0d | |||
| f07dc20b7c | |||
| a8eb7717ec | |||
| d914b688ab | |||
| 6c9ba69106 | |||
| ef937431c4 | |||
| e11c56d518 | |||
| 0e7586a009 | |||
| f14724dfb1 | |||
| cc53db4406 | |||
| fa055143ea | |||
| 875b28658f | |||
| 0e022036fb | |||
| f0ae3b9569 | |||
| 3b5837d354 | |||
| e1ff217e44 | |||
| ecda3779fa | |||
| a3e69a967b | |||
| 6359623e24 |
@@ -188,12 +188,15 @@
|
||||
"@types/bun": "catalog:",
|
||||
"@typescript/native-preview": "catalog:",
|
||||
"effect": "catalog:",
|
||||
"solid-js": "catalog:",
|
||||
},
|
||||
"peerDependencies": {
|
||||
"effect": "4.0.0-beta.101",
|
||||
"solid-js": ">=1.9.0",
|
||||
},
|
||||
"optionalPeers": [
|
||||
"effect",
|
||||
"solid-js",
|
||||
],
|
||||
},
|
||||
"packages/codemode": {
|
||||
@@ -612,6 +615,7 @@
|
||||
"@tsconfig/bun": "catalog:",
|
||||
"@types/bun": "catalog:",
|
||||
"@typescript/native-preview": "catalog:",
|
||||
"prettier": "3.6.2",
|
||||
"typescript": "catalog:",
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1,18 +1,6 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import type { OpenCodeEvent } from "@opencode-ai/client/promise"
|
||||
import { adaptServerEvent, coalesceServerEvents, resumeStreamAfterPageShow } from "./server-sdk"
|
||||
|
||||
describe("resumeStreamAfterPageShow", () => {
|
||||
test("restarts a stream only after a back-forward cache restore", () => {
|
||||
let starts = 0
|
||||
const start = () => starts++
|
||||
|
||||
resumeStreamAfterPageShow({ persisted: false } as PageTransitionEvent, start)
|
||||
resumeStreamAfterPageShow({ persisted: true } as PageTransitionEvent, start)
|
||||
|
||||
expect(starts).toBe(1)
|
||||
})
|
||||
})
|
||||
import { adaptServerEvent } from "./server-sdk"
|
||||
|
||||
describe("adaptServerEvent", () => {
|
||||
test("preserves current permission requests", () => {
|
||||
@@ -43,48 +31,3 @@ describe("adaptServerEvent", () => {
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("current event buffering", () => {
|
||||
const delta = (id: string, value: string, ordinal = 0) =>
|
||||
adaptServerEvent({
|
||||
id,
|
||||
created: 1,
|
||||
type: "session.text.delta",
|
||||
location: { directory: "/repo" },
|
||||
data: { sessionID: "ses", assistantMessageID: "msg", ordinal, delta: value },
|
||||
} as OpenCodeEvent)
|
||||
|
||||
test("merges adjacent text deltas for the same message and ordinal", () => {
|
||||
const result = coalesceServerEvents([delta("evt_1", "hello "), delta("evt_2", "world")])
|
||||
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0]?.current).toMatchObject({ id: "evt_2", data: { delta: "hello world" } })
|
||||
expect(result[0]?.properties).toMatchObject({ delta: "hello world" })
|
||||
})
|
||||
|
||||
test("coalesces current tool input deltas by tool ID", () => {
|
||||
const current = (eventID: string, id: string, delta: string) =>
|
||||
adaptServerEvent({
|
||||
id: eventID,
|
||||
created: 1,
|
||||
type: "session.tool.input.delta",
|
||||
location: { directory: "/repo" },
|
||||
data: { sessionID: "ses", assistantMessageID: "msg", id, delta },
|
||||
} as OpenCodeEvent)
|
||||
const result = coalesceServerEvents([
|
||||
current("evt_1", "call_1", "{"),
|
||||
current("evt_2", "call_1", "}"),
|
||||
current("evt_3", "call_2", "[]"),
|
||||
])
|
||||
|
||||
expect(result).toHaveLength(2)
|
||||
expect(result[0]?.current).toMatchObject({ id: "evt_2", data: { id: "call_1", delta: "{}" } })
|
||||
expect(result[1]?.current).toMatchObject({ id: "evt_3", data: { id: "call_2", delta: "[]" } })
|
||||
})
|
||||
|
||||
test("preserves boundaries between distinct delta streams", () => {
|
||||
const events = [delta("evt_1", "a"), delta("evt_2", "b", 1), delta("evt_3", "c")]
|
||||
|
||||
expect(coalesceServerEvents(events).map((event) => event.current?.id)).toEqual(["evt_1", "evt_2", "evt_3"])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import type { OpenCodeEvent } from "@opencode-ai/client/promise"
|
||||
import { createClientConnection, type ClientConnectionStatus } from "@opencode-ai/client/solid"
|
||||
import type { Event } from "@/types"
|
||||
import { createGlobalEmitter } from "@solid-primitives/event-bus"
|
||||
import { makeEventListener } from "@solid-primitives/event-listener"
|
||||
import { type Accessor, batch, onCleanup, onMount } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { type Accessor, onCleanup } from "solid-js"
|
||||
import { createApiForServer, type ServerApi } from "@/utils/server"
|
||||
import { usePlatform } from "./platform"
|
||||
import { ServerConnection } from "./servers"
|
||||
@@ -12,78 +11,15 @@ import { ServerScope } from "@/utils/server-scope"
|
||||
import { useServer } from "./server"
|
||||
|
||||
export type ServerEvent = Event & { id?: string; current?: OpenCodeEvent }
|
||||
type ServerEventMap = { [Type in ServerEvent["type"]]: Extract<ServerEvent, { type: Type }> }
|
||||
type CurrentDelta = Extract<
|
||||
OpenCodeEvent,
|
||||
{ type: "session.text.delta" | "session.reasoning.delta" | "session.tool.input.delta" | "session.compaction.delta" }
|
||||
>
|
||||
|
||||
export function adaptServerEvent(event: OpenCodeEvent): ServerEvent {
|
||||
return { id: event.id, type: event.type, properties: event.data, current: event } as ServerEvent
|
||||
}
|
||||
|
||||
export function coalesceServerEvents(events: ServerEvent[]) {
|
||||
const output: ServerEvent[] = []
|
||||
events.forEach((event) => {
|
||||
const current = currentDelta(event.current)
|
||||
if (current) {
|
||||
const previous = output[output.length - 1]
|
||||
const prior = currentDelta(previous?.current)
|
||||
if (
|
||||
previous &&
|
||||
prior &&
|
||||
prior.location?.directory === current.location?.directory &&
|
||||
currentDeltaKey(prior) === currentDeltaKey(current)
|
||||
) {
|
||||
const fragment = currentDeltaFragment(prior) + currentDeltaFragment(current)
|
||||
const data =
|
||||
current.type === "session.compaction.delta"
|
||||
? { ...current.data, text: fragment }
|
||||
: { ...current.data, delta: fragment }
|
||||
output[output.length - 1] = {
|
||||
...event,
|
||||
properties: data,
|
||||
current: { ...current, data } as CurrentDelta,
|
||||
} as ServerEvent
|
||||
return
|
||||
}
|
||||
output.push(event)
|
||||
return
|
||||
}
|
||||
output.push(event)
|
||||
})
|
||||
return output
|
||||
}
|
||||
|
||||
function currentDelta(event: OpenCodeEvent | undefined): CurrentDelta | undefined {
|
||||
if (
|
||||
event?.type === "session.text.delta" ||
|
||||
event?.type === "session.reasoning.delta" ||
|
||||
event?.type === "session.tool.input.delta" ||
|
||||
event?.type === "session.compaction.delta"
|
||||
)
|
||||
return event
|
||||
}
|
||||
|
||||
function currentDeltaKey(event: CurrentDelta) {
|
||||
if (event.type === "session.tool.input.delta")
|
||||
return `${event.type}:${event.data.sessionID}:${event.data.assistantMessageID}:${event.data.id}`
|
||||
if (event.type === "session.compaction.delta") return `${event.type}:${event.data.sessionID}`
|
||||
return `${event.type}:${event.data.sessionID}:${event.data.assistantMessageID}:${event.data.ordinal}`
|
||||
}
|
||||
|
||||
function currentDeltaFragment(event: CurrentDelta) {
|
||||
return event.type === "session.compaction.delta" ? event.data.text : event.data.delta
|
||||
}
|
||||
|
||||
export function resumeStreamAfterPageShow(event: PageTransitionEvent, start: () => unknown) {
|
||||
if (!event.persisted) return
|
||||
start()
|
||||
}
|
||||
|
||||
type ServerEventMap = { [Type in ServerEvent["type"]]: Extract<ServerEvent, { type: Type }> }
|
||||
type ServerEventEmitter = ReturnType<typeof createGlobalEmitter<ServerEventMap>>
|
||||
type ServerLocationEventEmitter = ReturnType<typeof createGlobalEmitter<{ [directory: string]: ServerEvent }>>
|
||||
export type ServerConnectionStatus = "connecting" | "connected" | "reconnecting"
|
||||
export type ServerConnectionStatus = ClientConnectionStatus
|
||||
type ServerSDKBase = {
|
||||
server: ServerConnection.Any
|
||||
scope: ServerScope
|
||||
@@ -105,227 +41,38 @@ type ServerSDKBase = {
|
||||
|
||||
function createServerSdkContextBase(server: ServerConnection.Any, scope: ServerScope): ServerSDKBase {
|
||||
const platform = usePlatform()
|
||||
const abort = new AbortController()
|
||||
|
||||
const eventFetch = (() => {
|
||||
if (!platform.fetch || !server) return
|
||||
try {
|
||||
const url = new URL(server.http.url)
|
||||
const loopback = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "::1"
|
||||
if (url.protocol === "http:" && !loopback) return platform.fetch
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
})()
|
||||
|
||||
const eventApi = createApiForServer({ server: server.http, fetch: eventFetch })
|
||||
const api = createApiForServer({ server: server.http, fetch: platform.fetch })
|
||||
const emitter = createGlobalEmitter<ServerEventMap>()
|
||||
const locations = createGlobalEmitter<{ [directory: string]: ServerEvent }>()
|
||||
|
||||
const FLUSH_FRAME_MS = 16
|
||||
const STREAM_YIELD_MS = 8
|
||||
const CONNECT_TIMEOUT_MS = 2_000
|
||||
const RECONNECT_DELAY_MS = 1_000
|
||||
|
||||
let queue: ServerEvent[] = []
|
||||
let buffer: ServerEvent[] = []
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
let last = 0
|
||||
|
||||
function flush() {
|
||||
if (timer) clearTimeout(timer)
|
||||
timer = undefined
|
||||
|
||||
if (queue.length === 0) return
|
||||
|
||||
const events = queue
|
||||
queue = buffer
|
||||
buffer = events
|
||||
queue.length = 0
|
||||
|
||||
last = Date.now()
|
||||
const output = coalesceServerEvents(events)
|
||||
batch(() => {
|
||||
output.forEach((event) => {
|
||||
emitter.emit(event.type, event)
|
||||
const directory = event.current?.location?.directory
|
||||
if (directory) locations.emit(directory, event)
|
||||
})
|
||||
})
|
||||
|
||||
buffer.length = 0
|
||||
}
|
||||
|
||||
function schedule() {
|
||||
if (timer) return
|
||||
const elapsed = Date.now() - last
|
||||
timer = setTimeout(flush, Math.max(0, FLUSH_FRAME_MS - elapsed))
|
||||
}
|
||||
|
||||
function publish(event: OpenCodeEvent) {
|
||||
queue.push(adaptServerEvent(event))
|
||||
schedule()
|
||||
}
|
||||
|
||||
function wait(delay: number, signal: AbortSignal) {
|
||||
return new Promise<void>((resolve) => {
|
||||
const timer = setTimeout(done, delay)
|
||||
signal.addEventListener("abort", done, { once: true })
|
||||
function done() {
|
||||
clearTimeout(timer)
|
||||
signal.removeEventListener("abort", done)
|
||||
resolve()
|
||||
}
|
||||
})
|
||||
}
|
||||
let attempt: AbortController | undefined
|
||||
let run: Promise<void> | undefined
|
||||
let started = false
|
||||
let generation = 0
|
||||
const [connection, setConnection] = createStore<{
|
||||
status: ServerConnectionStatus
|
||||
attempt: number
|
||||
error?: string
|
||||
}>({ status: "connecting", attempt: 0 })
|
||||
|
||||
async function connect(signal: AbortSignal): Promise<{ error: unknown; connectedAt: number | undefined }> {
|
||||
let connectedAt: number | undefined
|
||||
|
||||
// Bound the initial handshake and tie this request to the stream lifetime.
|
||||
const request = new AbortController()
|
||||
const cancel = () => request.abort(signal.reason)
|
||||
const timeout = setTimeout(() => request.abort(new Error("Timed out connecting to server")), CONNECT_TIMEOUT_MS)
|
||||
signal.addEventListener("abort", cancel, { once: true })
|
||||
|
||||
try {
|
||||
// Open the event stream and validate its initial handshake.
|
||||
const iterator = eventApi.event.subscribe({ signal: request.signal })[Symbol.asyncIterator]()
|
||||
const first = await iterator.next()
|
||||
|
||||
if (signal.aborted) return { error: undefined, connectedAt }
|
||||
if (first.done) {
|
||||
const error =
|
||||
request.signal.reason instanceof Error ? request.signal.reason : new Error("Event stream disconnected")
|
||||
return { error, connectedAt }
|
||||
}
|
||||
if (first.value.type !== "server.connected")
|
||||
return { error: new Error("Event stream did not start with server.connected"), connectedAt }
|
||||
|
||||
// Publish the connected state before forwarding live events.
|
||||
clearTimeout(timeout)
|
||||
publish(first.value)
|
||||
connectedAt = Date.now()
|
||||
setConnection({ status: "connected", attempt: 0, error: undefined })
|
||||
|
||||
// Forward events until the stream closes or this connection is cancelled.
|
||||
let yielded = Date.now()
|
||||
while (!signal.aborted) {
|
||||
const event = await iterator.next()
|
||||
if (signal.aborted) return { error: undefined, connectedAt }
|
||||
if (event.done) return { error: new Error("Event stream disconnected"), connectedAt }
|
||||
publish(event.value)
|
||||
if (Date.now() - yielded < STREAM_YIELD_MS) continue
|
||||
yielded = Date.now()
|
||||
await wait(0, signal)
|
||||
}
|
||||
return { error: undefined, connectedAt }
|
||||
} catch (error) {
|
||||
return { error, connectedAt }
|
||||
} finally {
|
||||
request.abort()
|
||||
clearTimeout(timeout)
|
||||
signal.removeEventListener("abort", cancel)
|
||||
}
|
||||
}
|
||||
|
||||
async function runStream(active: number) {
|
||||
let retries = 0
|
||||
// oxlint-disable-next-line no-unmodified-loop-condition -- stop() changes the lifecycle flags and aborts the active request
|
||||
while (!abort.signal.aborted && started && generation === active) {
|
||||
setConnection({ status: retries === 0 ? "connecting" : "reconnecting", attempt: retries, error: undefined })
|
||||
const controller = new AbortController()
|
||||
attempt = controller
|
||||
const onAbort = () => controller.abort()
|
||||
abort.signal.addEventListener("abort", onAbort)
|
||||
const result = await connect(controller.signal)
|
||||
abort.signal.removeEventListener("abort", onAbort)
|
||||
|
||||
if (abort.signal.aborted || !started || generation !== active) {
|
||||
if (attempt === controller) attempt = undefined
|
||||
return
|
||||
}
|
||||
if (result.connectedAt !== undefined && Date.now() - result.connectedAt >= 1_000) retries = 0
|
||||
retries += 1
|
||||
const message =
|
||||
result.error === undefined
|
||||
? undefined
|
||||
: result.error instanceof Error
|
||||
? result.error.message
|
||||
: String(result.error)
|
||||
console.info("[global-sdk] event stream disconnected", {
|
||||
url: server.http.url,
|
||||
fetch: eventFetch ? "platform" : "webview",
|
||||
attempt: retries,
|
||||
error: message,
|
||||
})
|
||||
setConnection({ status: "reconnecting", attempt: retries, error: message })
|
||||
await wait(RECONNECT_DELAY_MS, controller.signal)
|
||||
if (attempt === controller) attempt = undefined
|
||||
}
|
||||
}
|
||||
|
||||
function start() {
|
||||
if (started) return run
|
||||
started = true
|
||||
const active = ++generation
|
||||
const previous = run
|
||||
const current = (async () => {
|
||||
if (previous) await previous
|
||||
await runStream(active)
|
||||
})().finally(() => {
|
||||
if (run !== current) return
|
||||
run = undefined
|
||||
flush()
|
||||
})
|
||||
run = current
|
||||
return run
|
||||
}
|
||||
|
||||
function stop() {
|
||||
started = false
|
||||
generation++
|
||||
attempt?.abort()
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
makeEventListener(window, "pagehide", stop)
|
||||
makeEventListener(window, "pageshow", (event) => resumeStreamAfterPageShow(event, start))
|
||||
void start()
|
||||
const connection = createClientConnection(api, {
|
||||
flushInterval: 16,
|
||||
pageLifecycle: true,
|
||||
onEvent(event) {
|
||||
const adapted = adaptServerEvent(event)
|
||||
emitter.emit(adapted.type, adapted)
|
||||
const directory = event.location?.directory
|
||||
if (directory) locations.emit(directory, adapted)
|
||||
},
|
||||
log: {
|
||||
info(message, data) {
|
||||
if (message !== "event stream disconnected") return
|
||||
console.info("[global-sdk] event stream disconnected", { url: server.http.url, ...data })
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
onCleanup(() => {
|
||||
stop()
|
||||
abort.abort()
|
||||
if (timer) clearTimeout(timer)
|
||||
timer = undefined
|
||||
queue = []
|
||||
buffer = []
|
||||
emitter.clear()
|
||||
locations.clear()
|
||||
})
|
||||
|
||||
const api = createApiForServer({ server: server.http, fetch: platform.fetch })
|
||||
|
||||
return {
|
||||
server,
|
||||
scope,
|
||||
url: server.http.url,
|
||||
api,
|
||||
connection: {
|
||||
status: () => connection.status,
|
||||
attempt: () => connection.attempt,
|
||||
error: () => connection.error,
|
||||
},
|
||||
connection,
|
||||
event: {
|
||||
on: emitter.on.bind(emitter),
|
||||
listen: emitter.listen.bind(emitter),
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
"./promise": "./src/promise/index.ts",
|
||||
"./promise/api": "./src/promise/api.ts",
|
||||
"./service": "./src/promise/service.ts",
|
||||
"./solid": "./src/solid/index.ts",
|
||||
"./effect": "./src/effect/index.ts",
|
||||
"./effect/api": "./src/effect/api.ts",
|
||||
"./effect/service": "./src/effect/service.ts"
|
||||
@@ -36,11 +37,15 @@
|
||||
"@opencode-ai/protocol": "workspace:*"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"effect": "4.0.0-beta.101"
|
||||
"effect": "4.0.0-beta.101",
|
||||
"solid-js": ">=1.9.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"effect": {
|
||||
"optional": true
|
||||
},
|
||||
"solid-js": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -49,6 +54,7 @@
|
||||
"@tsconfig/bun": "catalog:",
|
||||
"@types/bun": "catalog:",
|
||||
"@typescript/native-preview": "catalog:",
|
||||
"effect": "catalog:"
|
||||
"effect": "catalog:",
|
||||
"solid-js": "catalog:"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -382,6 +382,15 @@ export type Endpoint5_31Output =
|
||||
readonly location?: Location.Ref | undefined
|
||||
readonly data: { readonly sessionID: Session.ID; readonly title: string }
|
||||
}
|
||||
| {
|
||||
readonly id: Event.ID
|
||||
readonly created: number
|
||||
readonly metadata?: { readonly [x: string]: unknown } | undefined
|
||||
readonly type: "session.viewed"
|
||||
readonly durable: { readonly aggregateID: string; readonly seq: Event.Seq; readonly version: Event.Version }
|
||||
readonly location?: Location.Ref | undefined
|
||||
readonly data: { readonly sessionID: Session.ID }
|
||||
}
|
||||
| {
|
||||
readonly id: Event.ID
|
||||
readonly created: number
|
||||
@@ -914,6 +923,10 @@ export type Endpoint5_34Input = { readonly sessionID: Session.ID; readonly messa
|
||||
export type Endpoint5_34Output = SessionMessage.Info
|
||||
export type SessionMessageOperation<E = never> = (input: Endpoint5_34Input) => Effect.Effect<Endpoint5_34Output, E>
|
||||
|
||||
export type Endpoint5_35Input = { readonly sessionID: Session.ID }
|
||||
export type Endpoint5_35Output = void
|
||||
export type SessionViewOperation<E = never> = (input: Endpoint5_35Input) => Effect.Effect<Endpoint5_35Output, E>
|
||||
|
||||
export interface SessionApi<E = never> {
|
||||
readonly list: SessionListOperation<E>
|
||||
readonly create: SessionCreateOperation<E>
|
||||
@@ -958,6 +971,7 @@ export interface SessionApi<E = never> {
|
||||
readonly interrupt: SessionInterruptOperation<E>
|
||||
readonly background: SessionBackgroundOperation<E>
|
||||
readonly message: SessionMessageOperation<E>
|
||||
readonly view: SessionViewOperation<E>
|
||||
}
|
||||
|
||||
export type Endpoint6_0Input = {
|
||||
|
||||
@@ -86,6 +86,8 @@ import type {
|
||||
Endpoint5_33Output,
|
||||
Endpoint5_34Input,
|
||||
Endpoint5_34Output,
|
||||
Endpoint5_35Input,
|
||||
Endpoint5_35Output,
|
||||
Endpoint6_0Input,
|
||||
Endpoint6_0Output,
|
||||
Endpoint7_0Input,
|
||||
@@ -610,6 +612,11 @@ const Endpoint5_34 = (raw: RawClient["server.session"]) => (input: Endpoint5_34I
|
||||
),
|
||||
)
|
||||
|
||||
const Endpoint5_35 = (raw: RawClient["server.session"]) => (input: Endpoint5_35Input) =>
|
||||
preserveEffect<Endpoint5_35Output>()(
|
||||
raw["session.view"]({ params: { sessionID: input["sessionID"] } }).pipe(Effect.mapError(mapClientError)),
|
||||
)
|
||||
|
||||
const adaptGroup5 = (raw: RawClient["server.session"]) => ({
|
||||
list: Endpoint5_0(raw),
|
||||
create: Endpoint5_1(raw),
|
||||
@@ -639,6 +646,7 @@ const adaptGroup5 = (raw: RawClient["server.session"]) => ({
|
||||
interrupt: Endpoint5_32(raw),
|
||||
background: Endpoint5_33(raw),
|
||||
message: Endpoint5_34(raw),
|
||||
view: Endpoint5_35(raw),
|
||||
})
|
||||
|
||||
const Endpoint6_0 = (raw: RawClient["server.message"]) => (input: Endpoint6_0Input) =>
|
||||
|
||||
@@ -80,6 +80,8 @@ import type {
|
||||
SessionBackgroundOutput,
|
||||
SessionMessageInput,
|
||||
SessionMessageOutput,
|
||||
SessionViewInput,
|
||||
SessionViewOutput,
|
||||
MessageListInput,
|
||||
MessageListOutput,
|
||||
ModelListInput,
|
||||
@@ -896,6 +898,17 @@ export function make(options: ClientOptions) {
|
||||
},
|
||||
requestOptions,
|
||||
).then((value) => value.data),
|
||||
view: (input: SessionViewInput, requestOptions?: RequestOptions) =>
|
||||
request<SessionViewOutput>(
|
||||
{
|
||||
method: "POST",
|
||||
path: `/api/session/${encodeURIComponent(input.sessionID)}/view`,
|
||||
successStatus: 204,
|
||||
declaredStatuses: [404, 401, 400],
|
||||
empty: true,
|
||||
},
|
||||
requestOptions,
|
||||
),
|
||||
},
|
||||
message: {
|
||||
list: (input: MessageListInput, requestOptions?: RequestOptions) =>
|
||||
|
||||
@@ -479,6 +479,16 @@ export type SessionRenamed = {
|
||||
data: { sessionID: string; title: string }
|
||||
}
|
||||
|
||||
export type SessionViewed = {
|
||||
id: string
|
||||
created: number
|
||||
metadata?: { [x: string]: any }
|
||||
type: "session.viewed"
|
||||
durable: { aggregateID: string; seq: number; version: 1 }
|
||||
location?: LocationRef
|
||||
data: { sessionID: string }
|
||||
}
|
||||
|
||||
export type SessionDeleted = {
|
||||
id: string
|
||||
created: number
|
||||
@@ -1510,7 +1520,7 @@ export type SessionInfo = {
|
||||
model?: ModelRef
|
||||
cost: MoneyUSD
|
||||
tokens: TokenUsageInfo
|
||||
time: { created: number; updated: number; archived?: number }
|
||||
time: { created: number; updated: number; idle?: number; viewed?: number; archived?: number }
|
||||
title?: string
|
||||
location: LocationRef
|
||||
subpath?: string
|
||||
@@ -1923,6 +1933,7 @@ export type SessionEventDurable =
|
||||
| SessionModelSelected
|
||||
| SessionMoved
|
||||
| SessionRenamed
|
||||
| SessionViewed
|
||||
| SessionDeleted
|
||||
| SessionForked
|
||||
| SessionInboxDelivered
|
||||
@@ -2013,6 +2024,7 @@ export type V2Event =
|
||||
| SessionModelSelected
|
||||
| SessionMoved
|
||||
| SessionRenamed
|
||||
| SessionViewed
|
||||
| SessionUsageUpdated
|
||||
| SessionDeleted
|
||||
| SessionForked
|
||||
@@ -2476,7 +2488,13 @@ export type SessionImportInput = {
|
||||
readonly reasoning: number
|
||||
readonly cache: { readonly read: number; readonly write: number }
|
||||
}
|
||||
readonly time: { readonly created: number; readonly updated: number; readonly archived?: number }
|
||||
readonly time: {
|
||||
readonly created: number
|
||||
readonly updated: number
|
||||
readonly idle?: number
|
||||
readonly viewed?: number
|
||||
readonly archived?: number
|
||||
}
|
||||
readonly title?: string
|
||||
readonly location: { readonly directory: string; readonly workspaceID?: string }
|
||||
readonly subpath?: string
|
||||
@@ -2743,7 +2761,13 @@ export type SessionImportInput = {
|
||||
readonly reasoning: number
|
||||
readonly cache: { readonly read: number; readonly write: number }
|
||||
}
|
||||
readonly time: { readonly created: number; readonly updated: number; readonly archived?: number }
|
||||
readonly time: {
|
||||
readonly created: number
|
||||
readonly updated: number
|
||||
readonly idle?: number
|
||||
readonly viewed?: number
|
||||
readonly archived?: number
|
||||
}
|
||||
readonly title?: string
|
||||
readonly location: { readonly directory: string; readonly workspaceID?: string }
|
||||
readonly subpath?: string
|
||||
@@ -3010,7 +3034,13 @@ export type SessionImportInput = {
|
||||
readonly reasoning: number
|
||||
readonly cache: { readonly read: number; readonly write: number }
|
||||
}
|
||||
readonly time: { readonly created: number; readonly updated: number; readonly archived?: number }
|
||||
readonly time: {
|
||||
readonly created: number
|
||||
readonly updated: number
|
||||
readonly idle?: number
|
||||
readonly viewed?: number
|
||||
readonly archived?: number
|
||||
}
|
||||
readonly title?: string
|
||||
readonly location: { readonly directory: string; readonly workspaceID?: string }
|
||||
readonly subpath?: string
|
||||
@@ -3936,6 +3966,10 @@ export type SessionMessageInput = {
|
||||
|
||||
export type SessionMessageOutput = { data: SessionMessageInfo }["data"]
|
||||
|
||||
export type SessionViewInput = { readonly sessionID: { readonly sessionID: string }["sessionID"] }
|
||||
|
||||
export type SessionViewOutput = void
|
||||
|
||||
export type MessageListInput = {
|
||||
readonly sessionID: { readonly sessionID: string }["sessionID"]
|
||||
readonly limit?: {
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
import { batch, onCleanup, onMount } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import type { OpenCodeClient, OpenCodeEvent } from "../promise"
|
||||
|
||||
export type ClientConnectionStatus = "connected" | "connecting" | "reconnecting"
|
||||
export type ClientConnectionEvent = {
|
||||
readonly type: "client.connection"
|
||||
readonly created: number
|
||||
readonly data: {
|
||||
readonly status: "connecting" | "connected" | "disconnected" | "reconnecting"
|
||||
readonly attempt: number
|
||||
readonly error?: string
|
||||
}
|
||||
}
|
||||
|
||||
export type ClientConnectionOptions = {
|
||||
readonly reconnect?: (signal: AbortSignal) => Promise<OpenCodeClient>
|
||||
readonly onEvent: (event: OpenCodeEvent) => void
|
||||
readonly flushInterval?: number
|
||||
readonly pageLifecycle?: boolean
|
||||
readonly log?: {
|
||||
readonly debug?: (message: string, data?: Readonly<Record<string, unknown>>) => void
|
||||
readonly info?: (message: string, data?: Readonly<Record<string, unknown>>) => void
|
||||
}
|
||||
}
|
||||
|
||||
const connectTimeout = 2_000
|
||||
const reconnectDelay = 1_000
|
||||
const connectionHistoryLimit = 50
|
||||
|
||||
export function createClientConnection(initialApi: OpenCodeClient, options: ClientConnectionOptions) {
|
||||
const abort = new AbortController()
|
||||
const history: ClientConnectionEvent[] = []
|
||||
const [connection, setConnection] = createStore<{
|
||||
status: ClientConnectionStatus
|
||||
attempt: number
|
||||
error?: string
|
||||
}>({ status: "connecting", attempt: 0 })
|
||||
let api = initialApi
|
||||
let pending: OpenCodeEvent[] = []
|
||||
let flushTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let stream: AbortController | undefined
|
||||
let run: Promise<void> | undefined
|
||||
let started = false
|
||||
let generation = 0
|
||||
|
||||
function record(status: ClientConnectionEvent["data"]["status"], attempt: number, error?: string) {
|
||||
history.push({ type: "client.connection", created: Date.now(), data: { status, attempt, error } })
|
||||
if (history.length > connectionHistoryLimit) history.shift()
|
||||
}
|
||||
|
||||
function publish(event: OpenCodeEvent) {
|
||||
pending.push(event)
|
||||
if (flushTimer) return
|
||||
flushTimer = setTimeout(() => {
|
||||
flushTimer = undefined
|
||||
const events = pending
|
||||
pending = []
|
||||
batch(() => events.forEach(options.onEvent))
|
||||
}, options.flushInterval ?? 10)
|
||||
}
|
||||
|
||||
async function connect(signal: AbortSignal, attempt: number) {
|
||||
let connectedAt: number | undefined
|
||||
const request = new AbortController()
|
||||
const cancel = () => request.abort(signal.reason)
|
||||
const timeout = setTimeout(() => request.abort(new Error("Timed out connecting to server")), connectTimeout)
|
||||
signal.addEventListener("abort", cancel, { once: true })
|
||||
|
||||
try {
|
||||
record(attempt === 0 ? "connecting" : "reconnecting", attempt)
|
||||
options.log?.info?.("event stream connecting", { attempt })
|
||||
const iterator = api.event.subscribe({ signal: request.signal })[Symbol.asyncIterator]()
|
||||
const first = await iterator.next()
|
||||
if (signal.aborted) return { error: undefined, connectedAt }
|
||||
if (first.done)
|
||||
return {
|
||||
error:
|
||||
request.signal.reason instanceof Error ? request.signal.reason : new Error("Event stream disconnected"),
|
||||
connectedAt,
|
||||
}
|
||||
if (first.value.type !== "server.connected")
|
||||
return { error: new Error("Event stream did not start with server.connected"), connectedAt }
|
||||
|
||||
clearTimeout(timeout)
|
||||
record("connected", attempt)
|
||||
connectedAt = Date.now()
|
||||
options.log?.info?.("event stream connected")
|
||||
publish(first.value)
|
||||
setConnection({ status: "connected", attempt: 0, error: undefined })
|
||||
|
||||
while (!signal.aborted) {
|
||||
const event = await iterator.next()
|
||||
if (signal.aborted) return { error: undefined, connectedAt }
|
||||
if (event.done) return { error: new Error("Event stream disconnected"), connectedAt }
|
||||
if ("durable" in event.value)
|
||||
options.log?.debug?.("event", {
|
||||
type: event.value.type,
|
||||
aggregateID: event.value.durable.aggregateID,
|
||||
seq: event.value.durable.seq,
|
||||
})
|
||||
publish(event.value)
|
||||
}
|
||||
return { error: undefined, connectedAt }
|
||||
} catch (error) {
|
||||
return { error, connectedAt }
|
||||
} finally {
|
||||
request.abort()
|
||||
clearTimeout(timeout)
|
||||
signal.removeEventListener("abort", cancel)
|
||||
}
|
||||
}
|
||||
|
||||
async function runStream(active: number) {
|
||||
let attempt = 0
|
||||
while (!abort.signal.aborted && started && generation === active) {
|
||||
setConnection({ status: attempt === 0 ? "connecting" : "reconnecting", attempt })
|
||||
const controller = new AbortController()
|
||||
stream = controller
|
||||
const cancel = () => controller.abort(abort.signal.reason)
|
||||
abort.signal.addEventListener("abort", cancel)
|
||||
const result = await connect(controller.signal, attempt)
|
||||
abort.signal.removeEventListener("abort", cancel)
|
||||
if (abort.signal.aborted || !started || generation !== active) return
|
||||
if (result.connectedAt !== undefined && Date.now() - result.connectedAt >= reconnectDelay) attempt = 0
|
||||
attempt += 1
|
||||
const message = errorMessage(result.error)
|
||||
record("disconnected", attempt, message)
|
||||
options.log?.info?.("event stream disconnected", { attempt, error: message })
|
||||
setConnection({ status: "reconnecting", attempt, error: message })
|
||||
|
||||
if (options.reconnect) {
|
||||
const next = await options.reconnect(controller.signal).catch((error) => {
|
||||
if (!controller.signal.aborted)
|
||||
options.log?.info?.("server resolution failed", { attempt, error: errorMessage(error) })
|
||||
})
|
||||
if (abort.signal.aborted || controller.signal.aborted || !started || generation !== active) return
|
||||
if (next) {
|
||||
api = next
|
||||
if (attempt === 1) continue
|
||||
}
|
||||
}
|
||||
await wait(reconnectDelay, controller.signal)
|
||||
}
|
||||
}
|
||||
|
||||
function start() {
|
||||
if (started) return run
|
||||
started = true
|
||||
const active = ++generation
|
||||
const previous = run
|
||||
const current = (async () => {
|
||||
if (previous) await previous
|
||||
await runStream(active)
|
||||
})().finally(() => {
|
||||
if (run !== current) return
|
||||
run = undefined
|
||||
})
|
||||
run = current
|
||||
return run
|
||||
}
|
||||
|
||||
function stop() {
|
||||
started = false
|
||||
generation += 1
|
||||
stream?.abort()
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
if (options.pageLifecycle) {
|
||||
const pagehide = () => stop()
|
||||
const pageshow = (event: PageTransitionEvent) => {
|
||||
if (event.persisted) void start()
|
||||
}
|
||||
window.addEventListener("pagehide", pagehide)
|
||||
window.addEventListener("pageshow", pageshow)
|
||||
onCleanup(() => {
|
||||
window.removeEventListener("pagehide", pagehide)
|
||||
window.removeEventListener("pageshow", pageshow)
|
||||
})
|
||||
}
|
||||
void start()
|
||||
})
|
||||
|
||||
onCleanup(() => {
|
||||
stop()
|
||||
abort.abort()
|
||||
if (flushTimer) clearTimeout(flushTimer)
|
||||
pending = []
|
||||
})
|
||||
|
||||
return {
|
||||
status: () => connection.status,
|
||||
attempt: () => connection.attempt,
|
||||
error: () => connection.error,
|
||||
internal: {
|
||||
history: () => history.slice(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown) {
|
||||
if (error === undefined) return undefined
|
||||
if (error instanceof Error) return error.message
|
||||
return String(error)
|
||||
}
|
||||
|
||||
function wait(delay: number, signal: AbortSignal) {
|
||||
return new Promise<void>((resolve) => {
|
||||
const timer = setTimeout(done, delay)
|
||||
signal.addEventListener("abort", done, { once: true })
|
||||
function done() {
|
||||
clearTimeout(timer)
|
||||
signal.removeEventListener("abort", done)
|
||||
resolve()
|
||||
}
|
||||
})
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,2 @@
|
||||
export * from "./data"
|
||||
export * from "./connection"
|
||||
@@ -136,8 +136,10 @@ test("event.subscribe terminates on Effect protocol decode failures", async () =
|
||||
|
||||
test("session methods retain decoded Effect inputs and outputs", async () => {
|
||||
const logQueries: Array<Record<string, string>> = []
|
||||
const requests: Array<{ method: string; url: string }> = []
|
||||
const httpClient = HttpClient.make((request) => {
|
||||
const url = request.url
|
||||
requests.push({ method: request.method, url })
|
||||
if (url.includes("/log")) {
|
||||
logQueries.push(Object.fromEntries(request.urlParams.params))
|
||||
return Effect.succeed(
|
||||
@@ -183,6 +185,7 @@ test("session methods retain decoded Effect inputs and outputs", async () => {
|
||||
const created = yield* client.session.create({
|
||||
location: Location.Ref.make({ directory: AbsolutePath.make("/tmp/project") }),
|
||||
})
|
||||
yield* client.session.view({ sessionID: Session.ID.make("ses_test") })
|
||||
yield* client.session.switchAgent({ sessionID: Session.ID.make("ses_test"), agent: Agent.ID.make("build") })
|
||||
yield* client.session.switchModel({
|
||||
sessionID: Session.ID.make("ses_test"),
|
||||
@@ -207,7 +210,11 @@ test("session methods retain decoded Effect inputs and outputs", async () => {
|
||||
return { page, active, created, admitted, context, log, message }
|
||||
}).pipe(Effect.provideService(HttpClient.HttpClient, httpClient), Effect.runPromise)
|
||||
|
||||
expect(DateTime.toEpochMillis(result.page.data[0].time.created)).toBe(1_717_171_717_000)
|
||||
const listed = result.page.data[0]
|
||||
if (!listed?.time.idle || !listed.time.viewed) throw new Error("Expected attention times")
|
||||
expect(DateTime.toEpochMillis(listed.time.created)).toBe(1_717_171_717_000)
|
||||
expect(DateTime.toEpochMillis(listed.time.idle)).toBe(1_717_171_717_002)
|
||||
expect(DateTime.toEpochMillis(listed.time.viewed)).toBe(1_717_171_717_001)
|
||||
expect(result.active).toEqual({ ses_test: { type: "running" } })
|
||||
expect(Object.getPrototypeOf(result.page.data[0])).toBe(Object.prototype)
|
||||
expect(Object.getPrototypeOf(result.created)).toBe(Object.prototype)
|
||||
@@ -217,11 +224,10 @@ test("session methods retain decoded Effect inputs and outputs", async () => {
|
||||
expect(DateTime.toEpochMillis(result.admitted.timeCreated)).toBe(1_717_171_717_000)
|
||||
expect(result.context).toEqual([])
|
||||
expect(logQueries[0]).toEqual({ after: "0" })
|
||||
expect(requests).toContainEqual({ method: "POST", url: "http://localhost:3000/api/session/ses_test/view" })
|
||||
const logged = Array.from(result.log)
|
||||
expect(logged.map((item) => item.type)).toEqual(["session.model.selected", "log.synced"])
|
||||
expect(logged[0]?.type === "session.model.selected" && DateTime.toEpochMillis(logged[0].created)).toBe(
|
||||
1_717_171_717_000,
|
||||
)
|
||||
expect(logged[0]?.type === "session.model.selected" && logged[0].created).toBe(1_717_171_717_000)
|
||||
expect(logged.at(-1)).toEqual(synced)
|
||||
expect(result.message).toEqual(expect.objectContaining({ id: "msg_model", type: "model-switched" }))
|
||||
})
|
||||
@@ -260,6 +266,8 @@ const session = {
|
||||
time: {
|
||||
created: 1_717_171_717_000,
|
||||
updated: 1_717_171_717_000,
|
||||
idle: 1_717_171_717_002,
|
||||
viewed: 1_717_171_717_001,
|
||||
},
|
||||
title: "Test",
|
||||
location: { directory: "/tmp/project" },
|
||||
|
||||
@@ -539,6 +539,7 @@ test("session methods use the public HTTP contract", async () => {
|
||||
const page = await client.session.list({ limit: 10, order: "desc", parentID: null })
|
||||
const active = await client.session.active()
|
||||
const created = await client.session.create({ location: { directory: "/tmp/project" } })
|
||||
await client.session.view({ sessionID: "ses_test" })
|
||||
await client.session.switchAgent({ sessionID: "ses_test", agent: "build" })
|
||||
await client.session.switchModel({
|
||||
sessionID: "ses_test",
|
||||
@@ -565,6 +566,7 @@ test("session methods use the public HTTP contract", async () => {
|
||||
const message = await client.session.message({ sessionID: "ses_test", messageID: "msg_model" })
|
||||
|
||||
expect(page.cursor.next).toBe("next")
|
||||
expect(page.data[0].time).toMatchObject({ idle: 1_717_171_717_002, viewed: 1_717_171_717_001 })
|
||||
expect(active).toEqual({ ses_test: { type: "running" } })
|
||||
expect(created.id).toBe("ses_test")
|
||||
expect(admitted.id).toBe("msg_test")
|
||||
@@ -577,6 +579,7 @@ test("session methods use the public HTTP contract", async () => {
|
||||
["GET", "http://localhost:3000/api/session?limit=10&order=desc&parentID=null"],
|
||||
["GET", "http://localhost:3000/api/session/active"],
|
||||
["POST", "http://localhost:3000/api/session"],
|
||||
["POST", "http://localhost:3000/api/session/ses_test/view"],
|
||||
["POST", "http://localhost:3000/api/session/ses_test/agent"],
|
||||
["POST", "http://localhost:3000/api/session/ses_test/model"],
|
||||
["POST", "http://localhost:3000/api/session/ses_test/prompt"],
|
||||
@@ -651,6 +654,8 @@ const session = {
|
||||
time: {
|
||||
created: 1_717_171_717_000,
|
||||
updated: 1_717_171_717_000,
|
||||
idle: 1_717_171_717_002,
|
||||
viewed: 1_717_171_717_001,
|
||||
},
|
||||
title: "Test",
|
||||
location: { directory: "/tmp/project" },
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"version": "7",
|
||||
"dialect": "sqlite",
|
||||
"id": "dcde8e6b-4bf4-4f6b-b2be-4030c2c3e936",
|
||||
"prevIds": ["5c1aa56b-c3ee-4283-9a84-c0bf626dc604"],
|
||||
"id": "94b6c496-ad84-426f-9d5d-3e1ac3ebfb56",
|
||||
"prevIds": ["dcde8e6b-4bf4-4f6b-b2be-4030c2c3e936"],
|
||||
"ddl": [
|
||||
{
|
||||
"name": "account_state",
|
||||
@@ -1350,6 +1350,26 @@
|
||||
"entityType": "columns",
|
||||
"table": "session_v2"
|
||||
},
|
||||
{
|
||||
"type": "integer",
|
||||
"notNull": false,
|
||||
"autoincrement": false,
|
||||
"default": null,
|
||||
"generated": null,
|
||||
"name": "time_idle",
|
||||
"entityType": "columns",
|
||||
"table": "session_v2"
|
||||
},
|
||||
{
|
||||
"type": "integer",
|
||||
"notNull": false,
|
||||
"autoincrement": false,
|
||||
"default": null,
|
||||
"generated": null,
|
||||
"name": "time_viewed",
|
||||
"entityType": "columns",
|
||||
"table": "session_v2"
|
||||
},
|
||||
{
|
||||
"type": "integer",
|
||||
"notNull": false,
|
||||
|
||||
+2
@@ -43,6 +43,7 @@ import m40 from "./migration/20260808023530_workspace_domain.js"
|
||||
import m41 from "./migration/20260811161259_execution_claim_attempts.js"
|
||||
import m42 from "./migration/20260812181746_session_inbox.js"
|
||||
import m43 from "./migration/20260812213948_worktree.js"
|
||||
import m44 from "./migration/20260815182818_session_viewed_state.js"
|
||||
|
||||
export const migrations = [
|
||||
m00,
|
||||
@@ -89,4 +90,5 @@ export const migrations = [
|
||||
m41,
|
||||
m42,
|
||||
m43,
|
||||
m44,
|
||||
] satisfies DatabaseMigration.Migration[]
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Effect } from "effect"
|
||||
import type { DatabaseMigration } from "../migration.js"
|
||||
|
||||
const migration: DatabaseMigration.Migration = {
|
||||
id: "20260815182818_session_viewed_state",
|
||||
up(tx) {
|
||||
return Effect.gen(function* () {
|
||||
yield* tx.run(`ALTER TABLE \`session_v2\` ADD \`time_idle\` integer;`)
|
||||
yield* tx.run(`ALTER TABLE \`session_v2\` ADD \`time_viewed\` integer;`)
|
||||
})
|
||||
},
|
||||
}
|
||||
|
||||
export default migration
|
||||
@@ -209,6 +209,8 @@ const schema: Omit<DatabaseMigration.Migration, "id"> = {
|
||||
\`model\` text,
|
||||
\`time_created\` integer NOT NULL,
|
||||
\`time_updated\` integer NOT NULL,
|
||||
\`time_idle\` integer,
|
||||
\`time_viewed\` integer,
|
||||
\`time_compacting\` integer,
|
||||
\`time_archived\` integer,
|
||||
\`time_suspended\` integer,
|
||||
|
||||
@@ -15,8 +15,10 @@ import { GoogleVertexPlugin } from "./provider/google-vertex.js"
|
||||
import { GroqPlugin } from "./provider/groq.js"
|
||||
import { KiloPlugin } from "./provider/kilo.js"
|
||||
import { LLMGatewayPlugin } from "./provider/llmgateway.js"
|
||||
import { LMStudioPlugin } from "./provider/lmstudio.js"
|
||||
import { MistralPlugin } from "./provider/mistral.js"
|
||||
import { NvidiaPlugin } from "./provider/nvidia.js"
|
||||
import { OllamaPlugin } from "./provider/ollama.js"
|
||||
import { OpenAIPlugin } from "./provider/openai.js"
|
||||
import { SnowflakeCortexPlugin } from "./provider/snowflake-cortex.js"
|
||||
import { OpenAICompatiblePlugin } from "./provider/openai-compatible.js"
|
||||
@@ -27,6 +29,7 @@ import { SapAICorePlugin } from "./provider/sap-ai-core.js"
|
||||
import { TogetherAIPlugin } from "./provider/togetherai.js"
|
||||
import { VercelPlugin } from "./provider/vercel.js"
|
||||
import { VenicePlugin } from "./provider/venice.js"
|
||||
import { VLLMPlugin } from "./provider/vllm.js"
|
||||
import { XAIPlugin } from "./provider/xai.js"
|
||||
import { ZenmuxPlugin } from "./provider/zenmux.js"
|
||||
import type { PluginInternal } from "./internal.js"
|
||||
@@ -48,8 +51,10 @@ export const ProviderPlugins: PluginInternal.InternalPlugin[] = [
|
||||
GroqPlugin,
|
||||
KiloPlugin,
|
||||
LLMGatewayPlugin,
|
||||
LMStudioPlugin,
|
||||
MistralPlugin,
|
||||
NvidiaPlugin,
|
||||
OllamaPlugin,
|
||||
OpencodePlugin,
|
||||
SnowflakeCortexPlugin,
|
||||
OpenAICompatiblePlugin,
|
||||
@@ -60,6 +65,7 @@ export const ProviderPlugins: PluginInternal.InternalPlugin[] = [
|
||||
TogetherAIPlugin,
|
||||
VercelPlugin,
|
||||
VenicePlugin,
|
||||
VLLMPlugin,
|
||||
XAIPlugin,
|
||||
ZenmuxPlugin,
|
||||
DynamicProviderPlugin,
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
import { define } from "@opencode-ai/plugin/effect/plugin"
|
||||
import { Document, type Entry } from "@opencode-ai/schema/config"
|
||||
import { Duration, Effect, Schedule, Schema, Semaphore, Stream } from "effect"
|
||||
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http"
|
||||
import { Config } from "../../config.js"
|
||||
import { Model } from "../../model.js"
|
||||
import { Provider } from "../../provider.js"
|
||||
import type { PluginInternal } from "../internal.js"
|
||||
|
||||
const providerID = "lmstudio"
|
||||
|
||||
const RemoteModel = Schema.Struct({
|
||||
type: Schema.Literals(["llm", "embedding"]),
|
||||
key: Schema.String,
|
||||
display_name: Schema.String,
|
||||
architecture: Schema.NullOr(Schema.String).pipe(Schema.optional),
|
||||
loaded_instances: Schema.Array(
|
||||
Schema.Struct({
|
||||
config: Schema.Struct({ context_length: Schema.Int }),
|
||||
}),
|
||||
),
|
||||
max_context_length: Schema.Int,
|
||||
capabilities: Schema.Struct({
|
||||
vision: Schema.Boolean,
|
||||
trained_for_tool_use: Schema.Boolean,
|
||||
}).pipe(Schema.optional),
|
||||
})
|
||||
|
||||
const Response = Schema.Struct({ models: Schema.Array(RemoteModel) })
|
||||
const discovery = new Map<string, { checked: number; apiKey?: string; models?: (typeof RemoteModel.Type)[] }>()
|
||||
const discoveryLock = Semaphore.makeUnsafe(1)
|
||||
|
||||
export function make(origin = "http://127.0.0.1:1234", interval: Duration.Input = "30 seconds") {
|
||||
return define({
|
||||
id: "opencode.provider.lmstudio",
|
||||
effect: Effect.fn(function* (ctx) {
|
||||
const http = HttpClient.filterStatusOk(yield* HttpClient.HttpClient)
|
||||
const config = yield* Config.Service
|
||||
const source = { current: configured(yield* config.entries(), origin) }
|
||||
const loaded = { models: [] as (typeof RemoteModel.Type)[], hash: "[]" }
|
||||
|
||||
yield* ctx.integration.transform((integrations) => {
|
||||
if (loaded.models.length === 0) return
|
||||
integrations.remove(providerID)
|
||||
})
|
||||
|
||||
yield* ctx.catalog.transform((catalog) => {
|
||||
if (loaded.models.length === 0) return
|
||||
for (const model of catalog.provider.get(providerID)?.models.values() ?? []) {
|
||||
catalog.model.remove(providerID, model.id)
|
||||
}
|
||||
catalog.provider.update(providerID, (provider) => {
|
||||
provider.name = "LM Studio"
|
||||
provider.activation = "enabled"
|
||||
provider.package = "@opencode-ai/ai/providers/openai-compatible"
|
||||
provider.settings = {
|
||||
baseURL: source.current.baseURL,
|
||||
provider: providerID,
|
||||
apiKey: source.current.apiKey ?? "",
|
||||
}
|
||||
provider.integrationID = undefined
|
||||
})
|
||||
for (const item of loaded.models) {
|
||||
catalog.model.update(providerID, item.key, (model) => {
|
||||
model.modelID = Model.ID.make(item.key)
|
||||
model.name = item.display_name || item.key
|
||||
model.family = item.architecture ? Model.Family.make(item.architecture) : undefined
|
||||
model.capabilities = {
|
||||
tools: item.capabilities?.trained_for_tool_use ?? false,
|
||||
input: ["text", ...(item.capabilities?.vision ? ["image"] : [])],
|
||||
output: ["text"],
|
||||
}
|
||||
model.limit = {
|
||||
context:
|
||||
item.loaded_instances.length === 0
|
||||
? item.max_context_length
|
||||
: Math.min(...item.loaded_instances.map((instance) => instance.config.context_length)),
|
||||
output: 0,
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
const discover = Effect.fn("LMStudioPlugin.discover")(function* () {
|
||||
const current = source.current
|
||||
if (!current.endpoint) return undefined
|
||||
return yield* discoveryLock.withPermit(
|
||||
Effect.gen(function* () {
|
||||
const cached = discovery.get(current.endpoint)
|
||||
if (cached && cached.apiKey === current.apiKey && Date.now() - cached.checked < Duration.toMillis(interval))
|
||||
return { source: current, models: cached.models }
|
||||
discovery.set(current.endpoint, {
|
||||
checked: Date.now(),
|
||||
apiKey: current.apiKey,
|
||||
models: cached && cached.apiKey === current.apiKey ? cached.models : undefined,
|
||||
})
|
||||
const request = current.apiKey
|
||||
? HttpClientRequest.get(current.endpoint).pipe(
|
||||
HttpClientRequest.acceptJson,
|
||||
HttpClientRequest.bearerToken(current.apiKey),
|
||||
)
|
||||
: HttpClientRequest.get(current.endpoint).pipe(HttpClientRequest.acceptJson)
|
||||
const response = yield* http
|
||||
.execute(request)
|
||||
.pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(Response)), Effect.timeout("1 second"))
|
||||
const models = response.models
|
||||
.filter((model) => model.type === "llm" && model.key.length > 0)
|
||||
.toSorted((a, b) => a.key.localeCompare(b.key))
|
||||
discovery.set(current.endpoint, { checked: Date.now(), apiKey: current.apiKey, models })
|
||||
return { source: current, models }
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
const refresh = Effect.fn("LMStudioPlugin.refresh")(function* () {
|
||||
const result = yield* discover()
|
||||
if (!result?.models || result.source !== source.current) return
|
||||
const hash = JSON.stringify(result.models)
|
||||
if (hash === loaded.hash) return
|
||||
loaded.models = result.models
|
||||
loaded.hash = hash
|
||||
yield* ctx.integration.reload()
|
||||
yield* ctx.catalog.reload()
|
||||
})
|
||||
|
||||
// Keep the last successful inventory through transient outages instead of flickering model availability.
|
||||
yield* refresh().pipe(Effect.ignore, Effect.repeat(Schedule.spaced(interval)), Effect.forkScoped)
|
||||
const reload = Effect.fn("LMStudioPlugin.reload")(function* () {
|
||||
const next = configured(yield* config.entries(), origin)
|
||||
if (
|
||||
next.baseURL === source.current.baseURL &&
|
||||
next.apiKey === source.current.apiKey &&
|
||||
next.endpoint === source.current.endpoint
|
||||
)
|
||||
return
|
||||
source.current = next
|
||||
loaded.models = []
|
||||
loaded.hash = "[]"
|
||||
yield* ctx.integration.reload()
|
||||
yield* ctx.catalog.reload()
|
||||
yield* refresh().pipe(Effect.ignore)
|
||||
})
|
||||
yield* ctx.event.subscribe().pipe(
|
||||
Stream.filter((event) => event.type === "config.updated"),
|
||||
Stream.runForEach(reload),
|
||||
Effect.forkScoped({ startImmediately: true }),
|
||||
)
|
||||
}),
|
||||
} satisfies PluginInternal.InternalPlugin)
|
||||
}
|
||||
|
||||
export const LMStudioPlugin = make()
|
||||
|
||||
function configured(entries: readonly Entry[], origin: string) {
|
||||
const settings = entries
|
||||
.filter((entry): entry is Document => entry.type === "document")
|
||||
.flatMap((entry) => {
|
||||
const settings = entry.info.providers?.[providerID]?.settings
|
||||
return settings ? [settings] : []
|
||||
})
|
||||
.reduce<Provider.Settings | undefined>((result, item) => Provider.mergeOverlay(result, item), undefined)
|
||||
const baseURL = (
|
||||
typeof settings?.baseURL === "string" ? settings.baseURL : `${origin.replace(/\/+$/, "")}/v1`
|
||||
).replace(/\/+$/, "")
|
||||
const apiKey = typeof settings?.apiKey === "string" ? settings.apiKey : undefined
|
||||
if (!URL.canParse(baseURL)) return { baseURL, apiKey }
|
||||
const url = new URL(baseURL)
|
||||
if (url.protocol !== "http:" && url.protocol !== "https:") return { baseURL, apiKey }
|
||||
const prefix = url.pathname.endsWith("/v1") ? url.pathname.slice(0, -3) : url.pathname.replace(/\/+$/, "")
|
||||
url.pathname = `${prefix}/api/v1/models`
|
||||
url.search = ""
|
||||
url.hash = ""
|
||||
return { baseURL, apiKey, endpoint: url.toString() }
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
import { define } from "@opencode-ai/plugin/effect/plugin"
|
||||
import { Document, type Entry } from "@opencode-ai/schema/config"
|
||||
import { Duration, Effect, Schedule, Schema, Semaphore, Stream } from "effect"
|
||||
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http"
|
||||
import { Config } from "../../config.js"
|
||||
import { Model } from "../../model.js"
|
||||
import { Provider } from "../../provider.js"
|
||||
import type { PluginInternal } from "../internal.js"
|
||||
|
||||
const providerID = "ollama"
|
||||
|
||||
const Details = Schema.Struct({
|
||||
parent_model: Schema.String.pipe(Schema.optional),
|
||||
format: Schema.String,
|
||||
family: Schema.String,
|
||||
families: Schema.Array(Schema.String).pipe(Schema.optional),
|
||||
parameter_size: Schema.String,
|
||||
quantization_level: Schema.String,
|
||||
})
|
||||
|
||||
const RemoteModel = Schema.Struct({
|
||||
name: Schema.String,
|
||||
model: Schema.String,
|
||||
remote_model: Schema.String.pipe(Schema.optional),
|
||||
remote_host: Schema.String.pipe(Schema.optional),
|
||||
modified_at: Schema.String,
|
||||
size: Schema.Int,
|
||||
digest: Schema.String,
|
||||
details: Details,
|
||||
})
|
||||
|
||||
const TagsResponse = Schema.Struct({ models: Schema.Array(RemoteModel) })
|
||||
const ShowRequest = Schema.Struct({ model: Schema.String })
|
||||
const ShowResponse = Schema.Struct({
|
||||
parameters: Schema.String.pipe(Schema.optional),
|
||||
license: Schema.String.pipe(Schema.optional),
|
||||
modified_at: Schema.String.pipe(Schema.optional),
|
||||
details: Details.pipe(Schema.optional),
|
||||
template: Schema.String.pipe(Schema.optional),
|
||||
capabilities: Schema.Array(Schema.String).pipe(Schema.optional),
|
||||
model_info: Schema.Record(Schema.String, Schema.Unknown).pipe(Schema.optional),
|
||||
})
|
||||
|
||||
type DiscoveredModel = typeof RemoteModel.Type & { show: typeof ShowResponse.Type }
|
||||
type Discovery = {
|
||||
checked: number
|
||||
apiKey?: string
|
||||
models?: DiscoveredModel[]
|
||||
shows: Map<string, { digest: string; info: typeof ShowResponse.Type }>
|
||||
}
|
||||
|
||||
const discovery = new Map<string, Discovery>()
|
||||
const discoveryLock = Semaphore.makeUnsafe(1)
|
||||
|
||||
export function make(origin = "http://127.0.0.1:11434", interval: Duration.Input = "30 seconds") {
|
||||
return define({
|
||||
id: "opencode.provider.ollama",
|
||||
effect: Effect.fn(function* (ctx) {
|
||||
const http = HttpClient.filterStatusOk(yield* HttpClient.HttpClient)
|
||||
const config = yield* Config.Service
|
||||
const source = { current: configured(yield* config.entries(), origin) }
|
||||
const loaded = { models: [] as DiscoveredModel[], hash: "[]" }
|
||||
|
||||
yield* ctx.integration.transform((integrations) => {
|
||||
if (loaded.models.length === 0) return
|
||||
integrations.remove(providerID)
|
||||
})
|
||||
|
||||
yield* ctx.catalog.transform((catalog) => {
|
||||
if (loaded.models.length === 0) return
|
||||
for (const model of catalog.provider.get(providerID)?.models.values() ?? []) {
|
||||
catalog.model.remove(providerID, model.id)
|
||||
}
|
||||
catalog.provider.update(providerID, (provider) => {
|
||||
provider.name = "Ollama"
|
||||
provider.activation = "enabled"
|
||||
provider.package = "@opencode-ai/ai/providers/openai-compatible"
|
||||
provider.settings = {
|
||||
baseURL: source.current.baseURL,
|
||||
provider: providerID,
|
||||
apiKey: source.current.apiKey ?? "",
|
||||
}
|
||||
provider.integrationID = undefined
|
||||
})
|
||||
for (const item of loaded.models) {
|
||||
catalog.model.update(providerID, item.model, (model) => {
|
||||
model.modelID = Model.ID.make(item.model)
|
||||
model.name = item.name || item.model
|
||||
model.family = item.show.details?.family
|
||||
? Model.Family.make(item.show.details.family)
|
||||
: item.details.family
|
||||
? Model.Family.make(item.details.family)
|
||||
: undefined
|
||||
model.capabilities = {
|
||||
tools: item.show.capabilities?.includes("tools") ?? false,
|
||||
input: ["text", ...(item.show.capabilities?.includes("vision") ? ["image"] : [])],
|
||||
output: ["text"],
|
||||
}
|
||||
model.limit = {
|
||||
context:
|
||||
Object.entries(item.show.model_info ?? {}).flatMap(([key, value]) =>
|
||||
key.endsWith(".context_length") && typeof value === "number" && value > 0 ? [value] : [],
|
||||
)[0] ?? 0,
|
||||
output: 0,
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
const discover = Effect.fn("OllamaPlugin.discover")(function* () {
|
||||
const current = source.current
|
||||
if (!current.tagsEndpoint || !current.showEndpoint) return undefined
|
||||
return yield* discoveryLock.withPermit(
|
||||
Effect.gen(function* () {
|
||||
const cached = discovery.get(current.tagsEndpoint)
|
||||
if (cached && cached.apiKey === current.apiKey && Date.now() - cached.checked < Duration.toMillis(interval))
|
||||
return { source: current, models: cached.models }
|
||||
const previous: Discovery =
|
||||
cached && cached.apiKey === current.apiKey
|
||||
? cached
|
||||
: { checked: 0, apiKey: current.apiKey, shows: new Map() }
|
||||
discovery.set(current.tagsEndpoint, { ...previous, checked: Date.now(), apiKey: current.apiKey })
|
||||
const tagsRequest = current.apiKey
|
||||
? HttpClientRequest.get(current.tagsEndpoint).pipe(
|
||||
HttpClientRequest.acceptJson,
|
||||
HttpClientRequest.bearerToken(current.apiKey),
|
||||
)
|
||||
: HttpClientRequest.get(current.tagsEndpoint).pipe(HttpClientRequest.acceptJson)
|
||||
const response = yield* http
|
||||
.execute(tagsRequest)
|
||||
.pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(TagsResponse)), Effect.timeout("1 second"))
|
||||
const summaries = response.models
|
||||
.filter((model) => model.model.length > 0)
|
||||
.toSorted((a, b) => a.model.localeCompare(b.model))
|
||||
const shows = new Map<string, { digest: string; info: typeof ShowResponse.Type }>()
|
||||
const models = yield* Effect.forEach(
|
||||
summaries,
|
||||
(model) =>
|
||||
Effect.gen(function* () {
|
||||
const saved = previous.shows.get(model.model)
|
||||
const info =
|
||||
saved?.digest === model.digest
|
||||
? saved.info
|
||||
: yield* HttpClientRequest.post(current.showEndpoint).pipe(
|
||||
HttpClientRequest.acceptJson,
|
||||
current.apiKey ? HttpClientRequest.bearerToken(current.apiKey) : (request) => request,
|
||||
HttpClientRequest.schemaBodyJson(ShowRequest)({ model: model.model }),
|
||||
Effect.flatMap(http.execute),
|
||||
Effect.flatMap(HttpClientResponse.schemaBodyJson(ShowResponse)),
|
||||
Effect.timeout("1 second"),
|
||||
)
|
||||
shows.set(model.model, { digest: model.digest, info })
|
||||
return { ...model, show: info }
|
||||
}).pipe(Effect.catch(() => Effect.succeed(undefined))),
|
||||
{ concurrency: 4 },
|
||||
)
|
||||
const filtered = models.filter(
|
||||
(model): model is DiscoveredModel =>
|
||||
model !== undefined && (model.show.capabilities?.includes("completion") ?? false),
|
||||
)
|
||||
discovery.set(current.tagsEndpoint, {
|
||||
checked: Date.now(),
|
||||
apiKey: current.apiKey,
|
||||
models: filtered,
|
||||
shows,
|
||||
})
|
||||
return { source: current, models: filtered }
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
const refresh = Effect.fn("OllamaPlugin.refresh")(function* () {
|
||||
const result = yield* discover()
|
||||
if (!result?.models || result.source !== source.current) return
|
||||
const hash = JSON.stringify(result.models)
|
||||
if (hash === loaded.hash) return
|
||||
loaded.models = result.models
|
||||
loaded.hash = hash
|
||||
yield* ctx.integration.reload()
|
||||
yield* ctx.catalog.reload()
|
||||
})
|
||||
|
||||
// Keep the last successful inventory through transient outages instead of flickering model availability.
|
||||
yield* refresh().pipe(Effect.ignore, Effect.repeat(Schedule.spaced(interval)), Effect.forkScoped)
|
||||
const reload = Effect.fn("OllamaPlugin.reload")(function* () {
|
||||
const next = configured(yield* config.entries(), origin)
|
||||
if (
|
||||
next.baseURL === source.current.baseURL &&
|
||||
next.apiKey === source.current.apiKey &&
|
||||
next.tagsEndpoint === source.current.tagsEndpoint
|
||||
)
|
||||
return
|
||||
source.current = next
|
||||
loaded.models = []
|
||||
loaded.hash = "[]"
|
||||
yield* ctx.integration.reload()
|
||||
yield* ctx.catalog.reload()
|
||||
yield* refresh().pipe(Effect.ignore)
|
||||
})
|
||||
yield* ctx.event.subscribe().pipe(
|
||||
Stream.filter((event) => event.type === "config.updated"),
|
||||
Stream.runForEach(reload),
|
||||
Effect.forkScoped({ startImmediately: true }),
|
||||
)
|
||||
}),
|
||||
} satisfies PluginInternal.InternalPlugin)
|
||||
}
|
||||
|
||||
export const OllamaPlugin = make()
|
||||
|
||||
function configured(entries: readonly Entry[], origin: string) {
|
||||
const settings = entries
|
||||
.filter((entry): entry is Document => entry.type === "document")
|
||||
.flatMap((entry) => {
|
||||
const settings = entry.info.providers?.[providerID]?.settings
|
||||
return settings ? [settings] : []
|
||||
})
|
||||
.reduce<Provider.Settings | undefined>((result, item) => Provider.mergeOverlay(result, item), undefined)
|
||||
const baseURL = (
|
||||
typeof settings?.baseURL === "string" ? settings.baseURL : `${origin.replace(/\/+$/, "")}/v1`
|
||||
).replace(/\/+$/, "")
|
||||
const apiKey = typeof settings?.apiKey === "string" ? settings.apiKey : undefined
|
||||
if (!URL.canParse(baseURL)) return { baseURL, apiKey }
|
||||
const url = new URL(baseURL)
|
||||
if (url.protocol !== "http:" && url.protocol !== "https:") return { baseURL, apiKey }
|
||||
const prefix = url.pathname.endsWith("/v1") ? url.pathname.slice(0, -3) : url.pathname.replace(/\/+$/, "")
|
||||
url.pathname = `${prefix}/api/tags`
|
||||
url.search = ""
|
||||
url.hash = ""
|
||||
const tagsEndpoint = url.toString()
|
||||
url.pathname = `${prefix}/api/show`
|
||||
return { baseURL, apiKey, tagsEndpoint, showEndpoint: url.toString() }
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
import { define } from "@opencode-ai/plugin/effect/plugin"
|
||||
import { Document, type Entry } from "@opencode-ai/schema/config"
|
||||
import { Duration, Effect, Schedule, Schema, Semaphore, Stream } from "effect"
|
||||
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http"
|
||||
import { Config } from "../../config.js"
|
||||
import { Model } from "../../model.js"
|
||||
import { Provider } from "../../provider.js"
|
||||
import type { PluginInternal } from "../internal.js"
|
||||
|
||||
const providerID = "vllm"
|
||||
|
||||
const RemoteModel = Schema.Struct({
|
||||
id: Schema.String,
|
||||
owned_by: Schema.String,
|
||||
max_model_len: Schema.NullOr(Schema.Int),
|
||||
})
|
||||
|
||||
const Response = Schema.Struct({ data: Schema.Array(RemoteModel) })
|
||||
const discovery = new Map<string, { checked: number; apiKey?: string; models?: (typeof RemoteModel.Type)[] }>()
|
||||
const discoveryLock = Semaphore.makeUnsafe(1)
|
||||
|
||||
export function make(origin = "http://127.0.0.1:8000", interval: Duration.Input = "30 seconds") {
|
||||
return define({
|
||||
id: "opencode.provider.vllm",
|
||||
effect: Effect.fn(function* (ctx) {
|
||||
const http = HttpClient.filterStatusOk(yield* HttpClient.HttpClient)
|
||||
const config = yield* Config.Service
|
||||
const source = { current: configured(yield* config.entries(), origin) }
|
||||
const loaded = { models: [] as (typeof RemoteModel.Type)[], hash: "[]" }
|
||||
|
||||
yield* ctx.integration.transform((integrations) => {
|
||||
if (loaded.models.length === 0) return
|
||||
integrations.remove(providerID)
|
||||
})
|
||||
|
||||
yield* ctx.catalog.transform((catalog) => {
|
||||
if (loaded.models.length === 0) return
|
||||
for (const model of catalog.provider.get(providerID)?.models.values() ?? []) {
|
||||
catalog.model.remove(providerID, model.id)
|
||||
}
|
||||
catalog.provider.update(providerID, (provider) => {
|
||||
provider.name = "vLLM"
|
||||
provider.package = "@opencode-ai/ai/providers/openai-compatible"
|
||||
provider.settings = {
|
||||
baseURL: source.current.baseURL,
|
||||
provider: providerID,
|
||||
apiKey: source.current.apiKey ?? "",
|
||||
}
|
||||
provider.integrationID = undefined
|
||||
provider.activation = "enabled"
|
||||
})
|
||||
for (const item of loaded.models) {
|
||||
catalog.model.update(providerID, item.id, (model) => {
|
||||
model.modelID = Model.ID.make(item.id)
|
||||
model.name = item.id
|
||||
// Tool calling depends on vLLM server flags and parsers that model discovery does not report.
|
||||
model.capabilities = { tools: false, input: ["text"], output: ["text"] }
|
||||
model.limit = { context: item.max_model_len ?? 0, output: 0 }
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
const discover = Effect.fn("VLLMPlugin.discover")(function* () {
|
||||
const current = source.current
|
||||
if (!current.healthEndpoint || !current.modelsEndpoint) return undefined
|
||||
return yield* discoveryLock.withPermit(
|
||||
Effect.gen(function* () {
|
||||
const endpoint = `${current.healthEndpoint}\n${current.modelsEndpoint}`
|
||||
const cached = discovery.get(endpoint)
|
||||
if (cached && cached.apiKey === current.apiKey && Date.now() - cached.checked < Duration.toMillis(interval))
|
||||
return { source: current, models: cached.models }
|
||||
discovery.set(endpoint, {
|
||||
checked: Date.now(),
|
||||
apiKey: current.apiKey,
|
||||
models: cached && cached.apiKey === current.apiKey ? cached.models : undefined,
|
||||
})
|
||||
const request = (endpoint: string) =>
|
||||
current.apiKey
|
||||
? HttpClientRequest.get(endpoint).pipe(
|
||||
HttpClientRequest.acceptJson,
|
||||
HttpClientRequest.bearerToken(current.apiKey),
|
||||
)
|
||||
: HttpClientRequest.get(endpoint).pipe(HttpClientRequest.acceptJson)
|
||||
yield* http.execute(request(current.healthEndpoint)).pipe(Effect.timeout("1 second"))
|
||||
const response = yield* http
|
||||
.execute(request(current.modelsEndpoint))
|
||||
.pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(Response)), Effect.timeout("1 second"))
|
||||
const models = response.data
|
||||
.filter((model) => model.owned_by === providerID && model.id.length > 0)
|
||||
.toSorted((a, b) => a.id.localeCompare(b.id))
|
||||
discovery.set(endpoint, { checked: Date.now(), apiKey: current.apiKey, models })
|
||||
return { source: current, models }
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
const refresh = Effect.fn("VLLMPlugin.refresh")(function* () {
|
||||
const result = yield* discover()
|
||||
if (!result?.models || result.source !== source.current) return
|
||||
const hash = JSON.stringify(result.models)
|
||||
if (hash === loaded.hash) return
|
||||
loaded.models = result.models
|
||||
loaded.hash = hash
|
||||
yield* ctx.integration.reload()
|
||||
yield* ctx.catalog.reload()
|
||||
})
|
||||
|
||||
// Keep the last successful inventory through transient outages instead of flickering model availability.
|
||||
yield* refresh().pipe(Effect.ignore, Effect.repeat(Schedule.spaced(interval)), Effect.forkScoped)
|
||||
const reload = Effect.fn("VLLMPlugin.reload")(function* () {
|
||||
const next = configured(yield* config.entries(), origin)
|
||||
if (
|
||||
next.baseURL === source.current.baseURL &&
|
||||
next.apiKey === source.current.apiKey &&
|
||||
next.healthEndpoint === source.current.healthEndpoint &&
|
||||
next.modelsEndpoint === source.current.modelsEndpoint
|
||||
)
|
||||
return
|
||||
source.current = next
|
||||
loaded.models = []
|
||||
loaded.hash = "[]"
|
||||
yield* ctx.integration.reload()
|
||||
yield* ctx.catalog.reload()
|
||||
yield* refresh().pipe(Effect.ignore)
|
||||
})
|
||||
yield* ctx.event.subscribe().pipe(
|
||||
Stream.filter((event) => event.type === "config.updated"),
|
||||
Stream.runForEach(reload),
|
||||
Effect.forkScoped({ startImmediately: true }),
|
||||
)
|
||||
}),
|
||||
} satisfies PluginInternal.InternalPlugin)
|
||||
}
|
||||
|
||||
export const VLLMPlugin = make()
|
||||
|
||||
function configured(entries: readonly Entry[], origin: string) {
|
||||
const settings = entries
|
||||
.filter((entry): entry is Document => entry.type === "document")
|
||||
.flatMap((entry) => {
|
||||
const settings = entry.info.providers?.[providerID]?.settings
|
||||
return settings ? [settings] : []
|
||||
})
|
||||
.reduce<Provider.Settings | undefined>((result, item) => Provider.mergeOverlay(result, item), undefined)
|
||||
const baseURL = (
|
||||
typeof settings?.baseURL === "string" ? settings.baseURL : `${origin.replace(/\/+$/, "")}/v1`
|
||||
).replace(/\/+$/, "")
|
||||
const apiKey = typeof settings?.apiKey === "string" ? settings.apiKey : undefined
|
||||
if (!URL.canParse(baseURL)) return { baseURL, apiKey }
|
||||
const models = new URL(baseURL)
|
||||
if (models.protocol !== "http:" && models.protocol !== "https:") return { baseURL, apiKey }
|
||||
models.pathname = `${models.pathname.replace(/\/+$/, "")}/models`
|
||||
models.search = ""
|
||||
models.hash = ""
|
||||
const health = new URL(baseURL)
|
||||
const path = health.pathname.replace(/\/+$/, "")
|
||||
const prefix = path.endsWith("/v1") ? path.slice(0, -3) : path
|
||||
health.pathname = `${prefix}/health`
|
||||
health.search = ""
|
||||
health.hash = ""
|
||||
return { baseURL, apiKey, healthEndpoint: health.toString(), modelsEndpoint: models.toString() }
|
||||
}
|
||||
@@ -29,10 +29,41 @@ V1 documentation and syntax may be consulted only when the user explicitly
|
||||
asks about V1 or when needed as migration input. Outputs and recommendations
|
||||
must still use V2 unless the user specifically requests a V1 result.
|
||||
|
||||
## [Configuration](https://opencode.ai/v2/docs/config)
|
||||
## [CLI](https://opencode.ai/v2/docs/cli)
|
||||
|
||||
OpenCode configuration uses JSON or JSONC. Include the published schema so the
|
||||
user's editor can validate fields and provide autocomplete:
|
||||
For questions about the terminal interface, command-line invocation, `run`,
|
||||
`mini`, terminal providers, or other CLI behavior, fetch the
|
||||
[CLI guide](https://opencode.ai/v2/docs/cli) and the relevant page linked from
|
||||
that section.
|
||||
|
||||
CLI and TUI preferences are separate from OpenCode's server and project
|
||||
configuration. They live in the global `~/.config/opencode/cli.json`, or
|
||||
`$XDG_CONFIG_HOME/opencode/cli.json` when `XDG_CONFIG_HOME` is set. There is no
|
||||
project-local CLI configuration. Most preferences can also be changed from the
|
||||
TUI by pressing `Ctrl+P` and selecting **Open settings**.
|
||||
|
||||
Fetch the full [CLI configuration guide](https://opencode.ai/v2/docs/cli/config)
|
||||
before editing `cli.json`. It covers terminal-only settings such as themes,
|
||||
keybindings, terminal plugins, scrolling, attention alerts, diff presentation,
|
||||
and terminal integration. Do not put these settings in `opencode.json(c)`.
|
||||
|
||||
### [Keybinds](https://opencode.ai/v2/docs/cli/keybinds)
|
||||
|
||||
Configure keybindings under `keybinds` in `cli.json`. The leader key is the
|
||||
`keybinds.leader` entry; leader timing is configured separately under
|
||||
`leader.timeout`. Bindings can use a string, an array of strings, or an object
|
||||
when event behavior such as `preventDefault` is required. Disable a binding
|
||||
with `"none"` or `false`.
|
||||
|
||||
Never guess a command ID, default binding, or accepted key syntax. Fetch the
|
||||
full [keybind reference](https://opencode.ai/v2/docs/cli/keybinds), which lists
|
||||
the current IDs and defaults, before answering or editing a binding.
|
||||
|
||||
## [OpenCode configuration](https://opencode.ai/v2/docs/config)
|
||||
|
||||
OpenCode's server and project configuration uses JSON or JSONC. Include the
|
||||
published schema so the user's editor can validate fields and provide
|
||||
autocomplete:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
@@ -55,6 +86,10 @@ Common configuration fields include `model`, `default_agent`, `permissions`,
|
||||
`agents`, `commands`, `plugins`, `providers`, `mcp`, `skills`, `instructions`,
|
||||
`references`, `formatter`, and `lsp`.
|
||||
|
||||
This configuration is distinct from `cli.json`. Use the
|
||||
[CLI configuration guide](https://opencode.ai/v2/docs/cli/config) for terminal
|
||||
preferences, especially themes and keybindings.
|
||||
|
||||
Do not guess field names or shapes. Fetch the V2 configuration guide and its
|
||||
linked topic guide as the source of truth, and preserve unrelated settings when
|
||||
editing an existing file. Keep the published `$schema` URL in configuration
|
||||
|
||||
@@ -165,6 +165,7 @@ export interface Interface {
|
||||
input: ForkInput,
|
||||
) => Effect.Effect<SessionSchema.Info, NotFoundError | MessageNotFoundError | ForkEmptyError>
|
||||
readonly get: (sessionID: SessionSchema.ID) => Effect.Effect<SessionSchema.Info, NotFoundError>
|
||||
readonly view: (input: { sessionID: SessionSchema.ID }) => Effect.Effect<void, NotFoundError>
|
||||
readonly remove: (sessionID: SessionSchema.ID) => Effect.Effect<void, NotFoundError>
|
||||
readonly messages: (input: {
|
||||
sessionID: SessionSchema.ID
|
||||
@@ -447,6 +448,17 @@ const layer = Layer.effect(
|
||||
if (!session) return yield* new NotFoundError({ sessionID })
|
||||
return session
|
||||
}),
|
||||
view: Effect.fn("Session.view")(function* (input) {
|
||||
const row = yield* db
|
||||
.select({ idle: SessionTable.time_idle, viewed: SessionTable.time_viewed })
|
||||
.from(SessionTable)
|
||||
.where(eq(SessionTable.id, input.sessionID))
|
||||
.get()
|
||||
.pipe(Effect.orDie)
|
||||
if (!row) return yield* new NotFoundError({ sessionID: input.sessionID })
|
||||
if (row.idle === null || (row.viewed !== null && row.viewed >= row.idle)) return
|
||||
yield* bus.publish(SessionEvent.Viewed, { sessionID: input.sessionID })
|
||||
}),
|
||||
remove: Effect.fn("Session.remove")(function* (sessionID) {
|
||||
const session = yield* result.get(sessionID)
|
||||
yield* execution.interrupt(sessionID)
|
||||
|
||||
@@ -53,6 +53,8 @@ export function fromRow(row: typeof SessionTable.$inferSelect): SessionSchema.In
|
||||
time: {
|
||||
created: DateTime.makeUnsafe(row.time_created),
|
||||
updated: DateTime.makeUnsafe(row.time_updated),
|
||||
idle: row.time_idle === null ? undefined : DateTime.makeUnsafe(row.time_idle),
|
||||
viewed: row.time_viewed === null ? undefined : DateTime.makeUnsafe(row.time_viewed),
|
||||
archived: row.time_archived ? DateTime.makeUnsafe(row.time_archived) : undefined,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -60,6 +60,7 @@ export function update(adapter: Adapter, event: SessionEvent.DurableEvent) {
|
||||
Match.type<SessionEvent.DurableEvent>(),
|
||||
Match.discriminatorsExhaustive("type")({
|
||||
"session.created": () => Effect.void,
|
||||
"session.viewed": () => Effect.void,
|
||||
"session.usage.recorded": () => Effect.void,
|
||||
"session.agent.selected": (event) => {
|
||||
return Effect.gen(function* () {
|
||||
|
||||
@@ -391,6 +391,30 @@ function insertMessage(db: DatabaseService, event: SessionEvent.DurableEvent, me
|
||||
.pipe(Effect.orDie)
|
||||
}
|
||||
|
||||
function projectIdle(
|
||||
db: DatabaseService,
|
||||
event:
|
||||
| typeof SessionEvent.Execution.Succeeded.Type
|
||||
| typeof SessionEvent.Execution.Failed.Type
|
||||
| typeof SessionEvent.Execution.Interrupted.Type,
|
||||
) {
|
||||
return Effect.gen(function* () {
|
||||
yield* run(db, event)
|
||||
if (event.type === SessionEvent.Execution.Interrupted.type && event.data.reason === "shutdown") return
|
||||
const time = event.created
|
||||
yield* db
|
||||
.update(SessionTable)
|
||||
.set({
|
||||
// Unread uses a strict timestamp comparison, so every terminal must advance even within one millisecond.
|
||||
time_idle: sql`max(${time}, coalesce(${SessionTable.time_idle} + 1, ${time}))`,
|
||||
time_updated: sql`${SessionTable.time_updated}`,
|
||||
})
|
||||
.where(eq(SessionTable.id, event.data.sessionID))
|
||||
.run()
|
||||
.pipe(Effect.orDie)
|
||||
})
|
||||
}
|
||||
|
||||
const layer = Layer.effectDiscard(
|
||||
Effect.gen(function* () {
|
||||
const bus = yield* Bus.Service
|
||||
@@ -512,6 +536,17 @@ const layer = Layer.effectDiscard(
|
||||
.run()
|
||||
.pipe(Effect.orDie),
|
||||
)
|
||||
yield* bus.project(SessionEvent.Viewed, (event) =>
|
||||
db
|
||||
.update(SessionTable)
|
||||
.set({
|
||||
time_viewed: sql`${SessionTable.time_idle}`,
|
||||
time_updated: sql`${SessionTable.time_updated}`,
|
||||
})
|
||||
.where(eq(SessionTable.id, event.data.sessionID))
|
||||
.run()
|
||||
.pipe(Effect.orDie),
|
||||
)
|
||||
yield* bus.project(SessionEvent.UsageRecorded, (event) => applyUsage(db, event.data.sessionID, event.data))
|
||||
yield* bus.project(SessionEvent.Forked, (event) => projectFork(db, event))
|
||||
yield* bus.project(SessionEvent.InboxDelivered, (event) =>
|
||||
@@ -580,9 +615,9 @@ const layer = Layer.effectDiscard(
|
||||
delivery: event.data.delivery,
|
||||
}),
|
||||
)
|
||||
yield* bus.project(SessionEvent.Execution.Succeeded, (event) => run(db, event))
|
||||
yield* bus.project(SessionEvent.Execution.Failed, (event) => run(db, event))
|
||||
yield* bus.project(SessionEvent.Execution.Interrupted, (event) => run(db, event))
|
||||
yield* bus.project(SessionEvent.Execution.Succeeded, (event) => projectIdle(db, event))
|
||||
yield* bus.project(SessionEvent.Execution.Failed, (event) => projectIdle(db, event))
|
||||
yield* bus.project(SessionEvent.Execution.Interrupted, (event) => projectIdle(db, event))
|
||||
yield* bus.project(SessionEvent.InstructionsUpdated, (event) =>
|
||||
Effect.gen(function* () {
|
||||
yield* run(db, event)
|
||||
|
||||
@@ -56,6 +56,8 @@ export const SessionTable = sqliteTable(
|
||||
variant?: string
|
||||
}>(),
|
||||
...Timestamps,
|
||||
time_idle: integer(),
|
||||
time_viewed: integer(),
|
||||
time_compacting: integer(),
|
||||
time_archived: integer(),
|
||||
/** The execution claim timestamp (historical column name; see SessionStore.claim). */
|
||||
|
||||
@@ -117,6 +117,10 @@ const layer = Layer.effect(
|
||||
tokens_cache_write: input.data.info.tokens.cache.write,
|
||||
time_created: DateTime.toEpochMillis(input.data.info.time.created),
|
||||
time_updated: DateTime.toEpochMillis(input.data.info.time.updated),
|
||||
time_idle: input.data.info.time.idle ? DateTime.toEpochMillis(input.data.info.time.idle) : null,
|
||||
time_viewed: input.data.info.time.viewed
|
||||
? DateTime.toEpochMillis(input.data.info.time.viewed)
|
||||
: null,
|
||||
time_archived: input.data.info.time.archived
|
||||
? DateTime.toEpochMillis(input.data.info.time.archived)
|
||||
: null,
|
||||
|
||||
@@ -13,6 +13,7 @@ import { tmpdir } from "./fixture/tmpdir"
|
||||
import type { SqlClient } from "effect/unstable/sql/SqlClient"
|
||||
import legacyCredentialsMigration from "@opencode-ai/core/database/migration/20260805200742_import_legacy_credentials"
|
||||
import worktreeMigration from "@opencode-ai/core/database/migration/20260812213948_worktree"
|
||||
import sessionViewedStateMigration from "@opencode-ai/core/database/migration/20260815182818_session_viewed_state"
|
||||
import { Global } from "@opencode-ai/util/global"
|
||||
|
||||
const run = <A, E>(
|
||||
@@ -73,6 +74,27 @@ describe("DatabaseMigration", () => {
|
||||
)
|
||||
})
|
||||
|
||||
test("adds nullable attention state to existing sessions", async () => {
|
||||
await run(
|
||||
Effect.gen(function* () {
|
||||
const db = yield* makeDb
|
||||
yield* db.run(sql`CREATE TABLE session_v2 (id text PRIMARY KEY, title text)`)
|
||||
yield* db.run(sql`INSERT INTO session_v2 (id, title) VALUES ('ses_existing', 'Existing')`)
|
||||
|
||||
yield* DatabaseMigration.applyOnly(db, [sessionViewedStateMigration])
|
||||
yield* DatabaseMigration.applyOnly(db, [sessionViewedStateMigration])
|
||||
|
||||
expect(yield* db.get(sql`SELECT id, title, time_idle, time_viewed FROM session_v2`)).toEqual({
|
||||
id: "ses_existing",
|
||||
title: "Existing",
|
||||
time_idle: null,
|
||||
time_viewed: null,
|
||||
})
|
||||
expect(yield* db.get(sql`SELECT count(*) AS count FROM migration`)).toEqual({ count: 1 })
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
test("rejects a non-empty database without a session table", async () => {
|
||||
await expect(
|
||||
run(
|
||||
|
||||
@@ -0,0 +1,341 @@
|
||||
import { Bus } from "@opencode-ai/core/bus"
|
||||
import { Catalog } from "@opencode-ai/core/catalog"
|
||||
import { Config } from "@opencode-ai/core/config"
|
||||
import { Integration } from "@opencode-ai/core/integration"
|
||||
import { Model } from "@opencode-ai/core/model"
|
||||
import { Plugin } from "@opencode-ai/core/plugin"
|
||||
import { PluginHost } from "@opencode-ai/core/plugin/host"
|
||||
import { LMStudioPlugin, make } from "@opencode-ai/core/plugin/provider/lmstudio"
|
||||
import { ProviderPlugins } from "@opencode-ai/core/plugin/provider"
|
||||
import { Provider } from "@opencode-ai/core/provider"
|
||||
import { Document, Event, Info } from "@opencode-ai/schema/config"
|
||||
import { describe, expect } from "bun:test"
|
||||
import { Duration, Effect, Layer, Schema } from "effect"
|
||||
import { testEffect } from "../lib/effect"
|
||||
import { PluginTestLayer } from "./fixture"
|
||||
|
||||
const it = testEffect(Layer.merge(PluginTestLayer, Config.testLayer()))
|
||||
const decode = Schema.decodeUnknownSync(Info)
|
||||
|
||||
const addPlugin = Effect.fn(function* (origin: string, interval: Duration.Input = "1 hour") {
|
||||
const plugin = yield* Plugin.Service
|
||||
const host = yield* PluginHost.make(plugin)
|
||||
yield* make(origin, interval).effect(host)
|
||||
})
|
||||
|
||||
function eventually<A>(
|
||||
effect: Effect.Effect<A>,
|
||||
predicate: (value: A) => boolean,
|
||||
remaining = 3000,
|
||||
): Effect.Effect<A, Error> {
|
||||
return Effect.gen(function* () {
|
||||
const value = yield* effect
|
||||
if (predicate(value)) return value
|
||||
if (remaining === 0) return yield* Effect.fail(new Error("Timed out waiting for value"))
|
||||
yield* Effect.promise(() => Bun.sleep(1))
|
||||
return yield* eventually(effect, predicate, remaining - 1)
|
||||
})
|
||||
}
|
||||
|
||||
describe("LMStudioPlugin", () => {
|
||||
it.effect("is registered as a built-in provider plugin", () =>
|
||||
Effect.sync(() => {
|
||||
expect(LMStudioPlugin.id).toBe("opencode.provider.lmstudio")
|
||||
expect(ProviderPlugins.map((item) => item.id)).toContain("opencode.provider.lmstudio")
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("discovers local language models with their capabilities and effective context", () =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.sync(() =>
|
||||
Bun.serve({
|
||||
port: 0,
|
||||
fetch: () =>
|
||||
Response.json({
|
||||
models: [
|
||||
{
|
||||
type: "llm",
|
||||
key: "google/gemma-4-26b-a4b",
|
||||
display_name: "Gemma 4 26B A4B",
|
||||
architecture: "gemma4",
|
||||
loaded_instances: [{ config: { context_length: 32_768 } }, { config: { context_length: 16_384 } }],
|
||||
max_context_length: 262_144,
|
||||
capabilities: { vision: true, trained_for_tool_use: true },
|
||||
},
|
||||
{
|
||||
type: "llm",
|
||||
key: "deepseek-r1",
|
||||
display_name: "DeepSeek R1",
|
||||
architecture: "deepseek",
|
||||
loaded_instances: [],
|
||||
max_context_length: 131_072,
|
||||
capabilities: { vision: false, trained_for_tool_use: false },
|
||||
},
|
||||
{
|
||||
type: "embedding",
|
||||
key: "nomic-embed",
|
||||
display_name: "Nomic Embed",
|
||||
loaded_instances: [],
|
||||
max_context_length: 2048,
|
||||
},
|
||||
],
|
||||
}),
|
||||
}),
|
||||
),
|
||||
(server) =>
|
||||
Effect.gen(function* () {
|
||||
const catalog = yield* Catalog.Service
|
||||
yield* addPlugin(server.url.origin)
|
||||
const providerID = Provider.ID.make("lmstudio")
|
||||
const gemma = yield* eventually(
|
||||
catalog.model.get(providerID, Model.ID.make("google/gemma-4-26b-a4b")),
|
||||
(model) => model !== undefined,
|
||||
)
|
||||
|
||||
expect(yield* catalog.provider.get(providerID)).toEqual({
|
||||
id: providerID,
|
||||
name: "LM Studio",
|
||||
activation: "enabled",
|
||||
package: "@opencode-ai/ai/providers/openai-compatible",
|
||||
settings: { baseURL: `${server.url.origin}/v1`, provider: "lmstudio", apiKey: "" },
|
||||
})
|
||||
expect((yield* catalog.provider.available()).map((provider) => provider.id)).toContain(providerID)
|
||||
expect(gemma).toMatchObject({
|
||||
family: "gemma4",
|
||||
name: "Gemma 4 26B A4B",
|
||||
capabilities: { tools: true, input: ["text", "image"], output: ["text"] },
|
||||
limit: { context: 16_384, output: 0 },
|
||||
})
|
||||
expect(yield* catalog.model.get(providerID, Model.ID.make("deepseek-r1"))).toMatchObject({
|
||||
capabilities: { tools: false, input: ["text"], output: ["text"] },
|
||||
limit: { context: 131_072, output: 0 },
|
||||
})
|
||||
expect(yield* catalog.model.get(providerID, Model.ID.make("nomic-embed"))).toBeUndefined()
|
||||
}),
|
||||
(server) => Effect.promise(() => server.stop(true)),
|
||||
),
|
||||
)
|
||||
|
||||
it.live("refreshes the catalog when LM Studio models change", () =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.sync(() => {
|
||||
const models: Array<Record<string, unknown>> = []
|
||||
return {
|
||||
models,
|
||||
server: Bun.serve({ port: 0, fetch: () => Response.json({ models }) }),
|
||||
}
|
||||
}),
|
||||
({ models, server }) =>
|
||||
Effect.gen(function* () {
|
||||
const catalog = yield* Catalog.Service
|
||||
const providerID = Provider.ID.make("lmstudio")
|
||||
yield* addPlugin(server.url.origin, "5 millis")
|
||||
expect(yield* catalog.provider.get(providerID)).toBeUndefined()
|
||||
|
||||
models.push({
|
||||
type: "llm",
|
||||
key: "qwen/qwen3-coder",
|
||||
display_name: "Qwen 3 Coder",
|
||||
architecture: "qwen3",
|
||||
loaded_instances: [],
|
||||
max_context_length: 65_536,
|
||||
capabilities: { vision: false, trained_for_tool_use: true },
|
||||
})
|
||||
expect(
|
||||
yield* eventually(
|
||||
catalog.model.get(providerID, Model.ID.make("qwen/qwen3-coder")),
|
||||
(model) => model !== undefined,
|
||||
),
|
||||
).toMatchObject({ name: "Qwen 3 Coder" })
|
||||
|
||||
models.splice(0)
|
||||
yield* eventually(catalog.provider.get(providerID), (provider) => provider === undefined)
|
||||
}),
|
||||
({ server }) => Effect.promise(() => server.stop(true)),
|
||||
),
|
||||
)
|
||||
|
||||
it.live(
|
||||
"discovers from configured endpoints with bearer authentication",
|
||||
() =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.sync(() => {
|
||||
const requests: Array<{ authorization: string | null; path: string }> = []
|
||||
const model = (key: string) => ({
|
||||
type: "llm",
|
||||
key,
|
||||
display_name: key,
|
||||
loaded_instances: [],
|
||||
max_context_length: 32_768,
|
||||
})
|
||||
return {
|
||||
requests,
|
||||
initial: Bun.serve({ port: 0, fetch: () => Response.json({ models: [model("initial-model")] }) }),
|
||||
configured: Bun.serve({
|
||||
port: 0,
|
||||
fetch: (request) => {
|
||||
requests.push({
|
||||
authorization: request.headers.get("authorization"),
|
||||
path: new URL(request.url).pathname,
|
||||
})
|
||||
return Response.json({ models: [model("configured-model")] })
|
||||
},
|
||||
}),
|
||||
}
|
||||
}),
|
||||
({ requests, initial, configured }) =>
|
||||
Effect.gen(function* () {
|
||||
const bus = yield* Bus.Service
|
||||
const catalog = yield* Catalog.Service
|
||||
const config = yield* Config.Test
|
||||
const providerID = Provider.ID.make("lmstudio")
|
||||
yield* addPlugin(initial.url.origin)
|
||||
yield* eventually(
|
||||
catalog.model.get(providerID, Model.ID.make("initial-model")),
|
||||
(model) => model !== undefined,
|
||||
)
|
||||
|
||||
const baseURL = `${configured.url.origin}/proxy/v1`
|
||||
yield* config.setEntries([configuration(baseURL, "secret")])
|
||||
yield* bus.publish(Event.Updated, {})
|
||||
yield* eventually(
|
||||
catalog.model.get(providerID, Model.ID.make("configured-model")),
|
||||
(model) => model !== undefined,
|
||||
)
|
||||
|
||||
expect(requests).toContainEqual({ authorization: "Bearer secret", path: "/proxy/api/v1/models" })
|
||||
expect(yield* catalog.model.get(providerID, Model.ID.make("initial-model"))).toBeUndefined()
|
||||
expect((yield* catalog.provider.get(providerID))?.settings).toEqual({
|
||||
baseURL,
|
||||
provider: "lmstudio",
|
||||
apiKey: "secret",
|
||||
})
|
||||
|
||||
requests.splice(0)
|
||||
yield* config.setEntries([configuration(baseURL, "secret"), configuration(baseURL, null)])
|
||||
yield* bus.publish(Event.Updated, {})
|
||||
yield* eventually(catalog.provider.get(providerID), (provider) => provider?.settings?.apiKey === "")
|
||||
expect(requests).toContainEqual({ authorization: null, path: "/proxy/api/v1/models" })
|
||||
}),
|
||||
({ initial, configured }) => Effect.promise(() => Promise.all([initial.stop(true), configured.stop(true)])),
|
||||
),
|
||||
10_000,
|
||||
)
|
||||
|
||||
it.live("shares discovery requests across plugin instances", () =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.sync(() => {
|
||||
const requests = { count: 0 }
|
||||
return {
|
||||
requests,
|
||||
server: Bun.serve({
|
||||
port: 0,
|
||||
fetch: () => {
|
||||
requests.count++
|
||||
return Response.json({
|
||||
models: [
|
||||
{
|
||||
type: "llm",
|
||||
key: "shared-model",
|
||||
display_name: "Shared Model",
|
||||
loaded_instances: [],
|
||||
max_context_length: 32_768,
|
||||
},
|
||||
],
|
||||
})
|
||||
},
|
||||
}),
|
||||
}
|
||||
}),
|
||||
({ requests, server }) =>
|
||||
Effect.gen(function* () {
|
||||
const catalog = yield* Catalog.Service
|
||||
yield* addPlugin(server.url.origin)
|
||||
yield* addPlugin(server.url.origin)
|
||||
yield* eventually(
|
||||
catalog.model.get(Provider.ID.make("lmstudio"), Model.ID.make("shared-model")),
|
||||
(model) => model !== undefined,
|
||||
)
|
||||
expect(requests.count).toBe(1)
|
||||
}),
|
||||
({ server }) => Effect.promise(() => server.stop(true)),
|
||||
),
|
||||
)
|
||||
|
||||
it.live("replaces the credential-gated Models.dev catalog when discovery succeeds", () =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.sync(() => {
|
||||
const models = [
|
||||
{
|
||||
type: "llm",
|
||||
key: "discovered-model",
|
||||
display_name: "Discovered Model",
|
||||
loaded_instances: [],
|
||||
max_context_length: 32_768,
|
||||
},
|
||||
]
|
||||
return { models, server: Bun.serve({ port: 0, fetch: () => Response.json({ models }) }) }
|
||||
}),
|
||||
({ models, server }) =>
|
||||
Effect.gen(function* () {
|
||||
const catalog = yield* Catalog.Service
|
||||
const integrations = yield* Integration.Service
|
||||
const providerID = Provider.ID.make("lmstudio")
|
||||
yield* integrations.transform((draft) => {
|
||||
draft.update(Integration.ID.make("lmstudio"), (integration) => {
|
||||
integration.name = "LMStudio"
|
||||
})
|
||||
draft.method.update({
|
||||
integrationID: Integration.ID.make("lmstudio"),
|
||||
method: { type: "env", names: ["LMSTUDIO_API_KEY"] },
|
||||
})
|
||||
})
|
||||
yield* catalog.transform((draft) => {
|
||||
draft.provider.update(providerID, (provider) => {
|
||||
provider.name = "LMStudio"
|
||||
provider.package = "aisdk:@ai-sdk/openai-compatible"
|
||||
provider.integrationID = Integration.ID.make("lmstudio")
|
||||
})
|
||||
draft.model.update(providerID, Model.ID.make("static-model"), () => {})
|
||||
})
|
||||
|
||||
expect((yield* catalog.provider.available()).map((provider) => provider.id)).not.toContain(providerID)
|
||||
yield* addPlugin(server.url.origin, "5 millis")
|
||||
yield* eventually(
|
||||
catalog.model.get(providerID, Model.ID.make("discovered-model")),
|
||||
(model) => model !== undefined,
|
||||
)
|
||||
|
||||
expect(yield* integrations.get(Integration.ID.make("lmstudio"))).toBeUndefined()
|
||||
expect((yield* catalog.provider.get(providerID))?.integrationID).toBeUndefined()
|
||||
expect(yield* catalog.model.get(providerID, Model.ID.make("static-model"))).toBeUndefined()
|
||||
expect((yield* catalog.provider.available()).map((provider) => provider.id)).toContain(providerID)
|
||||
|
||||
yield* integrations.transform((draft) => {
|
||||
draft.update(Integration.ID.make("lmstudio"), (integration) => {
|
||||
integration.name = "Configured LM Studio"
|
||||
})
|
||||
draft.method.update({ integrationID: Integration.ID.make("lmstudio"), method: { type: "key" } })
|
||||
})
|
||||
expect((yield* catalog.provider.available()).map((provider) => provider.id)).toContain(providerID)
|
||||
|
||||
models.splice(0)
|
||||
yield* eventually(
|
||||
catalog.model.get(providerID, Model.ID.make("static-model")),
|
||||
(model) => model !== undefined,
|
||||
)
|
||||
expect(yield* catalog.model.get(providerID, Model.ID.make("discovered-model"))).toBeUndefined()
|
||||
expect(yield* integrations.get(Integration.ID.make("lmstudio"))).toBeDefined()
|
||||
expect((yield* catalog.provider.get(providerID))?.integrationID).toBe(Integration.ID.make("lmstudio"))
|
||||
}),
|
||||
({ server }) => Effect.promise(() => server.stop(true)),
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
function configuration(baseURL: string, apiKey: string | null) {
|
||||
return new Document({
|
||||
type: "document",
|
||||
info: decode({ providers: { lmstudio: { settings: { baseURL, apiKey } } } }),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
import { Bus } from "@opencode-ai/core/bus"
|
||||
import { Catalog } from "@opencode-ai/core/catalog"
|
||||
import { Config } from "@opencode-ai/core/config"
|
||||
import { Integration } from "@opencode-ai/core/integration"
|
||||
import { Model } from "@opencode-ai/core/model"
|
||||
import { Plugin } from "@opencode-ai/core/plugin"
|
||||
import { PluginHost } from "@opencode-ai/core/plugin/host"
|
||||
import { OllamaPlugin, make } from "@opencode-ai/core/plugin/provider/ollama"
|
||||
import { ProviderPlugins } from "@opencode-ai/core/plugin/provider"
|
||||
import { Provider } from "@opencode-ai/core/provider"
|
||||
import { Document, Event, Info } from "@opencode-ai/schema/config"
|
||||
import { describe, expect } from "bun:test"
|
||||
import { Duration, Effect, Layer, Schema } from "effect"
|
||||
import { testEffect } from "../lib/effect"
|
||||
import { PluginTestLayer } from "./fixture"
|
||||
|
||||
const it = testEffect(Layer.merge(PluginTestLayer, Config.testLayer()))
|
||||
const decode = Schema.decodeUnknownSync(Info)
|
||||
const decodeShowRequest = Schema.decodeUnknownSync(Schema.Struct({ model: Schema.String }))
|
||||
|
||||
const addPlugin = Effect.fn(function* (origin: string, interval: Duration.Input = "1 hour") {
|
||||
const plugin = yield* Plugin.Service
|
||||
const host = yield* PluginHost.make(plugin)
|
||||
yield* make(origin, interval).effect(host)
|
||||
})
|
||||
|
||||
function eventually<A>(
|
||||
effect: Effect.Effect<A>,
|
||||
predicate: (value: A) => boolean,
|
||||
remaining = 3000,
|
||||
): Effect.Effect<A, Error> {
|
||||
return Effect.gen(function* () {
|
||||
const value = yield* effect
|
||||
if (predicate(value)) return value
|
||||
if (remaining === 0) return yield* Effect.fail(new Error("Timed out waiting for value"))
|
||||
yield* Effect.promise(() => Bun.sleep(1))
|
||||
return yield* eventually(effect, predicate, remaining - 1)
|
||||
})
|
||||
}
|
||||
|
||||
describe("OllamaPlugin", () => {
|
||||
it.live("discovers local completion models and native metadata", () =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.sync(() => {
|
||||
const requests: Array<{ method: string; path: string; model?: string }> = []
|
||||
return {
|
||||
requests,
|
||||
server: Bun.serve({
|
||||
port: 0,
|
||||
fetch: async (request) => {
|
||||
const path = new URL(request.url).pathname
|
||||
if (request.method === "GET") {
|
||||
requests.push({ method: request.method, path })
|
||||
return Response.json({
|
||||
models: [
|
||||
summary("gemma3:4b", "gemma-digest", "gemma3"),
|
||||
summary("nomic-embed", "embed-digest"),
|
||||
summary("removed-model", "removed-digest"),
|
||||
],
|
||||
})
|
||||
}
|
||||
const body = decodeShowRequest(await request.json())
|
||||
requests.push({ method: request.method, path, model: body.model })
|
||||
if (body.model === "removed-model") return new Response("Not found", { status: 404 })
|
||||
return Response.json(
|
||||
body.model === "gemma3:4b"
|
||||
? {
|
||||
capabilities: ["completion", "tools", "vision"],
|
||||
model_info: { "gemma3.context_length": 131_072 },
|
||||
}
|
||||
: show({ family: "nomic-bert", capabilities: ["embedding"], context: 8192 }),
|
||||
)
|
||||
},
|
||||
}),
|
||||
}
|
||||
}),
|
||||
({ requests, server }) =>
|
||||
Effect.gen(function* () {
|
||||
const catalog = yield* Catalog.Service
|
||||
const providerID = Provider.ID.make("ollama")
|
||||
expect(OllamaPlugin.id).toBe("opencode.provider.ollama")
|
||||
expect(ProviderPlugins.map((item) => item.id)).toContain("opencode.provider.ollama")
|
||||
yield* addPlugin(server.url.origin)
|
||||
const model = yield* eventually(
|
||||
catalog.model.get(providerID, Model.ID.make("gemma3:4b")),
|
||||
(item) => item !== undefined,
|
||||
)
|
||||
|
||||
expect(yield* catalog.provider.get(providerID)).toEqual({
|
||||
id: providerID,
|
||||
name: "Ollama",
|
||||
activation: "enabled",
|
||||
package: "@opencode-ai/ai/providers/openai-compatible",
|
||||
settings: { baseURL: `${server.url.origin}/v1`, provider: "ollama", apiKey: "" },
|
||||
})
|
||||
expect(model).toMatchObject({
|
||||
modelID: "gemma3:4b",
|
||||
name: "gemma3:4b",
|
||||
family: "gemma3",
|
||||
capabilities: { tools: true, input: ["text", "image"], output: ["text"] },
|
||||
limit: { context: 131_072, output: 0 },
|
||||
})
|
||||
expect(yield* catalog.model.get(providerID, Model.ID.make("nomic-embed"))).toBeUndefined()
|
||||
expect(requests).toContainEqual({ method: "GET", path: "/api/tags" })
|
||||
expect(requests).toContainEqual({ method: "POST", path: "/api/show", model: "gemma3:4b" })
|
||||
expect(requests).toContainEqual({ method: "POST", path: "/api/show", model: "nomic-embed" })
|
||||
expect(requests).toContainEqual({ method: "POST", path: "/api/show", model: "removed-model" })
|
||||
}),
|
||||
({ server }) => Effect.promise(() => server.stop(true)),
|
||||
),
|
||||
)
|
||||
|
||||
it.live("refreshes changed digests and retains inventory through transient failures", () =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.sync(() => {
|
||||
const state = { digest: "digest-1", context: 32_768, fail: false }
|
||||
const requests = { tags: 0, show: 0 }
|
||||
return {
|
||||
state,
|
||||
requests,
|
||||
server: Bun.serve({
|
||||
port: 0,
|
||||
fetch: async (request) => {
|
||||
if (request.method === "GET") {
|
||||
requests.tags++
|
||||
if (state.fail) return new Response("unavailable", { status: 503 })
|
||||
return Response.json({ models: [summary("qwen3:8b", state.digest, "qwen3")] })
|
||||
}
|
||||
decodeShowRequest(await request.json())
|
||||
requests.show++
|
||||
return Response.json(
|
||||
show({ family: "qwen3", capabilities: ["completion", "tools"], context: state.context }),
|
||||
)
|
||||
},
|
||||
}),
|
||||
}
|
||||
}),
|
||||
({ state, requests, server }) =>
|
||||
Effect.gen(function* () {
|
||||
const catalog = yield* Catalog.Service
|
||||
const providerID = Provider.ID.make("ollama")
|
||||
const modelID = Model.ID.make("qwen3:8b")
|
||||
yield* addPlugin(server.url.origin, "5 millis")
|
||||
yield* eventually(catalog.model.get(providerID, modelID), (model) => model?.limit.context === 32_768)
|
||||
yield* eventually(
|
||||
Effect.sync(() => requests.tags),
|
||||
(count) => count >= 2,
|
||||
)
|
||||
expect(requests.show).toBe(1)
|
||||
|
||||
state.digest = "digest-2"
|
||||
state.context = 65_536
|
||||
yield* eventually(catalog.model.get(providerID, modelID), (model) => model?.limit.context === 65_536)
|
||||
expect(requests.show).toBe(2)
|
||||
|
||||
state.fail = true
|
||||
yield* Effect.promise(() => Bun.sleep(30))
|
||||
expect((yield* catalog.model.get(providerID, modelID))?.limit.context).toBe(65_536)
|
||||
}),
|
||||
({ server }) => Effect.promise(() => server.stop(true)),
|
||||
),
|
||||
)
|
||||
|
||||
it.live("replaces and restores the same-ID Models.dev provider", () =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.sync(() => {
|
||||
const models = [summary("discovered-model", "digest")]
|
||||
return {
|
||||
models,
|
||||
server: Bun.serve({
|
||||
port: 0,
|
||||
fetch: async (request) => {
|
||||
if (request.method === "GET") return Response.json({ models })
|
||||
decodeShowRequest(await request.json())
|
||||
return Response.json(show({ capabilities: ["completion"], context: 32_768 }))
|
||||
},
|
||||
}),
|
||||
}
|
||||
}),
|
||||
({ models, server }) =>
|
||||
Effect.gen(function* () {
|
||||
const catalog = yield* Catalog.Service
|
||||
const integrations = yield* Integration.Service
|
||||
const providerID = Provider.ID.make("ollama")
|
||||
yield* integrations.transform((draft) => {
|
||||
draft.update(Integration.ID.make("ollama"), (integration) => {
|
||||
integration.name = "Ollama"
|
||||
})
|
||||
draft.method.update({
|
||||
integrationID: Integration.ID.make("ollama"),
|
||||
method: { type: "env", names: ["OLLAMA_API_KEY"] },
|
||||
})
|
||||
})
|
||||
yield* catalog.transform((draft) => {
|
||||
draft.provider.update(providerID, (provider) => {
|
||||
provider.name = "Ollama"
|
||||
provider.package = "aisdk:@ai-sdk/openai-compatible"
|
||||
provider.integrationID = Integration.ID.make("ollama")
|
||||
})
|
||||
draft.model.update(providerID, Model.ID.make("static-model"), () => {})
|
||||
})
|
||||
|
||||
yield* addPlugin(server.url.origin, "5 millis")
|
||||
yield* eventually(
|
||||
catalog.model.get(providerID, Model.ID.make("discovered-model")),
|
||||
(model) => model !== undefined,
|
||||
)
|
||||
expect(yield* integrations.get(Integration.ID.make("ollama"))).toBeUndefined()
|
||||
expect((yield* catalog.provider.get(providerID))?.activation).toBe("enabled")
|
||||
expect(yield* catalog.model.get(providerID, Model.ID.make("static-model"))).toBeUndefined()
|
||||
|
||||
models.splice(0)
|
||||
yield* eventually(
|
||||
catalog.model.get(providerID, Model.ID.make("static-model")),
|
||||
(model) => model !== undefined,
|
||||
)
|
||||
expect(yield* catalog.model.get(providerID, Model.ID.make("discovered-model"))).toBeUndefined()
|
||||
expect(yield* integrations.get(Integration.ID.make("ollama"))).toBeDefined()
|
||||
expect((yield* catalog.provider.get(providerID))?.activation).toBe("auto")
|
||||
expect((yield* catalog.provider.get(providerID))?.integrationID).toBe(Integration.ID.make("ollama"))
|
||||
}),
|
||||
({ server }) => Effect.promise(() => server.stop(true)),
|
||||
),
|
||||
)
|
||||
|
||||
it.live(
|
||||
"reloads layered endpoint and bearer authentication settings",
|
||||
() =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.sync(() => {
|
||||
const requests: Array<{ authorization: string | null; method: string; path: string }> = []
|
||||
return {
|
||||
requests,
|
||||
initial: Bun.serve({
|
||||
port: 0,
|
||||
fetch: async (request) => {
|
||||
if (request.method === "GET")
|
||||
return Response.json({ models: [summary("initial-model", "initial-digest")] })
|
||||
decodeShowRequest(await request.json())
|
||||
return Response.json(show({ capabilities: ["completion"], context: 4096 }))
|
||||
},
|
||||
}),
|
||||
configured: Bun.serve({
|
||||
port: 0,
|
||||
fetch: async (request) => {
|
||||
requests.push({
|
||||
authorization: request.headers.get("authorization"),
|
||||
method: request.method,
|
||||
path: new URL(request.url).pathname,
|
||||
})
|
||||
if (request.method === "GET")
|
||||
return Response.json({ models: [summary("configured-model", "configured-digest")] })
|
||||
decodeShowRequest(await request.json())
|
||||
return Response.json(show({ capabilities: ["completion", "vision"], context: 65_536 }))
|
||||
},
|
||||
}),
|
||||
}
|
||||
}),
|
||||
({ requests, initial, configured }) =>
|
||||
Effect.gen(function* () {
|
||||
const bus = yield* Bus.Service
|
||||
const catalog = yield* Catalog.Service
|
||||
const config = yield* Config.Test
|
||||
const providerID = Provider.ID.make("ollama")
|
||||
yield* addPlugin(initial.url.origin)
|
||||
yield* eventually(
|
||||
catalog.model.get(providerID, Model.ID.make("initial-model")),
|
||||
(model) => model !== undefined,
|
||||
)
|
||||
|
||||
const baseURL = `${configured.url.origin}/proxy/v1`
|
||||
yield* config.setEntries([configuration({ baseURL, apiKey: "old" }), configuration({ apiKey: "secret" })])
|
||||
yield* bus.publish(Event.Updated, {})
|
||||
yield* eventually(
|
||||
catalog.model.get(providerID, Model.ID.make("configured-model")),
|
||||
(model) => model !== undefined,
|
||||
)
|
||||
expect(requests).toContainEqual({ authorization: "Bearer secret", method: "GET", path: "/proxy/api/tags" })
|
||||
expect(requests).toContainEqual({ authorization: "Bearer secret", method: "POST", path: "/proxy/api/show" })
|
||||
expect(yield* catalog.model.get(providerID, Model.ID.make("initial-model"))).toBeUndefined()
|
||||
expect((yield* catalog.provider.get(providerID))?.settings).toEqual({
|
||||
baseURL,
|
||||
provider: "ollama",
|
||||
apiKey: "secret",
|
||||
})
|
||||
|
||||
requests.splice(0)
|
||||
yield* config.setEntries([configuration({ baseURL, apiKey: "secret" }), configuration({ apiKey: null })])
|
||||
yield* bus.publish(Event.Updated, {})
|
||||
yield* eventually(catalog.provider.get(providerID), (provider) => provider?.settings?.apiKey === "")
|
||||
expect(requests).toContainEqual({ authorization: null, method: "GET", path: "/proxy/api/tags" })
|
||||
expect(requests).toContainEqual({ authorization: null, method: "POST", path: "/proxy/api/show" })
|
||||
}),
|
||||
({ initial, configured }) => Effect.promise(() => Promise.all([initial.stop(true), configured.stop(true)])),
|
||||
),
|
||||
10_000,
|
||||
)
|
||||
})
|
||||
|
||||
function summary(model: string, digest: string, family = "llama") {
|
||||
return {
|
||||
name: model,
|
||||
model,
|
||||
modified_at: "2026-01-01T00:00:00Z",
|
||||
size: 1_000_000,
|
||||
digest,
|
||||
details: {
|
||||
format: "gguf",
|
||||
family,
|
||||
families: [family],
|
||||
parameter_size: "8B",
|
||||
quantization_level: "Q4_K_M",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function show(input: { family?: string; capabilities: string[]; context: number }) {
|
||||
const family = input.family ?? "llama"
|
||||
return {
|
||||
parameters: "temperature 0.7",
|
||||
details: {
|
||||
parent_model: "",
|
||||
format: "gguf",
|
||||
family,
|
||||
families: [family],
|
||||
parameter_size: "8B",
|
||||
quantization_level: "Q4_K_M",
|
||||
},
|
||||
capabilities: input.capabilities,
|
||||
model_info: {
|
||||
"general.architecture": family,
|
||||
[`${family}.context_length`]: input.context,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function configuration(settings: Record<string, string | null>) {
|
||||
return new Document({
|
||||
type: "document",
|
||||
info: decode({ providers: { ollama: { settings } } }),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
import { Bus } from "@opencode-ai/core/bus"
|
||||
import { Catalog } from "@opencode-ai/core/catalog"
|
||||
import { Config } from "@opencode-ai/core/config"
|
||||
import { Integration } from "@opencode-ai/core/integration"
|
||||
import { Model } from "@opencode-ai/core/model"
|
||||
import { Plugin } from "@opencode-ai/core/plugin"
|
||||
import { PluginHost } from "@opencode-ai/core/plugin/host"
|
||||
import { ProviderPlugins } from "@opencode-ai/core/plugin/provider"
|
||||
import { make, VLLMPlugin } from "@opencode-ai/core/plugin/provider/vllm"
|
||||
import { Provider } from "@opencode-ai/core/provider"
|
||||
import { Document, Event, Info } from "@opencode-ai/schema/config"
|
||||
import { describe, expect } from "bun:test"
|
||||
import { Duration, Effect, Layer, Schema } from "effect"
|
||||
import { testEffect } from "../lib/effect"
|
||||
import { PluginTestLayer } from "./fixture"
|
||||
|
||||
const it = testEffect(Layer.merge(PluginTestLayer, Config.testLayer()))
|
||||
const decode = Schema.decodeUnknownSync(Info)
|
||||
|
||||
const addPlugin = Effect.fn(function* (origin: string, interval: Duration.Input = "1 hour") {
|
||||
const plugin = yield* Plugin.Service
|
||||
const host = yield* PluginHost.make(plugin)
|
||||
yield* make(origin, interval).effect(host)
|
||||
})
|
||||
|
||||
function eventually<A>(
|
||||
effect: Effect.Effect<A>,
|
||||
predicate: (value: A) => boolean,
|
||||
remaining = 3000,
|
||||
): Effect.Effect<A, Error> {
|
||||
return Effect.gen(function* () {
|
||||
const value = yield* effect
|
||||
if (predicate(value)) return value
|
||||
if (remaining === 0) return yield* Effect.fail(new Error("Timed out waiting for value"))
|
||||
yield* Effect.promise(() => Bun.sleep(1))
|
||||
return yield* eventually(effect, predicate, remaining - 1)
|
||||
})
|
||||
}
|
||||
|
||||
const remoteModel = (id: string, max_model_len = 32_768, owned_by = "vllm") => ({
|
||||
id,
|
||||
object: "model",
|
||||
created: 1,
|
||||
owned_by,
|
||||
root: id,
|
||||
parent: null,
|
||||
max_model_len,
|
||||
permission: [],
|
||||
})
|
||||
|
||||
describe("VLLMPlugin", () => {
|
||||
it.live("waits for readiness and discovers official vLLM model metadata", () =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.sync(() => {
|
||||
const state = { healthy: false, models: 0 }
|
||||
return {
|
||||
state,
|
||||
server: Bun.serve({
|
||||
port: 0,
|
||||
fetch: (request) => {
|
||||
const path = new URL(request.url).pathname
|
||||
if (path === "/health") return new Response(null, { status: state.healthy ? 200 : 503 })
|
||||
state.models++
|
||||
return Response.json({
|
||||
object: "list",
|
||||
data: [remoteModel("Qwen/Qwen3-Coder", 65_536), remoteModel("foreign-model", 4096, "other")],
|
||||
})
|
||||
},
|
||||
}),
|
||||
}
|
||||
}),
|
||||
({ state, server }) =>
|
||||
Effect.gen(function* () {
|
||||
const catalog = yield* Catalog.Service
|
||||
const providerID = Provider.ID.make("vllm")
|
||||
expect(VLLMPlugin.id).toBe("opencode.provider.vllm")
|
||||
expect(ProviderPlugins.map((item) => item.id)).toContain("opencode.provider.vllm")
|
||||
yield* addPlugin(server.url.origin, "5 millis")
|
||||
yield* Effect.promise(() => Bun.sleep(20))
|
||||
expect(yield* catalog.provider.get(providerID)).toBeUndefined()
|
||||
expect(state.models).toBe(0)
|
||||
|
||||
state.healthy = true
|
||||
const model = yield* eventually(
|
||||
catalog.model.get(providerID, Model.ID.make("Qwen/Qwen3-Coder")),
|
||||
(item) => item !== undefined,
|
||||
)
|
||||
expect(yield* catalog.provider.get(providerID)).toEqual({
|
||||
id: providerID,
|
||||
name: "vLLM",
|
||||
package: "@opencode-ai/ai/providers/openai-compatible",
|
||||
settings: { baseURL: `${server.url.origin}/v1`, provider: "vllm", apiKey: "" },
|
||||
activation: "enabled",
|
||||
})
|
||||
expect((yield* catalog.provider.available()).map((provider) => provider.id)).toContain(providerID)
|
||||
expect(model).toMatchObject({
|
||||
modelID: "Qwen/Qwen3-Coder",
|
||||
name: "Qwen/Qwen3-Coder",
|
||||
capabilities: { tools: false, input: ["text"], output: ["text"] },
|
||||
limit: { context: 65_536, output: 0 },
|
||||
})
|
||||
expect(yield* catalog.model.get(providerID, Model.ID.make("foreign-model"))).toBeUndefined()
|
||||
}),
|
||||
({ server }) => Effect.promise(() => server.stop(true)),
|
||||
),
|
||||
)
|
||||
|
||||
it.live("refreshes inventory while retaining the last success through transient failures", () =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.sync(() => {
|
||||
const state = { failing: false, models: [remoteModel("first-model")] }
|
||||
return {
|
||||
state,
|
||||
server: Bun.serve({
|
||||
port: 0,
|
||||
fetch: (request) => {
|
||||
if (state.failing) return new Response(null, { status: 503 })
|
||||
if (new URL(request.url).pathname === "/health") return new Response()
|
||||
return Response.json({ object: "list", data: state.models })
|
||||
},
|
||||
}),
|
||||
}
|
||||
}),
|
||||
({ state, server }) =>
|
||||
Effect.gen(function* () {
|
||||
const catalog = yield* Catalog.Service
|
||||
const providerID = Provider.ID.make("vllm")
|
||||
yield* addPlugin(server.url.origin, "5 millis")
|
||||
yield* eventually(catalog.model.get(providerID, Model.ID.make("first-model")), (model) => model !== undefined)
|
||||
|
||||
state.failing = true
|
||||
state.models = [remoteModel("second-model")]
|
||||
yield* Effect.promise(() => Bun.sleep(30))
|
||||
expect(yield* catalog.model.get(providerID, Model.ID.make("first-model"))).toBeDefined()
|
||||
expect(yield* catalog.model.get(providerID, Model.ID.make("second-model"))).toBeUndefined()
|
||||
|
||||
state.failing = false
|
||||
yield* eventually(
|
||||
catalog.model.get(providerID, Model.ID.make("second-model")),
|
||||
(model) => model !== undefined,
|
||||
)
|
||||
expect(yield* catalog.model.get(providerID, Model.ID.make("first-model"))).toBeUndefined()
|
||||
}),
|
||||
({ server }) => Effect.promise(() => server.stop(true)),
|
||||
),
|
||||
)
|
||||
|
||||
it.live("replaces and restores same-ID Models.dev entries after an empty success", () =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.sync(() => {
|
||||
const models = [remoteModel("discovered-model")]
|
||||
return {
|
||||
models,
|
||||
server: Bun.serve({
|
||||
port: 0,
|
||||
fetch: (request) =>
|
||||
new URL(request.url).pathname === "/health"
|
||||
? new Response()
|
||||
: Response.json({ object: "list", data: models }),
|
||||
}),
|
||||
}
|
||||
}),
|
||||
({ models, server }) =>
|
||||
Effect.gen(function* () {
|
||||
const catalog = yield* Catalog.Service
|
||||
const integrations = yield* Integration.Service
|
||||
const providerID = Provider.ID.make("vllm")
|
||||
yield* integrations.transform((draft) => {
|
||||
draft.update(Integration.ID.make("vllm"), (integration) => {
|
||||
integration.name = "vLLM"
|
||||
})
|
||||
draft.method.update({
|
||||
integrationID: Integration.ID.make("vllm"),
|
||||
method: { type: "env", names: ["VLLM_API_KEY"] },
|
||||
})
|
||||
})
|
||||
yield* catalog.transform((draft) => {
|
||||
draft.provider.update(providerID, (provider) => {
|
||||
provider.name = "vLLM"
|
||||
provider.package = "aisdk:@ai-sdk/openai-compatible"
|
||||
provider.integrationID = Integration.ID.make("vllm")
|
||||
provider.activation = "auto"
|
||||
})
|
||||
draft.model.update(providerID, Model.ID.make("static-model"), () => {})
|
||||
})
|
||||
|
||||
yield* addPlugin(server.url.origin, "5 millis")
|
||||
yield* eventually(
|
||||
catalog.model.get(providerID, Model.ID.make("discovered-model")),
|
||||
(model) => model !== undefined,
|
||||
)
|
||||
expect(yield* integrations.get(Integration.ID.make("vllm"))).toBeUndefined()
|
||||
expect((yield* catalog.provider.get(providerID))?.integrationID).toBeUndefined()
|
||||
expect((yield* catalog.provider.get(providerID))?.activation).toBe("enabled")
|
||||
expect(yield* catalog.model.get(providerID, Model.ID.make("static-model"))).toBeUndefined()
|
||||
|
||||
models.splice(0)
|
||||
yield* eventually(
|
||||
catalog.model.get(providerID, Model.ID.make("static-model")),
|
||||
(model) => model !== undefined,
|
||||
)
|
||||
expect(yield* catalog.model.get(providerID, Model.ID.make("discovered-model"))).toBeUndefined()
|
||||
expect(yield* integrations.get(Integration.ID.make("vllm"))).toBeDefined()
|
||||
expect((yield* catalog.provider.get(providerID))?.integrationID).toBe(Integration.ID.make("vllm"))
|
||||
expect((yield* catalog.provider.get(providerID))?.activation).toBe("auto")
|
||||
}),
|
||||
({ server }) => Effect.promise(() => server.stop(true)),
|
||||
),
|
||||
)
|
||||
|
||||
it.live(
|
||||
"reloads layered custom endpoint and bearer authentication settings",
|
||||
() =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.sync(() => {
|
||||
const requests: Array<{ authorization: string | null; path: string }> = []
|
||||
return {
|
||||
requests,
|
||||
initial: Bun.serve({
|
||||
port: 0,
|
||||
fetch: (request) =>
|
||||
new URL(request.url).pathname === "/health"
|
||||
? new Response()
|
||||
: Response.json({ object: "list", data: [remoteModel("initial-model")] }),
|
||||
}),
|
||||
configured: Bun.serve({
|
||||
port: 0,
|
||||
fetch: (request) => {
|
||||
requests.push({
|
||||
authorization: request.headers.get("authorization"),
|
||||
path: new URL(request.url).pathname,
|
||||
})
|
||||
if (new URL(request.url).pathname === "/proxy/health") return new Response()
|
||||
return Response.json({ object: "list", data: [remoteModel("configured-model")] })
|
||||
},
|
||||
}),
|
||||
}
|
||||
}),
|
||||
({ requests, initial, configured }) =>
|
||||
Effect.gen(function* () {
|
||||
const bus = yield* Bus.Service
|
||||
const catalog = yield* Catalog.Service
|
||||
const config = yield* Config.Test
|
||||
const providerID = Provider.ID.make("vllm")
|
||||
yield* addPlugin(initial.url.origin)
|
||||
yield* eventually(
|
||||
catalog.model.get(providerID, Model.ID.make("initial-model")),
|
||||
(model) => model !== undefined,
|
||||
)
|
||||
|
||||
const baseURL = `${configured.url.origin}/proxy/v1`
|
||||
yield* config.setEntries([configuration({ baseURL }), configuration({ apiKey: "secret" })])
|
||||
yield* bus.publish(Event.Updated, {})
|
||||
yield* eventually(
|
||||
catalog.model.get(providerID, Model.ID.make("configured-model")),
|
||||
(model) => model !== undefined,
|
||||
)
|
||||
|
||||
expect(requests).toContainEqual({ authorization: "Bearer secret", path: "/proxy/health" })
|
||||
expect(requests).toContainEqual({ authorization: "Bearer secret", path: "/proxy/v1/models" })
|
||||
expect(yield* catalog.model.get(providerID, Model.ID.make("initial-model"))).toBeUndefined()
|
||||
expect((yield* catalog.provider.get(providerID))?.settings).toEqual({
|
||||
baseURL,
|
||||
provider: "vllm",
|
||||
apiKey: "secret",
|
||||
})
|
||||
|
||||
requests.splice(0)
|
||||
yield* config.setEntries([configuration({ baseURL }), configuration({ apiKey: "next-secret" })])
|
||||
yield* bus.publish(Event.Updated, {})
|
||||
yield* eventually(
|
||||
catalog.provider.get(providerID),
|
||||
(provider) => provider?.settings?.apiKey === "next-secret",
|
||||
)
|
||||
expect(requests).toContainEqual({ authorization: "Bearer next-secret", path: "/proxy/health" })
|
||||
expect(requests).toContainEqual({ authorization: "Bearer next-secret", path: "/proxy/v1/models" })
|
||||
}),
|
||||
({ initial, configured }) => Effect.promise(() => Promise.all([initial.stop(true), configured.stop(true)])),
|
||||
),
|
||||
10_000,
|
||||
)
|
||||
})
|
||||
|
||||
function configuration(settings: { baseURL?: string; apiKey?: string }) {
|
||||
return new Document({
|
||||
type: "document",
|
||||
info: decode({ providers: { vllm: { settings } } }),
|
||||
})
|
||||
}
|
||||
@@ -840,7 +840,15 @@ describe("SessionTransfer", () => {
|
||||
|
||||
const imported = yield* transfer.import({
|
||||
data: {
|
||||
info: { ...template, id: sessionID },
|
||||
info: {
|
||||
...template,
|
||||
id: sessionID,
|
||||
time: {
|
||||
...template.time,
|
||||
idle: DateTime.makeUnsafe(200),
|
||||
viewed: DateTime.makeUnsafe(150),
|
||||
},
|
||||
},
|
||||
messages: [
|
||||
{
|
||||
id: sourceMessageID,
|
||||
@@ -863,13 +871,18 @@ describe("SessionTransfer", () => {
|
||||
const messages = yield* session.messages({ sessionID, order: "asc" })
|
||||
|
||||
expect(imported).toMatchObject({ id: sessionID, title: "Exported", location })
|
||||
expect(imported.time).toMatchObject({ idle: DateTime.makeUnsafe(200), viewed: DateTime.makeUnsafe(150) })
|
||||
expect(messages).toMatchObject([
|
||||
{ id: sourceMessageID, type: "user", text: "Imported message" },
|
||||
{ id: errorMessageID, type: "compaction", error: { type: "test_error", message: "Original error" } },
|
||||
])
|
||||
expect(yield* Bus.latestSequence(db, sessionID)).toBe(2)
|
||||
expect((yield* transfer.export({ sessionID })).messages).toEqual(messages)
|
||||
expect((yield* transfer.export({ sessionID, sanitize: true })).messages).toMatchObject([
|
||||
const exported = yield* transfer.export({ sessionID })
|
||||
expect(exported.info.time).toMatchObject({ idle: DateTime.makeUnsafe(200), viewed: DateTime.makeUnsafe(150) })
|
||||
expect(exported.messages).toEqual(messages)
|
||||
const sanitized = yield* transfer.export({ sessionID, sanitize: true })
|
||||
expect(sanitized.info.time).toMatchObject({ idle: DateTime.makeUnsafe(200), viewed: DateTime.makeUnsafe(150) })
|
||||
expect(sanitized.messages).toMatchObject([
|
||||
{ id: sourceMessageID, text: `[redacted:text:${sourceMessageID}]` },
|
||||
{ id: errorMessageID, error: { type: "test_error", message: "Original error" } },
|
||||
])
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
import { describe, expect } from "bun:test"
|
||||
import path from "path"
|
||||
import { Bus } from "@opencode-ai/core/bus"
|
||||
import { Database } from "@opencode-ai/core/database/database"
|
||||
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
|
||||
import { EventTable } from "@opencode-ai/core/event/sql"
|
||||
import { Location } from "@opencode-ai/core/location"
|
||||
import { Project } from "@opencode-ai/core/project"
|
||||
import { ProjectTable } from "@opencode-ai/core/project/sql"
|
||||
import { AbsolutePath } from "@opencode-ai/core/schema"
|
||||
import { Session } from "@opencode-ai/core/session"
|
||||
import { SessionEvent } from "@opencode-ai/core/session/event"
|
||||
import { SessionExecution } from "@opencode-ai/core/session/execution"
|
||||
import { SessionProjector } from "@opencode-ai/core/session/projector"
|
||||
import { SessionTable } from "@opencode-ai/core/session/sql"
|
||||
import { SessionStore } from "@opencode-ai/core/session/store"
|
||||
import { LayerNode } from "@opencode-ai/util/effect/layer-node"
|
||||
import { DateTime, Effect, Layer } from "effect"
|
||||
import { asc, eq } from "drizzle-orm"
|
||||
import { tmpdir } from "./fixture/tmpdir"
|
||||
import { testEffect } from "./lib/effect"
|
||||
import { globalProjectLayer } from "./lib/project"
|
||||
|
||||
const it = testEffect(
|
||||
AppNodeBuilder.build(
|
||||
LayerNode.group([Database.node, Bus.node, SessionProjector.node, SessionStore.node, Session.node]),
|
||||
[
|
||||
[Bus.node, Bus.configured({ persist: true })],
|
||||
[Project.node, globalProjectLayer],
|
||||
[SessionExecution.node, SessionExecution.noopLayer],
|
||||
],
|
||||
),
|
||||
)
|
||||
const location = Location.Ref.make({ directory: AbsolutePath.make("/project") })
|
||||
|
||||
describe("Session.view", () => {
|
||||
it.effect("copies the latest idle time without changing session recency", () =>
|
||||
Effect.gen(function* () {
|
||||
const session = yield* Session.Service
|
||||
const bus = yield* Bus.Service
|
||||
const { db } = yield* Database.Service
|
||||
const created = yield* session.create({ location })
|
||||
|
||||
expect(created.time.idle).toBeUndefined()
|
||||
expect(created.time.viewed).toBeUndefined()
|
||||
|
||||
yield* session.view({ sessionID: created.id })
|
||||
expect((yield* session.get(created.id)).time.viewed).toBeUndefined()
|
||||
|
||||
yield* bus.publish(SessionEvent.Execution.Succeeded, { sessionID: created.id })
|
||||
const idle = yield* session.get(created.id)
|
||||
expect(idle.time.idle).toBeDefined()
|
||||
expect(idle.time.viewed).toBeUndefined()
|
||||
expect(idle.time.updated).toEqual(created.time.updated)
|
||||
|
||||
yield* session.view({ sessionID: created.id })
|
||||
const viewed = yield* session.get(created.id)
|
||||
if (!viewed.time.idle || !viewed.time.viewed) return yield* Effect.die(new Error("Expected attention times"))
|
||||
expect(viewed.time.viewed).toEqual(viewed.time.idle)
|
||||
expect(viewed.time.updated).toEqual(created.time.updated)
|
||||
expect(
|
||||
yield* db
|
||||
.select({ idle: SessionTable.time_idle, viewed: SessionTable.time_viewed })
|
||||
.from(SessionTable)
|
||||
.where(eq(SessionTable.id, created.id))
|
||||
.get(),
|
||||
).toEqual({
|
||||
idle: DateTime.toEpochMillis(viewed.time.idle),
|
||||
viewed: DateTime.toEpochMillis(viewed.time.viewed),
|
||||
})
|
||||
expect((yield* session.list()).data.find((item) => item.id === created.id)?.time).toEqual(viewed.time)
|
||||
|
||||
yield* session.view({ sessionID: created.id })
|
||||
expect((yield* session.get(created.id)).time).toEqual(viewed.time)
|
||||
|
||||
yield* bus.publish(SessionEvent.Execution.Failed, {
|
||||
sessionID: created.id,
|
||||
error: { type: "unknown", message: "failed" },
|
||||
})
|
||||
const unread = yield* session.get(created.id)
|
||||
if (!unread.time.idle || !unread.time.viewed) return yield* Effect.die(new Error("Expected attention times"))
|
||||
expect(DateTime.toEpochMillis(unread.time.idle)).toBeGreaterThan(DateTime.toEpochMillis(unread.time.viewed))
|
||||
|
||||
yield* session.view({ sessionID: created.id })
|
||||
expect((yield* session.get(created.id)).time.viewed).toEqual(unread.time.idle)
|
||||
|
||||
yield* bus.publish(SessionEvent.Execution.Interrupted, { sessionID: created.id, reason: "shutdown" })
|
||||
expect((yield* session.get(created.id)).time.idle).toEqual(unread.time.idle)
|
||||
|
||||
yield* bus.publish(SessionEvent.Execution.Interrupted, { sessionID: created.id, reason: "user" })
|
||||
const interrupted = yield* session.get(created.id)
|
||||
if (!interrupted.time.idle || !interrupted.time.viewed)
|
||||
return yield* Effect.die(new Error("Expected attention times"))
|
||||
expect(DateTime.toEpochMillis(interrupted.time.idle)).toBeGreaterThan(
|
||||
DateTime.toEpochMillis(interrupted.time.viewed),
|
||||
)
|
||||
expect(
|
||||
(yield* db
|
||||
.select({ type: EventTable.type })
|
||||
.from(EventTable)
|
||||
.where(eq(EventTable.aggregate_id, created.id))
|
||||
.all()).filter((event) => event.type === "session.viewed.1"),
|
||||
).toHaveLength(2)
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("rejects an unknown session", () =>
|
||||
Effect.gen(function* () {
|
||||
const session = yield* Session.Service
|
||||
const sessionID = Session.ID.make("ses_missing_view")
|
||||
expect(yield* Effect.flip(session.view({ sessionID }))).toEqual(new Session.NotFoundError({ sessionID }))
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("replays viewed state into a fresh database", () =>
|
||||
Effect.gen(function* () {
|
||||
const session = yield* Session.Service
|
||||
const bus = yield* Bus.Service
|
||||
const sourceDb = (yield* Database.Service).db
|
||||
const created = yield* session.create({ id: Session.ID.make("ses_view_replay"), location })
|
||||
yield* bus.publish(SessionEvent.Execution.Succeeded, { sessionID: created.id })
|
||||
yield* session.view({ sessionID: created.id })
|
||||
yield* bus.publish(SessionEvent.Execution.Failed, {
|
||||
sessionID: created.id,
|
||||
error: { type: "unknown", message: "failed" },
|
||||
})
|
||||
const expected = yield* session.get(created.id)
|
||||
if (!expected.time.idle || !expected.time.viewed) return yield* Effect.die(new Error("Expected attention times"))
|
||||
const expectedIdle = DateTime.toEpochMillis(expected.time.idle)
|
||||
const expectedViewed = DateTime.toEpochMillis(expected.time.viewed)
|
||||
const serialized = (yield* sourceDb
|
||||
.select()
|
||||
.from(EventTable)
|
||||
.where(eq(EventTable.aggregate_id, created.id))
|
||||
.orderBy(asc(EventTable.seq))
|
||||
.all()
|
||||
.pipe(Effect.orDie)).map((event) => ({
|
||||
id: event.id,
|
||||
created: event.created,
|
||||
aggregateID: event.aggregate_id,
|
||||
seq: event.seq,
|
||||
type: event.type,
|
||||
data: event.data,
|
||||
}))
|
||||
const tmp = yield* Effect.acquireRelease(
|
||||
Effect.promise(() => tmpdir()),
|
||||
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
|
||||
)
|
||||
const targetLayer = AppNodeBuilder.build(
|
||||
LayerNode.group([Database.node, Bus.node, SessionProjector.node, SessionStore.node]),
|
||||
[
|
||||
[Database.node, Database.configured({ path: path.join(tmp.path, "target.sqlite") })],
|
||||
[Bus.node, Bus.configured({ persist: true })],
|
||||
],
|
||||
)
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const db = (yield* Database.Service).db
|
||||
const targetBus = yield* Bus.Service
|
||||
const store = yield* SessionStore.Service
|
||||
yield* db
|
||||
.insert(ProjectTable)
|
||||
.values({ id: Project.ID.global, worktree: location.directory, sandboxes: [] })
|
||||
.run()
|
||||
.pipe(Effect.orDie)
|
||||
yield* Effect.forEach(serialized, (event) => targetBus.replay(event), { discard: true })
|
||||
|
||||
expect((yield* store.get(created.id))?.time).toEqual(expected.time)
|
||||
expect(expected.time.updated).toEqual(created.time.updated)
|
||||
expect(expectedIdle).toBeGreaterThan(expectedViewed)
|
||||
}).pipe(Effect.provide(Layer.fresh(targetLayer)))
|
||||
}),
|
||||
)
|
||||
})
|
||||
@@ -60,6 +60,8 @@ const session = (
|
||||
model: null,
|
||||
time_created: 1,
|
||||
time_updated: 2,
|
||||
time_idle: null,
|
||||
time_viewed: null,
|
||||
time_compacting: 3,
|
||||
time_archived: null,
|
||||
time_suspended: null,
|
||||
|
||||
@@ -4127,6 +4127,65 @@
|
||||
"summary": "Get session message"
|
||||
}
|
||||
},
|
||||
"/api/session/{sessionID}/view": {
|
||||
"post": {
|
||||
"tags": ["session"],
|
||||
"operationId": "v2.session.view",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "sessionID",
|
||||
"in": "path",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"allOf": [
|
||||
{
|
||||
"pattern": "^ses"
|
||||
}
|
||||
]
|
||||
},
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"security": [],
|
||||
"responses": {
|
||||
"204": {
|
||||
"description": "<No Content>"
|
||||
},
|
||||
"400": {
|
||||
"description": "InvalidRequestError",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/InvalidRequestError"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "UnauthorizedError",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/UnauthorizedError"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "SessionNotFoundError",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/SessionNotFoundError"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Mark the latest recorded idle transition as viewed.",
|
||||
"summary": "View session"
|
||||
}
|
||||
},
|
||||
"/api/session/{sessionID}/message": {
|
||||
"get": {
|
||||
"tags": ["session"],
|
||||
@@ -12135,6 +12194,12 @@
|
||||
"updated": {
|
||||
"type": "number"
|
||||
},
|
||||
"idle": {
|
||||
"type": "number"
|
||||
},
|
||||
"viewed": {
|
||||
"type": "number"
|
||||
},
|
||||
"archived": {
|
||||
"type": "number"
|
||||
}
|
||||
@@ -14276,6 +14341,71 @@
|
||||
"required": ["id", "created", "type", "durable", "data"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"session.viewed": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"allOf": [
|
||||
{
|
||||
"pattern": "^evt_"
|
||||
}
|
||||
]
|
||||
},
|
||||
"created": {
|
||||
"type": "number"
|
||||
},
|
||||
"metadata": {
|
||||
"type": "object"
|
||||
},
|
||||
"type": {
|
||||
"type": "string",
|
||||
"enum": ["session.viewed"]
|
||||
},
|
||||
"durable": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"aggregateID": {
|
||||
"type": "string"
|
||||
},
|
||||
"seq": {
|
||||
"type": "integer",
|
||||
"allOf": [
|
||||
{
|
||||
"minimum": 0
|
||||
}
|
||||
]
|
||||
},
|
||||
"version": {
|
||||
"type": "number",
|
||||
"enum": [1]
|
||||
}
|
||||
},
|
||||
"required": ["aggregateID", "seq", "version"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"location": {
|
||||
"$ref": "#/components/schemas/Location.Ref"
|
||||
},
|
||||
"data": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"sessionID": {
|
||||
"type": "string",
|
||||
"allOf": [
|
||||
{
|
||||
"pattern": "^ses"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": ["sessionID"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": ["id", "created", "type", "durable", "data"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"session.deleted": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -17296,6 +17426,9 @@
|
||||
{
|
||||
"$ref": "#/components/schemas/session.renamed"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/session.viewed"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/session.deleted"
|
||||
},
|
||||
@@ -22664,6 +22797,9 @@
|
||||
{
|
||||
"$ref": "#/components/schemas/session.renamed"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/session.viewed"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/session.usage.updated"
|
||||
},
|
||||
|
||||
@@ -33,6 +33,7 @@
|
||||
"@tsconfig/bun": "catalog:",
|
||||
"@types/bun": "catalog:",
|
||||
"@typescript/native-preview": "catalog:",
|
||||
"prettier": "3.6.2",
|
||||
"typescript": "catalog:"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { OpenApi } from "effect/unstable/httpapi"
|
||||
import { format } from "prettier"
|
||||
import { fileURLToPath } from "url"
|
||||
import { ClientApi } from "../src/client.js"
|
||||
|
||||
const document = JSON.stringify(OpenApi.fromApi(ClientApi), null, 2) + "\n"
|
||||
const document = await format(JSON.stringify(OpenApi.fromApi(ClientApi), null, 2), { parser: "json", printWidth: 120 })
|
||||
const target = fileURLToPath(new URL("../openapi.json", import.meta.url))
|
||||
|
||||
if (process.argv.includes("--check")) {
|
||||
|
||||
@@ -693,6 +693,19 @@ export const makeSessionGroup = <I extends HttpApiMiddleware.AnyId, S>(sessionLo
|
||||
}),
|
||||
),
|
||||
)
|
||||
.add(
|
||||
HttpApiEndpoint.post("session.view", "/api/session/:sessionID/view", {
|
||||
params: { sessionID: Session.ID },
|
||||
success: HttpApiSchema.NoContent,
|
||||
error: SessionNotFoundError,
|
||||
}).annotateMerge(
|
||||
OpenApi.annotations({
|
||||
identifier: "v2.session.view",
|
||||
summary: "View session",
|
||||
description: "Mark the latest recorded idle transition as viewed.",
|
||||
}),
|
||||
),
|
||||
)
|
||||
.annotateMerge(
|
||||
OpenApi.annotations({
|
||||
title: "session",
|
||||
|
||||
@@ -105,6 +105,13 @@ export const Renamed = Event.durable({
|
||||
})
|
||||
export type Renamed = typeof Renamed.Type
|
||||
|
||||
export const Viewed = Event.durable({
|
||||
type: "session.viewed",
|
||||
...options,
|
||||
schema: Base,
|
||||
})
|
||||
export type Viewed = typeof Viewed.Type
|
||||
|
||||
export const UsageRecorded = Event.durable({
|
||||
type: "session.usage.recorded",
|
||||
...options,
|
||||
@@ -580,6 +587,7 @@ export const Definitions = Event.inventory(
|
||||
ModelSelected,
|
||||
Moved,
|
||||
Renamed,
|
||||
Viewed,
|
||||
UsageUpdated,
|
||||
Deleted,
|
||||
Forked,
|
||||
|
||||
@@ -40,6 +40,8 @@ export const Info = Schema.Struct({
|
||||
time: Schema.Struct({
|
||||
created: DateTimeUtcFromMillis,
|
||||
updated: DateTimeUtcFromMillis,
|
||||
idle: DateTimeUtcFromMillis.pipe(optional),
|
||||
viewed: DateTimeUtcFromMillis.pipe(optional),
|
||||
archived: DateTimeUtcFromMillis.pipe(optional),
|
||||
}),
|
||||
title: Schema.String.pipe(optional),
|
||||
|
||||
@@ -54,17 +54,29 @@ describe("contract hygiene", () => {
|
||||
}),
|
||||
).toEqual({ text: "completed" })
|
||||
|
||||
const info = Session.Info.make({
|
||||
id: Session.ID.make("ses_untitled"),
|
||||
projectID: Project.ID.make("global"),
|
||||
cost: Money.USD.zero,
|
||||
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
time: {
|
||||
created: DateTime.makeUnsafe(0),
|
||||
updated: DateTime.makeUnsafe(0),
|
||||
idle: undefined,
|
||||
viewed: undefined,
|
||||
},
|
||||
title: undefined,
|
||||
location: { directory: AbsolutePath.make("/project") },
|
||||
})
|
||||
const encoded = Schema.encodeSync(Session.Info)(info)
|
||||
expect(encoded).not.toHaveProperty("title")
|
||||
expect(encoded.time).toEqual({ created: 0, updated: 0 })
|
||||
expect(
|
||||
Schema.encodeSync(Session.Info)({
|
||||
id: Session.ID.make("ses_untitled"),
|
||||
projectID: Project.ID.make("global"),
|
||||
cost: Money.USD.zero,
|
||||
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
time: { created: DateTime.makeUnsafe(0), updated: DateTime.makeUnsafe(0) },
|
||||
title: undefined,
|
||||
location: { directory: AbsolutePath.make("/project") },
|
||||
}),
|
||||
).not.toHaveProperty("title")
|
||||
...info,
|
||||
time: { ...info.time, idle: DateTime.makeUnsafe(2), viewed: DateTime.makeUnsafe(1) },
|
||||
}).time,
|
||||
).toEqual({ created: 0, updated: 0, idle: 2, viewed: 1 })
|
||||
})
|
||||
|
||||
test("session inbox items omit the internal enqueue sequence", () => {
|
||||
|
||||
@@ -83,6 +83,7 @@ describe("public event manifest", () => {
|
||||
"session.model.selected.1",
|
||||
"session.moved.1",
|
||||
"session.renamed.1",
|
||||
"session.viewed.1",
|
||||
"session.usage.recorded.1",
|
||||
"session.forked.2",
|
||||
"session.inbox.delivered.1",
|
||||
|
||||
@@ -180,6 +180,22 @@ export const SessionHandler = HttpApiBuilder.group(Api, "server.session", (handl
|
||||
}
|
||||
}),
|
||||
)
|
||||
.handle(
|
||||
"session.view",
|
||||
Effect.fn(function* (ctx) {
|
||||
yield* session.view({ sessionID: ctx.params.sessionID }).pipe(
|
||||
Effect.catchTag(
|
||||
"Session.NotFoundError",
|
||||
(error) =>
|
||||
new SessionNotFoundError({
|
||||
sessionID: error.sessionID,
|
||||
message: `Session not found: ${error.sessionID}`,
|
||||
}),
|
||||
),
|
||||
)
|
||||
return HttpApiSchema.NoContent.make()
|
||||
}),
|
||||
)
|
||||
.handle(
|
||||
"session.remove",
|
||||
Effect.fn(function* (ctx) {
|
||||
|
||||
@@ -52,6 +52,36 @@ it.live("serves unauthenticated and answers CORS preflight when no password is c
|
||||
}).pipe(Effect.scoped),
|
||||
)
|
||||
|
||||
it.live("serves the session view operation and missing-session error", () =>
|
||||
Effect.gen(function* () {
|
||||
const handler = yield* ServerFetch.make(options)
|
||||
const created = yield* Effect.promise(() =>
|
||||
handler(
|
||||
new Request("http://opencode.local/api/session", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: "{}",
|
||||
}),
|
||||
).then((response) => response.json()),
|
||||
)
|
||||
if (typeof created !== "object" || created === null || !("data" in created))
|
||||
return yield* Effect.die(new Error("Expected a session response"))
|
||||
const data = created.data
|
||||
if (typeof data !== "object" || data === null || !("id" in data) || typeof data.id !== "string")
|
||||
return yield* Effect.die(new Error("Expected a session ID"))
|
||||
|
||||
const viewed = yield* Effect.promise(() =>
|
||||
handler(new Request(`http://opencode.local/api/session/${data.id}/view`, { method: "POST" })),
|
||||
)
|
||||
expect(viewed.status).toBe(204)
|
||||
|
||||
const missing = yield* Effect.promise(() =>
|
||||
handler(new Request("http://opencode.local/api/session/ses_missing_view/view", { method: "POST" })),
|
||||
)
|
||||
expect(missing.status).toBe(404)
|
||||
}).pipe(Effect.scoped),
|
||||
)
|
||||
|
||||
// Pins the eager-boot guarantee: the application layer is built before the handler returns, so
|
||||
// an aborted first request cannot interrupt layer construction and wedge every later request
|
||||
// (the Effect-TS/effect#6319 failure class that lazy first-request builds are prone to).
|
||||
|
||||
@@ -13,13 +13,7 @@ type Experiment = {
|
||||
// In-flight features anyone can opt into. Each entry is temporary: an
|
||||
// experiment either graduates (delete the entry, make the behavior
|
||||
// unconditional) or dies (delete the entry and the branch it gated).
|
||||
export const experiments: Experiment[] = [
|
||||
{
|
||||
id: "tab_scroll",
|
||||
title: "Remember tab scroll",
|
||||
description: "Keep each open tab's reading position and show a shortcut back to the bottom.",
|
||||
},
|
||||
]
|
||||
export const experiments: Experiment[] = []
|
||||
|
||||
export function DialogExperiments() {
|
||||
const config = useConfig()
|
||||
|
||||
@@ -1,177 +1,39 @@
|
||||
import type { OpenCodeClient, OpenCodeEvent } from "@opencode-ai/client"
|
||||
import { createClientConnection } from "@opencode-ai/client/solid"
|
||||
import { createGlobalEmitter } from "@solid-primitives/event-bus"
|
||||
import { batch, onCleanup, onMount } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { errorMessage } from "../util/error"
|
||||
import { onCleanup } from "solid-js"
|
||||
import { createSimpleContext } from "./helper"
|
||||
import { useLog } from "./log"
|
||||
|
||||
export type ClientConnectionStatus = "connected" | "connecting" | "reconnecting"
|
||||
export type ClientConnectionEvent = {
|
||||
readonly type: "client.connection"
|
||||
readonly created: number
|
||||
readonly data: {
|
||||
readonly status: "connecting" | "connected" | "disconnected" | "reconnecting"
|
||||
readonly attempt: number
|
||||
readonly error?: string
|
||||
}
|
||||
}
|
||||
|
||||
type ManagedService = {
|
||||
reconnect: (signal: AbortSignal) => Promise<{ api: OpenCodeClient }>
|
||||
restart: () => Promise<void>
|
||||
}
|
||||
|
||||
type ClientEventMap = { [Type in OpenCodeEvent["type"]]: Extract<OpenCodeEvent, { type: Type }> }
|
||||
const connectTimeout = 2_000
|
||||
const connectionHistoryLimit = 50
|
||||
const eventFlushInterval = 10
|
||||
|
||||
export const { use: useClient, provider: ClientProvider } = createSimpleContext({
|
||||
name: "Client",
|
||||
init: (props: { api: OpenCodeClient; service?: ManagedService }) => {
|
||||
const log = useLog({ component: "client" })
|
||||
const abort = new AbortController()
|
||||
const history: ClientConnectionEvent[] = []
|
||||
let api = props.api
|
||||
const service = props.service
|
||||
const events = createGlobalEmitter<ClientEventMap>()
|
||||
let pending: OpenCodeEvent[] = []
|
||||
let flushTimer: ReturnType<typeof setTimeout> | undefined
|
||||
const [connection, setConnection] = createStore<{
|
||||
status: ClientConnectionStatus
|
||||
attempt: number
|
||||
error?: string
|
||||
}>({
|
||||
status: "connecting",
|
||||
attempt: 0,
|
||||
})
|
||||
let stream: AbortController | undefined
|
||||
let api = props.api
|
||||
|
||||
function record(status: ClientConnectionEvent["data"]["status"], attempt: number, error?: string) {
|
||||
history.push({ type: "client.connection", created: Date.now(), data: { status, attempt, error } })
|
||||
if (history.length > connectionHistoryLimit) history.shift()
|
||||
}
|
||||
|
||||
function flushEvents() {
|
||||
flushTimer = undefined
|
||||
const queued = pending
|
||||
pending = []
|
||||
batch(() => queued.forEach((event) => events.emit(event.type, event)))
|
||||
}
|
||||
|
||||
function emit(event: OpenCodeEvent) {
|
||||
pending.push(event)
|
||||
if (flushTimer) return
|
||||
flushTimer = setTimeout(flushEvents, eventFlushInterval)
|
||||
}
|
||||
|
||||
async function connect(signal: AbortSignal, attempt: number) {
|
||||
let connectedAt: number | undefined
|
||||
|
||||
// Bound the initial handshake and tie this request to the stream lifetime.
|
||||
const request = new AbortController()
|
||||
const cancel = () => request.abort(signal.reason)
|
||||
const timeout = setTimeout(() => request.abort(new Error("Timed out connecting to server")), connectTimeout)
|
||||
signal.addEventListener("abort", cancel, { once: true })
|
||||
|
||||
try {
|
||||
// Open the event stream and validate its initial handshake.
|
||||
record(attempt === 0 ? "connecting" : "reconnecting", attempt)
|
||||
log.info("event stream connecting", { attempt })
|
||||
|
||||
const iterator = api.event.subscribe({ signal: request.signal })[Symbol.asyncIterator]()
|
||||
const first = await iterator.next()
|
||||
|
||||
if (signal.aborted) return { error: undefined, connectedAt }
|
||||
if (first.done) {
|
||||
const error =
|
||||
request.signal.reason instanceof Error ? request.signal.reason : new Error("Event stream disconnected")
|
||||
return { error, connectedAt }
|
||||
}
|
||||
if (first.value.type !== "server.connected")
|
||||
return { error: new Error("Event stream did not start with server.connected"), connectedAt }
|
||||
|
||||
// Publish the connected state before forwarding live events.
|
||||
clearTimeout(timeout)
|
||||
record("connected", attempt)
|
||||
connectedAt = Date.now()
|
||||
log.info("event stream connected")
|
||||
emit(first.value)
|
||||
setConnection({ status: "connected", attempt: 0, error: undefined })
|
||||
|
||||
// Forward events until the stream closes or this connection is cancelled.
|
||||
while (!signal.aborted) {
|
||||
const event = await iterator.next()
|
||||
|
||||
if (signal.aborted) return { error: undefined, connectedAt }
|
||||
if (event.done) return { error: new Error("Event stream disconnected"), connectedAt }
|
||||
|
||||
if ("durable" in event.value)
|
||||
log.debug("event", {
|
||||
type: event.value.type,
|
||||
aggregateID: event.value.durable.aggregateID,
|
||||
seq: event.value.durable.seq,
|
||||
})
|
||||
|
||||
emit(event.value)
|
||||
}
|
||||
|
||||
return { error: undefined, connectedAt }
|
||||
} catch (error) {
|
||||
return { error, connectedAt }
|
||||
} finally {
|
||||
request.abort()
|
||||
clearTimeout(timeout)
|
||||
signal.removeEventListener("abort", cancel)
|
||||
}
|
||||
}
|
||||
|
||||
function start() {
|
||||
stream?.abort()
|
||||
const controller = new AbortController()
|
||||
stream = controller
|
||||
void (async () => {
|
||||
let attempt = 0
|
||||
while (!abort.signal.aborted && !controller.signal.aborted) {
|
||||
const result = await connect(controller.signal, attempt)
|
||||
if (abort.signal.aborted || controller.signal.aborted) return
|
||||
if (result.connectedAt !== undefined && Date.now() - result.connectedAt >= 1_000) attempt = 0
|
||||
attempt += 1
|
||||
const message = errorMessage(result.error)
|
||||
record("disconnected", attempt, message)
|
||||
log.info("event stream disconnected", {
|
||||
attempt,
|
||||
error: message,
|
||||
})
|
||||
setConnection({ status: "reconnecting", attempt, error: message })
|
||||
// Re-resolve the transport before retrying: the server may have
|
||||
// moved (service restarted on a new port) or need starting. Static
|
||||
// transports (--server, standalone) resolve to the same address.
|
||||
if (props.service) {
|
||||
const next = await props.service.reconnect(controller.signal).catch((error) => {
|
||||
if (!controller.signal.aborted)
|
||||
log.info("server resolution failed", {
|
||||
attempt,
|
||||
error: errorMessage(error),
|
||||
})
|
||||
})
|
||||
if (abort.signal.aborted || controller.signal.aborted) return
|
||||
if (next) {
|
||||
api = next.api
|
||||
if (attempt === 1) continue
|
||||
}
|
||||
const connection = createClientConnection(api, {
|
||||
reconnect: service
|
||||
? async (signal) => {
|
||||
api = (await service.reconnect(signal)).api
|
||||
return api
|
||||
}
|
||||
await wait(1_000, controller.signal)
|
||||
}
|
||||
})()
|
||||
}
|
||||
: undefined,
|
||||
onEvent(event) {
|
||||
events.emit(event.type, event)
|
||||
},
|
||||
log,
|
||||
})
|
||||
|
||||
onMount(start)
|
||||
onCleanup(() => {
|
||||
abort.abort()
|
||||
stream?.abort()
|
||||
if (flushTimer) clearTimeout(flushTimer)
|
||||
pending = []
|
||||
events.clear()
|
||||
})
|
||||
|
||||
@@ -183,35 +45,8 @@ export const { use: useClient, provider: ClientProvider } = createSimpleContext(
|
||||
on: events.on,
|
||||
listen: events.listen,
|
||||
},
|
||||
connection: {
|
||||
status() {
|
||||
return connection.status
|
||||
},
|
||||
attempt() {
|
||||
return connection.attempt
|
||||
},
|
||||
error() {
|
||||
return connection.error
|
||||
},
|
||||
internal: {
|
||||
history() {
|
||||
return history.slice()
|
||||
},
|
||||
},
|
||||
},
|
||||
restart: props.service?.restart,
|
||||
connection,
|
||||
restart: service?.restart,
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
function wait(delay: number, signal: AbortSignal) {
|
||||
return new Promise<void>((resolve) => {
|
||||
const timer = setTimeout(done, delay)
|
||||
signal.addEventListener("abort", done, { once: true })
|
||||
function done() {
|
||||
clearTimeout(timer)
|
||||
signal.removeEventListener("abort", done)
|
||||
resolve()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -25,12 +25,12 @@ import {
|
||||
type ClosedSessionTab,
|
||||
type SessionTab,
|
||||
type SessionTabHistory,
|
||||
type SessionTabUnread,
|
||||
} from "./session-tabs-model"
|
||||
|
||||
type TabsState = {
|
||||
tabs: SessionTab[]
|
||||
unread: Record<string, SessionTabUnread>
|
||||
// Read only long enough to remove the former client-owned state from persisted tab files.
|
||||
unread?: Record<string, unknown>
|
||||
}
|
||||
|
||||
type PersistedState = {
|
||||
@@ -43,7 +43,7 @@ type ScrollAnchor = {
|
||||
screenY: number
|
||||
}
|
||||
|
||||
const empty = (): TabsState => ({ tabs: [], unread: {} })
|
||||
const empty = (): TabsState => ({ tabs: [] })
|
||||
|
||||
// Deliberately after connect settles: the visible session's mount syncs win the first slots.
|
||||
const TAB_PREFETCH_DELAY = 300
|
||||
@@ -60,7 +60,7 @@ export const { use: useSessionTabs, provider: SessionTabsProvider } = createSimp
|
||||
const paths = useTuiPaths()
|
||||
const renderer = useRenderer()
|
||||
const enabled = () => config.tabs.enabled
|
||||
// Focus reporting emits transitions, so an interactive launch owns unread state until its first blur.
|
||||
// Focus reporting emits transitions, so an interactive launch may acknowledge viewed sessions until its first blur.
|
||||
const [focused, setFocused] = createSignal(true)
|
||||
// Keyed reconcile keeps tab object identity across reorders, so strip rows move instead of
|
||||
// mutating in place, which per-row animations and drag state depend on.
|
||||
@@ -87,11 +87,6 @@ export const { use: useSessionTabs, provider: SessionTabsProvider } = createSimp
|
||||
renderer.off("blur", onBlur)
|
||||
})
|
||||
|
||||
createEffect(() => {
|
||||
if (config.experimental?.tab_scroll === true) return
|
||||
scrollAnchors.clear()
|
||||
})
|
||||
|
||||
function state() {
|
||||
if (config.tabs.scope === "cwd") return store.cwd[paths.cwd] ?? fallback
|
||||
return store.global
|
||||
@@ -110,16 +105,15 @@ export const { use: useSessionTabs, provider: SessionTabsProvider } = createSimp
|
||||
const session = data.session.get(sessionID)
|
||||
return session?.title ?? persisted ?? fallback ?? (session ? withTimestampedFallback(session) : undefined)
|
||||
}
|
||||
const isUnread = (sessionID: string) => {
|
||||
const info = data.session.get(sessionID)
|
||||
return info?.time.idle !== undefined && (info.time.viewed === undefined || info.time.idle > info.time.viewed)
|
||||
}
|
||||
const normalize = (value: TabsState) => ({
|
||||
tabs: value.tabs.reduce<SessionTab[]>((tabs, tab) => {
|
||||
const sessionID = root(tab.sessionID)
|
||||
return openSessionTab(tabs, { sessionID, title: title(sessionID, tab.title) })
|
||||
}, []),
|
||||
unread: Object.entries(value.unread).reduce<Record<string, SessionTabUnread>>((result, entry) => {
|
||||
const sessionID = root(entry[0])
|
||||
result[sessionID] = result[sessionID] === "error" ? "error" : entry[1]
|
||||
return result
|
||||
}, {}),
|
||||
})
|
||||
const current = () => (route.data.type === "session" ? root(route.data.sessionID) : undefined)
|
||||
const newTab = createMemo((open = false) => {
|
||||
@@ -133,7 +127,7 @@ export const { use: useSessionTabs, provider: SessionTabsProvider } = createSimp
|
||||
const members = data.session.family(session)
|
||||
const family = members.length > 0 ? members : [session]
|
||||
return {
|
||||
unread: state().unread[session],
|
||||
unread: family.some(isUnread) ? ("activity" as const) : undefined,
|
||||
promptPulse: promptPulses()[session] ?? 0,
|
||||
attention: family.some(
|
||||
(id) => (data.session.permission.list(id)?.length ?? 0) > 0 || (data.session.form.list(id)?.length ?? 0) > 0,
|
||||
@@ -142,17 +136,6 @@ export const { use: useSessionTabs, provider: SessionTabsProvider } = createSimp
|
||||
}
|
||||
}
|
||||
|
||||
function markUnread(sessionID: string, unread: SessionTabUnread) {
|
||||
if (!enabled() || !focused()) return
|
||||
const session = root(sessionID)
|
||||
if (current() === session || !state().tabs.some((tab) => tab.sessionID === session)) return
|
||||
if (state().unread[session] === unread) return
|
||||
update((draft) => {
|
||||
if (!draft.tabs.some((tab) => tab.sessionID === session)) return
|
||||
draft.unread[session] = unread
|
||||
})
|
||||
}
|
||||
|
||||
createEffect(() => {
|
||||
if (!enabled()) return
|
||||
if (route.data.type !== "session" || route.data.sessionID === "dummy") return
|
||||
@@ -176,10 +159,11 @@ export const { use: useSessionTabs, provider: SessionTabsProvider } = createSimp
|
||||
if (!enabled() || !focused()) return
|
||||
if (route.data.type !== "session" || route.data.sessionID === "dummy") return
|
||||
const sessionID = root(route.data.sessionID)
|
||||
if (!state().unread[sessionID]) return
|
||||
update((draft) => {
|
||||
delete draft.unread[sessionID]
|
||||
})
|
||||
const members = data.session.family(sessionID)
|
||||
const family = members.length > 0 ? members : [sessionID]
|
||||
const unread = family.filter(isUnread)
|
||||
if (unread.length === 0) return
|
||||
void Promise.allSettled(unread.map((id) => client.api.session.view({ sessionID: id })))
|
||||
})
|
||||
|
||||
createEffect(() => {
|
||||
@@ -189,7 +173,7 @@ export const { use: useSessionTabs, provider: SessionTabsProvider } = createSimp
|
||||
update((draft) => {
|
||||
const next = normalize(draft)
|
||||
draft.tabs = next.tabs
|
||||
draft.unread = next.unread
|
||||
delete draft.unread
|
||||
})
|
||||
})
|
||||
|
||||
@@ -210,7 +194,7 @@ export const { use: useSessionTabs, provider: SessionTabsProvider } = createSimp
|
||||
const sessionIDs = signature.split("\n")
|
||||
let stale = false
|
||||
void (async () => {
|
||||
await Promise.allSettled(sessionIDs.map((sessionID) => data.session.sync(sessionID)))
|
||||
await Promise.allSettled(sessionIDs.map((sessionID) => data.session.sync(sessionID, { children: true })))
|
||||
if (stale) return
|
||||
const locations = new Map(
|
||||
sessionIDs
|
||||
@@ -244,9 +228,6 @@ export const { use: useSessionTabs, provider: SessionTabsProvider } = createSimp
|
||||
})
|
||||
})
|
||||
|
||||
onCleanup(event.on("session.execution.succeeded", (evt) => markUnread(evt.data.sessionID, "activity")))
|
||||
onCleanup(event.on("session.execution.interrupted", (evt) => markUnread(evt.data.sessionID, "activity")))
|
||||
onCleanup(event.on("session.execution.failed", (evt) => markUnread(evt.data.sessionID, "error")))
|
||||
onCleanup(
|
||||
event.on("session.moved", (evt) => {
|
||||
if (!enabled() || !state().tabs.some((tab) => tab.sessionID === root(evt.data.sessionID))) return
|
||||
@@ -282,7 +263,6 @@ export const { use: useSessionTabs, provider: SessionTabsProvider } = createSimp
|
||||
history = previous.history
|
||||
update((draft) => {
|
||||
draft.tabs = closeSessionTab(draft.tabs, target).tabs
|
||||
delete draft.unread[target]
|
||||
})
|
||||
setPromptPulses((pulses) => {
|
||||
if (pulses[target] === undefined) return pulses
|
||||
@@ -378,7 +358,7 @@ export const { use: useSessionTabs, provider: SessionTabsProvider } = createSimp
|
||||
cycleUnread(direction: 1 | -1) {
|
||||
if (!enabled()) return
|
||||
const tab = cycleSessionTab(state().tabs, current(), direction, (tab) =>
|
||||
Boolean(state().unread[tab.sessionID] || status(tab.sessionID).attention),
|
||||
Boolean(status(tab.sessionID).unread || status(tab.sessionID).attention),
|
||||
)
|
||||
if (tab) route.navigate({ type: "session", sessionID: tab.sessionID })
|
||||
},
|
||||
|
||||
@@ -429,7 +429,6 @@ export function Session(props: { verticalTabsWidth: number }) {
|
||||
return scroll.scrollTop < Math.max(0, scroll.scrollHeight - scroll.viewport.height) - 1
|
||||
}
|
||||
function updateAwayFromBottom() {
|
||||
if (config.experimental?.tab_scroll !== true) return
|
||||
if (awayTimer) clearTimeout(awayTimer)
|
||||
awayTimer = setTimeout(() => {
|
||||
awayTimer = undefined
|
||||
@@ -440,7 +439,7 @@ export function Session(props: { verticalTabsWidth: number }) {
|
||||
})
|
||||
}
|
||||
function saveScrollAnchor() {
|
||||
if (config.experimental?.tab_scroll !== true || !isAwayFromBottom()) {
|
||||
if (!isAwayFromBottom()) {
|
||||
sessionTabs.setScrollAnchor(sessionID, undefined)
|
||||
return
|
||||
}
|
||||
@@ -457,7 +456,7 @@ export function Session(props: { verticalTabsWidth: number }) {
|
||||
else sessionTabs.setScrollAnchor(sessionID, undefined)
|
||||
}
|
||||
function restoreScrollPosition() {
|
||||
const anchor = config.experimental?.tab_scroll === true ? sessionTabs.scrollAnchor(sessionID) : undefined
|
||||
const anchor = sessionTabs.scrollAnchor(sessionID)
|
||||
const index = anchor ? boundaries().indexOf(anchor.messageID) : -1
|
||||
if (!anchor || index === -1) {
|
||||
scroll.scrollTo(scroll.scrollHeight)
|
||||
@@ -1195,15 +1194,21 @@ export function Session(props: { verticalTabsWidth: number }) {
|
||||
</scrollbox>
|
||||
</box>
|
||||
<box height={1} flexShrink={0} flexDirection="row" justifyContent="flex-end">
|
||||
<Show when={config.experimental?.tab_scroll === true && awayFromBottom()}>
|
||||
<text
|
||||
fg={latestHovered() ? theme.text.default : theme.text.subdued}
|
||||
<Show when={awayFromBottom()}>
|
||||
<box
|
||||
paddingLeft={1}
|
||||
paddingRight={1}
|
||||
backgroundColor={
|
||||
latestHovered() ? theme.background.action.primary.focused : theme.background.action.primary.default
|
||||
}
|
||||
onMouseOver={() => setLatestHovered(true)}
|
||||
onMouseOut={() => setLatestHovered(false)}
|
||||
onMouseUp={toBottom}
|
||||
>
|
||||
Latest ↓
|
||||
</text>
|
||||
<text fg={latestHovered() ? theme.text.action.primary.focused : theme.text.action.primary.default}>
|
||||
Jump to latest ↓
|
||||
</text>
|
||||
</box>
|
||||
</Show>
|
||||
</box>
|
||||
<box flexShrink={0}>
|
||||
|
||||
@@ -35,6 +35,8 @@ async function renderSessionTabs(
|
||||
persisted?: string[]
|
||||
sessionGate?: Promise<void>
|
||||
sessionDirectories?: Record<string, string>
|
||||
sessionParents?: Record<string, string>
|
||||
sessionTimes?: Record<string, { idle?: number; viewed?: number }>
|
||||
newLocation?: "launch" | "inherit"
|
||||
},
|
||||
) {
|
||||
@@ -53,9 +55,13 @@ async function renderSessionTabs(
|
||||
}
|
||||
const events = createEventStream()
|
||||
const sessions: string[] = []
|
||||
const views: string[] = []
|
||||
const locations: string[] = []
|
||||
const vcsLocations: string[] = []
|
||||
const calls = createFetch(async (url) => {
|
||||
const sessionTimes = Object.fromEntries(
|
||||
Object.entries(options?.sessionTimes ?? {}).map(([sessionID, time]) => [sessionID, { ...time }]),
|
||||
)
|
||||
const calls = createFetch(async (url, request) => {
|
||||
if (url.pathname === "/api/location") {
|
||||
const requested = url.searchParams.get("location[directory]") ?? directory
|
||||
locations.push(requested)
|
||||
@@ -72,6 +78,13 @@ async function renderSessionTabs(
|
||||
data: { branch: { current: "main", default: "main" } },
|
||||
})
|
||||
}
|
||||
const viewed = url.pathname.match(/^\/api\/session\/([^/]+)\/view$/)?.[1]
|
||||
if (viewed && request.method === "POST") {
|
||||
views.push(viewed)
|
||||
const time = (sessionTimes[viewed] ??= {})
|
||||
time.viewed = time.idle
|
||||
return new Response(null, { status: 204 })
|
||||
}
|
||||
const sessionID = url.pathname.match(/^\/api\/session\/([^/]+)$/)?.[1]
|
||||
if (!sessionID) return undefined
|
||||
sessions.push(sessionID)
|
||||
@@ -79,12 +92,13 @@ async function renderSessionTabs(
|
||||
return json({
|
||||
data: {
|
||||
id: sessionID,
|
||||
parentID: options?.sessionParents?.[sessionID],
|
||||
title: sessionID === initialSessionID ? options?.title : undefined,
|
||||
projectID: "project",
|
||||
location: { directory: options?.sessionDirectories?.[sessionID] ?? directory },
|
||||
cost: 0,
|
||||
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
time: { created: 0, updated: 0 },
|
||||
time: { created: 0, updated: 0, ...sessionTimes[sessionID] },
|
||||
},
|
||||
})
|
||||
}, events)
|
||||
@@ -138,9 +152,13 @@ async function renderSessionTabs(
|
||||
route,
|
||||
data,
|
||||
sessions,
|
||||
views,
|
||||
locations,
|
||||
vcsLocations,
|
||||
state,
|
||||
setSessionTime(sessionID: string, time: { idle?: number; viewed?: number }) {
|
||||
sessionTimes[sessionID] = time
|
||||
},
|
||||
emit: (event: OpenCodeEvent) => events.emit({ ...event, location: { directory } }),
|
||||
focus: () => app.renderer.emit("focus"),
|
||||
blur: () => app.renderer.emit("blur"),
|
||||
@@ -153,14 +171,6 @@ async function renderSessionTabs(
|
||||
}
|
||||
}
|
||||
|
||||
const executionSucceeded = (sessionID: string): OpenCodeEvent => ({
|
||||
id: `evt_done_${sessionID}`,
|
||||
created: Date.now(),
|
||||
type: "session.execution.succeeded",
|
||||
durable: { aggregateID: sessionID, seq: 1, version: 1 },
|
||||
data: { sessionID },
|
||||
})
|
||||
|
||||
test("loads persisted tab metadata concurrently on connect", async () => {
|
||||
let release!: () => void
|
||||
const sessionGate = new Promise<void>((resolve) => (release = resolve))
|
||||
@@ -230,56 +240,111 @@ test("stores session tabs for the current working directory by default", async (
|
||||
const file = path.join(setup.state, "test", "tui", "tabs.json")
|
||||
await wait(() => Bun.file(file).size > 0)
|
||||
const stored = await Bun.file(file).json()
|
||||
expect(stored.global).toEqual({ tabs: [], unread: {} })
|
||||
expect(stored.global).toEqual({ tabs: [] })
|
||||
expect(Object.keys(stored.cwd)).toEqual([directory])
|
||||
expect(stored.cwd[directory].tabs.map((tab: { sessionID: string }) => tab.sessionID)).toEqual(["first"])
|
||||
expect(stored.cwd[directory].unread).toEqual({})
|
||||
expect(stored.cwd[directory]).not.toHaveProperty("unread")
|
||||
} finally {
|
||||
await setup.destroy()
|
||||
}
|
||||
})
|
||||
|
||||
test("only the foreground TUI mutates unread state", async () => {
|
||||
await using temporary = await tmpdir()
|
||||
let foreground: Awaited<ReturnType<typeof renderSessionTabs>> | undefined
|
||||
let background: Awaited<ReturnType<typeof renderSessionTabs>> | undefined
|
||||
test("keeps scroll anchors for open session tabs", async () => {
|
||||
const setup = await renderSessionTabs("first")
|
||||
|
||||
try {
|
||||
foreground = await renderSessionTabs("first", { state: temporary.path, persisted: ["first", "second"] })
|
||||
background = await renderSessionTabs("second", { state: temporary.path })
|
||||
foreground.focus()
|
||||
background.blur()
|
||||
await wait(() => foreground?.tabs.tabs().length === 2 && background?.tabs.tabs().length === 2, 2_000, "shared tabs")
|
||||
await wait(() => setup.tabs.current() === "first")
|
||||
setup.tabs.setScrollAnchor("first", { messageID: "msg_1", screenY: -3 })
|
||||
|
||||
const firstDone = executionSucceeded("first")
|
||||
foreground.emit(firstDone)
|
||||
background.emit(firstDone)
|
||||
await Promise.all([foreground.flush(), background.flush()])
|
||||
expect(foreground.tabs.status("first").unread).toBeUndefined()
|
||||
expect(background.tabs.status("first").unread).toBeUndefined()
|
||||
expect(setup.tabs.scrollAnchor("first")).toEqual({ messageID: "msg_1", screenY: -3 })
|
||||
|
||||
const secondDone = executionSucceeded("second")
|
||||
foreground.emit(secondDone)
|
||||
background.emit(secondDone)
|
||||
await wait(
|
||||
() =>
|
||||
foreground?.tabs.status("second").unread === "activity" &&
|
||||
background?.tabs.status("second").unread === "activity",
|
||||
10_000,
|
||||
"shared unread activity",
|
||||
)
|
||||
|
||||
foreground.tabs.select("second")
|
||||
await wait(
|
||||
() =>
|
||||
foreground?.tabs.status("second").unread === undefined &&
|
||||
background?.tabs.status("second").unread === undefined,
|
||||
10_000,
|
||||
"shared unread clearing",
|
||||
)
|
||||
setup.tabs.close("first")
|
||||
await wait(() => setup.tabs.tabs().every((tab) => tab.sessionID !== "first"))
|
||||
expect(setup.tabs.scrollAnchor("first")).toBeUndefined()
|
||||
} finally {
|
||||
if (foreground) await foreground.destroy()
|
||||
if (background) await background.destroy()
|
||||
await setup.destroy()
|
||||
}
|
||||
})
|
||||
|
||||
test("derives unread state from server session times", async () => {
|
||||
const setup = await renderSessionTabs("first", {
|
||||
home: true,
|
||||
persisted: ["first", "second"],
|
||||
sessionTimes: { second: { idle: 2 } },
|
||||
})
|
||||
try {
|
||||
await wait(() => setup.tabs.status("second").unread === "activity")
|
||||
expect(setup.tabs.status("first").unread).toBeUndefined()
|
||||
} finally {
|
||||
await setup.destroy()
|
||||
}
|
||||
})
|
||||
|
||||
test("refreshes server session times after terminal events", async () => {
|
||||
const setup = await renderSessionTabs("first", { home: true, persisted: ["first"] })
|
||||
try {
|
||||
setup.setSessionTime("first", { idle: 2 })
|
||||
setup.emit({
|
||||
id: "evt_done_first",
|
||||
created: 2,
|
||||
type: "session.execution.succeeded",
|
||||
durable: { aggregateID: "first", seq: 1, version: 1 },
|
||||
data: { sessionID: "first" },
|
||||
})
|
||||
await wait(() => setup.tabs.status("first").unread === "activity")
|
||||
} finally {
|
||||
await setup.destroy()
|
||||
}
|
||||
})
|
||||
|
||||
test("views a selected unread session only while focused", async () => {
|
||||
const setup = await renderSessionTabs("first", {
|
||||
home: true,
|
||||
persisted: ["first"],
|
||||
sessionTimes: { first: { idle: 2 } },
|
||||
})
|
||||
try {
|
||||
setup.blur()
|
||||
setup.route.navigate({ type: "session", sessionID: "first" })
|
||||
await wait(() => setup.tabs.current() === "first" && setup.tabs.status("first").unread === "activity")
|
||||
await Bun.sleep(20)
|
||||
expect(setup.views).toEqual([])
|
||||
|
||||
setup.focus()
|
||||
await wait(() => setup.views.includes("first"))
|
||||
setup.emit({
|
||||
id: "evt_viewed_first",
|
||||
created: 3,
|
||||
type: "session.viewed",
|
||||
durable: { aggregateID: "first", seq: 2, version: 1 },
|
||||
data: { sessionID: "first" },
|
||||
})
|
||||
await wait(() => setup.tabs.status("first").unread === undefined)
|
||||
} finally {
|
||||
await setup.destroy()
|
||||
}
|
||||
})
|
||||
|
||||
test("views unread child sessions through their root tab", async () => {
|
||||
const setup = await renderSessionTabs("root", {
|
||||
home: true,
|
||||
persisted: ["root"],
|
||||
sessionParents: { child: "root" },
|
||||
sessionTimes: { child: { idle: 2 } },
|
||||
})
|
||||
try {
|
||||
setup.blur()
|
||||
await setup.data.session.sync("child")
|
||||
await wait(() => setup.tabs.status("root").unread === "activity")
|
||||
|
||||
setup.route.navigate({ type: "session", sessionID: "root" })
|
||||
await Bun.sleep(20)
|
||||
expect(setup.views).toEqual([])
|
||||
setup.focus()
|
||||
await wait(() => setup.views.includes("child"))
|
||||
expect(setup.views).not.toContain("root")
|
||||
} finally {
|
||||
await setup.destroy()
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
}
|
||||
|
||||
[data-slot="animated-number-digit"] {
|
||||
display: inline-block;
|
||||
display: inline-grid;
|
||||
width: 1ch;
|
||||
height: 1em;
|
||||
line-height: 1em;
|
||||
@@ -41,19 +41,12 @@
|
||||
mask-repeat: no-repeat;
|
||||
}
|
||||
|
||||
[data-slot="animated-number-static"],
|
||||
[data-slot="animated-number-strip"] {
|
||||
display: inline-flex;
|
||||
flex-direction: column;
|
||||
transform: translateY(calc(var(--animated-number-offset, 10) * -1em));
|
||||
transition-property: transform;
|
||||
transition-duration: var(--animated-number-duration, 560ms);
|
||||
transition-timing-function: var(--tool-motion-ease, cubic-bezier(0.22, 1, 0.36, 1));
|
||||
}
|
||||
|
||||
[data-slot="animated-number-strip"][data-animating="false"] {
|
||||
transition-duration: 0ms;
|
||||
grid-area: 1 / 1;
|
||||
}
|
||||
|
||||
[data-slot="animated-number-static"],
|
||||
[data-slot="animated-number-cell"] {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
@@ -62,6 +55,24 @@
|
||||
height: 1em;
|
||||
line-height: 1em;
|
||||
}
|
||||
|
||||
[data-slot="animated-number-digit"][data-animating="true"] [data-slot="animated-number-static"] {
|
||||
visibility: hidden;
|
||||
}
|
||||
|
||||
[data-slot="animated-number-strip"] {
|
||||
display: inline-flex;
|
||||
flex-direction: column;
|
||||
margin-top: calc(var(--animated-number-offset, 10) * -1em);
|
||||
transition-property: margin-top;
|
||||
transition-duration: var(--animated-number-duration, 560ms);
|
||||
transition-timing-function: var(--tool-motion-ease, cubic-bezier(0.22, 1, 0.36, 1));
|
||||
}
|
||||
|
||||
[data-slot="animated-number-digit"][data-animating="false"] [data-slot="animated-number-strip"] {
|
||||
transition-duration: 0ms;
|
||||
visibility: hidden;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
@@ -71,5 +82,12 @@
|
||||
|
||||
[data-component="animated-number"] [data-slot="animated-number-strip"] {
|
||||
transition-duration: 0ms;
|
||||
visibility: hidden;
|
||||
}
|
||||
|
||||
[data-component="animated-number"]
|
||||
[data-slot="animated-number-digit"][data-animating]
|
||||
[data-slot="animated-number-static"] {
|
||||
visibility: visible;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,10 +43,10 @@ function Digit(props: { value: number; direction: 1 | -1 }) {
|
||||
)
|
||||
|
||||
return (
|
||||
<span data-slot="animated-number-digit">
|
||||
<span data-slot="animated-number-digit" data-animating={animating() ? "true" : "false"}>
|
||||
<span data-slot="animated-number-static">{props.value}</span>
|
||||
<span
|
||||
data-slot="animated-number-strip"
|
||||
data-animating={animating() ? "true" : "false"}
|
||||
onTransitionEnd={() => {
|
||||
setState("animating", false)
|
||||
setState("step", (value) => normalize(value) + 10)
|
||||
|
||||
@@ -152,6 +152,112 @@ provider and model configuration. An unknown variant fails model resolution inst
|
||||
|
||||
### Local models
|
||||
|
||||
#### Ollama
|
||||
|
||||
OpenCode automatically discovers language models from an Ollama server listening on its default address,
|
||||
`http://127.0.0.1:11434`. Discovered models use the `ollama` provider ID and Ollama's model name:
|
||||
|
||||
```jsonc title="opencode.jsonc"
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"model": "ollama/gemma3:4b",
|
||||
}
|
||||
```
|
||||
|
||||
OpenCode refreshes the inventory in the background and reads context, vision, and tool-use capabilities from Ollama.
|
||||
Embedding-only models are excluded because they cannot drive a session. Disable discovery with
|
||||
`"plugins": ["-opencode.provider.ollama"]`.
|
||||
|
||||
For a different host or port, configure Ollama's OpenAI-compatible base URL. Models are still discovered through the
|
||||
native Ollama API at the same path prefix:
|
||||
|
||||
```jsonc title="opencode.jsonc"
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"providers": {
|
||||
"ollama": {
|
||||
"settings": {
|
||||
"baseURL": "http://127.0.0.1:5678/v1",
|
||||
"apiKey": "{env:OLLAMA_API_KEY}",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Omit `apiKey` when the Ollama endpoint does not require bearer authentication.
|
||||
|
||||
#### LM Studio
|
||||
|
||||
OpenCode automatically discovers language models from an unauthenticated LM Studio server listening on its default
|
||||
address, `http://127.0.0.1:1234`. Discovered models use the `lmstudio` provider ID and LM Studio's model key:
|
||||
|
||||
```jsonc title="opencode.jsonc"
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"model": "lmstudio/google/gemma-4-26b-a4b",
|
||||
}
|
||||
```
|
||||
|
||||
OpenCode refreshes the inventory in the background and reads context, vision, and tool-use capabilities from LM
|
||||
Studio. Embedding models are excluded because they cannot drive a session. Disable discovery with
|
||||
`"plugins": ["-opencode.provider.lmstudio"]`.
|
||||
|
||||
For a different host or port, configure the OpenAI-compatible base URL. Models are still discovered automatically:
|
||||
|
||||
```jsonc title="opencode.jsonc"
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"providers": {
|
||||
"lmstudio": {
|
||||
"settings": {
|
||||
"baseURL": "http://127.0.0.1:5678/v1",
|
||||
"apiKey": "{env:LMSTUDIO_API_KEY}",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Omit `apiKey` when LM Studio authentication is disabled.
|
||||
|
||||
#### vLLM
|
||||
|
||||
OpenCode automatically discovers models from a vLLM server listening on its default address, `http://127.0.0.1:8000`.
|
||||
Discovered models use the `vllm` provider ID and the model ID reported by vLLM:
|
||||
|
||||
```jsonc title="opencode.jsonc"
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"model": "vllm/Qwen/Qwen3-Coder-30B-A3B-Instruct",
|
||||
}
|
||||
```
|
||||
|
||||
OpenCode checks vLLM's `/health` endpoint and refreshes `/v1/models` in the background. It uses the reported
|
||||
`max_model_len` as the context limit and only includes model cards owned by `vllm`. Discovered vLLM models advertise
|
||||
text input and output, but not vision or tools. Tool calling is conservative because vLLM enables it with server-level
|
||||
flags such as `--enable-auto-tool-choice` and `--tool-call-parser`, which model discovery does not report. Disable
|
||||
discovery with `"plugins": ["-opencode.provider.vllm"]`.
|
||||
|
||||
For a different endpoint or an authenticated server, configure its OpenAI-compatible base URL:
|
||||
|
||||
```jsonc title="opencode.jsonc"
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"providers": {
|
||||
"vllm": {
|
||||
"settings": {
|
||||
"baseURL": "http://127.0.0.1:9000/v1",
|
||||
"apiKey": "{env:VLLM_API_KEY}",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Omit `apiKey` when authentication is disabled. Path-prefixed proxy URLs are supported; for example,
|
||||
`https://example.com/vllm/v1` checks `/vllm/health` and discovers `/vllm/v1/models`.
|
||||
|
||||
For an OpenAI-compatible server, define a provider package, endpoint, and at least one model:
|
||||
|
||||
```jsonc title="opencode.jsonc"
|
||||
@@ -161,7 +267,7 @@ For an OpenAI-compatible server, define a provider package, endpoint, and at lea
|
||||
"providers": {
|
||||
"local": {
|
||||
"name": "Local server",
|
||||
"package": "aisdk:@ai-sdk/openai-compatible",
|
||||
"package": "@opencode-ai/ai/providers/openai-compatible",
|
||||
"settings": {
|
||||
"baseURL": "http://127.0.0.1:1234/v1",
|
||||
},
|
||||
|
||||
@@ -4127,6 +4127,65 @@
|
||||
"summary": "Get session message"
|
||||
}
|
||||
},
|
||||
"/api/session/{sessionID}/view": {
|
||||
"post": {
|
||||
"tags": ["session"],
|
||||
"operationId": "v2.session.view",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "sessionID",
|
||||
"in": "path",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"allOf": [
|
||||
{
|
||||
"pattern": "^ses"
|
||||
}
|
||||
]
|
||||
},
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"security": [],
|
||||
"responses": {
|
||||
"204": {
|
||||
"description": "<No Content>"
|
||||
},
|
||||
"400": {
|
||||
"description": "InvalidRequestError",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/InvalidRequestError"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "UnauthorizedError",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/UnauthorizedError"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "SessionNotFoundError",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/SessionNotFoundError"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Mark the latest recorded idle transition as viewed.",
|
||||
"summary": "View session"
|
||||
}
|
||||
},
|
||||
"/api/session/{sessionID}/message": {
|
||||
"get": {
|
||||
"tags": ["session"],
|
||||
@@ -12135,6 +12194,12 @@
|
||||
"updated": {
|
||||
"type": "number"
|
||||
},
|
||||
"idle": {
|
||||
"type": "number"
|
||||
},
|
||||
"viewed": {
|
||||
"type": "number"
|
||||
},
|
||||
"archived": {
|
||||
"type": "number"
|
||||
}
|
||||
@@ -14276,6 +14341,71 @@
|
||||
"required": ["id", "created", "type", "durable", "data"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"session.viewed": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"allOf": [
|
||||
{
|
||||
"pattern": "^evt_"
|
||||
}
|
||||
]
|
||||
},
|
||||
"created": {
|
||||
"type": "number"
|
||||
},
|
||||
"metadata": {
|
||||
"type": "object"
|
||||
},
|
||||
"type": {
|
||||
"type": "string",
|
||||
"enum": ["session.viewed"]
|
||||
},
|
||||
"durable": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"aggregateID": {
|
||||
"type": "string"
|
||||
},
|
||||
"seq": {
|
||||
"type": "integer",
|
||||
"allOf": [
|
||||
{
|
||||
"minimum": 0
|
||||
}
|
||||
]
|
||||
},
|
||||
"version": {
|
||||
"type": "number",
|
||||
"enum": [1]
|
||||
}
|
||||
},
|
||||
"required": ["aggregateID", "seq", "version"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"location": {
|
||||
"$ref": "#/components/schemas/Location.Ref"
|
||||
},
|
||||
"data": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"sessionID": {
|
||||
"type": "string",
|
||||
"allOf": [
|
||||
{
|
||||
"pattern": "^ses"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": ["sessionID"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": ["id", "created", "type", "durable", "data"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"session.deleted": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -17296,6 +17426,9 @@
|
||||
{
|
||||
"$ref": "#/components/schemas/session.renamed"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/session.viewed"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/session.deleted"
|
||||
},
|
||||
@@ -22664,6 +22797,9 @@
|
||||
{
|
||||
"$ref": "#/components/schemas/session.renamed"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/session.viewed"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/session.usage.updated"
|
||||
},
|
||||
|
||||
@@ -4127,6 +4127,65 @@
|
||||
"summary": "Get session message"
|
||||
}
|
||||
},
|
||||
"/api/session/{sessionID}/view": {
|
||||
"post": {
|
||||
"tags": ["session"],
|
||||
"operationId": "v2.session.view",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "sessionID",
|
||||
"in": "path",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"allOf": [
|
||||
{
|
||||
"pattern": "^ses"
|
||||
}
|
||||
]
|
||||
},
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"security": [],
|
||||
"responses": {
|
||||
"204": {
|
||||
"description": "<No Content>"
|
||||
},
|
||||
"400": {
|
||||
"description": "InvalidRequestError",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/InvalidRequestError"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "UnauthorizedError",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/UnauthorizedError"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "SessionNotFoundError",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/SessionNotFoundError"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "Mark the latest recorded idle transition as viewed.",
|
||||
"summary": "View session"
|
||||
}
|
||||
},
|
||||
"/api/session/{sessionID}/message": {
|
||||
"get": {
|
||||
"tags": ["session"],
|
||||
@@ -12135,6 +12194,12 @@
|
||||
"updated": {
|
||||
"type": "number"
|
||||
},
|
||||
"idle": {
|
||||
"type": "number"
|
||||
},
|
||||
"viewed": {
|
||||
"type": "number"
|
||||
},
|
||||
"archived": {
|
||||
"type": "number"
|
||||
}
|
||||
@@ -14276,6 +14341,71 @@
|
||||
"required": ["id", "created", "type", "durable", "data"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"session.viewed": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"allOf": [
|
||||
{
|
||||
"pattern": "^evt_"
|
||||
}
|
||||
]
|
||||
},
|
||||
"created": {
|
||||
"type": "number"
|
||||
},
|
||||
"metadata": {
|
||||
"type": "object"
|
||||
},
|
||||
"type": {
|
||||
"type": "string",
|
||||
"enum": ["session.viewed"]
|
||||
},
|
||||
"durable": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"aggregateID": {
|
||||
"type": "string"
|
||||
},
|
||||
"seq": {
|
||||
"type": "integer",
|
||||
"allOf": [
|
||||
{
|
||||
"minimum": 0
|
||||
}
|
||||
]
|
||||
},
|
||||
"version": {
|
||||
"type": "number",
|
||||
"enum": [1]
|
||||
}
|
||||
},
|
||||
"required": ["aggregateID", "seq", "version"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"location": {
|
||||
"$ref": "#/components/schemas/Location.Ref"
|
||||
},
|
||||
"data": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"sessionID": {
|
||||
"type": "string",
|
||||
"allOf": [
|
||||
{
|
||||
"pattern": "^ses"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": ["sessionID"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": ["id", "created", "type", "durable", "data"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"session.deleted": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -17296,6 +17426,9 @@
|
||||
{
|
||||
"$ref": "#/components/schemas/session.renamed"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/session.viewed"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/session.deleted"
|
||||
},
|
||||
@@ -22664,6 +22797,9 @@
|
||||
{
|
||||
"$ref": "#/components/schemas/session.renamed"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/session.viewed"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/session.usage.updated"
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user