Files
yetone 397da020de opendesign 0.1.13: each model says the two other APIs amr-link serves it on
gaubeebangeel on X: OpenDesign's Anthropic request to an Open Design
Cloud model went upstream as chat completions. Each model is declared on
one wire (the thinking choice of plugins#141), and magpie translated any
other API's request to it, though amr-link serves every model on chat
completions, Responses and Anthropic's messages (plugins#888).

Each model (the config seed, a kept copy, the models hook's) now lists
the other two packages as `also`. magpie from the matching release reads
it (plugin.Model.Also) and relays a client's request on any of the three
as it was sent; the declared wire stays the model's own, which a request
on another API is translated to. signFor already signs by the request's
path. An older magpie ignores the field.

Run: bun test packages/opendesign (32 pass) with a temp HOME on mote;
root bun test with a temp HOME on mote: 8704 pass, 20 skip, 0 fail.
2026-11-14 02:05:31 +08:00

564 lines
28 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { test, expect, mock, afterEach } from "bun:test"
import {
_internal as I,
OpenDesignAuthPlugin,
} from "./index.mjs"
import { MODELS } from "./models.mjs"
import { RATES } from "./rates.mjs"
// bun test runs every package's files in one process: a fetch left
// stubbed here answers every test file after this one
const realFetch = globalThis.fetch
afterEach(() => {
mock.restore()
globalThis.fetch = realFetch
})
// ---- the sign-in it keeps ----------------------------------------------------
test("authOf keeps both keys and the account they belong to", () => {
expect(I.authOf({ id: "u1", email: "ada@example.com" }, { controlKey: "vela_ctrl_a", runtimeKey: "sk-amr-b" }))
.toEqual({ type: "success", refresh: "", expires: 0, access: "sk-amr-b", control: "vela_ctrl_a", accountId: "ada@example.com", email: "ada@example.com", uid: "u1" })
})
test("authOf is nothing without both keys", () => {
expect(I.authOf({}, { runtimeKey: "sk-amr-b" })).toBe(null)
expect(I.authOf({}, { controlKey: "vela_ctrl_a" })).toBe(null)
expect(I.authOf(null, {})).toBe(null)
})
test("a control key is not taken as a runtime key", () => {
expect(I.runtimeKeyOf({ key: "vela_ctrl_a" })).toBe("")
expect(I.runtimeKeyOf({ access: "sk-amr-b" })).toBe("sk-amr-b")
expect(I.controlKeyOf({ key: "vela_ctrl_a" })).toBe("vela_ctrl_a")
expect(I.controlKeyOf({ metadata: { control: "vela_ctrl_c" } })).toBe("vela_ctrl_c")
expect(I.controlKeyOf({ access: "sk-amr-b" })).toBe("")
})
test("the poll takes the approval's keys, and says so when the code runs out", async () => {
const calls = []
globalThis.fetch = async (url, init) => {
calls.push(String(url))
const n = calls.length
const body = n < 2
? { status: "pending", controlKey: null, runtimeKey: null, user: null }
: { status: "approved", controlKey: "vela_ctrl_a", runtimeKey: "sk-amr-b", user: { id: "u1", email: "ada@example.com" } }
return new Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json" } })
}
const got = await I.waitForDevice({ deviceId: "d1", deviceSecret: "s1", interval: 0, until: Date.now() + 5000 }, { sleep: async () => {} })
expect(got).toMatchObject({ access: "sk-amr-b", control: "vela_ctrl_a", accountId: "ada@example.com", uid: "u1" })
expect(calls[0]).toBe("https://amr-api.open-design.ai/api/v1/cli/device-authorizations/d1/token")
globalThis.fetch = async () => new Response(JSON.stringify({ status: "expired" }), { status: 200 })
await expect(I.waitForDevice({ deviceId: "d2", deviceSecret: "s2", interval: 0, until: Date.now() + 5000 }, { sleep: async () => {} }))
.rejects.toThrow(/expired/)
globalThis.fetch = async () => new Response(JSON.stringify({ error: "invalid_device_secret" }), { status: 401 })
await expect(I.waitForDevice({ deviceId: "d3", deviceSecret: "s3", interval: 0, until: Date.now() + 5000 }, { sleep: async () => {} }))
.rejects.toThrow(/no longer valid/)
})
// ---- what the dashboard shows ------------------------------------------------
// one reading of /workspaces/{id}/billing/preflight, as the control plane
// answers it
const PREFLIGHT = {
balanceUsd: "1.5000",
funding: "wallet",
codingPlan: {
eligible: true,
tier: "go",
// out of order on purpose: the plugin's own sort is what puts the 5-hour
// window first, as the vendor's card shows them
windows: [
{ durationSeconds: 604800, usedCredits: "16251", limitCredits: "150000", resetsAt: "2026-10-18T06:36:14.000Z" },
{ durationSeconds: 18000, usedCredits: "16251", limitCredits: "50000", resetsAt: "2026-10-11T11:36:14.000Z" },
],
},
}
test("the plan's windows become magpie's, shortest first", () => {
expect(I.allowances(PREFLIGHT.codingPlan)).toEqual([
{ name: "5 hours", used: 32.5, span: 18000, resetsAt: "2026-10-11T11:36:14.000Z", display: "16.3k / 50k credits" },
{ name: "7 days", used: 10.8, span: 604800, resetsAt: "2026-10-18T06:36:14.000Z", display: "16.3k / 150k credits" },
])
})
test("a window with nothing to divide is left out", () => {
expect(I.allowances({ windows: [{ durationSeconds: 18000, usedCredits: "3", limitCredits: "0" }] })).toEqual([])
expect(I.allowances(null)).toEqual([])
})
test("window names follow the vendor's own card", () => {
expect(I.windowName(18000)).toBe("5 hours")
expect(I.windowName(604800)).toBe("7 days")
expect(I.windowName(3600)).toBe("1 hour")
expect(I.windowName(86400)).toBe("1 day")
expect(I.windowName(900)).toBe("15 minutes")
expect(I.windowName(0)).toBe("Allowance")
})
test("credits are shown short", () => {
expect(I.credits("16251")).toBe("16.3k")
expect(I.credits("9999")).toBe("9999")
expect(I.credits("477")).toBe("477")
expect(I.credits("150000")).toBe("150k")
expect(I.credits("2340000")).toBe("2.3M")
expect(I.credits(undefined)).toBe("")
})
test("the plan reads as the dashboard names it", () => {
expect(I.thePlan({ membershipTier: "go" }, "")).toBe("Design Plan Go")
expect(I.thePlan(null, "pro")).toBe("Design Plan Pro")
expect(I.thePlan(null, "")).toBe("Open Design")
})
test("the wallet shows as dollars", () => {
expect(I.money("1.5000")).toBe("$1.50")
expect(I.money(undefined)).toBe("")
})
// ---- the account's models ----------------------------------------------------
// one reading of amr-link's /v1/models
const CATALOG = {
data: [
{
id: "gpt-6-luna",
architecture: { input_modalities: ["text", "image", "file"], output_modalities: ["text"] },
metadata: { cost: "low", capability: "standard", context_limit: 1050000, context_budget: 304000 },
},
{
id: "deepseek-v4-pro",
architecture: { input_modalities: ["text"], output_modalities: ["text"] },
metadata: { cost: "high", capability: "advanced", context_limit: 1048000, context_budget: 232000 },
},
{ id: "brand-new-9", architecture: { input_modalities: ["text", "image"] }, metadata: { cost: "medium", capability: "advanced" } },
],
}
// what magpie's plugin host reads off a model provider.models gives back
// (internal/plugin/host.js, providers()): its thinking from
// capabilities.reasoning, its levels from the variants' names
const asMagpieReads = (m) => ({
reasoning: !!m.capabilities?.reasoning,
variants: Object.keys(m.variants ?? {}),
image: !!m.capabilities?.input?.image,
})
test("the account's list is the vendor's own, live", () => {
const models = I.modelsOf(CATALOG)
expect(Object.keys(models)).toEqual(["gpt-6-luna", "deepseek-v4-pro", "brand-new-9"])
expect(models["gpt-6-luna"]).toEqual({
id: "gpt-6-luna",
name: "GPT-6 Luna",
api: { id: "gpt-6-luna", url: "https://amr-link.open-design.ai/v1", npm: "@ai-sdk/openai-compatible" },
also: ["@ai-sdk/openai", "@ai-sdk/anthropic"],
status: "active",
headers: {},
options: {},
cost: { input: 0, output: 0, cache: { read: 0, write: 0 } },
limit: { context: 1050000, output: 304000 },
capabilities: {
temperature: true,
reasoning: false,
attachment: true,
toolcall: true,
input: { text: true, image: true, audio: false, video: false, pdf: false },
output: { text: true, image: false, audio: false, video: false, pdf: false },
interleaved: false,
},
release_date: "",
variants: {},
rate: "x4",
})
expect(models["deepseek-v4-pro"]).toMatchObject({ rate: "x1", limit: { context: 1048000, output: 232000 } })
// a model the seed doesn't know is named by its id, and a catalog entry
// without limits still gets a workable entry
expect(models["brand-new-9"]).toMatchObject({
id: "brand-new-9",
name: "brand-new-9",
rate: "x1",
limit: { context: 200000, output: 32000 },
})
})
// #137 (sryimnoob123): amr-link took reasoning_effort low and high (max too,
// plugins#141) on all 11
// models, and every one but GPT-6 Luna thought at it, "standard" or not
test("a signed-in account's models reason at the levels amr-link took (#137)", () => {
const models = I.modelsOf(CATALOG)
expect(asMagpieReads(models["deepseek-v4-pro"])).toEqual({ reasoning: true, variants: ["low", "high", "max"], image: false })
expect(models["deepseek-v4-pro"].variants).toEqual({ low: { reasoningEffort: "low" }, high: { reasoningEffort: "high" }, max: { reasoningEffort: "max" } })
// took the level and never thought at it
expect(asMagpieReads(models["gpt-6-luna"])).toEqual({ reasoning: false, variants: [], image: true })
// "advanced" but never measured: it reasons, at no level said for it
expect(asMagpieReads(models["brand-new-9"])).toEqual({ reasoning: true, variants: [], image: true })
// the catalog calls these "standard"; they thought at both levels
const standard = I.modelsOf({
data: ["claude-haiku-5.5", "deepseek-v4-flash", "deepseek-v4-flash-vision-exp", "mimo-v2.6-flash"].map((id) => ({ id, metadata: { capability: "standard" } })),
})
for (const m of Object.values(standard)) expect(asMagpieReads(m)).toMatchObject({ reasoning: true, variants: ["low", "high", "max"] })
})
test("the seed's models carry the measured levels as the config's variants", async () => {
const hooks = await OpenDesignAuthPlugin({})
const cfg = {}
await hooks.config(cfg)
const models = cfg.provider.opendesign.models
const levels = Object.fromEntries(Object.entries(models).map(([id, m]) => [id, m.reasoning ? Object.keys(m.variants ?? {}) : null]))
expect(levels).toEqual({
"claude-haiku-5.5": ["low", "high", "max"],
"deepseek-v4-flash": ["low", "high", "max"],
"deepseek-v4-flash-vision-exp": ["low", "high", "max"],
"deepseek-v4-pro": ["low", "high", "max"],
"deepseek-v4.1-flash": ["low", "high", "max"],
"deepseek-v4.1-flash-eco": ["low", "high", "max"],
"glm-5.3-flash": ["low", "high", "max"],
"glm-5.3-flashx": ["low", "high", "max"],
"gpt-6-luna": null,
"kimi-k2.7-code": ["low", "high", "max"],
"mimo-v2.6-flash": ["low", "high", "max"],
"mimo-v2.6-pro": ["low", "high", "max"],
})
expect(models["claude-haiku-5.5"].variants.high).toEqual({ reasoningEffort: "high" })
})
test("the seed gives the eco schedule the model V4.1 Flash is", () => {
const { "deepseek-v4.1-flash": flash, "deepseek-v4.1-flash-eco": eco } = MODELS
expect(eco).toEqual({ ...flash, name: "DeepSeek V4.1 Flash Eco" })
expect(Object.keys(MODELS)).toContain("deepseek-v4.1-flash-eco")
})
// the plan's deduction multipliers, "额度扣除倍率", published at
// https://open-design.ai/zh/model-credits/ (read 2026-11-06)
test("the plan's multipliers are the vendor's own table, not the catalog's cost words", () => {
expect(RATES).toEqual({
"claude-haiku-5.5": 2,
"deepseek-v4-flash": 1,
"deepseek-v4-flash-vision-exp": 1,
"deepseek-v4-pro": 1,
"deepseek-v4.1-flash": 0.5,
"deepseek-v4.1-flash-eco": 0.27,
"glm-5.3-flash": 1,
"glm-5.3-flashx": 2,
"gpt-6-luna": 4,
"hy4-preview": 1,
"kimi-k2.7-code": 1,
"mimo-v2.6-flash": 1,
"mimo-v2.6-pro": 1,
"minimax-m3.1-flash": 1,
})
// each seed model is rated by the table; a model it doesn't name keeps the
// catalog's word (brand-new-9 below, and any model the vendor adds later)
const WORD = {
"claude-haiku-5.5": ["low", "x2"],
"gpt-6-luna": ["low", "x4"],
"glm-5.3-flash": ["low", "x1"],
"glm-5.3-flashx": ["medium", "x2"],
"deepseek-v4-pro": ["high", "x1"],
"deepseek-v4.1-flash": ["low", "x0.5"],
"deepseek-v4.1-flash-eco": ["low", "x0.27"],
"brand-new-9": ["high", "x2"],
}
const models = I.modelsOf({ data: Object.entries(WORD).map(([id, [cost]]) => ({ id, metadata: { cost } })) })
for (const [id, [, rate]] of Object.entries(WORD)) expect([id, models[id].rate]).toEqual([id, rate])
})
test("a kept model's rate is re-declared, so a charge an earlier version wrote can't linger", async () => {
const kept = {
provider: {
opendesign: {
models: {
"gpt-6-luna": { id: "gpt-6-luna", name: "GPT-6 Luna", rate: "x0.5" },
"brand-new-9": { id: "brand-new-9", name: "brand-new-9", rate: "x1" },
},
},
},
}
await (await OpenDesignAuthPlugin({})).config(kept)
const models = kept.provider.opendesign.models
expect(models["gpt-6-luna"].rate).toBe("x4")
// a kept name is still kept
expect(models["gpt-6-luna"].name).toBe("GPT-6 Luna")
// a model the table doesn't name keeps the rate it had
expect(models["brand-new-9"].rate).toBe("x1")
})
// #827 (Gitleonan): amr-link's catalog publishes more output than its API
// takes for two models, and asking for the published number is a 400 that
// names no field. The catalog entries are the reporter's numbers; the caps
// are what they measured on 2026-11-09 (131072 and 65536 taken, one more
// refused).
test("a model's output is capped where amr-link takes less than its catalog says (#827)", async () => {
const models = I.modelsOf({
data: [
{ id: "glm-5.3-flash", architecture: { input_modalities: ["text", "image", "video"] }, metadata: { cost: "low", capability: "advanced", context_limit: 1048000, context_budget: 232000 } },
{ id: "gemini-3.8-flash", architecture: { input_modalities: ["text"] }, metadata: { cost: "low", capability: "standard", context_limit: 1048576, context_budget: 264000 } },
// a catalog that says less than the cap is taken as it says
{ id: "deepseek-v4.1-flash", metadata: { context_limit: 1048000, context_budget: 232000 } },
],
})
expect(models["glm-5.3-flash"].limit).toEqual({ context: 1048000, output: 131072 })
expect(models["gemini-3.8-flash"].limit).toEqual({ context: 1048576, output: 65536 })
expect(models["deepseek-v4.1-flash"].limit.output).toBe(232000)
expect(I.modelsOf({ data: [{ id: "glm-5.3-flash", metadata: { context_budget: 100000 } }] })["glm-5.3-flash"].limit.output).toBe(100000)
// the seed, and a copy an earlier version kept with the catalog's number
const cfg = { provider: { opendesign: { models: { "gemini-3.8-flash": { id: "gemini-3.8-flash", name: "gemini-3.8-flash", limit: { context: 1048576, output: 264000 } } } } } }
await (await OpenDesignAuthPlugin({})).config(cfg)
const served = cfg.provider.opendesign.models
expect(served["glm-5.3-flash"].limit.output).toBe(131072)
expect(served["gemini-3.8-flash"].limit).toEqual({ context: 1048576, output: 65536 })
expect(served["deepseek-v4.1-flash"].limit.output).toBe(232000)
})
// #829 (exposir): the signed-in catalog's DeepSeek V4.1 Flash Eco entry
// left image out, so it was served text-only and magpie sent another model's
// description of the image instead, while amr-link took the image itself
test("a kind the seed declares stays when the catalog leaves it out (#829)", () => {
const models = I.modelsOf({
data: [
// listed, text only
{ id: "deepseek-v4.1-flash-eco", architecture: { input_modalities: ["text"] }, metadata: { cost: "low", capability: "advanced", context_limit: 1048000, context_budget: 232000 } },
// no architecture at all, nor limits or words
{ id: "glm-5.3-flashx" },
// the catalog's own kinds add to the seed's
{ id: "kimi-k2.7-code", architecture: { input_modalities: ["text", "image", "video"] } },
// a model the seed says takes text only stays text only
{ id: "deepseek-v4-pro", architecture: { input_modalities: ["text"] } },
// a model the seed doesn't know is the catalog's alone
{ id: "brand-new-9", architecture: { input_modalities: ["text"] } },
],
})
const input = (id) => Object.entries(models[id].capabilities.input).filter(([, on]) => on).map(([k]) => k)
expect(asMagpieReads(models["deepseek-v4.1-flash-eco"]).image).toBe(true)
expect(input("deepseek-v4.1-flash-eco")).toEqual(["text", "image"])
expect(input("glm-5.3-flashx")).toEqual(["text", "image", "video"])
expect(input("kimi-k2.7-code")).toEqual(["text", "image", "video"])
expect(input("deepseek-v4-pro")).toEqual(["text"])
expect(input("brand-new-9")).toEqual(["text"])
// the limits and words the catalog leaves out are the seed's, not 200K/32K
expect(models["glm-5.3-flashx"].limit).toEqual({ context: 1000000, output: 232000 })
expect(models["glm-5.3-flashx"].rate).toBe("x2")
expect(models["brand-new-9"].limit).toEqual({ context: 200000, output: 32000 })
})
test("an empty catalog is no models", () => {
expect(I.modelsOf({ data: [] })).toEqual({})
expect(I.modelsOf(null)).toEqual({})
})
test("each model is asked on the API amr-link thinks on (plugins#141)", async () => {
expect(I.modelsOf(CATALOG)["deepseek-v4-pro"].api.npm).toBe("@ai-sdk/openai")
expect(I.modelsOf(CATALOG)["gpt-6-luna"].api.npm).toBe("@ai-sdk/openai-compatible")
// a model kept from 0.1.5, which put every model on the Responses API,
// is moved to its own wire
const kept = { "glm-5.3-flash": { id: "glm-5.3-flash", name: "GLM", provider: { npm: "@ai-sdk/openai" }, api: { npm: "@ai-sdk/openai" } } }
const cfg = { provider: { opendesign: { npm: "@ai-sdk/openai", models: kept } } }
await (await OpenDesignAuthPlugin({})).config(cfg)
const p = cfg.provider.opendesign
expect(p.npm).toBe("@ai-sdk/openai-compatible")
expect(p.models["glm-5.3-flash"].provider.npm).toBe("@ai-sdk/anthropic")
expect(p.models["glm-5.3-flash"].api.npm).toBe("@ai-sdk/anthropic")
expect(p.models["glm-5.3-flash"].name).toBe("GLM")
expect(p.models["claude-haiku-5.5"].provider.npm).toBe("@ai-sdk/openai")
expect(p.models["kimi-k2.7-code"].provider.npm).toBe("@ai-sdk/openai-compatible")
})
test("each model says the two other APIs amr-link serves it on (plugins#888)", async () => {
// magpie relays a client's request on any of them as it was sent: an
// Anthropic request to a chat model went upstream as chat completions
// (gaubeebangeel on X)
const models = I.modelsOf(CATALOG)
expect(models["gpt-6-luna"].also).toEqual(["@ai-sdk/openai", "@ai-sdk/anthropic"])
expect(models["deepseek-v4-pro"].also).toEqual(["@ai-sdk/openai-compatible", "@ai-sdk/anthropic"])
const cfg = {}
await (await OpenDesignAuthPlugin({})).config(cfg)
expect(cfg.provider.opendesign.models["glm-5.3-flash"].also).toEqual(["@ai-sdk/openai-compatible", "@ai-sdk/openai"])
expect(cfg.provider.opendesign.models["deepseek-v4.1-flash"].also).toEqual(["@ai-sdk/openai", "@ai-sdk/anthropic"])
})
// ---- what magpie is given ----------------------------------------------------
test("the plugin declares the provider and answers its methods", async () => {
const hooks = await OpenDesignAuthPlugin({})
const cfg = {}
await hooks.config(cfg)
expect(cfg.provider.opendesign).toMatchObject({
name: "Open Design",
npm: "@ai-sdk/openai-compatible",
api: "https://amr-link.open-design.ai/v1",
})
// the seed models.mjs carries, which a signed-in account's list replaces
expect(Object.keys(cfg.provider.opendesign.models)).toHaveLength(12)
expect(cfg.provider.opendesign.models["deepseek-v4.1-flash"]).toEqual({
id: "deepseek-v4.1-flash",
name: "DeepSeek V4.1 Flash",
api: { npm: "@ai-sdk/openai-compatible" },
provider: { npm: "@ai-sdk/openai-compatible" },
also: ["@ai-sdk/openai", "@ai-sdk/anthropic"],
attachment: true,
tool_call: true,
reasoning: true,
variants: { low: { reasoningEffort: "low" }, high: { reasoningEffort: "high" }, max: { reasoningEffort: "max" } },
rate: "x0.5",
limit: { context: 1048000, output: 232000 },
modalities: { input: ["text", "image"], output: ["text"] },
})
// the eco schedule is the same model: same limits, same levels, its own 0.27×
expect(cfg.provider.opendesign.models["deepseek-v4.1-flash-eco"]).toEqual({
...cfg.provider.opendesign.models["deepseek-v4.1-flash"],
id: "deepseek-v4.1-flash-eco",
name: "DeepSeek V4.1 Flash Eco",
rate: "x0.27",
})
expect(hooks.auth.provider).toBe("opendesign")
expect(hooks.auth.methods.map((m) => m.type)).toEqual(["oauth", "api"])
expect(hooks.provider.id).toBe("opendesign")
})
test("the loader hands the runtime key to the model plane", async () => {
const hooks = await OpenDesignAuthPlugin({})
const o = await hooks.auth.loader(async () => ({ access: "sk-amr-b", control: "vela_ctrl_a" }))
expect(o).toMatchObject({ baseURL: "https://amr-link.open-design.ai/v1", apiKey: "sk-amr-b" })
expect(typeof o.fetch).toBe("function")
expect(await hooks.auth.loader(async () => null)).toEqual({})
})
// keyblues (plugins#888): amr-link serves every model on chat completions,
// Responses and Anthropic's messages. The host signs a request with the
// header of the package the model is declared on, so a model asked on
// another API than its own must be signed for the API it is asked on.
test("a model asked on any of the three APIs is signed as that API takes the key (plugins#888)", async () => {
const seen = []
globalThis.fetch = async (url, init) => {
const h = new Headers(init?.headers)
seen.push({ url: url instanceof Request ? url.url : String(url), auth: h.get("authorization"), xkey: h.get("x-api-key"), version: h.get("anthropic-version"), body: init?.body })
return new Response("{}", { status: 200 })
}
const hooks = await OpenDesignAuthPlugin({})
const { fetch: send } = await hooks.auth.loader(async () => ({ access: "sk-amr-b", control: "vela_ctrl_a" }))
const base = "https://amr-link.open-design.ai/v1"
// kimi-k2.7-code is declared on chat completions, so the host sent the
// Bearer header: asked on Anthropic's messages it goes with x-api-key
await send(base + "/messages", { method: "POST", headers: { authorization: "Bearer sk-amr-b", "content-type": "application/json" }, body: '{"model":"kimi-k2.7-code"}' })
await send(base + "/messages/count_tokens", { method: "POST", headers: { authorization: "Bearer sk-amr-b" }, body: "{}" })
// glm-5.3-flash is declared on Anthropic's messages: asked on chat
// completions or Responses it goes with the Bearer
await send(base + "/chat/completions", { method: "POST", headers: { "x-api-key": "sk-amr-b", "anthropic-version": "2023-06-01" }, body: '{"model":"glm-5.3-flash"}' })
await send(new Request(base + "/responses", { method: "POST", headers: { "x-api-key": "sk-amr-b" }, body: "{}" }))
expect(seen.map(({ url, auth, xkey }) => [url.replace(base, ""), auth, xkey])).toEqual([
["/messages", null, "sk-amr-b"],
["/messages/count_tokens", null, "sk-amr-b"],
["/chat/completions", "Bearer sk-amr-b", null],
["/responses", "Bearer sk-amr-b", null],
])
// Anthropic's messages carry a version, the client's own when it sent one
expect(seen[0].version).toBe("2023-06-01")
expect(seen[0].body).toBe('{"model":"kimi-k2.7-code"}')
// the declared API's own requests go as they did
await send(base + "/messages", { method: "POST", headers: { "x-api-key": "sk-amr-b", "anthropic-version": "2024-01-01" }, body: "{}" })
expect([seen[4].auth, seen[4].xkey, seen[4].version]).toEqual([null, "sk-amr-b", "2024-01-01"])
})
test("the account's models are read at its own key", async () => {
const hooks = await OpenDesignAuthPlugin({})
const seen = []
globalThis.fetch = async (url, init) => {
seen.push([String(url), new Headers(init.headers).get("authorization")])
return new Response(JSON.stringify(CATALOG), { status: 200, headers: { "content-type": "application/json" } })
}
const given = { models: {} }
const models = await hooks.provider.models(given, { auth: { access: "sk-amr-b", control: "vela_ctrl_a" } })
expect(seen).toEqual([["https://amr-link.open-design.ai/v1/models", "Bearer sk-amr-b"]])
expect(Object.keys(models)).toEqual(["gpt-6-luna", "deepseek-v4-pro", "brand-new-9"])
// a vendor that refuses the key marks the account
globalThis.fetch = async () => new Response(JSON.stringify({ error: { message: "invalid_api_key" } }), { status: 401 })
await expect(hooks.provider.models(given, { auth: { access: "sk-amr-b" } })).rejects.toThrow(/invalid_api_key/)
// a vendor hiccup keeps the list magpie had
globalThis.fetch = async () => new Response("{}", { status: 500 })
expect(await hooks.provider.models(given, { auth: { access: "sk-amr-b" } })).toBe(given.models)
// nothing signed in: the list it was given
expect(await hooks.provider.models(given, { auth: null })).toBe(given.models)
})
test("usage reads the plan, the wallet and the windows at the control key", async () => {
const hooks = await OpenDesignAuthPlugin({})
const seen = []
globalThis.fetch = async (url, init) => {
const u = String(url)
seen.push([u, new Headers(init.headers).get("authorization")])
if (u.endsWith("/api/v1/workspaces/current")) return new Response(JSON.stringify({ activeWorkspaceId: "ws1", personalMembershipTier: "go" }), { status: 200 })
if (u.includes("/billing/preflight")) return new Response(JSON.stringify(PREFLIGHT), { status: 200 })
if (u.includes("/billing/summary")) {
return new Response(JSON.stringify({
membershipTier: "go",
subscriptionStatus: "active",
subscriptionCancelAtPeriodEnd: false,
subscriptionCurrentPeriodEnd: "2026-11-11T06:36:14.000Z",
balanceUsd: "1.5000",
}), { status: 200 })
}
return new Response("{}", { status: 404 })
}
const auth = { access: "sk-amr-b", control: "vela_ctrl_a", email: "ada@example.com" }
expect(await hooks.auth.usage(async () => auth)).toEqual({
plan: "Design Plan Go",
user: "ada@example.com",
balance: "$1.50",
until: "2026-11-11T06:36:14.000Z",
renew: "auto",
windows: [
{ name: "5 hours", used: 32.5, span: 18000, resetsAt: "2026-10-11T11:36:14.000Z", display: "16.3k / 50k credits" },
{ name: "7 days", used: 10.8, span: 604800, resetsAt: "2026-10-18T06:36:14.000Z", display: "16.3k / 150k credits" },
],
signIn: "kept",
})
expect(seen.every(([, key]) => key === "Bearer vela_ctrl_a")).toBe(true)
})
test("usage says a refused sign-in marks the account, and that an API key has none", async () => {
const hooks = await OpenDesignAuthPlugin({})
globalThis.fetch = async (url) => (String(url).endsWith("/workspaces/current")
? new Response(JSON.stringify({ activeWorkspaceId: "ws1" }), { status: 200 })
: new Response(JSON.stringify({ error: "unauthenticated" }), { status: 401 }))
expect(await hooks.auth.usage(async () => ({ access: "sk-amr-b", control: "vela_ctrl_a" })))
.toMatchObject({ signIn: "expired", windows: [] })
expect(await hooks.auth.usage(async () => ({ access: "sk-amr-b" })))
.toMatchObject({ signIn: "kept", windows: [], error: expect.stringMatching(/API key/) })
})
test("the API key method takes the key as it is", async () => {
const hooks = await OpenDesignAuthPlugin({})
const m = hooks.auth.methods.find((x) => x.type === "api")
expect(m.type).toBe("api")
// magpie's own prompt saves what the user pasted; the plugin adds nothing
expect(m.authorize).toBeUndefined()
})
test("everything the manifest ships is on disk", async () => {
// `files` naming a file that isn't there ships a package missing it, which
// is how 0.1.2 went out without refresh-models.mjs. The manifest is found
// by walking up, so this file works in `test/` and at a package root alike.
const { existsSync } = await import("node:fs")
const { dirname, join } = await import("node:path")
const { fileURLToPath } = await import("node:url")
let root = dirname(fileURLToPath(import.meta.url))
while (!existsSync(join(root, "package.json"))) {
const up = dirname(root)
if (up === root) throw new Error("no package.json above this test")
root = up
}
const pkg = await Bun.file(join(root, "package.json")).json()
for (const f of pkg.files) expect(existsSync(join(root, f))).toBe(true)
// the plugin's own imports are among them (npm ships package.json itself,
// whatever `files` says)
const src = await Bun.file(join(root, pkg.main ?? "index.mjs")).text()
const imports = [...src.matchAll(/from "\.\/([^"]+)"/g)].map((m) => m[1]).filter((f) => f !== "package.json")
expect(imports.length).toBeGreaterThan(0)
for (const spec of imports) expect(pkg.files).toContain(spec)
})