mirror of
https://github.com/anomalyco/opencode.git
synced 2026-08-16 17:41:16 -04:00
Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 61742bc045 | |||
| d4f10fa9be | |||
| 08dd3f51ed | |||
| 0e99cb987a | |||
| 7731d1235d | |||
| 174c0a742c | |||
| b080f216a5 | |||
| 0d7fe6e074 | |||
| 01b7b53eeb | |||
| 613c570a3b | |||
| a48d44955e |
@@ -466,6 +466,7 @@ jobs:
|
||||
VITE_SENTRY_ENVIRONMENT: ${{ (github.ref_name == 'beta' && 'beta') || 'production' }}
|
||||
VITE_SENTRY_RELEASE: desktop@${{ needs.version.outputs.version }}
|
||||
OPENCODE_CLI_TARGET: ${{ matrix.settings.target }}
|
||||
OPENCODE_CLI_DIST: ${{ github.workspace }}/packages/cli/dist
|
||||
|
||||
- name: Package
|
||||
if: needs.version.outputs.release
|
||||
|
||||
@@ -60,7 +60,11 @@ export function NewSessionView(props: {
|
||||
<Show
|
||||
when={props.workspace.bar.visible()}
|
||||
fallback={
|
||||
<PromptGitStatus branch={props.workspace.bar.branch()} noGit={!props.workspace.project.git()} />
|
||||
<PromptGitStatus
|
||||
branch={props.workspace.bar.branch()}
|
||||
noGit={!props.workspace.project.git()}
|
||||
class="ms-1"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<PromptWorkspaceSelector
|
||||
|
||||
@@ -5,7 +5,8 @@ const fs = require("fs")
|
||||
const path = require("path")
|
||||
const os = require("os")
|
||||
|
||||
const forwardedSignals = ["SIGINT", "SIGTERM", "SIGHUP"]
|
||||
const forwardedSignals =
|
||||
process.platform === "win32" ? ["SIGINT", "SIGTERM", "SIGHUP"] : ["SIGINT", "SIGTERM", "SIGHUP", "SIGUSR1"]
|
||||
|
||||
function run(target) {
|
||||
const child = childProcess.spawn(target, process.argv.slice(2), { stdio: "inherit" })
|
||||
|
||||
@@ -117,9 +117,9 @@ for (const item of targets) {
|
||||
autoloadTsconfig: true,
|
||||
autoloadPackageJson: true,
|
||||
target: target.replace(binary, "bun") as Bun.Build.CompileTarget,
|
||||
executablePath,
|
||||
...(executablePath ? { executablePath } : {}),
|
||||
outfile: path.join(outdir, name, "bin", binary),
|
||||
execArgv: [`--user-agent=${binary}/${Script.version}`, "--use-system-ca", "--"],
|
||||
execArgv: [`--user-agent=${binary}/${Script.version}`, "--use-system-ca", "--no-warnings", "--"],
|
||||
windows: {},
|
||||
},
|
||||
define: {
|
||||
|
||||
@@ -20,7 +20,6 @@ async function publish(dir: string, name: string, version: string) {
|
||||
await $`bun pm pack`.cwd(dir)
|
||||
await $`npm publish *.tgz --access public --tag ${Script.channel}`.cwd(dir)
|
||||
}
|
||||
if (Script.channel === "beta") await $`npm dist-tag add ${`${name}@${version}`} next`
|
||||
}
|
||||
|
||||
async function publishDistribution(input: { root: string; name: string; binary: string; packagePrefix: string }) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Argument, Flag } from "effect/unstable/cli"
|
||||
import { Argument, Command, Flag } from "effect/unstable/cli"
|
||||
import { Spec } from "../framework/spec"
|
||||
import { GlobalFlags } from "./global-flags"
|
||||
|
||||
declare const OPENCODE_CLI_NAME: string | undefined
|
||||
|
||||
@@ -26,7 +27,7 @@ const PermissionParams = {
|
||||
),
|
||||
}
|
||||
|
||||
export const Commands = Spec.make(typeof OPENCODE_CLI_NAME === "string" ? OPENCODE_CLI_NAME : "opencode", {
|
||||
const Root = Spec.make(typeof OPENCODE_CLI_NAME === "string" ? OPENCODE_CLI_NAME : "opencode", {
|
||||
description: "OpenCode 2.0 preview command line interface",
|
||||
params: {
|
||||
...ServerParams,
|
||||
@@ -70,7 +71,7 @@ export const Commands = Spec.make(typeof OPENCODE_CLI_NAME === "string" ? OPENCO
|
||||
description: "Debugging and troubleshooting tools",
|
||||
commands: [
|
||||
Spec.make("agents", { description: "List all agents" }),
|
||||
Spec.make("config", { description: "Show resolved configuration" }),
|
||||
Spec.make("config", { description: "List configuration sources" }),
|
||||
],
|
||||
}),
|
||||
Spec.make("console", {
|
||||
@@ -277,3 +278,5 @@ export const Commands = Spec.make(typeof OPENCODE_CLI_NAME === "string" ? OPENCO
|
||||
}),
|
||||
],
|
||||
})
|
||||
|
||||
export const Commands = { ...Root, spec: Root.spec.pipe(Command.withGlobalFlags(GlobalFlags.all)) }
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
export * as GlobalFlags from "./global-flags"
|
||||
|
||||
import { Flag, GlobalFlag } from "effect/unstable/cli"
|
||||
|
||||
export const CpuProfile = GlobalFlag.setting("cpu-profile")({
|
||||
flag: Flag.string("cpu-profile").pipe(
|
||||
Flag.withDescription("Write a CPU profile to this path when the process stops"),
|
||||
Flag.optional,
|
||||
),
|
||||
})
|
||||
|
||||
export const all = [CpuProfile] as const
|
||||
@@ -0,0 +1,45 @@
|
||||
export * as CpuProfile from "./cpu-profile"
|
||||
|
||||
import { Effect, FileSystem } from "effect"
|
||||
import { Session } from "node:inspector"
|
||||
import path from "node:path"
|
||||
|
||||
export function run<A, E, R>(file: string, effect: Effect.Effect<A, E, R>) {
|
||||
const target = path.resolve(file)
|
||||
return Effect.acquireUseRelease(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem
|
||||
yield* fs.makeDirectory(path.dirname(target), { recursive: true })
|
||||
const session = new Session()
|
||||
session.connect()
|
||||
yield* command(session, "Profiler.enable")
|
||||
yield* command(session, "Profiler.start")
|
||||
yield* Effect.logInfo("CPU profile started", { path: target })
|
||||
return session
|
||||
}),
|
||||
() => effect,
|
||||
(session) =>
|
||||
Effect.tryPromise(
|
||||
() =>
|
||||
new Promise<void>((resolve, reject) => {
|
||||
session.post("Profiler.stop", (error, result) => {
|
||||
session.disconnect()
|
||||
if (error) return reject(error)
|
||||
Bun.write(target, JSON.stringify(result.profile)).then(() => resolve(), reject)
|
||||
})
|
||||
}),
|
||||
).pipe(
|
||||
Effect.andThen(Effect.logInfo("CPU profile written", { path: target })),
|
||||
Effect.catchCause((cause) => Effect.logError("Failed to write CPU profile", { path: target, cause })),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
function command(session: Session, method: "Profiler.enable" | "Profiler.start") {
|
||||
return Effect.tryPromise(
|
||||
() =>
|
||||
new Promise<void>((resolve, reject) => {
|
||||
session.post(method, (error) => (error ? reject(error) : resolve()))
|
||||
}),
|
||||
)
|
||||
}
|
||||
@@ -1,10 +1,13 @@
|
||||
import { Effect, FileSystem, Scope } from "effect"
|
||||
import { Effect, FileSystem, Option, Scope } from "effect"
|
||||
import { Command } from "effect/unstable/cli"
|
||||
import { Spec } from "./spec"
|
||||
import { Global } from "@opencode-ai/util/global"
|
||||
import { Updater } from "../services/updater"
|
||||
import { Config } from "../config"
|
||||
import { Npm } from "@opencode-ai/util/npm"
|
||||
import { GlobalFlags } from "../commands/global-flags"
|
||||
import { CpuProfile } from "../cpu-profile"
|
||||
import path from "node:path"
|
||||
|
||||
export type Input<Value> =
|
||||
Value extends Spec.Node<infer _Name, infer Command, infer _Commands>
|
||||
@@ -86,7 +89,22 @@ function provide(node: Spec.Any, handlers: ReadonlyArray<LazyHandler>): Provided
|
||||
? node.spec.pipe(
|
||||
Command.withHandler((input) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.flatMap(Effect.promise(handler.load), (module) => module.default(input))
|
||||
const module = yield* Effect.promise(handler.load)
|
||||
const cpuProfile = Option.getOrUndefined(yield* GlobalFlags.CpuProfile)
|
||||
if (!cpuProfile) return yield* module.default(input)
|
||||
const target = path.resolve(cpuProfile)
|
||||
const previous = process.env.OPENCODE_CPU_PROFILE
|
||||
process.env.OPENCODE_CPU_PROFILE = target
|
||||
return yield* (
|
||||
node.name === "serve" ? CpuProfile.run(target, module.default(input)) : module.default(input)
|
||||
).pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
if (previous === undefined) delete process.env.OPENCODE_CPU_PROFILE
|
||||
else process.env.OPENCODE_CPU_PROFILE = previous
|
||||
}),
|
||||
),
|
||||
)
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { Global } from "@opencode-ai/util/global"
|
||||
import { Effect, Queue } from "effect"
|
||||
import path from "node:path"
|
||||
|
||||
export const listen = Effect.gen(function* () {
|
||||
const global = yield* Global.Service
|
||||
if (process.platform === "win32") return
|
||||
const signals = yield* Queue.dropping<void>(1)
|
||||
yield* Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
const handler = () => Queue.offerUnsafe(signals, undefined)
|
||||
process.on("SIGUSR1", handler)
|
||||
return handler
|
||||
}),
|
||||
(handler) => Effect.sync(() => process.off("SIGUSR1", handler)),
|
||||
)
|
||||
yield* Queue.take(signals).pipe(
|
||||
Effect.andThen(
|
||||
Effect.suspend(() => {
|
||||
const file = path.join(
|
||||
global.log,
|
||||
`heap-${process.pid}-${new Date().toISOString().replace(/[:.]/g, "")}.heapsnapshot`,
|
||||
)
|
||||
return Effect.gen(function* () {
|
||||
yield* Effect.logInfo("writing heap snapshot", { path: file })
|
||||
const { writeHeapSnapshot } = yield* Effect.tryPromise(() => import("node:v8"))
|
||||
yield* Effect.try(() => writeHeapSnapshot(file))
|
||||
yield* Effect.logInfo("heap snapshot written", { path: file })
|
||||
}).pipe(Effect.catchCause((cause) => Effect.logError("failed to write heap snapshot", { path: file, cause })))
|
||||
}),
|
||||
),
|
||||
Effect.forever,
|
||||
Effect.forkScoped({ startImmediately: true }),
|
||||
)
|
||||
})
|
||||
|
||||
export * as Heap from "./heap"
|
||||
@@ -12,6 +12,7 @@ import { Global } from "@opencode-ai/util/global"
|
||||
import { AppProcess } from "@opencode-ai/util/process"
|
||||
import { Config } from "./config"
|
||||
import { Npm } from "@opencode-ai/util/npm"
|
||||
import { Heap } from "./heap"
|
||||
|
||||
const Handlers = Runtime.handlers(Commands, {
|
||||
$: () => import("./commands/handlers/default"),
|
||||
@@ -54,13 +55,16 @@ const Handlers = Runtime.handlers(Commands, {
|
||||
serve: () => import("./commands/handlers/serve"),
|
||||
})
|
||||
|
||||
Effect.logInfo("cli starting", {
|
||||
version: OPENCODE_VERSION,
|
||||
channel: OPENCODE_CHANNEL,
|
||||
local: OPENCODE_LOCAL,
|
||||
args: process.argv.slice(2),
|
||||
Effect.gen(function* () {
|
||||
yield* Heap.listen
|
||||
yield* Effect.logInfo("cli starting", {
|
||||
version: OPENCODE_VERSION,
|
||||
channel: OPENCODE_CHANNEL,
|
||||
local: OPENCODE_LOCAL,
|
||||
args: process.argv.slice(2),
|
||||
})
|
||||
return yield* Runtime.run(Commands, Handlers, { version: OPENCODE_VERSION })
|
||||
}).pipe(
|
||||
Effect.flatMap(() => Runtime.run(Commands, Handlers, { version: OPENCODE_VERSION })),
|
||||
Effect.annotateLogs({ role: "cli" }),
|
||||
Effect.provide(Config.layer),
|
||||
Effect.provide(Updater.layer),
|
||||
|
||||
@@ -104,7 +104,12 @@ export const options = Effect.fnUntraced(function* (input: { readonly checkVersi
|
||||
return {
|
||||
file,
|
||||
version: input.checkVersion ? OPENCODE_VERSION : undefined,
|
||||
command: [...selfCommand(), "serve", "--service"],
|
||||
command: [
|
||||
...selfCommand(),
|
||||
"serve",
|
||||
"--service",
|
||||
...(process.env.OPENCODE_CPU_PROFILE ? ["--cpu-profile", process.env.OPENCODE_CPU_PROFILE] : []),
|
||||
],
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -10,9 +10,10 @@ describe("debug config command", () => {
|
||||
|
||||
expect(debug.exitCode).toBe(0)
|
||||
expect(debug.stdout).toContain("config")
|
||||
expect(debug.stdout).toContain("Show resolved configuration")
|
||||
expect(debug.stdout).toContain("List configuration sources")
|
||||
expect(config.exitCode).toBe(0)
|
||||
expect(config.stdout).toContain("opencode debug config [flags]")
|
||||
expect(config.stdout).toContain("List configuration sources")
|
||||
})
|
||||
|
||||
test("prints config entries from the invoking directory without reordering permissions", async () => {
|
||||
|
||||
@@ -19,6 +19,29 @@ test("managed service ports are stable per installation channel", () => {
|
||||
expect(ServiceConfig.defaultPort("preview-a")).not.toBe(ServiceConfig.defaultPort("preview-b"))
|
||||
})
|
||||
|
||||
test("managed service forwards the CPU profile path to the server", async () => {
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-service-profile-"))
|
||||
const profile = path.join(root, "server.cpuprofile")
|
||||
try {
|
||||
const previous = process.env.OPENCODE_CPU_PROFILE
|
||||
process.env.OPENCODE_CPU_PROFILE = profile
|
||||
try {
|
||||
const options = await Effect.runPromise(
|
||||
ServiceConfig.options().pipe(
|
||||
Effect.provide(Global.layerWith({ config: path.join(root, "config"), state: path.join(root, "state") })),
|
||||
Effect.provide(NodeFileSystem.layer),
|
||||
),
|
||||
)
|
||||
expect(options.command.slice(-2)).toEqual(["--cpu-profile", profile])
|
||||
} finally {
|
||||
if (previous === undefined) delete process.env.OPENCODE_CPU_PROFILE
|
||||
else process.env.OPENCODE_CPU_PROFILE = previous
|
||||
}
|
||||
} finally {
|
||||
await fs.rm(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("local channel stores service config with the local service filename", async () => {
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-service-"))
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { APIEvent } from "@solidjs/start/server"
|
||||
import { Referral } from "@opencode-ai/console-core/referral.js"
|
||||
import { safeEqual } from "@opencode-ai/console-core/util/crypto.js"
|
||||
import { Resource } from "@opencode-ai/console-resource"
|
||||
import z from "zod"
|
||||
|
||||
const Body = z.object({
|
||||
workspaceID: z.string().startsWith("wrk_"),
|
||||
referralID: z.string().startsWith("ref_"),
|
||||
})
|
||||
|
||||
export async function POST(event: APIEvent) {
|
||||
if (!safeEqual(event.request.headers.get("authorization") ?? "", `Bearer ${Resource.SUPPORT_API_KEY.value}`)) {
|
||||
return Response.json({ error: "Unauthorized" }, { status: 401 })
|
||||
}
|
||||
|
||||
const body = Body.safeParse(await event.request.json().catch(() => undefined))
|
||||
if (!body.success) {
|
||||
return Response.json({ error: "Invalid request", issues: body.error.issues }, { status: 400 })
|
||||
}
|
||||
return Referral.restoreReward(body.data)
|
||||
.then((result) => Response.json({ success: true, message: "Referral reward restored", result }))
|
||||
.catch((error) => Response.json({ error: error instanceof Error ? error.message : String(error) }, { status: 400 }))
|
||||
}
|
||||
@@ -475,6 +475,38 @@ export namespace Referral {
|
||||
})
|
||||
}
|
||||
|
||||
export async function restoreReward(input: { workspaceID: string; referralID: string }) {
|
||||
return Database.transaction(async (tx) => {
|
||||
const reward = await tx
|
||||
.select({ timeApplied: ReferralRewardTable.timeApplied })
|
||||
.from(ReferralRewardTable)
|
||||
.innerJoin(ReferralTable, eq(ReferralTable.id, ReferralRewardTable.referralID))
|
||||
.where(
|
||||
and(
|
||||
eq(ReferralRewardTable.workspaceID, input.workspaceID),
|
||||
eq(ReferralRewardTable.referralID, input.referralID),
|
||||
isNull(ReferralRewardTable.timeDeleted),
|
||||
isNull(ReferralTable.timeDeleted),
|
||||
),
|
||||
)
|
||||
.then((rows) => rows[0])
|
||||
if (!reward) throw new Error("Referral reward not found")
|
||||
|
||||
await tx
|
||||
.update(ReferralRewardTable)
|
||||
.set({ timeApplied: null })
|
||||
.where(
|
||||
and(
|
||||
eq(ReferralRewardTable.workspaceID, input.workspaceID),
|
||||
eq(ReferralRewardTable.referralID, input.referralID),
|
||||
isNull(ReferralRewardTable.timeDeleted),
|
||||
),
|
||||
)
|
||||
|
||||
return { restored: reward.timeApplied !== null }
|
||||
})
|
||||
}
|
||||
|
||||
export async function completeFromLiteSubscription(input: { workspaceID: string; userID: string }) {
|
||||
return Database.transaction(async (tx) => {
|
||||
const invitee = await tx
|
||||
|
||||
@@ -16,7 +16,6 @@ import { GroqPlugin } from "./provider/groq.js"
|
||||
import { KiloPlugin } from "./provider/kilo.js"
|
||||
import { LLMGatewayPlugin } from "./provider/llmgateway.js"
|
||||
import { MistralPlugin } from "./provider/mistral.js"
|
||||
import { ModalPlugin } from "./provider/modal.js"
|
||||
import { NvidiaPlugin } from "./provider/nvidia.js"
|
||||
import { OpenAIPlugin } from "./provider/openai.js"
|
||||
import { SnowflakeCortexPlugin } from "./provider/snowflake-cortex.js"
|
||||
@@ -50,7 +49,6 @@ export const ProviderPlugins: PluginInternal.InternalPlugin[] = [
|
||||
KiloPlugin,
|
||||
LLMGatewayPlugin,
|
||||
MistralPlugin,
|
||||
ModalPlugin,
|
||||
NvidiaPlugin,
|
||||
OpencodePlugin,
|
||||
SnowflakeCortexPlugin,
|
||||
|
||||
@@ -1,176 +0,0 @@
|
||||
import { Money } from "@opencode-ai/schema/money"
|
||||
import { define } from "@opencode-ai/plugin/effect/plugin"
|
||||
import { Effect, Schema, Semaphore, Stream } from "effect"
|
||||
import { Bus } from "../../bus.js"
|
||||
import { Catalog } from "../../catalog.js"
|
||||
import { Integration } from "../../integration.js"
|
||||
import { Model } from "../../model.js"
|
||||
import { Provider } from "../../provider.js"
|
||||
|
||||
const providerID = Provider.ID.make("modal")
|
||||
|
||||
const ReasoningOption = Schema.Struct({
|
||||
type: Schema.Literal("effort"),
|
||||
values: Schema.Array(Schema.NullOr(Schema.String)),
|
||||
})
|
||||
|
||||
const Response = Schema.Struct({
|
||||
data: Schema.Array(
|
||||
Schema.Struct({
|
||||
id: Schema.String,
|
||||
base_model_id: Schema.optional(Schema.String),
|
||||
hugging_face_id: Schema.optional(Schema.String),
|
||||
name: Schema.optional(Schema.String),
|
||||
input_modalities: Schema.optional(Schema.Array(Schema.String)),
|
||||
output_modalities: Schema.optional(Schema.Array(Schema.String)),
|
||||
context_length: Schema.optional(Schema.Number),
|
||||
max_output_length: Schema.optional(Schema.Number),
|
||||
pricing: Schema.optional(
|
||||
Schema.Struct({
|
||||
prompt: Schema.optional(Schema.Union([Schema.String, Schema.Number])),
|
||||
completion: Schema.optional(Schema.Union([Schema.String, Schema.Number])),
|
||||
input_cache_read: Schema.optional(Schema.Union([Schema.String, Schema.Number])),
|
||||
}),
|
||||
),
|
||||
supported_features: Schema.optional(Schema.Array(Schema.String)),
|
||||
reasoning_options: Schema.optional(Schema.Array(ReasoningOption)),
|
||||
interleaved: Schema.optional(
|
||||
Schema.Union([
|
||||
Schema.Boolean,
|
||||
Schema.Struct({ field: Schema.Literals(["reasoning", "reasoning_content", "reasoning_details"]) }),
|
||||
]),
|
||||
),
|
||||
}),
|
||||
),
|
||||
})
|
||||
|
||||
const decode = Schema.decodeUnknownSync(Response)
|
||||
|
||||
export const ModalPlugin = define({
|
||||
id: "opencode.provider.modal",
|
||||
effect: Effect.fn(function* (ctx) {
|
||||
const bus = yield* Bus.Service
|
||||
const catalog = yield* Catalog.Service
|
||||
const loading = Semaphore.makeUnsafe(1)
|
||||
let templates: Map<Model.ID, Model.Info> | undefined
|
||||
let models: Map<Model.ID, Model.Info> | undefined
|
||||
|
||||
const load = Effect.fn("ModalPlugin.load")(function* () {
|
||||
const existing =
|
||||
templates ??
|
||||
new Map(
|
||||
(yield* catalog.model.all())
|
||||
.filter((model) => model.providerID === providerID)
|
||||
.map((model) => [model.id, model]),
|
||||
)
|
||||
templates = existing
|
||||
const connection = yield* ctx.integration.connection.active("modal")
|
||||
const credential = connection
|
||||
? yield* ctx.integration.connection.resolve(connection).pipe(Effect.catch(() => Effect.succeed(undefined)))
|
||||
: undefined
|
||||
const provider = yield* catalog.provider.get(providerID)
|
||||
const baseURL = typeof provider?.settings?.baseURL === "string" ? provider.settings.baseURL : undefined
|
||||
if (credential?.type !== "key" || !baseURL) {
|
||||
models = new Map()
|
||||
return
|
||||
}
|
||||
|
||||
models = yield* Effect.tryPromise({
|
||||
try: () => discover(baseURL, credential.key, existing),
|
||||
catch: (cause) => cause,
|
||||
}).pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("failed to sync Modal models", { cause }).pipe(Effect.as(new Map<Model.ID, Model.Info>())),
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
yield* ctx.catalog.transform((draft) => {
|
||||
if (!models) return
|
||||
const provider = draft.provider.get(providerID)
|
||||
if (!provider) return
|
||||
for (const id of provider.models.keys()) {
|
||||
if (!models.has(Model.ID.make(id))) draft.model.remove(providerID, Model.ID.make(id))
|
||||
}
|
||||
for (const [id, model] of models) {
|
||||
draft.model.update(providerID, id, (item) => Object.assign(item, structuredClone(model)))
|
||||
}
|
||||
})
|
||||
const refresh = () => loading.withPermit(load().pipe(Effect.andThen(ctx.catalog.reload())))
|
||||
yield* bus.subscribe(Integration.Event.ConnectionUpdated).pipe(
|
||||
Stream.filter((event) => event.data.integrationID === Integration.ID.make("modal")),
|
||||
Stream.runForEach(refresh),
|
||||
Effect.forkScoped({ startImmediately: true }),
|
||||
)
|
||||
yield* refresh().pipe(Effect.forkScoped)
|
||||
}),
|
||||
})
|
||||
|
||||
async function discover(baseURL: string, apiKey: string, templates: ReadonlyMap<Model.ID, Model.Info>) {
|
||||
const response = await fetch(`${baseURL.replace(/\/+$/, "")}/models`, {
|
||||
headers: { Authorization: `Bearer ${apiKey}` },
|
||||
signal: AbortSignal.timeout(3_000),
|
||||
})
|
||||
if (!response.ok) throw new Error(`Failed to fetch Modal models: ${response.status}`)
|
||||
|
||||
return new Map(
|
||||
decode(await response.json()).data.map((item) => {
|
||||
const id = Model.ID.make(item.id)
|
||||
const template = templates.get(Model.ID.make(item.base_model_id ?? item.hugging_face_id ?? item.id))
|
||||
return [id, build(id, item, baseURL, template)]
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
function build(id: Model.ID, item: (typeof Response.Type)["data"][number], baseURL: string, template?: Model.Info) {
|
||||
const fallback: Model.Info = template ?? Model.Info.make(Model.Info.default(providerID, id))
|
||||
const baseCost = fallback.cost[0]
|
||||
const variants = item.reasoning_options?.flatMap((option) =>
|
||||
option.values.map((value) => {
|
||||
const effort = value ?? "none"
|
||||
return {
|
||||
id: Model.VariantID.make(effort),
|
||||
settings: { reasoningEffort: effort },
|
||||
}
|
||||
}),
|
||||
)
|
||||
return Model.Info.make({
|
||||
...structuredClone(fallback),
|
||||
id,
|
||||
modelID: id,
|
||||
providerID,
|
||||
name: item.name ?? fallback.name,
|
||||
compatibility: Model.compatibility(item.interleaved) ?? fallback.compatibility,
|
||||
package: fallback.package ?? Provider.aisdk("@ai-sdk/openai-compatible"),
|
||||
settings: Provider.mergeOverlay(fallback.settings, { baseURL }),
|
||||
capabilities: {
|
||||
tools: item.supported_features?.includes("tools") ?? fallback.capabilities.tools,
|
||||
input: item.input_modalities ? [...item.input_modalities] : [...fallback.capabilities.input],
|
||||
output: item.output_modalities ? [...item.output_modalities] : [...fallback.capabilities.output],
|
||||
},
|
||||
variants: variants ?? [...fallback.variants],
|
||||
cost: [
|
||||
{
|
||||
input: price(item.pricing?.prompt, baseCost?.input ?? Money.USDPerMillionTokens.zero),
|
||||
output: price(item.pricing?.completion, baseCost?.output ?? Money.USDPerMillionTokens.zero),
|
||||
cache: {
|
||||
read: price(item.pricing?.input_cache_read, baseCost?.cache.read ?? Money.USDPerMillionTokens.zero),
|
||||
write: baseCost?.cache.write ?? Money.USDPerMillionTokens.zero,
|
||||
},
|
||||
},
|
||||
],
|
||||
limit: {
|
||||
context: item.context_length ?? fallback.limit.context,
|
||||
input: fallback.limit.input,
|
||||
output: item.max_output_length ?? fallback.limit.output,
|
||||
},
|
||||
status: fallback.status,
|
||||
enabled: fallback.enabled,
|
||||
})
|
||||
}
|
||||
|
||||
function price(value: string | number | undefined, fallback: number) {
|
||||
if (value === undefined) return Money.USDPerMillionTokens.make(fallback)
|
||||
const parsed = Number(value)
|
||||
return Money.USDPerMillionTokens.make(Number.isFinite(parsed) ? parsed * 1_000_000 : fallback)
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
import { Catalog } from "@opencode-ai/core/catalog"
|
||||
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 { ModalPlugin } from "@opencode-ai/core/plugin/provider/modal"
|
||||
import { Provider } from "@opencode-ai/core/provider"
|
||||
import { State } from "@opencode-ai/core/state"
|
||||
import { Money } from "@opencode-ai/schema/money"
|
||||
import { expect } from "bun:test"
|
||||
import { Effect } from "effect"
|
||||
import { testEffect } from "../lib/effect"
|
||||
import { PluginTestLayer } from "./fixture"
|
||||
|
||||
const it = testEffect(PluginTestLayer)
|
||||
const providerID = Provider.ID.make("modal")
|
||||
const integrationID = Integration.ID.make("modal")
|
||||
const baseModelID = Model.ID.make("thinkingmachines/Inkling-NVFP4")
|
||||
const runtimeModelID = Model.ID.make("workspace--inkling.us-west.modal.direct")
|
||||
|
||||
function eventually<A>(
|
||||
effect: Effect.Effect<A>,
|
||||
predicate: (value: A) => boolean,
|
||||
remaining = 1000,
|
||||
): 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 setup = Effect.fn(function* (baseURL: string, key?: string) {
|
||||
const catalog = yield* Catalog.Service
|
||||
const integrations = yield* Integration.Service
|
||||
yield* integrations.transform((draft) => {
|
||||
draft.method.update({ integrationID, method: { type: "key" } })
|
||||
})
|
||||
if (key) yield* integrations.connection.key({ integrationID, key })
|
||||
yield* State.batch(
|
||||
Effect.gen(function* () {
|
||||
yield* catalog.transform((draft) => {
|
||||
draft.provider.update(providerID, (provider) => {
|
||||
provider.name = "Modal"
|
||||
provider.package = Provider.aisdk("@ai-sdk/openai-compatible")
|
||||
provider.settings = { baseURL }
|
||||
provider.integrationID = integrationID
|
||||
})
|
||||
draft.model.update(providerID, baseModelID, (model) => {
|
||||
model.name = "Inkling"
|
||||
model.family = Model.Family.make("ling")
|
||||
model.compatibility = { reasoningField: "reasoning_content" }
|
||||
model.capabilities = { tools: true, input: ["text", "image", "audio"], output: ["text"] }
|
||||
model.variants = [{ id: Model.VariantID.make("fallback"), settings: { reasoningEffort: "fallback" } }]
|
||||
model.cost = [
|
||||
{
|
||||
input: Money.USDPerMillionTokens.make(1),
|
||||
output: Money.USDPerMillionTokens.make(4),
|
||||
cache: {
|
||||
read: Money.USDPerMillionTokens.make(0.2),
|
||||
write: Money.USDPerMillionTokens.zero,
|
||||
},
|
||||
},
|
||||
]
|
||||
model.limit = { context: 128_000, output: 8_192 }
|
||||
model.time = { released: Date.parse("2026-07-15") }
|
||||
})
|
||||
})
|
||||
yield* ModalPlugin.effect(yield* PluginHost.make(yield* Plugin.Service))
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it.live("discovers Modal workspace models", () =>
|
||||
Effect.gen(function* () {
|
||||
const requests: Array<{ authorization: string | null; path: string }> = []
|
||||
using server = Bun.serve({
|
||||
port: 0,
|
||||
fetch(request) {
|
||||
requests.push({ authorization: request.headers.get("authorization"), path: new URL(request.url).pathname })
|
||||
return Response.json({
|
||||
data: [
|
||||
{
|
||||
id: runtimeModelID,
|
||||
base_model_id: baseModelID,
|
||||
name: "Thinking Machines: Inkling",
|
||||
input_modalities: ["text", "image", "audio"],
|
||||
output_modalities: ["text"],
|
||||
context_length: 1_048_576,
|
||||
max_output_length: 262_144,
|
||||
pricing: { prompt: "0.0000012", completion: "0.000005", input_cache_read: "0.00000027" },
|
||||
supported_features: ["tools", "reasoning"],
|
||||
reasoning_options: [{ type: "effort", values: ["none", "low", "high"] }],
|
||||
interleaved: { field: "reasoning_content" },
|
||||
},
|
||||
],
|
||||
})
|
||||
},
|
||||
})
|
||||
yield* setup(`${server.url}v1`, "test-token")
|
||||
|
||||
const models = yield* eventually(
|
||||
(yield* Catalog.Service).model
|
||||
.all()
|
||||
.pipe(Effect.map((models) => models.filter((model) => model.providerID === providerID))),
|
||||
(models) => models.some((model) => model.id === runtimeModelID),
|
||||
)
|
||||
expect(requests).toEqual([{ authorization: "Bearer test-token", path: "/v1/models" }])
|
||||
expect(models).toHaveLength(1)
|
||||
expect(models[0]).toMatchObject({
|
||||
id: runtimeModelID,
|
||||
modelID: runtimeModelID,
|
||||
name: "Thinking Machines: Inkling",
|
||||
family: "ling",
|
||||
compatibility: { reasoningField: "reasoning_content" },
|
||||
settings: { baseURL: `${server.url}v1` },
|
||||
capabilities: { tools: true, input: ["text", "image", "audio"], output: ["text"] },
|
||||
variants: [
|
||||
{ id: "none", settings: { reasoningEffort: "none" } },
|
||||
{ id: "low", settings: { reasoningEffort: "low" } },
|
||||
{ id: "high", settings: { reasoningEffort: "high" } },
|
||||
],
|
||||
cost: [{ input: 1.2, output: 5, cache: { read: 0.27, write: 0 } }],
|
||||
limit: { context: 1_048_576, output: 262_144 },
|
||||
})
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("hides static Modal models when discovery fails", () =>
|
||||
Effect.gen(function* () {
|
||||
using server = Bun.serve({ port: 0, fetch: () => new Response(null, { status: 503 }) })
|
||||
yield* setup(`${server.url}v1`, "test-token")
|
||||
const models = yield* eventually(
|
||||
(yield* Catalog.Service).model
|
||||
.all()
|
||||
.pipe(Effect.map((models) => models.filter((model) => model.providerID === providerID))),
|
||||
(models) => models.length === 0,
|
||||
)
|
||||
expect(models).toEqual([])
|
||||
}),
|
||||
)
|
||||
@@ -68,22 +68,6 @@ await $`bun ./packages/core/script/publish.ts`
|
||||
console.log("\n=== ui ===\n")
|
||||
await $`bun ./packages/ui/script/publish.ts`
|
||||
|
||||
if (Script.channel === "beta") {
|
||||
const packages = [
|
||||
"@opencode-ai/schema",
|
||||
"@opencode-ai/codemode",
|
||||
"@opencode-ai/theme",
|
||||
"@opencode-ai/ai",
|
||||
"@opencode-ai/util",
|
||||
"@opencode-ai/protocol",
|
||||
"@opencode-ai/client",
|
||||
"@opencode-ai/plugin",
|
||||
"@opencode-ai/core",
|
||||
"@opencode-ai/ui",
|
||||
]
|
||||
await Promise.all(packages.map((name) => $`npm dist-tag add ${`${name}@${Script.version}`} next`))
|
||||
}
|
||||
|
||||
if (Script.release) {
|
||||
await $`bun ./packages/desktop/scripts/finalize-latest-json.ts`
|
||||
await $`bun ./packages/desktop/scripts/finalize-latest-yml.ts`
|
||||
|
||||
Reference in New Issue
Block a user