all: load on OpenCode 2.x through a default {id, setup} (#657)
nbczw8750 (#657): trae 0.2.26 on OpenCode 2.2.5 fails with "Plugin must export a default definition with an id and an effect or setup function. (cause: SchemaError(Missing key at ["default"]))". 2.x imports a package's exports["."] (a plugin dir and an npm install alike) and has no V1 path at all, so every package here that serves models failed the same way, not only trae. Every one of the 32 model packages now has: - opencode2.mjs, exports["."]: a copy of scripts/opencode2.mjs, an adapter that runs the package's V1 plugins inside 2.x's promise API. Config providers become 2.x providers (package pinned so the aisdk sdk hook runs), V1 auth methods become integration methods (oauth auto/code with forms; api without authorize as a key method), V1 credentials are kept in metadata.v1, the loader's baseURL, apiKey, headers and fetch are applied through the sdk hook, an auth.set renewal is stored per credential, and credential.switched /updated reload the account's own model list. - opencode.mjs, main: re-exports the V1 plugin functions only. OpenCode 1.x and magpie's host.js take main. On 1.x, trae 0.2.26's main exported a non-plugin (_internal) and 1.19.5 refused it ("Plugin export is not a function"); the new main fixes that too. - both files in "files"; patch version bumped. devin already had 2.x and is unchanged. scripts/check.mjs fails a model package whose 2.x entry has no default {id, setup}, whose opencode2.mjs differs from the canonical one, whose entry is missing from files, or whose main exports a non-plugin. Run at this head (mote): - HOME=$(mktemp -d) bun test, as CI runs it: 4900 pass, 0 fail (4914 tests, 374 files). A first run set globalThis.fetch for the whole process from opencode2.test and failed 528 tests in other packages; the block is now set and put back around that file's tests. - bun scripts/check.mjs: every package passes. With the network blocked cloudflare-workers-ai fails on its fetched catalog, the same on origin/main. - Real OpenCode 2.2.5 (npm opencode-ai), sandbox HOME, packed trae 0.2.27: loads with no error; /api/integration lists trae-cn "Trae CN" and trae-global "Trae Global" with their browser sign-ins; `auth login` starts the trae.cn authorization and waits (cancelled there); with a fake credential POSTed to /api/credential, `opencode models` lists trae-cn's six models. - Real 2.2.5 with a fake V1 key plugin through the same adapter against a local fake server: `auth login` with a key, `models`, `opencode run` reached /real/v1/chat/completions with the loader's "Bearer loader-sk-fake" and header, and printed the fake's reply; with @ai-sdk/anthropic it reached /real/v1/messages with x-api-key from the loader. This run found the key method missing after 2.x's second integration transform (a once-only flag outside the transform); fixed, and opencode2.test checks a rebuild. - Real OpenCode 1.19.5, sandbox HOME, trae 0.2.27: `opencode models` lists trae-cn and trae-global models; 0.2.26 failed there. Broken by hand (scratch copy, bun test scripts/ and check.mjs): - trae's exports back to "./index.mjs": the trae 2.x test fails (default.id undefined), check fails trae with "OpenCode 2.x: ./index.mjs has no default {id, setup} (plugins#657)". - zed's opencode2.mjs changed: the copies test fails, check fails zed "differs from scripts/opencode2.mjs". - the key flag back outside the transform: the 1.x plugin test fails on the rebuilt sign-ins (key missing). Not tried: a real sign-in with a real account on 2.x; Windows (the reporter's OS); chat.headers, chat.params, usage and tool hooks, which the adapter doesn't carry to 2.x; the tools/pages packages (calc, goanyapi, layerfs, search1api, aelios, agent-console, chat, fingerprint, nowledge-mem, kimi-desktop), which still load only on 1.x.
This commit is contained in:
+40
-2
@@ -1,7 +1,10 @@
|
||||
// Loads every package's plugin the way OpenCode (and magpie) do and checks
|
||||
// the shape of what it returns: an auth hook with a provider, a loader and
|
||||
// methods OpenCode knows, or, for a plugin of tools alone, its tools. It
|
||||
// signs in to nothing and sends no request. It checks registry.json first,
|
||||
// methods OpenCode knows, or, for a plugin of tools alone, its tools. A
|
||||
// package that serves models is also loaded the way OpenCode 2.x loads it
|
||||
// (exports["."], a default {id, setup}; plugins#657), and its main the way
|
||||
// OpenCode 1.x does (every export a plugin). It signs in to nothing and
|
||||
// sends no request. It checks registry.json first,
|
||||
// as magpie's Plugins page reads it (scripts/registry.mjs).
|
||||
import { readdirSync, readFileSync, existsSync } from "node:fs"
|
||||
import { join, resolve } from "node:path"
|
||||
@@ -40,6 +43,12 @@ for (const name of readdirSync(root)) {
|
||||
// navigates to: no provider, no tools. It isn't started here (it would
|
||||
// take a port and write config); the package's own tests start it.
|
||||
if (v1 && !pkg.magpie?.page) fns.push(v1)
|
||||
// OpenCode 1.x refuses a main with anything but plugins among its
|
||||
// exports, unless its default is the {id, server} form
|
||||
if (!v1 && !(mod.default && typeof mod.default === "object" && ("id" in mod.default || "server" in mod.default || "tui" in mod.default)))
|
||||
for (const [k, v] of Object.entries(mod))
|
||||
if (typeof v !== "function" && typeof v?.server !== "function") problems.push(`main exports ${k}, which OpenCode 1.x takes for a plugin and refuses`)
|
||||
let servesModels = false
|
||||
const client = { app: { log: async () => {} }, auth: { set: async () => {} }, tui: { showToast: async () => {} }, config: { get: async () => ({ data: {} }) } }
|
||||
for (const fn of fns) {
|
||||
const hooks = await fn({ client, directory: process.cwd(), worktree: process.cwd(), $: undefined, project: {} })
|
||||
@@ -73,11 +82,15 @@ for (const name of readdirSync(root)) {
|
||||
const usageOnly = typeof auth.usage === "function" && p?.models && !Object.keys(p.models).length && !p.npm && !p.api
|
||||
if (p && !signInOnly && !usageOnly) {
|
||||
needsLoader = true
|
||||
servesModels = true
|
||||
if (!p.npm || !p.models || !Object.keys(p.models).length) problems.push(`${fn.name}: config gives ${auth.provider} no npm or models`)
|
||||
}
|
||||
}
|
||||
if ((needsLoader || auth.loader !== undefined) && typeof auth.loader !== "function") problems.push(`${fn.name}: auth.loader`)
|
||||
// a provider OpenCode has built in, served by the plugin's loader
|
||||
if (!hooks.config && typeof auth.loader === "function") servesModels = true
|
||||
}
|
||||
if (servesModels) problems.push(...(await opencode2Problems(dir, pkg)))
|
||||
} catch (e) {
|
||||
problems.push(String(e?.stack ?? e))
|
||||
}
|
||||
@@ -85,3 +98,28 @@ for (const name of readdirSync(root)) {
|
||||
console.log(problems.length ? `✗ ${name}\n ${problems.join("\n ")}` : `✓ ${name}`)
|
||||
}
|
||||
process.exit(failed ? 1 : 0)
|
||||
|
||||
// opencode2Problems loads a package as OpenCode 2.x does: its exports["."]
|
||||
// (a bare string exports is the same), else main, and wants the default to
|
||||
// be {id, setup}. The adapter it ships is scripts/opencode2.mjs, byte for
|
||||
// byte.
|
||||
async function opencode2Problems(dir, pkg) {
|
||||
const e = pkg.exports
|
||||
const entry = typeof e === "string" ? e : e && typeof e === "object" ? (e["."]?.import ?? e["."]?.default ?? e["."]) : (pkg.main ?? "index.mjs")
|
||||
if (typeof entry !== "string") return ["OpenCode 2.x: exports[\".\"] is not a file"]
|
||||
const out = []
|
||||
const mod = await import(pathToFileURL(join(dir, entry)).href)
|
||||
const d = mod.default
|
||||
if (!d || typeof d !== "object" || typeof d.id !== "string" || !d.id || (typeof d.setup !== "function" && typeof d.effect !== "function"))
|
||||
out.push(`OpenCode 2.x: ${entry} has no default {id, setup} (plugins#657)`)
|
||||
const canon = resolve(import.meta.dir, "opencode2.mjs")
|
||||
const copy = join(dir, "opencode2.mjs")
|
||||
if (existsSync(copy) && existsSync(canon) && readFileSync(copy, "utf8") !== readFileSync(canon, "utf8"))
|
||||
out.push("opencode2.mjs differs from scripts/opencode2.mjs: copy it again")
|
||||
for (const f of [entry, existsSync(copy) ? "opencode2.mjs" : null, pkg.main].filter(Boolean)) {
|
||||
const name = f.replace(/^\.\//, "")
|
||||
if (Array.isArray(pkg.files) && !pkg.files.some((g) => g === name || name.startsWith(g.replace(/\/?$/, "/"))))
|
||||
out.push(`${name} is not in files`)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
+39
-2
@@ -8,15 +8,17 @@ import { registryProblems } from "./registry.mjs"
|
||||
// real plugin, credential file or network client.
|
||||
const okRegistry = JSON.stringify({ version: 1, plugins: [{ package: "fixture", name: "Fixture", community: true, summary: { en: "A fixture.", zh: "示例。" } }] })
|
||||
|
||||
function check(source, registry = okRegistry) {
|
||||
function check(source, registry = okRegistry, pkg = { main: "index.mjs" }, files = {}) {
|
||||
const dir = mkdtempSync(join(tmpdir(), "magpie-check-test-"))
|
||||
try {
|
||||
mkdirSync(join(dir, "scripts"))
|
||||
mkdirSync(join(dir, "packages", "fixture"), { recursive: true })
|
||||
copyFileSync(new URL("./check.mjs", import.meta.url), join(dir, "scripts", "check.mjs"))
|
||||
copyFileSync(new URL("./registry.mjs", import.meta.url), join(dir, "scripts", "registry.mjs"))
|
||||
copyFileSync(new URL("./opencode2.mjs", import.meta.url), join(dir, "scripts", "opencode2.mjs"))
|
||||
if (registry !== null) writeFileSync(join(dir, "registry.json"), registry)
|
||||
writeFileSync(join(dir, "packages", "fixture", "package.json"), JSON.stringify({ main: "index.mjs" }))
|
||||
writeFileSync(join(dir, "packages", "fixture", "package.json"), JSON.stringify({ name: "fixture", ...pkg }))
|
||||
for (const [f, body] of Object.entries(files)) writeFileSync(join(dir, "packages", "fixture", f), body)
|
||||
writeFileSync(join(dir, "packages", "fixture", "index.mjs"), source)
|
||||
const result = Bun.spawnSync([process.execPath, join(dir, "scripts", "check.mjs")])
|
||||
return { code: result.exitCode, output: result.stdout.toString() + result.stderr.toString() }
|
||||
@@ -154,3 +156,38 @@ test("registry entries are held to what magpie's market reads", () => {
|
||||
expect(registryProblems(JSON.stringify({ version: 2, plugins: [base] }))).toEqual(["version 2, not 1"])
|
||||
expect(registryProblems("[]")).toEqual(["registry.json is not an object"])
|
||||
})
|
||||
|
||||
// a model provider as the packages were before plugins#657: named 1.x
|
||||
// exports and nothing OpenCode 2.x can load
|
||||
const provider = `export const Plugin = async () => ({
|
||||
auth: {...${auth}, loader: async () => ({})},
|
||||
config: async (cfg) => { cfg.provider.fixture = {npm: "@ai-sdk/openai-compatible", models: {m: {}}} }
|
||||
})`
|
||||
const adapter = readFileSync(new URL("./opencode2.mjs", import.meta.url), "utf8")
|
||||
|
||||
test("check fails a model provider OpenCode 2.x can't load (plugins#657)", () => {
|
||||
for (const pkg of [{ main: "index.mjs" }, { main: "index.mjs", exports: "./index.mjs" }]) {
|
||||
const result = check(provider, okRegistry, pkg)
|
||||
expect(result.code).toBe(1)
|
||||
expect(result.output).toContain("has no default {id, setup} (plugins#657)")
|
||||
}
|
||||
})
|
||||
|
||||
test("check passes a model provider with the 2.x adapter and a 1.x main", () => {
|
||||
const files = { "opencode.mjs": 'export { Plugin } from "./index.mjs"\n', "opencode2.mjs": adapter }
|
||||
const pkg = { main: "./opencode.mjs", exports: { ".": "./opencode2.mjs" }, files: ["index.mjs", "opencode.mjs", "opencode2.mjs"] }
|
||||
const ok = check(provider, okRegistry, pkg, files)
|
||||
expect(ok.output).toContain("✓ fixture")
|
||||
expect(ok.code).toBe(0)
|
||||
// a copy that drifted from scripts/opencode2.mjs, and a file npm won't ship
|
||||
const drift = check(provider, okRegistry, { ...pkg, files: ["index.mjs", "opencode.mjs"] }, { ...files, "opencode2.mjs": adapter + "\n// edited\n" })
|
||||
expect(drift.code).toBe(1)
|
||||
expect(drift.output).toContain("differs from scripts/opencode2.mjs")
|
||||
expect(drift.output).toContain("opencode2.mjs is not in files")
|
||||
})
|
||||
|
||||
test("check fails a main OpenCode 1.x refuses: an export that isn't a plugin", () => {
|
||||
const result = check(provider + "\nexport const _internal = {}\n", okRegistry, {}, {})
|
||||
expect(result.code).toBe(1)
|
||||
expect(result.output).toContain("main exports _internal")
|
||||
})
|
||||
|
||||
@@ -0,0 +1,594 @@
|
||||
// The OpenCode 2.x face of a package whose plugins are written for
|
||||
// OpenCode 1.x (and magpie's plugin host).
|
||||
//
|
||||
// OpenCode 2.x loads a package's `exports["."]` and wants its default to be
|
||||
// {id, setup(ctx)}; it has no fallback for a 1.x plugin's named functions
|
||||
// (plugins#657). This file is that default. It runs each 1.x plugin the
|
||||
// package's opencode.mjs exports and hands 2.x what the plugin's hooks say:
|
||||
//
|
||||
// auth.methods → the integration's sign-in methods
|
||||
// config() → the provider, its package, base URL and models
|
||||
// provider.models → the signed-in account's own model list
|
||||
// auth.loader → each request's base URL, key, headers and fetch
|
||||
//
|
||||
// What 2.x has no place for is left out: chat.headers and chat.params
|
||||
// (2.x's sdk hook doesn't carry the session), magpie's usage and checkin,
|
||||
// tools and events.
|
||||
//
|
||||
// scripts/opencode2.mjs is the one copy that is edited. Every package that
|
||||
// has it carries the same bytes as packages/<name>/opencode2.mjs, and
|
||||
// scripts/check.mjs fails when a copy differs.
|
||||
|
||||
import { readFileSync } from "node:fs"
|
||||
import * as v1 from "./opencode.mjs"
|
||||
|
||||
const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8"))
|
||||
|
||||
// The key the SDK is made with: the account's own goes on each request in
|
||||
// its place (see wrapFetch), so a key read when the SDK was made can't go
|
||||
// out after the account changed.
|
||||
const PLACEHOLDER = "opencode2-v1-key"
|
||||
|
||||
// The SDK package a 1.x npm name runs as on 2.x. A version keeps 2.x from
|
||||
// swapping @ai-sdk/* for its native providers, which never call the sdk
|
||||
// hook below; openai-compatible's is the one 2.x ships, the others are AI
|
||||
// SDK v6's dist-tag, the line 2.x's bridge runs.
|
||||
export function packageOf(npm) {
|
||||
const name = npm || "@ai-sdk/openai-compatible"
|
||||
if (name === "@ai-sdk/openai-compatible") return "aisdk:@ai-sdk/openai-compatible@2.0.41"
|
||||
if (/^@ai-sdk\/[^/@]+$/.test(name)) return `aisdk:${name}@ai-v6`
|
||||
return `aisdk:${name}`
|
||||
}
|
||||
|
||||
// The plugins a 1.x module exports, as magpie's host and OpenCode 1.x read
|
||||
// them: a default {server} is the one plugin, else every function export
|
||||
// and every {server} object.
|
||||
export function pluginsOf(mod) {
|
||||
const d = mod?.default
|
||||
if (d && typeof d === "object" && ("server" in d || "id" in d || "tui" in d))
|
||||
return typeof d.server === "function" ? [d.server] : []
|
||||
const out = []
|
||||
for (const value of Object.values(mod ?? {})) {
|
||||
const fn = typeof value === "function" ? value : value && typeof value === "object" && typeof value.server === "function" ? value.server : null
|
||||
if (fn && !out.includes(fn)) out.push(fn)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const int = (n, fallback = 0) => {
|
||||
const v = Math.trunc(Number(n))
|
||||
return Number.isFinite(v) && v >= 0 ? v : fallback
|
||||
}
|
||||
const money = (n) => (Number.isFinite(Number(n)) && Number(n) >= 0 ? Number(n) : 0)
|
||||
const record = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {})
|
||||
const json = (v) => {
|
||||
try {
|
||||
return JSON.parse(JSON.stringify(v ?? null))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
const strings = (v) => Object.fromEntries(Object.entries(record(v)).filter(([, s]) => typeof s === "string"))
|
||||
const nonEmpty = (o) => (Object.keys(o).length ? o : undefined)
|
||||
|
||||
// connKey names a connection the way 2.x does.
|
||||
const connKey = (c) => (!c ? "" : c.type === "credential" ? `credential:${c.id}` : `env:${c.name}`)
|
||||
|
||||
// ---- sign-in ------------------------------------------------------------
|
||||
|
||||
// fields is a 1.x method's prompts as a 2.x form.
|
||||
export function fieldsOf(prompts) {
|
||||
const out = []
|
||||
for (const p of prompts ?? []) {
|
||||
if (!p?.key) continue
|
||||
const f = { key: String(p.key), type: "string", title: String(p.message ?? p.key) }
|
||||
if (p.placeholder) f.placeholder = String(p.placeholder)
|
||||
if (p.type === "select" && Array.isArray(p.options))
|
||||
f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
|
||||
// a prompt shown only when another answer says so can't be required
|
||||
if (!p.condition) f.required = true
|
||||
out.push(f)
|
||||
}
|
||||
return out.length ? out : undefined
|
||||
}
|
||||
|
||||
// v1Saved is what a 1.x sign-in's success is saved as, the way 1.x writes
|
||||
// auth.json: the result without its type and provider.
|
||||
function v1Saved(r) {
|
||||
const { type: _t, provider: _p, ...rest } = r
|
||||
if ("key" in r) return { type: "api", ...rest }
|
||||
return { type: "oauth", ...rest }
|
||||
}
|
||||
|
||||
// credentialOf is a 1.x sign-in's success as a 2.x credential: OAuth for
|
||||
// both kinds, the 1.x auth kept whole in its metadata. No refresh is
|
||||
// registered, so 2.x hands the credential over as it is and the plugin's
|
||||
// own loader renews it, as it does on 1.x.
|
||||
export function credentialOf(methodID, r) {
|
||||
if (!r || r.type !== "success") throw new Error(r?.error || r?.message || "the sign-in failed")
|
||||
const saved = json(v1Saved(r))
|
||||
if (saved.type === "api")
|
||||
return { type: "oauth", methodID, access: String(saved.key ?? ""), refresh: "", expires: 0, metadata: { v1: saved } }
|
||||
return {
|
||||
type: "oauth",
|
||||
methodID,
|
||||
access: String(saved.access ?? ""),
|
||||
refresh: String(saved.refresh ?? ""),
|
||||
expires: int(saved.expires),
|
||||
metadata: { v1: saved },
|
||||
}
|
||||
}
|
||||
|
||||
// authOfValue is the 1.x auth a 2.x credential stands for.
|
||||
export function authOfValue(value) {
|
||||
if (!value) return null
|
||||
if (value.type === "oauth") {
|
||||
const v1 = record(value.metadata).v1
|
||||
if (v1 && typeof v1 === "object") return v1
|
||||
return { type: "oauth", access: value.access, refresh: value.refresh, expires: value.expires }
|
||||
}
|
||||
if (value.type === "key") {
|
||||
const meta = value.metadata && Object.keys(value.metadata).length ? { metadata: value.metadata } : {}
|
||||
return { type: "api", key: value.key, ...meta }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const fingerprint = (a) => JSON.stringify([a?.type, a?.access ?? a?.key ?? "", a?.refresh ?? ""])
|
||||
|
||||
// ---- models -------------------------------------------------------------
|
||||
|
||||
const MODALITIES = ["text", "audio", "image", "video", "pdf"]
|
||||
|
||||
// internalOf is a config model as 1.x hands it to provider.models: what
|
||||
// fromModelsDevModel makes of it, with the config's own variants.
|
||||
export function internalOf(providerID, conf, key, m) {
|
||||
const mods = record(m.modalities)
|
||||
const has = (list, k) => Array.isArray(list) && list.includes(k)
|
||||
const cost = record(m.cost)
|
||||
return {
|
||||
...m,
|
||||
id: key,
|
||||
providerID,
|
||||
name: m.name ?? key,
|
||||
api: { id: m.id ?? key, url: m.provider?.api ?? conf.api ?? conf.options?.baseURL ?? "", npm: m.provider?.npm ?? conf.npm ?? "@ai-sdk/openai-compatible" },
|
||||
status: m.status ?? "active",
|
||||
headers: m.headers ?? {},
|
||||
options: m.options ?? {},
|
||||
cost: { input: money(cost.input), output: money(cost.output), cache: { read: money(cost.cache_read), write: money(cost.cache_write) } },
|
||||
limit: { context: int(m.limit?.context), input: m.limit?.input, output: int(m.limit?.output) },
|
||||
capabilities: {
|
||||
temperature: m.temperature ?? false,
|
||||
reasoning: m.reasoning ?? false,
|
||||
attachment: m.attachment ?? false,
|
||||
toolcall: m.tool_call ?? true,
|
||||
input: Object.fromEntries(MODALITIES.map((k) => [k, mods.input ? has(mods.input, k) : k === "text"])),
|
||||
output: Object.fromEntries(MODALITIES.map((k) => [k, mods.output ? has(mods.output, k) : k === "text"])),
|
||||
interleaved: m.interleaved ?? false,
|
||||
},
|
||||
release_date: m.release_date ?? "",
|
||||
variants: record(m.variants),
|
||||
}
|
||||
}
|
||||
|
||||
// modelOf is a 1.x model, in config or internal form, as a 2.x Model.Info.
|
||||
export function modelOf(providerID, provider, key, m) {
|
||||
const caps = record(m.capabilities)
|
||||
const listFrom = (obj, list) => {
|
||||
if (obj && typeof obj === "object") return MODALITIES.filter((k) => obj[k])
|
||||
if (Array.isArray(list)) return list.map(String)
|
||||
return ["text"]
|
||||
}
|
||||
const input = listFrom(caps.input, m.modalities?.input)
|
||||
const output = listFrom(caps.output, m.modalities?.output)
|
||||
const c = record(m.cost)
|
||||
const cache = record(c.cache)
|
||||
const npm = m.api?.npm ?? m.provider?.npm
|
||||
const url = m.api?.url ?? m.provider?.api
|
||||
const settings = { ...record(json(m.options)) }
|
||||
if (url && url !== provider.baseURL) settings.baseURL = url
|
||||
const variants = Object.entries(record(m.variants))
|
||||
.filter(([, v]) => !record(v).disabled)
|
||||
.map(([id, v]) => {
|
||||
const { disabled: _d, ...rest } = record(json(v))
|
||||
return nonEmpty(rest) ? { id, settings: rest } : { id }
|
||||
})
|
||||
const status = ["alpha", "beta", "deprecated", "active"].includes(m.status) ? m.status : "active"
|
||||
const out = {
|
||||
id: key,
|
||||
modelID: String(m.api?.id ?? m.id ?? key),
|
||||
providerID,
|
||||
name: String(m.name ?? key),
|
||||
capabilities: {
|
||||
tools: caps.toolcall ?? m.tool_call ?? true,
|
||||
input: input.length ? input : ["text"],
|
||||
output: output.length ? output : ["text"],
|
||||
...(typeof (caps.temperature ?? m.temperature) === "boolean" ? { temperature: caps.temperature ?? m.temperature } : {}),
|
||||
},
|
||||
variants,
|
||||
time: { released: Date.parse(m.release_date ?? "") || 0 },
|
||||
cost: [{ input: money(c.input), output: money(c.output), cache: { read: money(cache.read ?? c.cache_read), write: money(cache.write ?? c.cache_write) } }],
|
||||
status,
|
||||
enabled: true,
|
||||
limit: { context: int(m.limit?.context, 128000) || 128000, output: int(m.limit?.output, 8192) || 8192 },
|
||||
}
|
||||
if (m.limit?.input) out.limit.input = int(m.limit.input)
|
||||
if (npm && npm !== provider.npm) out.package = packageOf(npm)
|
||||
if (nonEmpty(settings)) out.settings = settings
|
||||
const headers = strings(m.headers)
|
||||
if (nonEmpty(headers)) out.headers = headers
|
||||
return out
|
||||
}
|
||||
|
||||
// ---- requests -----------------------------------------------------------
|
||||
|
||||
const urlOf = (input) => (typeof input === "string" ? input : input instanceof URL ? input.href : input?.url ?? String(input))
|
||||
|
||||
// wrapFetch sends a request the SDK made from the provider's settings the
|
||||
// way 1.x would have sent it with the loader's options: the loader's base
|
||||
// URL in place of the configured one, the account's key in place of the
|
||||
// placeholder, the loader's headers added, through the loader's fetch.
|
||||
export function wrapFetch(next, base, options) {
|
||||
return async (input, init = {}) => {
|
||||
const o = await options()
|
||||
let url = urlOf(input)
|
||||
const from = String(base ?? "").replace(/\/+$/, "")
|
||||
const to = o.baseURL ? String(o.baseURL).replace(/\/+$/, "") : ""
|
||||
if (from && to && from !== to && url.startsWith(from)) url = to + url.slice(from.length)
|
||||
const req = input instanceof Request ? input : null
|
||||
const headers = new Headers(init.headers ?? req?.headers ?? undefined)
|
||||
for (const [k, v] of [...headers.entries()]) {
|
||||
if (!v.includes(PLACEHOLDER)) continue
|
||||
if (o.key) headers.set(k, v.replaceAll(PLACEHOLDER, o.key))
|
||||
else headers.delete(k)
|
||||
}
|
||||
for (const [k, v] of Object.entries(strings(o.headers))) headers.set(k, v)
|
||||
const send = typeof o.fetch === "function" ? o.fetch : next ?? fetch
|
||||
if (req && init.body === undefined) {
|
||||
const body = req.method === "GET" || req.method === "HEAD" ? undefined : await req.text()
|
||||
return send(url, { method: req.method, headers, body, signal: init.signal ?? req.signal })
|
||||
}
|
||||
return send(url, { ...init, headers })
|
||||
}
|
||||
}
|
||||
|
||||
// ---- one plugin ---------------------------------------------------------
|
||||
|
||||
async function setupPlugin(ctx, fn, live) {
|
||||
const directory = ctx?.location?.directory ?? process.cwd()
|
||||
// the active account each provider was last read for, and the renewed
|
||||
// auth a plugin saved for it (2.x has no way for a plugin to write a
|
||||
// credential back, so it is kept in the plugin's storage, under the
|
||||
// credential it renews and the token it was renewed from)
|
||||
const current = new Map()
|
||||
const saved = new Map()
|
||||
const signingIn = new Map()
|
||||
const storeKey = (id, key) => `v1auth/${id}/${key}`
|
||||
|
||||
const client = {
|
||||
auth: {
|
||||
async set(arg) {
|
||||
const id = arg?.path?.id
|
||||
const body = json(arg?.body)
|
||||
const cur = id && current.get(id)
|
||||
// a sign-in's own saves belong to the credential it is about to
|
||||
// make, not the one that was active when it started
|
||||
if (!cur || !body || signingIn.get(id) > 0) return { data: true }
|
||||
const entry = { fp: cur.fp, auth: body }
|
||||
saved.set(storeKey(id, cur.key), entry)
|
||||
await Promise.resolve()
|
||||
.then(() => ctx.storage?.set?.(storeKey(id, cur.key), entry))
|
||||
.catch(() => {})
|
||||
return { data: true }
|
||||
},
|
||||
async get() {
|
||||
return { data: undefined }
|
||||
},
|
||||
},
|
||||
app: { log: async () => ({ data: true }) },
|
||||
}
|
||||
|
||||
const hooks = (await fn({ client, directory, worktree: directory, project: {}, serverUrl: undefined, $: undefined }, {})) ?? {}
|
||||
const cfg = { provider: {} }
|
||||
try {
|
||||
await hooks.config?.(cfg)
|
||||
} catch {}
|
||||
const auth = hooks.auth
|
||||
const authID = auth?.provider ? String(auth.provider) : undefined
|
||||
const providers = record(cfg.provider)
|
||||
|
||||
// getAuth reads the active account: the credential 2.x holds, or what the
|
||||
// plugin last saved renewing it.
|
||||
const getAuth = async (id) => {
|
||||
const connection = await ctx.integration.connection.active(id).catch(() => undefined)
|
||||
if (!connection) {
|
||||
current.delete(id)
|
||||
return undefined
|
||||
}
|
||||
const value = await ctx.integration.connection.resolve(connection).catch(() => undefined)
|
||||
const base = authOfValue(value)
|
||||
if (!base) {
|
||||
current.delete(id)
|
||||
return undefined
|
||||
}
|
||||
const key = connKey(connection)
|
||||
const fp = fingerprint(base)
|
||||
// ours: a credential one of this plugin's own sign-ins made
|
||||
const ours = value?.type === "oauth" && !!record(value.metadata).v1
|
||||
current.set(id, { key, fp, ours })
|
||||
const sk = storeKey(id, key)
|
||||
let entry = saved.get(sk)
|
||||
if (!entry) {
|
||||
entry = await Promise.resolve()
|
||||
.then(() => ctx.storage?.get?.(sk))
|
||||
.catch(() => undefined)
|
||||
if (entry) saved.set(sk, entry)
|
||||
}
|
||||
return entry && entry.fp === fp && entry.auth ? entry.auth : base
|
||||
}
|
||||
|
||||
// the sign-in methods
|
||||
if (authID && Array.isArray(auth.methods) && auth.methods.length) {
|
||||
const label = (c) => {
|
||||
const a = authOfValue(c)
|
||||
const name = a?.name ?? a?.email ?? a?.metadata?.name ?? a?.metadata?.email ?? a?.account
|
||||
return typeof name === "string" && name ? name : undefined
|
||||
}
|
||||
const begin = () => signingIn.set(authID, (signingIn.get(authID) ?? 0) + 1)
|
||||
const end = () => signingIn.set(authID, Math.max(0, (signingIn.get(authID) ?? 1) - 1))
|
||||
const title = record(providers[authID]).name
|
||||
// 2.x runs a transform again on every reload, from nothing
|
||||
await ctx.integration.transform((editor) => {
|
||||
let keyed = false
|
||||
// the integration 2.x makes for an id it doesn't know is named by the
|
||||
// id; the provider's own name reads better in the sign-in list
|
||||
if (typeof title === "string" && title)
|
||||
try {
|
||||
editor.update?.(authID, (i) => {
|
||||
if (i && (!i.name || i.name === authID)) i.name = title
|
||||
})
|
||||
} catch {}
|
||||
auth.methods.forEach((m, i) => {
|
||||
if (!m) return
|
||||
const methodID = `v1-${i}`
|
||||
const form = fieldsOf(m.prompts)
|
||||
if (m.type === "api" && typeof m.authorize !== "function") {
|
||||
if (keyed) return
|
||||
keyed = true
|
||||
editor.method.update({ integrationID: authID, method: { type: "key", label: String(m.label ?? "API key"), ...(form ? { form } : {}) } })
|
||||
return
|
||||
}
|
||||
if (typeof m.authorize !== "function") return
|
||||
editor.method.update({
|
||||
integrationID: authID,
|
||||
method: { id: methodID, type: "oauth", label: String(m.label ?? authID), ...(form ? { form } : {}) },
|
||||
async authorize(answer) {
|
||||
begin()
|
||||
let ended = false
|
||||
const done = () => {
|
||||
if (!ended) end()
|
||||
ended = true
|
||||
}
|
||||
try {
|
||||
const inputs = Object.fromEntries(Object.entries(record(answer)).map(([k, v]) => [k, String(v)]))
|
||||
const r = await m.authorize(inputs)
|
||||
if (m.type === "api") {
|
||||
done()
|
||||
return { url: "", instructions: "", mode: "auto", callback: Promise.resolve().then(() => credentialOf(methodID, r)) }
|
||||
}
|
||||
if (r?.method === "code")
|
||||
return {
|
||||
url: String(r.url ?? ""),
|
||||
instructions: String(r.instructions ?? ""),
|
||||
mode: "code",
|
||||
callback: async (code) => {
|
||||
try {
|
||||
return credentialOf(methodID, await r.callback(code))
|
||||
} finally {
|
||||
done()
|
||||
}
|
||||
},
|
||||
}
|
||||
const callback = Promise.resolve()
|
||||
.then(() => r.callback())
|
||||
.then((res) => credentialOf(methodID, res))
|
||||
.finally(done)
|
||||
callback.catch(() => {})
|
||||
return { url: String(r?.url ?? ""), instructions: String(r?.instructions ?? ""), mode: "auto", callback }
|
||||
} catch (e) {
|
||||
done()
|
||||
throw e
|
||||
}
|
||||
},
|
||||
label,
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// the loader's options for the account signed in now, read again when
|
||||
// the account changes
|
||||
let loaded = null
|
||||
const loaderOptions = async (id) => {
|
||||
if (id !== authID || typeof auth?.loader !== "function") {
|
||||
const a = authID === id ? await getAuth(id) : undefined
|
||||
return { key: a?.type === "api" ? a.key : undefined }
|
||||
}
|
||||
const a = await getAuth(id)
|
||||
if (!a) return {}
|
||||
const fp = current.get(id)?.key + "\0" + fingerprint(a)
|
||||
if (loaded?.fp !== fp) {
|
||||
const p = Promise.resolve()
|
||||
.then(() => auth.loader(() => getAuth(id), providerOf(id)))
|
||||
.then((o) => record(o))
|
||||
loaded = { fp, p }
|
||||
p.catch(() => {
|
||||
if (loaded?.fp === fp) loaded = null
|
||||
})
|
||||
}
|
||||
const o = await loaded.p
|
||||
const key = typeof o.apiKey === "string" && o.apiKey ? o.apiKey : a.type === "api" ? a.key : undefined
|
||||
return { baseURL: o.baseURL, key, headers: o.headers, fetch: o.fetch }
|
||||
}
|
||||
|
||||
// the providers, with the list the account's own read last gave each
|
||||
const source = new Map()
|
||||
// providerOf is a provider as 1.x hands it to provider.models and
|
||||
// auth.loader
|
||||
const providerOf = (id) => {
|
||||
const conf = record(providers[id])
|
||||
const models = Object.fromEntries(Object.entries(record(conf.models)).map(([k, m]) => [k, internalOf(id, conf, k, record(m))]))
|
||||
return { id, name: conf.name ?? id, source: "config", env: [], options: record(conf.options), models }
|
||||
}
|
||||
const listed = new Set()
|
||||
for (const [id, conf0] of Object.entries(providers)) {
|
||||
const conf = record(conf0)
|
||||
// a provider entry that only names the sign-in (no package, no models)
|
||||
// is not a provider of models
|
||||
if (!conf.npm && !Object.keys(record(conf.models)).length) continue
|
||||
const options = record(conf.options)
|
||||
const { apiKey: _k, baseURL: _b, fetch: _f, headers: optHeaders, ...rest } = options
|
||||
// with no base URL the config leaves it to the loader: a name that
|
||||
// can't resolve stands in for it, and each request swaps in the
|
||||
// loader's (wrapFetch)
|
||||
const baseURL = options.baseURL ?? conf.api ?? `https://${id.replace(/[^a-z0-9-]/gi, "-")}.opencode2-v1.invalid`
|
||||
const npm = conf.npm ?? "@ai-sdk/openai-compatible"
|
||||
const info = {
|
||||
id,
|
||||
...(id === authID ? { integrationID: id } : {}),
|
||||
name: String(conf.name ?? id),
|
||||
activation: "auto",
|
||||
package: packageOf(npm),
|
||||
settings: { ...record(json(rest)), ...(baseURL ? { baseURL: String(baseURL) } : {}) },
|
||||
}
|
||||
const headers = { ...strings(conf.headers), ...strings(optHeaders) }
|
||||
if (nonEmpty(headers)) info.headers = headers
|
||||
const prov = { baseURL, npm }
|
||||
const fromConfig = () =>
|
||||
Object.entries(record(conf.models)).map(([key, m]) => modelOf(id, prov, key, internalOf(id, conf, key, record(m))))
|
||||
listed.add(id)
|
||||
await ctx.provider.transform((editor) => {
|
||||
const s = source.get(id)
|
||||
editor.add({ info, models: s?.models ?? fromConfig(), sourceConnection: s?.connection })
|
||||
})
|
||||
source.set(id, { conf, prov, models: null, connection: undefined })
|
||||
}
|
||||
|
||||
// each request: the placeholder key, and the fetch that swaps in the
|
||||
// account's. A provider the package doesn't list (one 2.x has built in
|
||||
// that the plugin only signs in to) is left to 2.x unless the plugin's
|
||||
// loader serves it and one of the plugin's own sign-ins is active.
|
||||
const own = authID && !listed.has(authID) && typeof auth?.loader === "function" ? [authID] : []
|
||||
for (const id of new Set([...listed, ...own])) {
|
||||
const base = source.get(id)?.prov.baseURL
|
||||
await ctx.aisdk.hook(
|
||||
"sdk",
|
||||
async (evt) => {
|
||||
const opts = evt.options
|
||||
if (!opts || opts.__opencode2) return
|
||||
if (!listed.has(id)) {
|
||||
await getAuth(id)
|
||||
if (!current.get(id)?.ours) return
|
||||
}
|
||||
opts.__opencode2 = true
|
||||
opts.apiKey = PLACEHOLDER
|
||||
opts.fetch = wrapFetch(opts.fetch, opts.baseURL ?? base, () => loaderOptions(id))
|
||||
},
|
||||
{ providerID: id },
|
||||
)
|
||||
}
|
||||
|
||||
// refresh reads the account's own list after a sign-in or a switch
|
||||
const listID = hooks.provider?.id ? String(hooks.provider.id) : undefined
|
||||
let refreshing = null
|
||||
let again = false
|
||||
// the account the list was last read for: a credential.updated that
|
||||
// leaves it as it was reads nothing again
|
||||
let readFor = null
|
||||
const stateOf = async () => {
|
||||
const c = await ctx.integration.connection.active(authID).catch(() => undefined)
|
||||
const a = c ? await getAuth(authID) : undefined
|
||||
return connKey(c) + "\0" + (a ? fingerprint(a) : "")
|
||||
}
|
||||
const refresh = () => {
|
||||
if (refreshing) {
|
||||
again = true
|
||||
return refreshing
|
||||
}
|
||||
refreshing = (async () => {
|
||||
try {
|
||||
if (!authID || !source.has(authID)) return
|
||||
const s = source.get(authID)
|
||||
const connection = await ctx.integration.connection.active(authID).catch(() => undefined)
|
||||
const a = connection ? await getAuth(authID) : undefined
|
||||
readFor = connKey(connection) + "\0" + (a ? fingerprint(a) : "")
|
||||
if (!a || listID !== authID || typeof hooks.provider?.models !== "function") {
|
||||
if (s.connection || s.models) {
|
||||
s.connection = undefined
|
||||
s.models = null
|
||||
await ctx.provider.reload()
|
||||
}
|
||||
return
|
||||
}
|
||||
const provider = providerOf(authID)
|
||||
let got
|
||||
try {
|
||||
got = await hooks.provider.models(provider, { auth: a })
|
||||
} catch {
|
||||
got = null
|
||||
}
|
||||
if (connKey(await ctx.integration.connection.active(authID).catch(() => undefined)) !== connKey(connection)) {
|
||||
again = true
|
||||
return
|
||||
}
|
||||
s.connection = connection
|
||||
s.models = got && typeof got === "object" ? Object.entries(got).map(([k, m]) => modelOf(authID, s.prov, k, record(m))) : null
|
||||
await ctx.provider.reload()
|
||||
await ctx.model?.reload?.()
|
||||
} finally {
|
||||
refreshing = null
|
||||
if (again && live.on) {
|
||||
again = false
|
||||
void refresh()
|
||||
}
|
||||
}
|
||||
})()
|
||||
return refreshing
|
||||
}
|
||||
|
||||
if (authID && ctx.event?.subscribe)
|
||||
void (async () => {
|
||||
try {
|
||||
// a switch names the integration; an update (a sign-in, a removal)
|
||||
// names nothing, so it reads again only when this account changed
|
||||
const types = ["credential.switched", "credential.updated"]
|
||||
for await (const event of ctx.event.subscribe({ types })) {
|
||||
if (!live.on) return
|
||||
if (event?.type === "credential.switched" && event?.data?.integrationID === authID) {
|
||||
loaded = null
|
||||
await refresh()
|
||||
} else if (event?.type === "credential.updated" && (await stateOf()) !== readFor) {
|
||||
await refresh()
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
})()
|
||||
void refresh()
|
||||
}
|
||||
|
||||
export async function setup(ctx, mod = v1) {
|
||||
const live = { on: true }
|
||||
for (const fn of pluginsOf(mod)) {
|
||||
try {
|
||||
await setupPlugin(ctx, fn, live)
|
||||
} catch (e) {
|
||||
// one plugin failing to start leaves the package's others working
|
||||
console.error(`${pkg.name}: ${e?.message ?? e}`)
|
||||
}
|
||||
}
|
||||
return () => {
|
||||
live.on = false
|
||||
}
|
||||
}
|
||||
|
||||
export default { id: pkg.name, setup: (ctx) => setup(ctx) }
|
||||
@@ -0,0 +1,273 @@
|
||||
// OpenCode 2.x loads a package's exports["."] and wants a default
|
||||
// {id, setup(ctx)} (plugins#657, nbczw8750: trae 0.2.26 on OpenCode 2.2.5,
|
||||
// "Plugin must export a default definition with an id and an effect or
|
||||
// setup function"). These load packages the way 2.x does and run the
|
||||
// adapter, scripts/opencode2.mjs, against a fake of 2.x's plugin context:
|
||||
// no OpenCode, no network, no account.
|
||||
import { afterAll, beforeAll, expect, test } from "bun:test"
|
||||
import { readFileSync } from "node:fs"
|
||||
import { join } from "node:path"
|
||||
|
||||
const packages = new URL("../packages/", import.meta.url).pathname
|
||||
// no request leaves these tests; fetch is put back after them, since a
|
||||
// root `bun test` runs every package's files in this one process
|
||||
const realFetch = globalThis.fetch
|
||||
beforeAll(() => {
|
||||
globalThis.fetch = async (input) => {
|
||||
throw new Error("a test asked " + (input?.url ?? input) + " with no fake in place")
|
||||
}
|
||||
})
|
||||
afterAll(() => {
|
||||
globalThis.fetch = realFetch
|
||||
})
|
||||
|
||||
// entryOf is the file 2.x imports for a package: exports["."], a bare
|
||||
// string exports, else main
|
||||
function entryOf(name) {
|
||||
const pkg = JSON.parse(readFileSync(join(packages, name, "package.json"), "utf8"))
|
||||
const e = pkg.exports
|
||||
const entry = typeof e === "string" ? e : e && typeof e === "object" ? (e["."]?.import ?? e["."]?.default ?? e["."]) : (pkg.main ?? "index.mjs")
|
||||
return join(packages, name, entry)
|
||||
}
|
||||
|
||||
// fakeContext is the part of 2.x's promise plugin context the adapter uses
|
||||
function fakeContext() {
|
||||
const methods = []
|
||||
const providerTransforms = []
|
||||
const integrationTransforms = []
|
||||
const hooks = []
|
||||
const storage = new Map()
|
||||
const conns = new Map()
|
||||
const events = []
|
||||
let wake = null
|
||||
const reloads = { provider: 0, model: 0 }
|
||||
const ctx = {
|
||||
location: { directory: "/nowhere" },
|
||||
integration: {
|
||||
transform: async (fn) => {
|
||||
integrationTransforms.push(fn)
|
||||
fn({ method: { update: (m) => methods.push(m) } })
|
||||
},
|
||||
connection: {
|
||||
active: async (id) => conns.get(id)?.connection,
|
||||
resolve: async (c) => [...conns.values()].find((x) => x.connection === c)?.value,
|
||||
},
|
||||
},
|
||||
provider: {
|
||||
transform: async (fn) => providerTransforms.push(fn),
|
||||
reload: async () => void reloads.provider++,
|
||||
},
|
||||
model: { reload: async () => void reloads.model++ },
|
||||
aisdk: { hook: async (name, fn, filter) => hooks.push({ name, fn, filter }) },
|
||||
storage: { get: async (k) => storage.get(k), set: async (k, v) => void storage.set(k, v) },
|
||||
event: {
|
||||
async *subscribe() {
|
||||
for (;;) {
|
||||
while (events.length) yield events.shift()
|
||||
await new Promise((r) => (wake = r))
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
const providers = () => {
|
||||
const out = []
|
||||
for (const fn of providerTransforms) fn({ add: (p) => out.push(p) })
|
||||
return out
|
||||
}
|
||||
const emit = (e) => {
|
||||
events.push(e)
|
||||
wake?.()
|
||||
}
|
||||
// 2.x runs every integration transform again, on a fresh editor, each
|
||||
// time it rebuilds the list
|
||||
const rebuild = () => {
|
||||
const out = []
|
||||
for (const fn of integrationTransforms) fn({ method: { update: (m) => out.push(m) } })
|
||||
return out
|
||||
}
|
||||
return { ctx, methods, providers, rebuild, hooks, storage, conns, emit, reloads }
|
||||
}
|
||||
|
||||
const until = async (cond) => {
|
||||
for (let i = 0; i < 200 && !cond(); i++) await new Promise((r) => setTimeout(r, 5))
|
||||
expect(cond()).toBe(true)
|
||||
}
|
||||
|
||||
test("trae loads on OpenCode 2.x: a default {id, setup} (plugins#657)", async () => {
|
||||
const mod = await import(entryOf("trae"))
|
||||
expect(typeof mod.default?.id).toBe("string")
|
||||
expect(mod.default.id).toBe("@magpie-community/opencode-trae-auth")
|
||||
expect(typeof mod.default.setup).toBe("function")
|
||||
// and 2.x gets both of its providers with their sign-ins, before any
|
||||
// account is signed in, without a request
|
||||
const f = fakeContext()
|
||||
await mod.default.setup(f.ctx)
|
||||
const ids = f.providers().map((p) => p.info.id)
|
||||
expect(ids).toEqual(expect.arrayContaining(["trae-cn", "trae-global"]))
|
||||
for (const p of f.providers()) {
|
||||
expect(p.info.integrationID).toBe(p.info.id)
|
||||
expect(p.models.length).toBeGreaterThan(0)
|
||||
for (const m of p.models) {
|
||||
expect(Number.isInteger(m.limit.context) && Number.isInteger(m.limit.output)).toBe(true)
|
||||
expect(m.providerID).toBe(p.info.id)
|
||||
}
|
||||
}
|
||||
const signIns = new Set(f.methods.map((m) => m.integrationID))
|
||||
expect([...signIns].sort()).toEqual(["trae-cn", "trae-global"])
|
||||
expect(f.methods.every((m) => m.method.type === "key" || typeof m.authorize === "function")).toBe(true)
|
||||
})
|
||||
|
||||
test("trae's main is what OpenCode 1.x and magpie's host take: plugins only", async () => {
|
||||
const pkg = JSON.parse(readFileSync(join(packages, "trae", "package.json"), "utf8"))
|
||||
const mod = await import(join(packages, "trae", pkg.main))
|
||||
const entries = Object.entries(mod)
|
||||
expect(entries.length).toBeGreaterThan(0)
|
||||
for (const [, v] of entries) expect(typeof v).toBe("function")
|
||||
for (const f of ["index.mjs", "opencode.mjs", "opencode2.mjs"]) expect(pkg.files).toContain(f)
|
||||
})
|
||||
|
||||
test("every package's opencode2.mjs is scripts/opencode2.mjs", async () => {
|
||||
const { readdirSync, existsSync } = await import("node:fs")
|
||||
const canon = readFileSync(new URL("./opencode2.mjs", import.meta.url), "utf8")
|
||||
let n = 0
|
||||
for (const name of readdirSync(packages)) {
|
||||
const f = join(packages, name, "opencode2.mjs")
|
||||
if (!existsSync(f)) continue
|
||||
n++
|
||||
expect([name, readFileSync(f, "utf8") === canon]).toEqual([name, true])
|
||||
}
|
||||
expect(n).toBeGreaterThan(20)
|
||||
})
|
||||
|
||||
// a 1.x plugin as the packages write them: an OAuth sign-in and a key, a
|
||||
// config provider with a model, its own list and a loader with its own
|
||||
// base URL, key, header and fetch
|
||||
function acme(sent) {
|
||||
return {
|
||||
AcmePlugin: async ({ client }) => ({
|
||||
auth: {
|
||||
provider: "acme",
|
||||
methods: [
|
||||
{
|
||||
type: "oauth",
|
||||
label: "Sign in with Acme",
|
||||
prompts: [{ type: "text", key: "region", message: "Region" }],
|
||||
authorize: async (inputs) => ({
|
||||
url: "https://acme.invalid/login",
|
||||
instructions: "Finish in the browser",
|
||||
method: "auto",
|
||||
callback: async () => ({ type: "success", access: "tok-" + inputs.region, refresh: "r1", expires: 1234.5, email: "a@acme.invalid" }),
|
||||
}),
|
||||
},
|
||||
{ type: "api", label: "Acme key" },
|
||||
],
|
||||
async loader(getAuth) {
|
||||
const a = await getAuth()
|
||||
return {
|
||||
baseURL: "http://127.0.0.1:9/real/v1",
|
||||
apiKey: a.access ?? a.key,
|
||||
headers: { "x-acme": "1" },
|
||||
async fetch(url, init) {
|
||||
const h = Object.fromEntries(new Headers(init.headers))
|
||||
sent.push({ url: String(url), headers: h, body: init.body })
|
||||
if (a.access === "tok-eu") await client.auth.set({ path: { id: "acme" }, body: { type: "oauth", access: "tok-eu2", refresh: "r2", expires: 99 } })
|
||||
return new Response("{}")
|
||||
},
|
||||
}
|
||||
},
|
||||
},
|
||||
config: async (cfg) => {
|
||||
cfg.provider.acme = { npm: "@ai-sdk/openai-compatible", name: "Acme", models: { m1: { name: "M1", limit: { context: 1000, output: 100 }, variants: { high: { reasoningEffort: "high" } } } } }
|
||||
// sign-in only: no package, no models
|
||||
cfg.provider["acme-usage"] = { models: {} }
|
||||
},
|
||||
provider: { id: "acme", models: async (p, { auth }) => ({ m2: { ...p.models.m1, id: "m2", name: "M2 for " + auth.email } }) },
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
test("a 1.x plugin's sign-in, models and requests on 2.x", async () => {
|
||||
const { setup } = await import(join(packages, "trae", "opencode2.mjs"))
|
||||
const sent = []
|
||||
const f = fakeContext()
|
||||
const stop = await setup(f.ctx, acme(sent))
|
||||
|
||||
// the provider, its package pinned so 2.x's sdk hook runs, and its model
|
||||
const provs = f.providers()
|
||||
expect(provs.map((p) => p.info.id)).toEqual(["acme"])
|
||||
const p = provs[0]
|
||||
expect(p.info).toMatchObject({ id: "acme", integrationID: "acme", activation: "auto", package: "aisdk:@ai-sdk/openai-compatible@2.0.41" })
|
||||
expect(p.models.map((m) => [m.id, m.name, m.limit])).toEqual([["m1", "M1", { context: 1000, output: 100 }]])
|
||||
expect(p.models[0].variants).toEqual([{ id: "high", settings: { reasoningEffort: "high" } }])
|
||||
|
||||
// the sign-ins: OAuth with its form, then the key
|
||||
expect(f.methods.map((m) => m.method.type)).toEqual(["oauth", "key"])
|
||||
// and again each time 2.x rebuilds the list: a key sign-in missing from
|
||||
// the second build left `opencode auth login` with no key method
|
||||
expect(f.rebuild().map((m) => m.method.type)).toEqual(["oauth", "key"])
|
||||
expect(f.rebuild().map((m) => m.method.type)).toEqual(["oauth", "key"])
|
||||
const oauth = f.methods[0]
|
||||
expect(oauth.method.form).toEqual([{ key: "region", type: "string", title: "Region", required: true }])
|
||||
const started = await oauth.authorize({ region: "eu" })
|
||||
expect(started).toMatchObject({ url: "https://acme.invalid/login", mode: "auto" })
|
||||
const cred = await started.callback
|
||||
expect(cred).toMatchObject({ type: "oauth", methodID: oauth.method.id, access: "tok-eu", refresh: "r1", expires: 1234 })
|
||||
expect(cred.metadata.v1).toMatchObject({ type: "oauth", access: "tok-eu", email: "a@acme.invalid" })
|
||||
expect(oauth.label(cred)).toBe("a@acme.invalid")
|
||||
|
||||
// signed in: the account's own list replaces the config's
|
||||
const connection = { type: "credential", id: "cred_1" }
|
||||
f.conns.set("acme", { connection, value: cred })
|
||||
f.emit({ type: "credential.updated", data: {} })
|
||||
await until(() => f.reloads.model > 0)
|
||||
expect(f.providers()[0].models.map((m) => m.name)).toEqual(["M2 for a@acme.invalid"])
|
||||
expect(f.providers()[0].sourceConnection).toBe(connection)
|
||||
|
||||
// a request: the SDK is made with the configured base URL and a stand-in
|
||||
// key; what goes out has the loader's URL, the account's key, the
|
||||
// loader's header, through the loader's fetch
|
||||
const hook = f.hooks.find((h) => h.filter.providerID === "acme")
|
||||
expect(hook.name).toBe("sdk")
|
||||
const options = { baseURL: p.info.settings.baseURL ?? "http://127.0.0.1:9/configured" }
|
||||
await hook.fn({ model: {}, package: p.info.package, options })
|
||||
expect(options.apiKey).not.toContain("tok")
|
||||
await options.fetch(options.baseURL + "/chat/completions", { method: "POST", headers: { authorization: `Bearer ${options.apiKey}` }, body: "{}" })
|
||||
expect(sent).toHaveLength(1)
|
||||
expect(sent[0].url).toBe("http://127.0.0.1:9/real/v1/chat/completions")
|
||||
expect(sent[0].headers).toMatchObject({ authorization: "Bearer tok-eu", "x-acme": "1" })
|
||||
|
||||
// the loader renewed the token: the next request uses it, and it is kept
|
||||
// for this credential
|
||||
expect([...f.storage.values()].map((e) => e.auth.access)).toEqual(["tok-eu2"])
|
||||
await options.fetch(options.baseURL + "/chat/completions", { method: "POST", headers: { authorization: `Bearer ${options.apiKey}` }, body: "{}" })
|
||||
expect(sent[1].headers.authorization).toBe("Bearer tok-eu2")
|
||||
|
||||
// a switch to a key account reads its own key
|
||||
f.conns.set("acme", { connection: { type: "credential", id: "cred_2" }, value: { type: "key", key: "sk-2" } })
|
||||
f.emit({ type: "credential.switched", data: { integrationID: "acme", credentialID: "cred_2" } })
|
||||
await until(() => f.reloads.model > 1)
|
||||
await options.fetch(options.baseURL + "/chat/completions", { method: "POST", headers: { authorization: `Bearer ${options.apiKey}` }, body: "{}" })
|
||||
expect(sent[2].headers.authorization).toBe("Bearer sk-2")
|
||||
stop()
|
||||
})
|
||||
|
||||
test("a 1.x code sign-in is a 2.x code sign-in", async () => {
|
||||
const { setup } = await import(join(packages, "trae", "opencode2.mjs"))
|
||||
const f = fakeContext()
|
||||
await setup(f.ctx, {
|
||||
P: async () => ({
|
||||
auth: {
|
||||
provider: "acme",
|
||||
methods: [{ type: "oauth", label: "Paste a code", authorize: async () => ({ url: "https://acme.invalid", instructions: "Paste it", method: "code", callback: async (code) => (code === "ok" ? { type: "success", access: "a", refresh: "r", expires: 1 } : { type: "failed" }) }) }],
|
||||
loader: async () => ({}),
|
||||
},
|
||||
config: async (cfg) => (cfg.provider.acme = { npm: "@ai-sdk/anthropic", models: { m: {} } }),
|
||||
}),
|
||||
})
|
||||
expect(f.providers()[0].info.package).toBe("aisdk:@ai-sdk/anthropic@ai-v6")
|
||||
const r = await f.methods[0].authorize({})
|
||||
expect(r.mode).toBe("code")
|
||||
expect((await r.callback("ok")).access).toBe("a")
|
||||
const again = await f.methods[0].authorize({})
|
||||
await expect(again.callback("bad")).rejects.toThrow()
|
||||
})
|
||||
Reference in New Issue
Block a user