From 3db704a6770a0fcb9cd0b5c0df43912d6135ea9f Mon Sep 17 00:00:00 2001 From: dbydd <44134872+dbydd@users.noreply.github.com> Date: Thu, 15 Oct 2026 06:44:45 +0800 Subject: [PATCH] opendesign 0.1.4: Open Design Cloud (Design Plan) as a provider (#84, dbydd) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New package @magpie-community/opencode-opendesign-auth 0.1.4, provider id `opendesign`: an Open Design Cloud account's Design Plan as a magpie provider (dbydd, #84). Reviewed at this head (37ef688), as in the PR's last review: `HOME= bun test` for packages/opendesign, 19 pass; `bun scripts/check.mjs opendesign` ✓; the package loads under Node and Bun; `npm pack --dry-run` packs 5 files; a stubbed usage call sent its User-Agent to amr-api.open-design.ai only. The only hosts in it are amr-api.open-design.ai and amr-link.open-design.ai, with no install script, child process, or write outside OpenCode's auth store. It no longer waits on its first npm publish: the publish workflow packs it onto the dist branch, and magpie 0.1.1243 and later install it from there until npm has it. --- README.md | 1 + packages/opendesign/README.md | 122 +++++++ packages/opendesign/index.mjs | 421 +++++++++++++++++++++++++ packages/opendesign/index.test.mjs | 300 ++++++++++++++++++ packages/opendesign/models.mjs | 23 ++ packages/opendesign/package.json | 29 ++ packages/opendesign/refresh-models.mjs | 102 ++++++ registry.json | 2 + 8 files changed, 1000 insertions(+) create mode 100644 packages/opendesign/README.md create mode 100644 packages/opendesign/index.mjs create mode 100644 packages/opendesign/index.test.mjs create mode 100644 packages/opendesign/models.mjs create mode 100644 packages/opendesign/package.json create mode 100644 packages/opendesign/refresh-models.mjs diff --git a/README.md b/README.md index eae57ff..c37045e 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ subscription and makes its requests. The packages work in OpenCode and in | [minimax](packages/minimax) | MiniMax Code (China): account credits and M Plan, with MiniMax Code's device sign-in | `minimax-code` | | [minimax](packages/minimax) | MiniMax Code (international): account credits and M Plan, with MiniMax Code's device sign-in | `minimax-code-global` | | [mimo](packages/mimo) | Xiaomi MiMo, with a Xiaomi account | `mimo-app` | +| [opendesign](packages/opendesign) | Open Design Cloud (open-design.ai), with the Open Design CLI's device sign-in | `opendesign` | | [qoder](packages/qoder) | Qoder subscription (qoder.com), with Qoder's device sign-in | `qoder` | | [qoder](packages/qoder) | Qoder CN subscription (qoder.cn), with Qoder CN's device sign-in | `qoder-cn` | | [trae](packages/trae) | Trae CN (trae.cn) and Trae international (trae.ai), free tier included, with Trae's browser sign-in (experimental) | `trae-cn`, `trae-global` | diff --git a/packages/opendesign/README.md b/packages/opendesign/README.md new file mode 100644 index 0000000..6d10fc8 --- /dev/null +++ b/packages/opendesign/README.md @@ -0,0 +1,122 @@ +# @magpie-community/opencode-opendesign-auth + +Open Design (open-design.ai) Cloud as a magpie / OpenCode provider: sign in +with the Open Design account, use the models its **Design Plan** entitles the +account to, and watch the plan's **5-hour and 7-day allowance** and wallet +balance where every other subscription's usage shows. + +Works in [magpie](https://usemagpie.ai) (which runs OpenCode provider plugins) +and in OpenCode. + +``` +magpie plugin add @magpie-community/opencode-opendesign-auth +magpie plugin login opendesign +``` + +In OpenCode, `opencode.json`: + +```json +{ "plugin": ["@magpie-community/opencode-opendesign-auth"] } +``` + +then `opencode auth login`. + +## What it signs in to + +Open Design's cloud is two planes: + +| Plane | Host | Key | Used for | +| --- | --- | --- | --- | +| Control | `amr-api.open-design.ai` | `vela_ctrl_…` | plan, wallet balance, the Design Plan's allowance windows, the workspace | +| Model | `amr-link.open-design.ai/v1` | `sk-amr-…` | `/models`, `/responses` (the OpenAI Responses API) | + +A sign-in is the same device authorization the Open Design CLI +(`vela login`) runs: + +1. the plugin POSTs `/api/v1/cli/device-authorizations` and gets a code + (`4HYFNA`) and an activation page (`open-design.ai/cloud/cli/activate?…`); +2. magpie opens that page; approving it says the CLI is signing in; +3. the plugin polls it and receives both keys for that account, with the + account's email and id. + +Nothing else is needed, and nothing of the desktop app's own sign-in +(`~/.amr/config.json`, a different machine-issued pair of keys) is read or +written. + +## Sign-in methods + +| Method | What it stores | Allowance | +| --- | --- | --- | +| **Open Design account** | the account's control + runtime keys | 5-hour and 7-day windows, wallet balance, plan | +| **Open Design API key** | a pasted `sk-amr-…` key | not readable: `amr-api` doesn't take API keys | + +The account sign-in is the one that shows the allowance; the API key one +is there for a machine that can't open the approval page. + +## Models + +Nothing is listed per account at request time from anywhere but the vendor: +magpie calls the plugin's `provider.models`, which reads `amr-link`'s live +`/v1/models` at that account's key on every listing, so what a signed-in +account is offered is what its plan entitles it to right now. Limits, input +modalities and the vendor's own cost words (`rate`, e.g. `x0.5` for "low") +come from that same catalog; a model whose vendor tier is `advanced` is +marked as one that reasons. + +`models.mjs` is the seed the provider has *before* anyone signs in. Refresh +it from the live catalog with: + +```bash +magpie plugin login opendesign # once, so the key is on hand +bun refresh-models.mjs # or OPENDESIGN_KEY=sk-amr-… bun … +``` + +The script keeps the names already chosen — the catalog carries ids only — +and reads nothing else: no secret is written to the file or printed. + +Requests go to the **Responses** API (`@ai-sdk/openai` at +`https://amr-link.open-design.ai/v1`), which is what an Open Design API key +page recommends for Codex-style clients and what keeps thinking intact. + +## Where the sign-in is kept + +magpie's `plugin-auth.json` (mode 600), as an oauth account: +`{ type: "oauth", access: , control: , accountId: +, uid: }`. Neither key expires, so there is nothing to +renew and `refresh` is empty. + +## Use + +``` +magpie plugin # opendesign (Open Design, 11 models) signed in +magpie provider test opendesign +magpie quota # opendesign · Design Plan Go · 5h 32% ↻3h +``` + +### Replacing a custom provider + +The plugin signs in to the provider id `opendesign`. A **custom provider** +of that same id (Providers → the host and key by hand) takes the id first, +so the plugin's provider is then listed as `opendesign-plugin`, with no +models of its own. Delete the custom provider — `magpie provider rm +opendesign` — and the plugin's provider takes the plain id, so agent +configs pointing at `opendesign/` keep working, now with the +allowance card. + +## The allowance in routing + +The windows are gating windows (magpie's `aside` is left off), so magpie's +own routing reads them like any subscription's: + +* a window magpie reads as used up makes the account count as used up, so + routing groups skip it and a direct call to `opendesign/` is refused + with a 429 until that window renews; +* `magpie provider account-cap opendesign [percent|off]` holds the + account at a share of each window, and `--window "5 hours" 70` caps one + window alone, which is how to leave headroom instead of spending the plan + to the last credit. + +Since Open Design falls back to the wallet balance once the Design Plan +allowance is out, an exhausted window holds the account rather than spending +the wallet. Set the account to spend its credits, or cap the windows, to +choose which of the two magpie does. diff --git a/packages/opendesign/index.mjs b/packages/opendesign/index.mjs new file mode 100644 index 0000000..a8ad229 --- /dev/null +++ b/packages/opendesign/index.mjs @@ -0,0 +1,421 @@ +// Open Design (open-design.ai) Cloud, as its own CLI signs in to it: the +// sign-in is a device authorization at the Vela control plane +// (amr-api.open-design.ai), which answers with two keys — a control key +// (vela_ctrl_…) for the account's plan and its Design Plan allowance, and a +// runtime key (sk-amr-…) that the model plane (amr-link.open-design.ai) +// takes. Model requests are the OpenAI Responses API at the runtime key; +// the model list, the plan and the 5-hour and 7-day allowance windows all +// come from the control plane. +// +// Not to be confused with the OpenDesign desktop app on this machine: it +// keeps its own sign-in in ~/.amr/config.json, a different (machine-issued) +// pair of keys, and this plugin never touches it. + +import { hostname } from "node:os" + +// JSON modules have a default export only, in Bun as in Node +import pkg from "./package.json" with { type: "json" } + +import { MODELS } from "./models.mjs" + +const ID = "opendesign" +const CONTROL = "https://amr-api.open-design.ai" +const LINK = "https://amr-link.open-design.ai/v1" +const NPM = "@ai-sdk/openai" // the Responses API, at LINK +const SOURCE = "opencode-opendesign-auth/" + pkg.version // as the manifest has it +const CLI_VERSION = "0.1.4" // what the sign-in says it is, as the CLI does +const TIMEOUT = 20_000 +const HOUR = 3600 +const WEEK = 7 * 24 * HOUR + +// The vendor's spending words as magpie's rate, and its quality words as +// whether the model thinks before it answers. +const COST = { low: "x0.5", medium: "x1", high: "x2", very_high: "x4" } +const THINKING = { advanced: true, standard: false } + +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)) +const text = (v) => (typeof v === "string" && v.trim() ? v.trim() : "") + +// The runtime key rides model requests; the control key reads the plan. A +// pasted key is one or the other, so each reader takes what fits it. +const runtimeKeyOf = (a) => { + const access = text(a?.access) || text(a?.key) + return access.startsWith("vela_ctrl_") ? "" : access +} +const controlKeyOf = (a) => text(a?.control) || text(a?.metadata?.control) || (text(a?.key).startsWith("vela_ctrl_") ? text(a.key) : "") + +// authOf keeps a successful sign-in the way magpie saves an oauth one: the +// two keys, the account they belong to, and refresh "" so one is stored. +// The keys don't expire, so there is nothing to renew. +function authOf(user, keys = {}) { + const access = text(keys.runtimeKey) || text(user?.runtimeKey) + const control = text(keys.controlKey) || text(user?.controlKey) + if (!access || !control) return null + const email = text(user?.email) + const uid = text(user?.id) || text(user?.appUserId) + return { + type: "success", + refresh: "", + expires: 0, + access, + control, + ...(email && { accountId: email, email }), + ...(uid && { uid }), + } +} + +// ---- HTTP -------------------------------------------------------------------- + +async function readJSON(res) { + const raw = await res.text().catch(() => "") + try { + return raw ? JSON.parse(raw) : null + } catch { + return { __text: raw } + } +} + +// said() is the vendor's own words, never a page of HTML. +function said(body, fallback) { + const raw = body?.error?.message ?? body?.message ?? body?.error ?? body?.__text + const s = typeof raw === "string" ? raw.trim() : "" + if (!s || s.startsWith("<")) return fallback + return s.length > 300 ? s.slice(0, 300) + "…" : s +} + +async function api(base, path, { key, body, method = "GET", signal } = {}) { + const headers = { accept: "application/json", "user-agent": SOURCE } + if (key) headers.authorization = "Bearer " + key + if (body !== undefined) headers["content-type"] = "application/json" + const res = await fetch(base + path, { + method, + headers, + body: body === undefined ? undefined : JSON.stringify(body), + signal: signal ?? AbortSignal.timeout(TIMEOUT), + }) + return { status: res.status, ok: res.ok, body: await readJSON(res) } +} + +// ---- the sign-in ------------------------------------------------------------- + +// startDevice opens a device authorization: a code, the page that approves +// it, and the secret the approval is polled with. +async function startDevice({ signal } = {}) { + const r = await api(CONTROL, "/api/v1/cli/device-authorizations", { + method: "POST", + body: { cliVersion: CLI_VERSION, host: hostname() || "magpie", profile: "prod" }, + signal, + }) + const d = r.body + if (!r.ok || !d?.deviceId || !d?.deviceSecret) { + throw new Error(`Open Design sign-in: the control plane answered ${r.status} (${said(d, "no device authorization")})`) + } + return { + deviceId: String(d.deviceId), + deviceSecret: String(d.deviceSecret), + userCode: text(d.userCode), + url: text(d.activationUrl), + interval: Number(d.pollIntervalSeconds) > 0 ? Number(d.pollIntervalSeconds) : 2, + until: Date.parse(d.expiresAt ?? "") || Date.now() + 10 * 60_000, + } +} + +// waitForDevice polls until the page approves, giving the account's two +// keys; a code that runs out or is refused says so. +async function waitForDevice(d, { signal, sleep: nap = sleep } = {}) { + for (;;) { + if (signal?.aborted) throw new Error("Open Design sign-in: cancelled") + if (Date.now() > d.until) throw new Error("Open Design sign-in: the code ran out before it was approved") + await nap((d.interval ?? 2) * 1000) + let r + try { + r = await api(CONTROL, `/api/v1/cli/device-authorizations/${encodeURIComponent(d.deviceId)}/token`, { + method: "POST", + body: { deviceSecret: d.deviceSecret }, + signal, + }) + } catch { + // a hiccup on the way to the approval is not the sign-in failing + if (signal?.aborted) throw new Error("Open Design sign-in: cancelled") + continue + } + const auth = authOf(r.body?.user, { controlKey: r.body?.controlKey, runtimeKey: r.body?.runtimeKey }) + if (auth) return auth + const status = String(r.body?.status ?? "").toLowerCase() + if (r.status === 404 || ["expired", "canceled", "cancelled", "denied", "rejected"].includes(status)) { + throw new Error(`Open Design sign-in: the request was ${status || "not found"} — start again`) + } + if (r.status === 401) { + const why = text(r.body?.error) + throw new Error(`Open Design sign-in: ${why === "invalid_device_secret" ? "the code is no longer valid" : said(r.body, "the approval is no longer valid")} — start again`) + } + // pending, or an answer this plugin doesn't know: wait for the next poll + } +} + +// ---- shaping the readings ---------------------------------------------------- + +// The workspace whose allowance is shown; a personal account has one. +async function workspaceOf(controlKey, { signal } = {}) { + const r = await api(CONTROL, "/api/v1/workspaces/current", { key: controlKey, signal }) + if (!r.ok) throw new Error(`the workspaces read answered ${r.status} (${said(r.body, "unauthorized")})`) + const id = text(r.body?.activeWorkspaceId) || text(r.body?.workspaceId) + if (!id) throw new Error("the account has no active workspace") + return { id, tier: text(r.body?.personalMembershipTier) } +} + +// credits() shows the plan's credits short: whole below five figures, then +// thousands, then millions, as a plan's own card rounds them. +function credits(v) { + const n = Number(v) + if (!Number.isFinite(n)) return text(v) + const whole = Math.round(n) + const a = Math.abs(whole) + if (a < 10_000) return String(whole) + if (a < 1_000_000) { + const k = whole / 1000 + return (Math.abs(k) >= 100 ? Math.round(k) : Math.round(k * 10) / 10) + "k" + } + return Math.round((whole / 1_000_000) * 10) / 10 + "M" +} + +function usedPercent(used, limit) { + const u = Number(used) + const l = Number(limit) + if (!Number.isFinite(u) || !Number.isFinite(l) || l <= 0) return null + return Math.round(Math.max(0, (u / l) * 100) * 10) / 10 +} + +// The window's name as the vendor's card says it: hours under a day, days +// above, the week's as "7 days". +function windowName(seconds) { + const s = Number(seconds) + if (!Number.isFinite(s) || s <= 0) return "Allowance" + const says = (n, one, many) => `${n} ${n === 1 ? one : many}` + if (s % WEEK === 0) return says((s / WEEK) * 7, "day", "days") + if (s % (24 * HOUR) === 0) return says(s / (24 * HOUR), "day", "days") + if (s % HOUR === 0) return says(s / HOUR, "hour", "hours") + return says(Math.round(s / 60), "minute", "minutes") +} + +const money = (v) => { + const n = Number(v) + return Number.isFinite(n) ? `$${n.toFixed(2)}` : "" +} + +const when = (v) => { + const t = typeof v === "number" ? (v < 1e11 ? v * 1000 : v) : Date.parse(text(v)) + return Number.isFinite(t) ? new Date(t).toISOString() : undefined +} + +// allowances() turns the Design Plan's windows into magpie's, shortest +// first, as the vendor's card lists them. +function allowances(plan) { + const out = [] + for (const w of plan?.windows ?? []) { + const used = usedPercent(w?.usedCredits, w?.limitCredits) + if (used === null) continue + out.push({ + name: windowName(w?.durationSeconds), + used, + span: Math.max(0, Number(w?.durationSeconds) || 0), + resetsAt: when(w?.resetsAt), + display: `${credits(w?.usedCredits)} / ${credits(w?.limitCredits)} credits`, + }) + } + return out.sort((a, b) => a.span - b.span) +} + +// thePlan names the subscription the way the dashboard does. +function thePlan(summary, tier) { + const t = text(summary?.membershipTier) || text(tier) + if (!t) return "Open Design" + return "Design Plan " + t[0].toUpperCase() + t.slice(1) +} + +// modelOf turns one model's facts — models.mjs's, or amr-link's catalog +// read again — into the model magpie shows. +function modelOf(id, m) { + const rate = COST[text(m?.cost)] + const thinking = THINKING[text(m?.capability)] + const context = Number(m?.context) + const output = Number(m?.output) + const input = Array.isArray(m?.input) ? m.input.filter((x) => typeof x === "string" && x !== "text") : [] + return { + id, + name: text(m?.name) || id, + attachment: true, + tool_call: true, + reasoning: thinking ?? !!m?.reasoning, + ...(rate && { rate }), + limit: { + context: Number.isFinite(context) && context > 0 ? context : 200_000, + output: Number.isFinite(output) && output > 0 ? output : 32_000, + }, + modalities: { input: ["text", ...input], output: ["text"] }, + } +} + +// facts() is amr-link's catalog entry in the seed's own shape. +function facts(m) { + const meta = m?.metadata ?? {} + const input = Array.isArray(m?.architecture?.input_modalities) + ? m.architecture.input_modalities.filter((x) => typeof x === "string" && x !== "text") + : [] + return { + context: Number(meta.context_limit), + output: Number(meta.context_budget), + input, + cost: text(meta.cost), + capability: text(meta.capability), + } +} + +// seed() is what the provider has before anyone signs in, from models.mjs. +function seed() { + return Object.fromEntries(Object.entries(MODELS).map(([id, m]) => [id, modelOf(id, m)])) +} + +// modelsOf() shapes amr-link's live catalog as magpie's models: the list an +// account's plan entitles it to right now, in the seed's shape. A model the +// seed knows keeps its name; the catalog carries ids only. +function modelsOf(catalog) { + const out = {} + for (const m of catalog?.data ?? []) { + const id = text(m?.id) + if (!id) continue + out[id] = modelOf(id, { ...facts(m), name: MODELS[id]?.name ?? id }) + } + return out +} + +// ---- the plugin -------------------------------------------------------------- + +export const OpenDesignAuthPlugin = async () => { + // the account's workspace, one read for a while + const workspaces = new Map() + const workspace = async (controlKey) => { + const had = workspaces.get(controlKey) + if (had && Date.now() - had.at < 10 * 60_000) return had.id + const { id } = await workspaceOf(controlKey) + workspaces.set(controlKey, { id, at: Date.now() }) + return id + } + + // usage is magpie's own hook: the plan, the wallet, and the Design Plan's + // 5-hour and 7-day allowance, as the dashboard shows them. The control + // plane doesn't take an API key, so an API key sign-in has no allowance + // to read; an account sign-in does. Each reading keeps the sign-in + // (signIn "kept"), as the account's keys neither lapse nor renew. + const usage = async (getAuth) => { + const a = await getAuth().catch(() => null) + const controlKey = controlKeyOf(a) + if (!controlKey) { + return { windows: [], error: "Signed in with an API key: the Design Plan allowance needs the account sign-in.", signIn: "kept" } + } + const signal = AbortSignal.timeout(30_000) + try { + const id = await workspace(controlKey) + const preflight = await api(CONTROL, `/api/v1/workspaces/${encodeURIComponent(id)}/billing/preflight`, { key: controlKey, signal }) + if (preflight.status === 401 || preflight.status === 403) { + return { windows: [], error: "Open Design refused the account's sign-in — sign in again.", signIn: "expired" } + } + if (!preflight.ok) throw new Error(`the Design Plan read answered ${preflight.status} (${said(preflight.body, "no reading")})`) + // the summary takes a timeZone, but nothing read here depends on it + // (only its own updatedAt and usageCount do), so none is sent + const summary = await api(CONTROL, "/api/v1/billing/summary", { key: controlKey, signal }) + const plan = preflight.body?.codingPlan ?? null + const out = { + plan: thePlan(summary.ok ? summary.body : null, ""), + user: text(a?.email) || text(a?.accountId), + balance: money(preflight.body?.balanceUsd ?? (summary.ok ? summary.body?.balanceUsd : "")), + windows: allowances(plan), + signIn: "kept", + } + if (summary.ok) { + const until = when(summary.body?.subscriptionCurrentPeriodEnd) + if (until) out.until = until + if (text(summary.body?.subscriptionStatus)) out.renew = summary.body?.subscriptionCancelAtPeriodEnd ? "off" : "auto" + } + if (plan && plan.eligible === false) { + out.error = "This account has no Design Plan allowance: its requests draw on the wallet balance." + } + return out + } catch (e) { + return { windows: [], error: `Open Design usage: ${e?.message ?? e}`, signIn: "kept" } + } + } + + return { + config: async (cfg) => { + cfg.provider ??= {} + const was = cfg.provider[ID] ?? {} + cfg.provider[ID] = { + name: "Open Design", + npm: NPM, + api: LINK, + ...was, + models: { ...seed(), ...(was.models ?? {}) }, + } + }, + // the plan decides which models an account gets, so the list is read + // per account, at that account's runtime key + provider: { + id: ID, + async models(provider, { auth } = {}) { + const key = runtimeKeyOf(auth) + if (!key) return provider.models + const r = await api(LINK, "/models", { key }) + if (r.status === 401 || r.status === 403) { + throw Object.assign(new Error(`Open Design refused the account's key (${said(r.body, "unauthorized")}) — sign in again`), { signIn: "expired" }) + } + if (!r.ok) return provider.models // magpie keeps the list it had + const models = modelsOf(r.body) + return Object.keys(models).length ? models : provider.models + }, + }, + auth: { + provider: ID, + usage, + loader: async (getAuth) => { + const key = runtimeKeyOf(await getAuth().catch(() => null)) + if (!key) return {} + return { baseURL: LINK, apiKey: key } + }, + methods: [ + { + type: "oauth", + label: "Open Design account", + async authorize() { + const d = await startDevice() + return { + url: d.url, + instructions: d.userCode + ? `Approve the CLI sign-in on the page that opens (code ${d.userCode}). It finishes here by itself.` + : "Approve the CLI sign-in on the page that opens. It finishes here by itself.", + method: "auto", + async callback() { + try { + return await waitForDevice(d) + } catch (e) { + return { type: "failed", error: e?.message ?? String(e) } + } + }, + } + }, + }, + { + // magpie's own key prompt: the key it saves is taken as it is, so + // a key that isn't right is the vendor's own answer to say + type: "api", + label: "Open Design API key", + placeholder: "sk-amr-…", + }, + ], + }, + } +} + +// _internal is what the tests read through; magpie calls every exported +// function as a plugin, so only the plugin itself is exported bare. +export const _internal = { authOf, allowances, controlKeyOf, credits, modelsOf, money, runtimeKeyOf, said, thePlan, usedPercent, waitForDevice, windowName, when, workspaceOf } diff --git a/packages/opendesign/index.test.mjs b/packages/opendesign/index.test.mjs new file mode 100644 index 0000000..652d7c0 --- /dev/null +++ b/packages/opendesign/index.test.mjs @@ -0,0 +1,300 @@ +import { test, expect, mock, afterEach } from "bun:test" +import { + _internal as I, + OpenDesignAuthPlugin, +} from "./index.mjs" + +afterEach(() => { + mock.restore() +}) + +// ---- 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" } }, + ], +} + +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", + reasoning: false, + rate: "x0.5", + tool_call: true, + attachment: true, + limit: { context: 1050000, output: 304000 }, + modalities: { input: ["text", "image", "file"], output: ["text"] }, + }) + expect(models["deepseek-v4-pro"]).toMatchObject({ reasoning: true, rate: "x2", 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"]).toEqual({ + id: "brand-new-9", + name: "brand-new-9", + attachment: true, + tool_call: true, + reasoning: true, + rate: "x1", + limit: { context: 200000, output: 32000 }, + modalities: { input: ["text", "image"], output: ["text"] }, + }) +}) + +test("an empty catalog is no models", () => { + expect(I.modelsOf({ data: [] })).toEqual({}) + expect(I.modelsOf(null)).toEqual({}) +}) + +// ---- 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", + 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(11) + expect(cfg.provider.opendesign.models["deepseek-v4.1-flash"]).toEqual({ + id: "deepseek-v4.1-flash", + name: "DeepSeek V4.1 Flash", + attachment: true, + tool_call: true, + reasoning: true, + rate: "x0.5", + limit: { context: 1048000, output: 232000 }, + modalities: { input: ["text", "image"], output: ["text"] }, + }) + 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({}) + expect(await hooks.auth.loader(async () => ({ access: "sk-amr-b", control: "vela_ctrl_a" }))) + .toEqual({ baseURL: "https://amr-link.open-design.ai/v1", apiKey: "sk-amr-b" }) + expect(await hooks.auth.loader(async () => null)).toEqual({}) +}) + +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) +}) diff --git a/packages/opendesign/models.mjs b/packages/opendesign/models.mjs new file mode 100644 index 0000000..4cad69a --- /dev/null +++ b/packages/opendesign/models.mjs @@ -0,0 +1,23 @@ +// The models an account is offered before anyone has signed in — the seed +// magpie and OpenCode read for the provider. Regenerate with +// `bun refresh-models.mjs` (beside this seed): it +// reads amr-link's catalog at the signed-in account's key, which is the same +// list a signed-in account is given again on every listing. +// +// name: what the model is called; context/output: its token limits; input: +// the non-text modalities it takes; cost and capability: the vendor's own +// words, which the plugin turns into magpie's rate and thinking flags. + +export const MODELS = { + "claude-haiku-5.5": { name: "Claude Haiku 5.5", context: 1000000, output: 132000, input: ["image", "file"], cost: "low", capability: "standard" }, + "deepseek-v4-flash": { name: "DeepSeek V4 Flash", context: 1048000, output: 232000, cost: "medium", capability: "standard" }, + "deepseek-v4-flash-vision-exp": { name: "DeepSeek V4 Flash Vision (exp)", context: 1048000, output: 232000, input: ["image"], cost: "medium", capability: "standard" }, + "deepseek-v4-pro": { name: "DeepSeek V4 Pro", context: 1048000, output: 232000, cost: "high", capability: "advanced" }, + "deepseek-v4.1-flash": { name: "DeepSeek V4.1 Flash", context: 1048000, output: 232000, input: ["image"], cost: "low", capability: "advanced" }, + "glm-5.3-flash": { name: "GLM 5.3 Flash", context: 1048000, output: 232000, input: ["image", "video"], cost: "low", capability: "advanced" }, + "glm-5.3-flashx": { name: "GLM 5.3 FlashX", context: 1000000, output: 232000, input: ["image", "file", "video"], cost: "medium", capability: "advanced" }, + "gpt-6-luna": { name: "GPT-6 Luna", context: 1050000, output: 304000, input: ["image", "file"], cost: "low", capability: "standard" }, + "kimi-k2.7-code": { name: "Kimi K2.7 Code", context: 262000, output: 262000, input: ["image"], cost: "medium", capability: "advanced" }, + "mimo-v2.6-flash": { name: "MiMo V2.6 Flash", context: 1048000, output: 232000, input: ["image", "audio", "video"], cost: "low", capability: "standard" }, + "mimo-v2.6-pro": { name: "MiMo V2.6 Pro", context: 1048000, output: 232000, input: ["image", "audio", "video"], cost: "medium", capability: "advanced" }, +} diff --git a/packages/opendesign/package.json b/packages/opendesign/package.json new file mode 100644 index 0000000..794ef2e --- /dev/null +++ b/packages/opendesign/package.json @@ -0,0 +1,29 @@ +{ + "name": "@magpie-community/opencode-opendesign-auth", + "version": "0.1.4", + "description": "Open Design Cloud (Design Plan) in OpenCode and magpie: the account's device sign-in, its models, and the plan's 5-hour and 7-day allowance", + "type": "module", + "main": "./index.mjs", + "files": [ + "index.mjs", + "models.mjs", + "refresh-models.mjs", + "README.md" + ], + "keywords": [ + "opencode", + "opencode-plugin", + "magpie", + "opendesign" + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/magpie-community/plugins.git", + "directory": "packages/opendesign" + }, + "magpie": { + "icon": "https://open-design.ai/favicon.svg" + }, + "exports": "./index.mjs" +} diff --git a/packages/opendesign/refresh-models.mjs b/packages/opendesign/refresh-models.mjs new file mode 100644 index 0000000..799bd54 --- /dev/null +++ b/packages/opendesign/refresh-models.mjs @@ -0,0 +1,102 @@ +// Regenerates models.mjs — the models the provider offers before anyone has +// signed in — from amr-link's live catalog, which is the account's own list +// (it is what the plugin reads for a signed-in account too). +// +// bun refresh-models.mjs # key from magpie's sign-in +// OPENDESIGN_KEY=sk-amr-… bun refresh-models.mjs +// +// The key is the account's runtime key: magpie keeps it in plugin-auth.json +// after `magpie plugin login opendesign`, and it is never printed or written +// anywhere but the Authorization header. A name already in models.mjs is +// kept — the catalog carries ids, not names. +// +// magpie runs a plugin host per command, so `magpie plugin login` has to have +// finished before this reads the key it saved. + +import { existsSync, readFileSync, writeFileSync } from "node:fs" +import { homedir } from "node:os" +import { dirname, join } from "node:path" +import { fileURLToPath, pathToFileURL } from "node:url" + +// the seed this writes, beside the script: the package root here, and the +// package root when npm installs it +const HERE = dirname(fileURLToPath(import.meta.url)) +const TARGET = join(HERE, "models.mjs") +const API = "https://amr-link.open-design.ai/v1" + +if (!existsSync(TARGET)) { + console.error("no models.mjs beside this script") + process.exit(1) +} + +const magpieKey = () => { + const dir = process.env.XDG_CONFIG_HOME || join(homedir(), ".config") + try { + const auth = JSON.parse(readFileSync(join(dir, "magpie", "plugin-auth.json"), "utf8")).opendesign + return auth?.access || auth?.key || "" + } catch { + return "" + } +} + +const key = (process.env.OPENDESIGN_KEY || "").trim() || magpieKey() +if (!key) { + console.error("No key: sign in with `magpie plugin login opendesign`, or set OPENDESIGN_KEY=sk-amr-…") + process.exit(1) +} + +const res = await fetch(`${API}/models`, { headers: { authorization: `Bearer ${key}` } }) +if (!res.ok) { + console.error(`amr-link answered ${res.status}: ${(await res.text()).slice(0, 200)}`) + process.exit(1) +} +const body = await res.json() +const catalog = (body?.data ?? []).filter((m) => typeof m?.id === "string" && m.id.trim()) +if (!catalog.length) { + console.error("amr-link listed no models") + process.exit(1) +} + +// names already chosen are kept: the catalog has ids only +let before = {} +try { + ;({ MODELS: before } = await import(pathToFileURL(TARGET).href)) +} catch {} + +const input = (m) => { + const said = Array.isArray(m?.architecture?.input_modalities) ? m.architecture.input_modalities : [] + return said.filter((x) => typeof x === "string" && x !== "text") +} +const lines = [] +for (const m of catalog) { + const id = m.id.trim() + const meta = m.metadata ?? {} + const facts = [] + const context = Number(meta.context_limit) + const output = Number(meta.context_budget) + if (Number.isFinite(context) && context > 0) facts.push(`context: ${context}`) + if (Number.isFinite(output) && output > 0) facts.push(`output: ${output}`) + const extra = input(m) + if (extra.length) facts.push(`input: [${extra.map((x) => JSON.stringify(x)).join(", ")}]`) + if (typeof meta.cost === "string") facts.push(`cost: ${JSON.stringify(meta.cost)}`) + if (typeof meta.capability === "string") facts.push(`capability: ${JSON.stringify(meta.capability)}`) + const name = before[id]?.name ?? id + lines.push(` ${JSON.stringify(id)}: { name: ${JSON.stringify(name)}${facts.length ? ", " + facts.join(", ") : ""} },`) +} + +const header = `// The models an account is offered before anyone has signed in — the seed +// magpie and OpenCode read for the provider. Regenerate with +// \`bun refresh-models.mjs\` (beside this seed): it +// reads amr-link's catalog at the signed-in account's key, which is the same +// list a signed-in account is given again on every listing. +// +// name: what the model is called; context/output: its token limits; input: +// the non-text modalities it takes; cost and capability: the vendor's own +// words, which the plugin turns into magpie's rate and thinking flags. + +export const MODELS = { +${lines.join("\n")} +} +` +writeFileSync(TARGET, header) +console.log(`${TARGET}: ${lines.length} models`) diff --git a/registry.json b/registry.json index f4baf8d..58582e0 100644 --- a/registry.json +++ b/registry.json @@ -31,6 +31,8 @@ "summary": { "en": "Cline's models on your own Cline account — usage billing, ClinePass and Cline's free models — with Cline's device sign-in or an API key.", "zh": "用自己的 Cline 账号使用 Cline 的模型——用量计费、ClinePass 与免费模型——支持 Cline 设备登录或 API key。" } }, { "package": "@magpie-community/opencode-trae-auth", "name": "Trae", "icon": "trae", "providers": ["trae-cn", "trae-global"], "community": true, "summary": { "en": "Trae CN (trae.cn) and Trae international (trae.ai) models with your own account, free tier included — Trae's own browser sign-in. Experimental.", "zh": "用 Trae CN(trae.cn)与 Trae 国际版(trae.ai)账号使用各自的模型,含免费版,使用 Trae 自己的浏览器登录。实验性。" } }, + { "package": "@magpie-community/opencode-opendesign-auth", "name": "Open Design", "providers": ["opendesign"], "community": true, + "summary": { "en": "Open Design Cloud's Design Plan (open-design.ai): the account's device sign-in, the models the plan entitles it to, and the plan's 5-hour and 7-day allowance and wallet balance.", "zh": "Open Design Cloud 的 Design Plan(open-design.ai):账号设备登录、套餐可用的模型,以及 5 小时与 7 天额度、钱包余额。" } }, { "package": "@magpie-community/middleware-param-override", "name": "Param Override", "kind": "middleware", "community": true, "summary": { "en": "New API's parameter override: set, delete, move or rewrite fields of every request, by model or by condition.", "zh": "New API 的参数覆盖:按模型或条件设置、删除、移动或改写每个请求的字段。" } }, { "package": "@magpie-community/middleware-model-map", "name": "Model Map", "kind": "middleware", "community": true,