Files
plugins/scripts/check.test.mjs
T
yetone 17e5ef7457 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.
2026-11-03 13:54:26 +08:00

194 lines
9.3 KiB
JavaScript

import { expect, test } from "bun:test"
import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { registryProblems } from "./registry.mjs"
// Exercise the checker in a tiny independent repository, without loading any
// 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, 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({ 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() }
} finally {
rmSync(dir, { recursive: true, force: true })
}
}
const tool = `{search: {description: "Search the web", args: {type: "object"}, execute() {}}}`
const auth = `{provider: "fixture", methods: [{type: "api", label: "API key"}]}`
test("check accepts tools with sign-in and no chat models or loader", () => {
const result = check(`export const Plugin = async () => ({
auth: ${auth}, tool: ${tool},
config: async (cfg) => { cfg.provider.fixture = {name: "Fixture", models: {}} }
})`)
expect(result.code).toBe(0)
expect(result.output).toContain("✓ fixture")
})
test("check still checks tool definitions and auth methods together", () => {
const result = check(`export const Plugin = async () => ({
auth: {provider: "fixture", methods: [{type: "unknown"}]},
tool: {search: {args: {type: "object"}}}
})`)
expect(result.code).toBe(1)
expect(result.output).toContain("search has no execute")
expect(result.output).toContain("search has no description")
expect(result.output).toContain("method type unknown")
})
test("check still requires loaders for providers, including providers with tools", () => {
for (const tools of ["", `tool: ${tool},`]) {
const result = check(`export const Plugin = async () => ({
auth: ${auth}, ${tools}
config: async (cfg) => { cfg.provider.fixture = {npm: "@ai-sdk/openai", models: {example: {}}} }
})`)
expect(result.code).toBe(1)
expect(result.output).toContain("auth.loader")
}
})
const fine = `export const Plugin = async () => ({ tool: ${tool} })`
test("check accepts quota-only providers with a loader and no model transport", () => {
const result = check(`export const Plugin = async () => ({
auth: {...${auth}, usage: async () => ({windows: []}), loader: async () => ({})},
config: async (cfg) => { cfg.provider.fixture = {name: "Fixture", models: {}} }
})`)
expect(result.code).toBe(0)
expect(result.output).toContain("✓ fixture")
})
test("quota hooks do not exempt incomplete model providers or missing loaders", () => {
for (const config of [
`{models: {}, api: "https://example.invalid/v1"}`,
`{models: {}, npm: "@ai-sdk/openai"}`,
`{models: {example: {}}}`,
]) {
const result = check(`export const Plugin = async () => ({
auth: {...${auth}, usage: async () => ({windows: []}), loader: async () => ({})},
config: async (cfg) => { cfg.provider.fixture = ${config} }
})`)
expect(result.code).toBe(1)
expect(result.output).toContain("no npm or models")
}
const result = check(`export const Plugin = async () => ({
auth: {...${auth}, usage: async () => ({windows: []})},
config: async (cfg) => { cfg.provider.fixture = {models: {}} }
})`)
expect(result.code).toBe(1)
expect(result.output).toContain("auth.loader")
})
test("check passes this repository's own registry.json", () => {
expect(registryProblems(readFileSync(new URL("../registry.json", import.meta.url), "utf8"))).toEqual([])
})
test("check fails a registry.json that is not JSON (#612)", () => {
const result = check(fine, okRegistry.slice(0, -2))
expect(result.code).toBe(1)
expect(result.output).toContain("✗ registry.json")
expect(result.output).toContain("not JSON")
expect(result.output).toContain("✓ fixture")
})
test("check fails an entry with a kind magpie doesn't know (#612)", () => {
const r = JSON.parse(okRegistry)
r.plugins[0].kind = "bogus"
const result = check(fine, JSON.stringify(r))
expect(result.code).toBe(1)
expect(result.output).toContain('kind "bogus"')
})
test("check fails a missing registry.json", () => {
const result = check(fine, null)
expect(result.code).toBe(1)
expect(result.output).toContain("registry.json is missing")
})
test("check passes a good registry.json and plugin", () => {
const result = check(fine)
expect(result.code).toBe(0)
expect(result.output).toContain("✓ registry.json")
})
// each of these loses the entry, or every entry, in magpie's reader
test("registry entries are held to what magpie's market reads", () => {
const base = { package: "@magpie-community/opencode-acme-auth", name: "Acme", community: true, providers: ["acme"], summary: { en: "Acme.", zh: "Acme。" } }
const of = (...plugins) => registryProblems(JSON.stringify({ version: 1, plugins }))
expect(of(base, { ...base, package: "tools-x", kind: "tools", providers: undefined })).toEqual([])
for (const kind of ["middleware", "hooks", "agent", "tools", "page"]) expect(of({ ...base, kind })).toEqual([])
const cases = [
[{ ...base, package: "Acme" }, "not an npm package name"],
[{ ...base, package: "@scope" }, "not an npm package name"],
[{ ...base, package: "a b" }, "not an npm package name"],
[{ ...base, package: undefined }, "not an npm package name"],
[{ ...base, name: "" }, "no name"],
[{ ...base, kind: "provider" }, 'kind "provider"'],
[{ ...base, community: "true" }, "community is not true or false"],
[{ ...base, providers: "acme" }, "providers is not a list"],
[{ ...base, providers: [] }, "providers is not a list"],
[{ ...base, icon: "http://acme.example/i.svg" }, "is not https or data:image"],
[{ ...base, summary: { en: "Acme." } }, "no summary.zh"],
[{ ...base, summary: undefined }, "no summary"],
[{ ...base, kinds: "tools" }, 'unknown field "kinds"'],
[{ ...base, replaces: 3 }, "replaces is not"],
]
for (const [entry, want] of cases) {
const got = of(JSON.parse(JSON.stringify(entry)))
expect(got.join("\n")).toContain(want)
}
expect(of(base, { ...base, name: "Again" }).join("\n")).toContain("package listed again (first at plugins[0])")
expect(registryProblems(JSON.stringify({ version: 1, plugins: [] }))).toEqual(["plugins is not a list of entries"])
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")
})