mirror of
https://github.com/anomalyco/opencode.git
synced 2026-08-14 15:32:52 -04:00
Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2c294640aa | |||
| 05478afeff | |||
| c02bdd3a14 | |||
| 6adbbc9320 | |||
| 8ff5959cf1 | |||
| 5f78183eaa |
@@ -19,13 +19,6 @@
|
||||
- Expose the meaningful state dimensions through story keybindings and list them in `StoryFooter`; include a reset command when combinations can leave the fixture in a confusing state.
|
||||
- Run a specific story with `OPENCODE_STORY=<story-id> bun run dev:live` from the development worktree, and exercise narrow and wide terminal sizes when layout is relevant.
|
||||
|
||||
## TUI Theme Tokens
|
||||
|
||||
- Choose theme tokens by semantic role, not by their current color. Do not use raw `theme.hue` values or borrow an unrelated semantic token to achieve a preferred appearance.
|
||||
- Use `text.feedback` and `background.feedback` only for outcome or status feedback such as errors, warnings, success messages, and informational messages. Use `formfield` states for form-control text, ordinals, and selection markers, and `action` states for actions.
|
||||
- If the theme does not expose a token for the required semantic role, extend the theme schema, defaults, resolution, and types with that role before using it in a component. Do not repurpose the nearest-looking existing token.
|
||||
- When changing the public theme token surface, verify the built-in light and dark defaults and the custom-theme fallback path in addition to the affected TUI component.
|
||||
|
||||
## Branch Names
|
||||
|
||||
Use a short branch name of at most three words, separated by hyphens. Do not use slashes or type prefixes such as `feat/` or `fix/`.
|
||||
|
||||
@@ -15,6 +15,7 @@ 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 { OpenAIPlugin } from "./provider/openai.js"
|
||||
@@ -48,6 +49,7 @@ export const ProviderPlugins: PluginInternal.InternalPlugin[] = [
|
||||
GroqPlugin,
|
||||
KiloPlugin,
|
||||
LLMGatewayPlugin,
|
||||
LMStudioPlugin,
|
||||
MistralPlugin,
|
||||
NvidiaPlugin,
|
||||
OpencodePlugin,
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
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.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,338 @@
|
||||
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",
|
||||
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 } } } }),
|
||||
})
|
||||
}
|
||||
+125
-277
@@ -4,10 +4,6 @@ import { Rpc, RpcGroup } from "effect/unstable/rpc"
|
||||
const JsonRpcID = Schema.Union([Schema.String, Schema.Number, Schema.Null])
|
||||
const decodeJson = Schema.decodeUnknownSync(Schema.Json)
|
||||
|
||||
// Generated schema unions lose mapped tuple types even though both come from the same operation tuple.
|
||||
// eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion, typescript-eslint/no-unnecessary-type-parameters
|
||||
const decoded = <Type>(value: unknown) => value as Type
|
||||
|
||||
export namespace JsonRpc {
|
||||
export const RequestFields = {
|
||||
jsonrpc: Schema.Literal("2.0"),
|
||||
@@ -26,33 +22,13 @@ export namespace JsonRpc {
|
||||
data: Schema.optional(Schema.Json),
|
||||
})
|
||||
|
||||
export type Response =
|
||||
| {
|
||||
readonly jsonrpc: "2.0"
|
||||
readonly id: string | number | null
|
||||
readonly result: Schema.Schema.Type<typeof Schema.Json>
|
||||
readonly error?: never
|
||||
}
|
||||
| {
|
||||
readonly jsonrpc: "2.0"
|
||||
readonly id: string | number | null
|
||||
readonly error: Schema.Schema.Type<typeof ErrorObject>
|
||||
readonly result?: never
|
||||
}
|
||||
export const Response = decoded<Schema.Decoder<Response>>(
|
||||
Schema.Struct({
|
||||
jsonrpc: Schema.Literal("2.0"),
|
||||
id: JsonRpcID,
|
||||
result: Schema.optionalKey(Schema.Json),
|
||||
error: Schema.optionalKey(ErrorObject),
|
||||
}).check(
|
||||
Schema.makeFilter((response) =>
|
||||
"result" in response === "error" in response
|
||||
? "JSON-RPC responses must contain exactly one of result or error"
|
||||
: undefined,
|
||||
),
|
||||
),
|
||||
)
|
||||
export const Response = Schema.Struct({
|
||||
jsonrpc: Schema.Literal("2.0"),
|
||||
id: JsonRpcID,
|
||||
result: Schema.optional(Schema.Json),
|
||||
error: Schema.optional(ErrorObject),
|
||||
})
|
||||
export interface Response extends Schema.Schema.Type<typeof Response> {}
|
||||
|
||||
export const decodeRequest = Schema.decodeUnknownSync(Request)
|
||||
|
||||
@@ -73,161 +49,6 @@ export namespace JsonRpc {
|
||||
}
|
||||
}
|
||||
|
||||
export class SimulationRequestError extends Schema.TaggedErrorClass<SimulationRequestError>()(
|
||||
"SimulationRequestError",
|
||||
{
|
||||
method: Schema.String,
|
||||
code: Schema.Number,
|
||||
message: Schema.String,
|
||||
data: Schema.optionalKey(Schema.Json),
|
||||
},
|
||||
) {}
|
||||
|
||||
const request = <
|
||||
const Tag extends string,
|
||||
Payload extends Schema.Top | Schema.Struct.Fields = typeof Schema.Void,
|
||||
Success extends Schema.Top = typeof Schema.Void,
|
||||
>(
|
||||
tag: Tag,
|
||||
options?: {
|
||||
readonly payload?: Payload
|
||||
readonly success?: Success
|
||||
},
|
||||
) => Rpc.make(tag, { ...options, error: SimulationRequestError })
|
||||
|
||||
function operation<const Tag extends string, Success extends Schema.Decoder<unknown>>(method: Tag, success: Success) {
|
||||
return {
|
||||
method,
|
||||
success,
|
||||
request: Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal(method) }),
|
||||
rpc: request(method, { success }),
|
||||
}
|
||||
}
|
||||
|
||||
function operationWithPayload<
|
||||
const Tag extends string,
|
||||
Payload extends Schema.Decoder<unknown>,
|
||||
Success extends Schema.Decoder<unknown>,
|
||||
>(method: Tag, payload: Payload, success: Success) {
|
||||
return {
|
||||
method,
|
||||
payload,
|
||||
success,
|
||||
request: Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal(method), params: payload }),
|
||||
rpc: request(method, { payload, success }),
|
||||
}
|
||||
}
|
||||
|
||||
function operationWithRpcPayload<
|
||||
const Tag extends string,
|
||||
Payload extends Schema.Decoder<unknown>,
|
||||
RpcPayload extends Schema.Decoder<unknown>,
|
||||
Success extends Schema.Decoder<unknown>,
|
||||
>(method: Tag, payload: Payload, rpcPayload: RpcPayload, success: Success) {
|
||||
return {
|
||||
method,
|
||||
payload,
|
||||
success,
|
||||
request: Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal(method), params: payload }),
|
||||
rpc: request(method, { payload: rpcPayload, success }),
|
||||
}
|
||||
}
|
||||
|
||||
function notification<const Method extends string, Payload extends Schema.Decoder<unknown>>(
|
||||
method: Method,
|
||||
payload: Payload,
|
||||
) {
|
||||
return {
|
||||
method,
|
||||
payload,
|
||||
schema: Schema.Struct({
|
||||
jsonrpc: Schema.Literal("2.0"),
|
||||
method: Schema.Literal(method),
|
||||
params: payload,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
type OperationRequest<Operation> = Operation extends {
|
||||
readonly method: infer Method extends string
|
||||
readonly payload: infer Payload extends Schema.Top
|
||||
}
|
||||
? Omit<JsonRpc.Request, "method" | "params"> & {
|
||||
readonly method: Method
|
||||
readonly params: Schema.Schema.Type<Payload>
|
||||
}
|
||||
: Operation extends { readonly method: infer Method extends string }
|
||||
? Omit<JsonRpc.Request, "method" | "params"> & { readonly method: Method }
|
||||
: never
|
||||
|
||||
type EndpointRequest<Operations extends ReadonlyArray<{ readonly method: string }>> =
|
||||
| Handshake.Request
|
||||
| OperationRequest<Operations[number]>
|
||||
|
||||
type EndpointNotification<Notifications extends ReadonlyArray<{ readonly schema: Schema.Top }>> = Schema.Schema.Type<
|
||||
Notifications[number]["schema"]
|
||||
>
|
||||
|
||||
function endpoint<
|
||||
const Operations extends ReadonlyArray<{
|
||||
readonly method: string
|
||||
readonly success: Schema.Top
|
||||
readonly rpc: Rpc.Any
|
||||
readonly request: Schema.Decoder<unknown>
|
||||
readonly payload?: Schema.Decoder<unknown>
|
||||
}>,
|
||||
const Notifications extends ReadonlyArray<{
|
||||
readonly method: string
|
||||
readonly payload: Schema.Decoder<unknown>
|
||||
readonly schema: Schema.Decoder<unknown>
|
||||
}>,
|
||||
const Capabilities extends ReadonlyArray<Handshake.Capability>,
|
||||
>(
|
||||
operations: Operations,
|
||||
notifications: Notifications,
|
||||
features: ReadonlyArray<Handshake.Capability>,
|
||||
Capabilities: Capabilities,
|
||||
) {
|
||||
const requests: ReadonlyArray<Schema.Decoder<unknown>> = [
|
||||
Handshake.Request,
|
||||
...operations.map((operation) => operation.request),
|
||||
]
|
||||
const Request = Schema.Union(requests)
|
||||
const Notification =
|
||||
notifications.length === 0 ? Schema.Never : Schema.Union(notifications.map((notification) => notification.schema))
|
||||
const decodeRequest = Schema.decodeUnknownSync(Request)
|
||||
const decodeRequestEffect = Schema.decodeUnknownEffect(Schema.fromJsonString(Request))
|
||||
const decodeNotification = Schema.decodeUnknownSync(Notification)
|
||||
const decodeNotificationEffect = Schema.decodeUnknownEffect(Schema.fromJsonString(Notification))
|
||||
const handshake = request("simulation.handshake", { payload: Handshake.Params, success: Handshake.Response })
|
||||
const rpcs = RpcGroup.make(handshake, ...operations.map((operation) => operation.rpc)) as RpcGroup.RpcGroup<
|
||||
typeof handshake | Operations[number]["rpc"]
|
||||
>
|
||||
const derived = [
|
||||
...operations.map((operation) => operation.method),
|
||||
...notifications.map((notification) => notification.method),
|
||||
...features,
|
||||
]
|
||||
if (
|
||||
new Set(Capabilities).size !== Capabilities.length ||
|
||||
derived.length !== Capabilities.length ||
|
||||
derived.some((capability) => !Capabilities.includes(capability))
|
||||
)
|
||||
throw new Error("Simulation capabilities must exactly match endpoint operations")
|
||||
return {
|
||||
Capabilities,
|
||||
Request: decoded<Schema.Decoder<EndpointRequest<Operations>>>(Request),
|
||||
Notification: decoded<Schema.Decoder<EndpointNotification<Notifications>>>(Notification),
|
||||
decodeRequest: (input: unknown) => decoded<EndpointRequest<Operations>>(decodeRequest(input)),
|
||||
decodeRequestEffect: (input: string) =>
|
||||
decodeRequestEffect(input).pipe(Effect.map(decoded<EndpointRequest<Operations>>)),
|
||||
decodeNotification: (input: unknown) => decoded<EndpointNotification<Notifications>>(decodeNotification(input)),
|
||||
decodeNotificationEffect: (input: string) =>
|
||||
decodeNotificationEffect(input).pipe(Effect.map(decoded<EndpointNotification<Notifications>>)),
|
||||
rpcs,
|
||||
}
|
||||
}
|
||||
|
||||
export namespace Handshake {
|
||||
export const ProtocolVersion = Schema.Literal(1)
|
||||
export type ProtocolVersion = Schema.Schema.Type<typeof ProtocolVersion>
|
||||
@@ -260,7 +81,7 @@ export namespace Handshake {
|
||||
protocolVersion: ProtocolVersion,
|
||||
role: EndpointRole,
|
||||
server: Identity,
|
||||
capabilities: Schema.Array(Capability).check(Schema.isUnique()),
|
||||
capabilities: Schema.Array(Capability),
|
||||
})
|
||||
export interface Response extends Schema.Schema.Type<typeof Response> {}
|
||||
|
||||
@@ -344,6 +165,23 @@ export namespace Handshake {
|
||||
}
|
||||
|
||||
export namespace Frontend {
|
||||
export const Capabilities = [
|
||||
"ui.type",
|
||||
"ui.press",
|
||||
"ui.enter",
|
||||
"ui.arrow",
|
||||
"ui.focus",
|
||||
"ui.click",
|
||||
"ui.click.semantic",
|
||||
"ui.resize",
|
||||
"ui.matches",
|
||||
"ui.state",
|
||||
"ui.snapshot",
|
||||
"ui.capture",
|
||||
"ui.recording.finish",
|
||||
] as const satisfies ReadonlyArray<Handshake.Capability>
|
||||
export type Capability = (typeof Capabilities)[number]
|
||||
|
||||
export const KeyModifiers = Schema.Struct({
|
||||
ctrl: Schema.optional(Schema.Boolean),
|
||||
shift: Schema.optional(Schema.Boolean),
|
||||
@@ -499,51 +337,44 @@ export namespace Frontend {
|
||||
|
||||
export const ResizeParams = Schema.Struct({ cols: Schema.Number, rows: Schema.Number })
|
||||
export interface ResizeParams extends Schema.Schema.Type<typeof ResizeParams> {}
|
||||
}
|
||||
|
||||
const FrontendOperations = [
|
||||
operation("ui.state", Frontend.State),
|
||||
operation("ui.snapshot", Frontend.SemanticSnapshot),
|
||||
operation("ui.capture", Frontend.CapturedFrame),
|
||||
operationWithPayload("ui.matches", Frontend.MatchesParams, Frontend.Matches),
|
||||
operation("ui.recording.finish", Frontend.RecordingFinish),
|
||||
operationWithPayload("ui.type", Frontend.TypeParams, Frontend.State),
|
||||
operationWithPayload("ui.press", Frontend.PressParams, Frontend.State),
|
||||
operation("ui.enter", Frontend.State),
|
||||
operationWithPayload("ui.arrow", Frontend.ArrowParams, Frontend.State),
|
||||
operationWithPayload("ui.focus", Frontend.FocusParams, Frontend.State),
|
||||
operationWithPayload("ui.click", Frontend.ClickParams, Frontend.State),
|
||||
operationWithPayload("ui.resize", Frontend.ResizeParams, Frontend.State),
|
||||
] as const
|
||||
const FrontendCapabilities = [
|
||||
"ui.type",
|
||||
"ui.press",
|
||||
"ui.enter",
|
||||
"ui.arrow",
|
||||
"ui.focus",
|
||||
"ui.click",
|
||||
"ui.click.semantic",
|
||||
"ui.resize",
|
||||
"ui.matches",
|
||||
"ui.state",
|
||||
"ui.snapshot",
|
||||
"ui.capture",
|
||||
"ui.recording.finish",
|
||||
] as const
|
||||
const FrontendEndpoint = endpoint(FrontendOperations, [], ["ui.click.semantic"], FrontendCapabilities)
|
||||
type FrontendRequest = EndpointRequest<typeof FrontendOperations>
|
||||
|
||||
export namespace Frontend {
|
||||
export const Capabilities: typeof FrontendCapabilities = FrontendEndpoint.Capabilities
|
||||
export type Capability = (typeof Capabilities)[number]
|
||||
export const Request: Schema.Decoder<FrontendRequest> = FrontendEndpoint.Request
|
||||
export type Request = FrontendRequest
|
||||
export const decodeRequest: (input: unknown) => Request = FrontendEndpoint.decodeRequest
|
||||
export const decodeRequestEffect: (input: string) => Effect.Effect<Request, Schema.SchemaError> =
|
||||
FrontendEndpoint.decodeRequestEffect
|
||||
export const Request = Schema.Union([
|
||||
Handshake.Request,
|
||||
Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal("ui.type"), params: TypeParams }),
|
||||
Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal("ui.press"), params: PressParams }),
|
||||
Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal("ui.arrow"), params: ArrowParams }),
|
||||
Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal("ui.focus"), params: FocusParams }),
|
||||
Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal("ui.click"), params: ClickParams }),
|
||||
Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal("ui.resize"), params: ResizeParams }),
|
||||
Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal("ui.matches"), params: MatchesParams }),
|
||||
Schema.Struct({
|
||||
...JsonRpc.RequestFields,
|
||||
method: Schema.Literals(["ui.enter", "ui.state", "ui.snapshot", "ui.recording.finish"]),
|
||||
}),
|
||||
Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal("ui.capture") }),
|
||||
])
|
||||
export type Request = Schema.Schema.Type<typeof Request>
|
||||
export const decodeRequest = Schema.decodeUnknownSync(Request)
|
||||
export const decodeRequestEffect = Schema.decodeUnknownEffect(Schema.fromJsonString(Request))
|
||||
}
|
||||
|
||||
export namespace Backend {
|
||||
export const Capabilities = [
|
||||
"llm.attach",
|
||||
"llm.chunk",
|
||||
"llm.finish",
|
||||
"llm.disconnect",
|
||||
"llm.pending",
|
||||
"llm.request",
|
||||
"llm.tool-input-delta",
|
||||
"tool.attach",
|
||||
"tool.update",
|
||||
"tool.finish",
|
||||
"tool.fail",
|
||||
"tool.invocation",
|
||||
"tool.cancel",
|
||||
] as const satisfies ReadonlyArray<Handshake.Capability>
|
||||
|
||||
export const Item = Schema.Union([
|
||||
Schema.Struct({ type: Schema.Literal("textDelta"), text: Schema.String }),
|
||||
Schema.Struct({ type: Schema.Literal("reasoningDelta"), text: Schema.String }),
|
||||
@@ -702,6 +533,24 @@ export namespace Backend {
|
||||
export const DisconnectParams = Schema.Struct({ id: Schema.String })
|
||||
export interface DisconnectParams extends Schema.Schema.Type<typeof DisconnectParams> {}
|
||||
|
||||
export const Request = Schema.Union([
|
||||
Handshake.Request,
|
||||
Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal("llm.chunk"), params: ChunkParams }),
|
||||
Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal("llm.finish"), params: FinishParams }),
|
||||
Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal("llm.disconnect"), params: DisconnectParams }),
|
||||
Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal("tool.attach"), params: ToolAttachParams }),
|
||||
Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal("tool.update"), params: ToolUpdateParams }),
|
||||
Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal("tool.finish"), params: ToolFinishParams }),
|
||||
Schema.Struct({ ...JsonRpc.RequestFields, method: Schema.Literal("tool.fail"), params: ToolFailParams }),
|
||||
Schema.Struct({
|
||||
...JsonRpc.RequestFields,
|
||||
method: Schema.Literals(["llm.attach", "llm.pending"]),
|
||||
}),
|
||||
])
|
||||
export type Request = Schema.Schema.Type<typeof Request>
|
||||
export const decodeRequest = Schema.decodeUnknownSync(Request)
|
||||
export const decodeRequestEffect = Schema.decodeUnknownEffect(Schema.fromJsonString(Request))
|
||||
|
||||
export const ProviderInvocation = Schema.Struct({ id: Schema.String, url: Schema.String, body: Schema.Json })
|
||||
export interface ProviderInvocation extends Schema.Schema.Type<typeof ProviderInvocation> {}
|
||||
|
||||
@@ -717,54 +566,53 @@ export namespace Backend {
|
||||
export interface NetworkLogEntry extends Schema.Schema.Type<typeof NetworkLogEntry> {}
|
||||
}
|
||||
|
||||
const BackendOperations = [
|
||||
operation("llm.attach", Backend.Attached),
|
||||
operation("llm.pending", Backend.Pending),
|
||||
operationWithPayload("llm.chunk", Backend.ChunkParams, Backend.Ok),
|
||||
operationWithRpcPayload("llm.finish", Backend.FinishParams, Backend.FinishPayload, Backend.Ok),
|
||||
operationWithPayload("llm.disconnect", Backend.DisconnectParams, Backend.Ok),
|
||||
operationWithPayload("tool.attach", Backend.ToolAttachParams, Backend.Attached),
|
||||
operationWithPayload("tool.update", Backend.ToolUpdateParams, Backend.Ok),
|
||||
operationWithPayload("tool.finish", Backend.ToolFinishParams, Backend.Ok),
|
||||
operationWithPayload("tool.fail", Backend.ToolFailParams, Backend.Ok),
|
||||
] as const
|
||||
const BackendNotifications = [
|
||||
notification("llm.request", Backend.ProviderInvocation),
|
||||
notification("tool.invocation", Backend.ToolInvocation),
|
||||
notification("tool.cancel", Backend.ToolCancellation),
|
||||
] as const
|
||||
const BackendCapabilities = [
|
||||
"llm.attach",
|
||||
"llm.chunk",
|
||||
"llm.finish",
|
||||
"llm.disconnect",
|
||||
"llm.pending",
|
||||
"llm.request",
|
||||
"llm.tool-input-delta",
|
||||
"tool.attach",
|
||||
"tool.update",
|
||||
"tool.finish",
|
||||
"tool.fail",
|
||||
"tool.invocation",
|
||||
"tool.cancel",
|
||||
] as const
|
||||
const BackendEndpoint = endpoint(BackendOperations, BackendNotifications, ["llm.tool-input-delta"], BackendCapabilities)
|
||||
type BackendRequest = EndpointRequest<typeof BackendOperations>
|
||||
type BackendNotification = EndpointNotification<typeof BackendNotifications>
|
||||
export class SimulationRequestError extends Schema.TaggedErrorClass<SimulationRequestError>()(
|
||||
"SimulationRequestError",
|
||||
{
|
||||
method: Schema.String,
|
||||
code: Schema.Number,
|
||||
message: Schema.String,
|
||||
data: Schema.optionalKey(Schema.Json),
|
||||
},
|
||||
) {}
|
||||
|
||||
export namespace Backend {
|
||||
export const Capabilities: typeof BackendCapabilities = BackendEndpoint.Capabilities
|
||||
export const Request: Schema.Decoder<BackendRequest> = BackendEndpoint.Request
|
||||
export type Request = BackendRequest
|
||||
export const decodeRequest: (input: unknown) => Request = BackendEndpoint.decodeRequest
|
||||
export const decodeRequestEffect: (input: string) => Effect.Effect<Request, Schema.SchemaError> =
|
||||
BackendEndpoint.decodeRequestEffect
|
||||
export const Notification: Schema.Decoder<BackendNotification> = BackendEndpoint.Notification
|
||||
export type Notification = BackendNotification
|
||||
export const decodeNotification: (input: unknown) => Notification = BackendEndpoint.decodeNotification
|
||||
export const decodeNotificationEffect: (input: string) => Effect.Effect<Notification, Schema.SchemaError> =
|
||||
BackendEndpoint.decodeNotificationEffect
|
||||
}
|
||||
const request = <
|
||||
const Tag extends string,
|
||||
Payload extends Schema.Top | Schema.Struct.Fields = typeof Schema.Void,
|
||||
Success extends Schema.Top = typeof Schema.Void,
|
||||
>(
|
||||
tag: Tag,
|
||||
options?: {
|
||||
readonly payload?: Payload
|
||||
readonly success?: Success
|
||||
},
|
||||
) => Rpc.make(tag, { ...options, error: SimulationRequestError })
|
||||
|
||||
export const UiRpcs = FrontendEndpoint.rpcs
|
||||
export const BackendRpcs = BackendEndpoint.rpcs
|
||||
export const UiRpcs = RpcGroup.make(
|
||||
request("simulation.handshake", { payload: Handshake.Params, success: Handshake.Response }),
|
||||
request("ui.state", { success: Frontend.State }),
|
||||
request("ui.snapshot", { success: Frontend.SemanticSnapshot }),
|
||||
request("ui.capture", { success: Frontend.CapturedFrame }),
|
||||
request("ui.matches", { payload: Frontend.MatchesParams, success: Frontend.Matches }),
|
||||
request("ui.recording.finish", { success: Frontend.RecordingFinish }),
|
||||
request("ui.type", { payload: Frontend.TypeParams, success: Frontend.State }),
|
||||
request("ui.press", { payload: Frontend.PressParams, success: Frontend.State }),
|
||||
request("ui.enter", { success: Frontend.State }),
|
||||
request("ui.arrow", { payload: Frontend.ArrowParams, success: Frontend.State }),
|
||||
request("ui.focus", { payload: Frontend.FocusParams, success: Frontend.State }),
|
||||
request("ui.click", { payload: Frontend.ClickParams, success: Frontend.State }),
|
||||
request("ui.resize", { payload: Frontend.ResizeParams, success: Frontend.State }),
|
||||
)
|
||||
|
||||
export const BackendRpcs = RpcGroup.make(
|
||||
request("simulation.handshake", { payload: Handshake.Params, success: Handshake.Response }),
|
||||
request("llm.attach", { success: Backend.Attached }),
|
||||
request("llm.pending", { success: Backend.Pending }),
|
||||
request("llm.chunk", { payload: Backend.ChunkParams, success: Backend.Ok }),
|
||||
request("llm.finish", { payload: Backend.FinishPayload, success: Backend.Ok }),
|
||||
request("llm.disconnect", { payload: Backend.DisconnectParams, success: Backend.Ok }),
|
||||
request("tool.attach", { payload: Backend.ToolAttachParams, success: Backend.Attached }),
|
||||
request("tool.update", { payload: Backend.ToolUpdateParams, success: Backend.Ok }),
|
||||
request("tool.finish", { payload: Backend.ToolFinishParams, success: Backend.Ok }),
|
||||
request("tool.fail", { payload: Backend.ToolFailParams, success: Backend.Ok }),
|
||||
)
|
||||
|
||||
@@ -1,110 +1,6 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { Effect, Schema } from "effect"
|
||||
import { Backend, BackendRpcs, Frontend, Handshake, JsonRpc, UiRpcs } from "../src/protocol"
|
||||
|
||||
const uiCapability: Frontend.Capability = "ui.state"
|
||||
// @ts-expect-error capability literals must remain narrow for consumers
|
||||
const invalidUiCapability: Frontend.Capability = "ui.future"
|
||||
const successResponse: Schema.Schema.Type<typeof JsonRpc.Response> = { jsonrpc: "2.0", id: 1, result: null }
|
||||
// @ts-expect-error responses require one outcome
|
||||
const missingResponse: Schema.Schema.Type<typeof JsonRpc.Response> = { jsonrpc: "2.0", id: 1 }
|
||||
// @ts-expect-error responses cannot contain both outcomes
|
||||
const invalidResponse: Schema.Schema.Type<typeof JsonRpc.Response> = {
|
||||
jsonrpc: "2.0",
|
||||
id: 1,
|
||||
result: null,
|
||||
error: { code: -32600, message: "Invalid request" },
|
||||
}
|
||||
void [uiCapability, invalidUiCapability, successResponse, missingResponse, invalidResponse]
|
||||
|
||||
test("preserves capability order and keeps request capabilities aligned with RPC groups", () => {
|
||||
expect(Frontend.Capabilities).toEqual([
|
||||
"ui.type",
|
||||
"ui.press",
|
||||
"ui.enter",
|
||||
"ui.arrow",
|
||||
"ui.focus",
|
||||
"ui.click",
|
||||
"ui.click.semantic",
|
||||
"ui.resize",
|
||||
"ui.matches",
|
||||
"ui.state",
|
||||
"ui.snapshot",
|
||||
"ui.capture",
|
||||
"ui.recording.finish",
|
||||
])
|
||||
expect(Backend.Capabilities).toEqual([
|
||||
"llm.attach",
|
||||
"llm.chunk",
|
||||
"llm.finish",
|
||||
"llm.disconnect",
|
||||
"llm.pending",
|
||||
"llm.request",
|
||||
"llm.tool-input-delta",
|
||||
"tool.attach",
|
||||
"tool.update",
|
||||
"tool.finish",
|
||||
"tool.fail",
|
||||
"tool.invocation",
|
||||
"tool.cancel",
|
||||
])
|
||||
expect(new Set<string>(Frontend.Capabilities.filter((capability) => capability !== "ui.click.semantic"))).toEqual(
|
||||
new Set(Array.from(UiRpcs.requests.keys()).filter((method) => method !== "simulation.handshake")),
|
||||
)
|
||||
expect(
|
||||
new Set<string>(
|
||||
Backend.Capabilities.filter(
|
||||
(capability) => !["llm.request", "llm.tool-input-delta", "tool.invocation", "tool.cancel"].includes(capability),
|
||||
),
|
||||
),
|
||||
).toEqual(new Set(Array.from(BackendRpcs.requests.keys()).filter((method) => method !== "simulation.handshake")))
|
||||
})
|
||||
|
||||
test("normalizes an omitted finish reason", () => {
|
||||
expect(Backend.decodeRequest({ jsonrpc: "2.0", id: 1, method: "llm.finish", params: { id: "inv_1" } })).toMatchObject(
|
||||
{ params: { id: "inv_1", reason: "stop" } },
|
||||
)
|
||||
})
|
||||
|
||||
test("decodes typed backend notifications", () => {
|
||||
expect(
|
||||
Backend.decodeNotification({
|
||||
jsonrpc: "2.0",
|
||||
method: "tool.cancel",
|
||||
params: { id: "tool_1", reason: "interrupted" },
|
||||
}),
|
||||
).toEqual({
|
||||
jsonrpc: "2.0",
|
||||
method: "tool.cancel",
|
||||
params: { id: "tool_1", reason: "interrupted" },
|
||||
})
|
||||
expect(() =>
|
||||
Backend.decodeNotification({
|
||||
jsonrpc: "2.0",
|
||||
method: "tool.cancel",
|
||||
params: { id: "tool_1", reason: "unknown" },
|
||||
}),
|
||||
).toThrow()
|
||||
})
|
||||
|
||||
test("requires exactly one JSON-RPC response outcome", () => {
|
||||
const decode = Schema.decodeUnknownSync(JsonRpc.Response)
|
||||
expect(decode({ jsonrpc: "2.0", id: 1, result: null })).toEqual({ jsonrpc: "2.0", id: 1, result: null })
|
||||
expect(decode({ jsonrpc: "2.0", id: 1, error: { code: -32600, message: "Invalid request" } })).toEqual({
|
||||
jsonrpc: "2.0",
|
||||
id: 1,
|
||||
error: { code: -32600, message: "Invalid request" },
|
||||
})
|
||||
expect(() => decode({ jsonrpc: "2.0", id: 1 })).toThrow()
|
||||
expect(() =>
|
||||
decode({
|
||||
jsonrpc: "2.0",
|
||||
id: 1,
|
||||
result: null,
|
||||
error: { code: -32600, message: "Invalid request" },
|
||||
}),
|
||||
).toThrow()
|
||||
})
|
||||
import { Backend, Frontend, Handshake } from "../src/protocol"
|
||||
|
||||
test("decodes ui.matches text params", () => {
|
||||
expect(
|
||||
|
||||
@@ -83,7 +83,7 @@ test("streams a Drive-controlled provider response and removes the finished invo
|
||||
jsonrpc: "2.0",
|
||||
id: 3,
|
||||
method: "llm.finish",
|
||||
params: { id: params.id },
|
||||
params: { id: params.id, reason: "stop" },
|
||||
}),
|
||||
)
|
||||
expect(yield* Queue.take(messages)).toMatchObject({ id: 3, result: { ok: true } })
|
||||
|
||||
@@ -1349,7 +1349,9 @@ function App(props: { pair?: DialogPairCredentials }) {
|
||||
width={1}
|
||||
height="100%"
|
||||
backgroundColor={
|
||||
tabsResizeHovered() || tabsResizing() ? tabsTheme.background.action.primary.hovered : undefined
|
||||
tabsResizeHovered() || tabsResizing()
|
||||
? tabsTheme.background.action.primary.hovered
|
||||
: tabsTheme.background.default
|
||||
}
|
||||
/>
|
||||
</box>
|
||||
|
||||
@@ -307,7 +307,6 @@ function VerticalSessionTabs(props: { controller?: SessionTabsController; animat
|
||||
const [addHovered, setAddHovered] = createSignal(false)
|
||||
const marquee = createTabMarquee(animations)
|
||||
const hovered = marquee.hovered
|
||||
// OpenTUI captures the first drag target, which may differ from the tab pressed on a fast move.
|
||||
const [dragging, setDragging] = createSignal<string>()
|
||||
const [preview, setPreview] = createSignal<{ sessionID: string; index: number }>()
|
||||
const [contextMenu, setContextMenu] = createSignal<TabContextMenuState>()
|
||||
@@ -344,9 +343,6 @@ function VerticalSessionTabs(props: { controller?: SessionTabsController; animat
|
||||
const itemStatus = (tab: SessionTab) => statuses().get(tab.sessionID)!
|
||||
let rail: { screenX: number; screenY: number } | undefined
|
||||
let scroll: ScrollBoxRenderable | undefined
|
||||
let didDrag = false
|
||||
// A captured drag ends with a synthetic up on its drop target; do not turn that into a click.
|
||||
let suppressClick = false
|
||||
|
||||
createEffect(() => {
|
||||
const pending = preview()
|
||||
@@ -368,29 +364,6 @@ function VerticalSessionTabs(props: { controller?: SessionTabsController; animat
|
||||
}
|
||||
})
|
||||
|
||||
const release = () => {
|
||||
const source = dragging()
|
||||
if (!source) return
|
||||
if (didDrag) suppressClick = true
|
||||
setDragging(undefined)
|
||||
const pending = preview()
|
||||
if (pending?.sessionID === source) tabs.move(pending.sessionID, pending.index)
|
||||
tabs.select(source)
|
||||
}
|
||||
|
||||
const drag = (event: MouseEvent) => {
|
||||
if (!rail) return
|
||||
const source = dragging()
|
||||
if (!source) return
|
||||
didDrag = true
|
||||
const target = Math.max(
|
||||
0,
|
||||
Math.min(tabs.tabs().length - 1, Math.floor((event.y - rail.screenY - 1 + (scroll?.scrollTop ?? 0)) / 3)),
|
||||
)
|
||||
const sourceIndex = items().findIndex((item) => item.sessionID === source)
|
||||
if (target !== sourceIndex && preview()?.index !== target) setPreview({ sessionID: source, index: target })
|
||||
}
|
||||
|
||||
return (
|
||||
<box
|
||||
ref={(element) => (rail = element)}
|
||||
@@ -402,15 +375,6 @@ function VerticalSessionTabs(props: { controller?: SessionTabsController; animat
|
||||
paddingTop={1}
|
||||
backgroundColor={theme.background.default}
|
||||
onMouseOut={marquee.leaveHovered}
|
||||
onMouseUp={(event) => {
|
||||
if (event.button === RIGHT_MOUSE_BUTTON) return
|
||||
release()
|
||||
if (!didDrag) return
|
||||
didDrag = false
|
||||
queueMicrotask(() => (suppressClick = false))
|
||||
}}
|
||||
onMouseDrag={drag}
|
||||
onMouseDragEnd={release}
|
||||
>
|
||||
<scrollbox ref={(element) => (scroll = element)} flexGrow={1} scrollbarOptions={{ visible: false }}>
|
||||
<box flexShrink={0} flexDirection="column" gap={1}>
|
||||
@@ -558,6 +522,12 @@ function VerticalSessionTabs(props: { controller?: SessionTabsController; animat
|
||||
: color
|
||||
return separator ? tint(faded, pulseBackground(), 0.55) : faded
|
||||
}
|
||||
const release = () => {
|
||||
setDragging(undefined)
|
||||
const pending = preview()
|
||||
if (pending?.sessionID === tab.sessionID) tabs.move(pending.sessionID, pending.index)
|
||||
tabs.select(tab.sessionID)
|
||||
}
|
||||
return (
|
||||
<box
|
||||
height={2}
|
||||
@@ -569,7 +539,6 @@ function VerticalSessionTabs(props: { controller?: SessionTabsController; animat
|
||||
onMouseOut={() => marquee.leave(tab.sessionID)}
|
||||
onMouseDown={(event) => {
|
||||
if (event.button === RIGHT_MOUSE_BUTTON) {
|
||||
didDrag = false
|
||||
setDragging(undefined)
|
||||
if (!rail) return
|
||||
setContextMenu({
|
||||
@@ -582,10 +551,26 @@ function VerticalSessionTabs(props: { controller?: SessionTabsController; animat
|
||||
event.stopPropagation()
|
||||
return
|
||||
}
|
||||
didDrag = false
|
||||
marquee.enter(tab.sessionID, title(), hoveredTitleWidth())
|
||||
setDragging(tab.sessionID)
|
||||
}}
|
||||
onMouseUp={(event) => {
|
||||
if (event.button === RIGHT_MOUSE_BUTTON) return
|
||||
release()
|
||||
}}
|
||||
onMouseDrag={(event) => {
|
||||
if (!rail) return
|
||||
const target = Math.max(
|
||||
0,
|
||||
Math.min(
|
||||
tabs.tabs().length - 1,
|
||||
Math.floor((event.y - rail.screenY - 1 + (scroll?.scrollTop ?? 0)) / 3),
|
||||
),
|
||||
)
|
||||
if (target !== index() && preview()?.index !== target)
|
||||
setPreview({ sessionID: tab.sessionID, index: target })
|
||||
}}
|
||||
onMouseDragEnd={release}
|
||||
>
|
||||
<TabPulse
|
||||
top={-1}
|
||||
@@ -692,14 +677,8 @@ function VerticalSessionTabs(props: { controller?: SessionTabsController; animat
|
||||
selectable={false}
|
||||
onMouseOver={() => setCloseHovered(true)}
|
||||
onMouseOut={() => setCloseHovered(false)}
|
||||
onMouseDown={(event) => {
|
||||
if (event.button === RIGHT_MOUSE_BUTTON || hovered() !== tab.sessionID) return
|
||||
didDrag = false
|
||||
event.stopPropagation()
|
||||
}}
|
||||
onMouseUp={(event) => {
|
||||
if (event.button === RIGHT_MOUSE_BUTTON) return
|
||||
if (suppressClick) return
|
||||
if (hovered() !== tab.sessionID) return
|
||||
event.stopPropagation()
|
||||
tabs.close(tab.sessionID)
|
||||
@@ -758,8 +737,6 @@ function VerticalSessionTabs(props: { controller?: SessionTabsController; animat
|
||||
onMouseOver={() => setAddHovered(true)}
|
||||
onMouseOut={() => setAddHovered(false)}
|
||||
onMouseDown={(event: MouseEvent) => {
|
||||
didDrag = false
|
||||
setDragging(undefined)
|
||||
if (event.button !== RIGHT_MOUSE_BUTTON) return
|
||||
if (!rail) return
|
||||
setContextMenu({ x: event.x, y: event.y })
|
||||
@@ -768,7 +745,6 @@ function VerticalSessionTabs(props: { controller?: SessionTabsController; animat
|
||||
}}
|
||||
onMouseUp={(event: MouseEvent) => {
|
||||
if (event.button === RIGHT_MOUSE_BUTTON) return
|
||||
if (suppressClick) return
|
||||
if (!newTab()) tabs.add?.()
|
||||
}}
|
||||
>
|
||||
@@ -798,7 +774,6 @@ function VerticalSessionTabs(props: { controller?: SessionTabsController; animat
|
||||
selectable={false}
|
||||
onMouseUp={(event) => {
|
||||
if (event.button === RIGHT_MOUSE_BUTTON) return
|
||||
if (suppressClick) return
|
||||
if (!addHovered()) return
|
||||
event.stopPropagation()
|
||||
tabs.close()
|
||||
@@ -828,7 +803,6 @@ function HorizontalSessionTabs(props: { controller?: SessionTabsController; anim
|
||||
const [addHovered, setAddHovered] = createSignal(false)
|
||||
const marquee = createTabMarquee(animations)
|
||||
const hovered = marquee.hovered
|
||||
// OpenTUI captures the first drag target, which may differ from the tab pressed on a fast move.
|
||||
const [dragging, setDragging] = createSignal<string>()
|
||||
// A drag reorders a local preview and persists one move on release instead of writing
|
||||
// per slot crossing; the preview holds after release until the store reflects the move,
|
||||
@@ -836,9 +810,6 @@ function HorizontalSessionTabs(props: { controller?: SessionTabsController; anim
|
||||
const [preview, setPreview] = createSignal<{ sessionID: string; index: number }>()
|
||||
const [contextMenu, setContextMenu] = createSignal<TabContextMenuState>()
|
||||
let strip: { screenX: number; screenY: number } | undefined
|
||||
let didDrag = false
|
||||
// A captured drag ends with a synthetic up on its drop target; do not turn that into a click.
|
||||
let suppressClick = false
|
||||
const hueStep = () => (mode() === "light" ? 800 : 200)
|
||||
const accent = () => theme.hue.accent[hueStep()]
|
||||
const activeNumber = () => theme.hue.interactive[hueStep()]
|
||||
@@ -960,29 +931,6 @@ function HorizontalSessionTabs(props: { controller?: SessionTabsController; anim
|
||||
return layout().before + layout().widths.length - 1
|
||||
}
|
||||
|
||||
const release = () => {
|
||||
const source = dragging()
|
||||
if (!source) return
|
||||
if (didDrag) suppressClick = true
|
||||
setDragging(undefined)
|
||||
const pending = preview()
|
||||
if (pending?.sessionID === source) tabs.move(pending.sessionID, pending.index)
|
||||
if (source === NEW_SESSION_TAB.sessionID) return
|
||||
tabs.select(source)
|
||||
}
|
||||
|
||||
const drag = (event: MouseEvent) => {
|
||||
const source = dragging()
|
||||
if (!source || source === NEW_SESSION_TAB.sessionID) return
|
||||
didDrag = true
|
||||
const slot = slotAt(event.x)
|
||||
const target = slot === undefined ? undefined : Math.min(slot, tabs.tabs().length - 1)
|
||||
const sourceIndex = items().findIndex((item) => item.sessionID === source)
|
||||
if (target !== undefined && target !== sourceIndex && preview()?.index !== target) {
|
||||
setPreview({ sessionID: source, index: target })
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<box
|
||||
ref={(element) => (strip = element)}
|
||||
@@ -992,15 +940,6 @@ function HorizontalSessionTabs(props: { controller?: SessionTabsController; anim
|
||||
flexDirection="row"
|
||||
zIndex={1}
|
||||
onMouseOut={marquee.leaveHovered}
|
||||
onMouseUp={(event) => {
|
||||
if (event.button === RIGHT_MOUSE_BUTTON) return
|
||||
release()
|
||||
if (!didDrag) return
|
||||
didDrag = false
|
||||
queueMicrotask(() => (suppressClick = false))
|
||||
}}
|
||||
onMouseDrag={drag}
|
||||
onMouseDragEnd={release}
|
||||
renderAfter={function (buffer) {
|
||||
const x = Math.max(0, this.screenX)
|
||||
const y = this.screenY + this.height
|
||||
@@ -1112,6 +1051,15 @@ function HorizontalSessionTabs(props: { controller?: SessionTabsController; anim
|
||||
}
|
||||
const bold = () => (selected() || dragged() ? TextAttributes.BOLD : undefined)
|
||||
const closeColor = () => tint(theme.text.subdued, theme.text.default, 0.6)
|
||||
// Releasing a drag (or a plain click) selects the tab, matching browser tab strips and
|
||||
// keeping sloppy clicks indistinguishable from clean ones.
|
||||
const release = () => {
|
||||
setDragging(undefined)
|
||||
const pending = preview()
|
||||
if (pending?.sessionID === tab.sessionID) tabs.move(pending.sessionID, pending.index)
|
||||
if (tab === NEW_SESSION_TAB) return
|
||||
tabs.select(tab.sessionID)
|
||||
}
|
||||
return (
|
||||
<box
|
||||
width={width()}
|
||||
@@ -1122,7 +1070,6 @@ function HorizontalSessionTabs(props: { controller?: SessionTabsController; anim
|
||||
onMouseOut={() => marquee.leave(tab.sessionID)}
|
||||
onMouseDown={(event) => {
|
||||
if (event.button === RIGHT_MOUSE_BUTTON) {
|
||||
didDrag = false
|
||||
setDragging(undefined)
|
||||
setContextMenu({
|
||||
x: event.x,
|
||||
@@ -1134,10 +1081,20 @@ function HorizontalSessionTabs(props: { controller?: SessionTabsController; anim
|
||||
event.stopPropagation()
|
||||
return
|
||||
}
|
||||
didDrag = false
|
||||
marquee.enter(tab.sessionID, title(), hoveredTitleWidth())
|
||||
setDragging(tab.sessionID)
|
||||
}}
|
||||
onMouseUp={(event) => {
|
||||
if (event.button === RIGHT_MOUSE_BUTTON) return
|
||||
release()
|
||||
}}
|
||||
onMouseDrag={(event) => {
|
||||
if (tab === NEW_SESSION_TAB) return
|
||||
const slot = slotAt(event.x)
|
||||
if (slot !== undefined && slot !== tabNumber() - 1)
|
||||
setPreview({ sessionID: tab.sessionID, index: slot })
|
||||
}}
|
||||
onMouseDragEnd={release}
|
||||
>
|
||||
<TabPulse
|
||||
enabled={animations()}
|
||||
@@ -1183,14 +1140,8 @@ function HorizontalSessionTabs(props: { controller?: SessionTabsController; anim
|
||||
selectable={false}
|
||||
onMouseOver={() => setCloseHovered(true)}
|
||||
onMouseOut={() => setCloseHovered(false)}
|
||||
onMouseDown={(event) => {
|
||||
if (event.button === RIGHT_MOUSE_BUTTON || hovered() !== tab.sessionID) return
|
||||
didDrag = false
|
||||
event.stopPropagation()
|
||||
}}
|
||||
onMouseUp={(event) => {
|
||||
if (event.button === RIGHT_MOUSE_BUTTON) return
|
||||
if (suppressClick) return
|
||||
// The close mark only renders while hovered; without motion events a click can
|
||||
// land here first, and must select the tab instead of closing it invisibly.
|
||||
if (hovered() !== tab.sessionID) return
|
||||
@@ -1219,8 +1170,6 @@ function HorizontalSessionTabs(props: { controller?: SessionTabsController; anim
|
||||
onMouseOver={() => setAddHovered(true)}
|
||||
onMouseOut={() => setAddHovered(false)}
|
||||
onMouseDown={(event) => {
|
||||
didDrag = false
|
||||
setDragging(undefined)
|
||||
if (event.button !== RIGHT_MOUSE_BUTTON) return
|
||||
setContextMenu({ x: event.x, y: event.y })
|
||||
event.preventDefault()
|
||||
@@ -1228,7 +1177,6 @@ function HorizontalSessionTabs(props: { controller?: SessionTabsController; anim
|
||||
}}
|
||||
onMouseUp={(event) => {
|
||||
if (event.button === RIGHT_MOUSE_BUTTON) return
|
||||
if (suppressClick) return
|
||||
tabs.add?.()
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -904,13 +904,7 @@ export function FormPrompt(props: {
|
||||
<text
|
||||
width={4}
|
||||
flexShrink={0}
|
||||
fg={
|
||||
active()
|
||||
? theme.text.formfield.focused
|
||||
: picked()
|
||||
? theme.text.formfield.selected
|
||||
: theme.text.subdued
|
||||
}
|
||||
fg={picked() ? theme.text.feedback.success.default : theme.text.subdued}
|
||||
>
|
||||
[{picked() ? "✓" : " "}]
|
||||
</text>
|
||||
@@ -920,7 +914,7 @@ export function FormPrompt(props: {
|
||||
</text>
|
||||
</box>
|
||||
<Show when={!multi()}>
|
||||
<text fg={theme.text.formfield.selected}>{picked() ? " ✓" : ""}</text>
|
||||
<text fg={theme.text.feedback.success.default}>{picked() ? " ✓" : ""}</text>
|
||||
</Show>
|
||||
</box>
|
||||
<Show when={row.description}>
|
||||
@@ -959,13 +953,7 @@ export function FormPrompt(props: {
|
||||
<text
|
||||
width={4}
|
||||
flexShrink={0}
|
||||
fg={
|
||||
other()
|
||||
? theme.text.formfield.focused
|
||||
: customChecked()
|
||||
? theme.text.formfield.selected
|
||||
: theme.text.subdued
|
||||
}
|
||||
fg={customChecked() ? theme.text.feedback.success.default : theme.text.subdued}
|
||||
>
|
||||
[{customChecked() ? "✓" : " "}]
|
||||
</text>
|
||||
@@ -978,7 +966,7 @@ export function FormPrompt(props: {
|
||||
{input() || "Type your own answer"}
|
||||
</text>
|
||||
<Show when={!multi() && customPicked()}>
|
||||
<text fg={theme.text.formfield.selected}>✓</text>
|
||||
<text fg={theme.text.feedback.success.default}>✓</text>
|
||||
</Show>
|
||||
</>
|
||||
}
|
||||
|
||||
@@ -162,6 +162,38 @@ provider and model configuration. An unknown variant fails model resolution inst
|
||||
|
||||
### Local models
|
||||
|
||||
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.
|
||||
|
||||
For an OpenAI-compatible server, define a provider package, endpoint, and at least one model:
|
||||
|
||||
```jsonc title="opencode.jsonc"
|
||||
@@ -171,7 +203,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",
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user