@magpie-community/opencode-opendesign-auth 0.0.0-stage → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,129 @@
1
- # Temporary Holding Version
1
+ # @magpie-community/opencode-opendesign-auth
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Open Design (open-design.ai) Cloud as a magpie / OpenCode provider: sign in
4
+ with the Open Design account, use the models its **Design Plan** entitles the
5
+ account to, and watch the plan's **5-hour and 7-day allowance** and wallet
6
+ balance where every other subscription's usage shows.
7
+
8
+ Works in [magpie](https://usemagpie.ai) (which runs OpenCode provider plugins)
9
+ and in OpenCode.
10
+
11
+ ```
12
+ magpie plugin add @magpie-community/opencode-opendesign-auth
13
+ magpie plugin login opendesign
14
+ ```
15
+
16
+ In OpenCode, `opencode.json`:
17
+
18
+ ```json
19
+ { "plugin": ["@magpie-community/opencode-opendesign-auth"] }
20
+ ```
21
+
22
+ then `opencode auth login`.
23
+
24
+ ## What it signs in to
25
+
26
+ Open Design's cloud is two planes:
27
+
28
+ | Plane | Host | Key | Used for |
29
+ | --- | --- | --- | --- |
30
+ | Control | `amr-api.open-design.ai` | `vela_ctrl_…` | plan, wallet balance, the Design Plan's allowance windows, the workspace |
31
+ | Model | `amr-link.open-design.ai/v1` | `sk-amr-…` | `/models`, `/responses` (the OpenAI Responses API) |
32
+
33
+ A sign-in is the same device authorization the Open Design CLI
34
+ (`vela login`) runs:
35
+
36
+ 1. the plugin POSTs `/api/v1/cli/device-authorizations` and gets a code
37
+ (`4HYFNA`) and an activation page (`open-design.ai/cloud/cli/activate?…`);
38
+ 2. magpie opens that page; approving it says the CLI is signing in;
39
+ 3. the plugin polls it and receives both keys for that account, with the
40
+ account's email and id.
41
+
42
+ Nothing else is needed, and nothing of the desktop app's own sign-in
43
+ (`~/.amr/config.json`, a different machine-issued pair of keys) is read or
44
+ written.
45
+
46
+ ## Sign-in methods
47
+
48
+ | Method | What it stores | Allowance |
49
+ | --- | --- | --- |
50
+ | **Open Design account** | the account's control + runtime keys | 5-hour and 7-day windows, wallet balance, plan |
51
+ | **Open Design API key** | a pasted `sk-amr-…` key | not readable: `amr-api` doesn't take API keys |
52
+
53
+ The account sign-in is the one that shows the allowance; the API key one
54
+ is there for a machine that can't open the approval page.
55
+
56
+ ## Models
57
+
58
+ Nothing is listed per account at request time from anywhere but the vendor:
59
+ magpie calls the plugin's `provider.models`, which reads `amr-link`'s live
60
+ `/v1/models` at that account's key on every listing, so what a signed-in
61
+ account is offered is what its plan entitles it to right now. Limits, input
62
+ modalities and the vendor's own cost words (`rate`, e.g. `x0.5` for "low")
63
+ come from that same catalog.
64
+
65
+ Reasoning levels are not in the catalog, so `models.mjs` records the ones
66
+ measured against `amr-link` (#137): every model took `reasoning_effort`
67
+ `low` and `high`, and all but GPT-6 Luna thought at them, the ones the
68
+ catalog calls `standard` too. Those models reason at `low` and `high`;
69
+ GPT-6 Luna has no levels. A model the seed doesn't know reasons when its
70
+ vendor tier is `advanced`, with no levels until it is measured.
71
+
72
+ `models.mjs` is the seed the provider has *before* anyone signs in. Refresh
73
+ it from the live catalog with:
74
+
75
+ ```bash
76
+ magpie plugin login opendesign # once, so the key is on hand
77
+ bun refresh-models.mjs # or OPENDESIGN_KEY=sk-amr-… bun …
78
+ ```
79
+
80
+ The script keeps the names and measured levels already there — the catalog
81
+ carries neither — and reads nothing else: no secret is written to the file or
82
+ printed.
83
+
84
+ Requests go to the **Responses** API (`@ai-sdk/openai` at
85
+ `https://amr-link.open-design.ai/v1`), which is what an Open Design API key
86
+ page recommends for Codex-style clients and what keeps thinking intact.
87
+
88
+ ## Where the sign-in is kept
89
+
90
+ magpie's `plugin-auth.json` (mode 600), as an oauth account:
91
+ `{ type: "oauth", access: <runtime key>, control: <control key>, accountId:
92
+ <email>, uid: <account id> }`. Neither key expires, so there is nothing to
93
+ renew and `refresh` is empty.
94
+
95
+ ## Use
96
+
97
+ ```
98
+ magpie plugin # opendesign (Open Design, 11 models) signed in
99
+ magpie provider test opendesign
100
+ magpie quota # opendesign · Design Plan Go · 5h 32% ↻3h
101
+ ```
102
+
103
+ ### Replacing a custom provider
104
+
105
+ The plugin signs in to the provider id `opendesign`. A **custom provider**
106
+ of that same id (Providers → the host and key by hand) takes the id first,
107
+ so the plugin's provider is then listed as `opendesign-plugin`, with no
108
+ models of its own. Delete the custom provider — `magpie provider rm
109
+ opendesign` — and the plugin's provider takes the plain id, so agent
110
+ configs pointing at `opendesign/<model>` keep working, now with the
111
+ allowance card.
112
+
113
+ ## The allowance in routing
114
+
115
+ The windows are gating windows (magpie's `aside` is left off), so magpie's
116
+ own routing reads them like any subscription's:
117
+
118
+ * a window magpie reads as used up makes the account count as used up, so
119
+ routing groups skip it and a direct call to `opendesign/<model>` is refused
120
+ with a 429 until that window renews;
121
+ * `magpie provider account-cap opendesign <account> [percent|off]` holds the
122
+ account at a share of each window, and `--window "5 hours" 70` caps one
123
+ window alone, which is how to leave headroom instead of spending the plan
124
+ to the last credit.
125
+
126
+ Since Open Design falls back to the wallet balance once the Design Plan
127
+ allowance is out, an exhausted window holds the account rather than spending
128
+ the wallet. Set the account to spend its credits, or cap the windows, to
129
+ choose which of the two magpie does.
package/index.mjs ADDED
@@ -0,0 +1,471 @@
1
+ // Open Design (open-design.ai) Cloud, as its own CLI signs in to it: the
2
+ // sign-in is a device authorization at the Vela control plane
3
+ // (amr-api.open-design.ai), which answers with two keys — a control key
4
+ // (vela_ctrl_…) for the account's plan and its Design Plan allowance, and a
5
+ // runtime key (sk-amr-…) that the model plane (amr-link.open-design.ai)
6
+ // takes. Model requests are the OpenAI Responses API at the runtime key;
7
+ // the model list, the plan and the 5-hour and 7-day allowance windows all
8
+ // come from the control plane.
9
+ //
10
+ // Not to be confused with the OpenDesign desktop app on this machine: it
11
+ // keeps its own sign-in in ~/.amr/config.json, a different (machine-issued)
12
+ // pair of keys, and this plugin never touches it.
13
+
14
+ import { hostname } from "node:os"
15
+
16
+ // JSON modules have a default export only, in Bun as in Node
17
+ import pkg from "./package.json" with { type: "json" }
18
+
19
+ import { MODELS } from "./models.mjs"
20
+
21
+ const ID = "opendesign"
22
+ const CONTROL = "https://amr-api.open-design.ai"
23
+ const LINK = "https://amr-link.open-design.ai/v1"
24
+ const NPM = "@ai-sdk/openai" // the Responses API, at LINK
25
+ const SOURCE = "opencode-opendesign-auth/" + pkg.version // as the manifest has it
26
+ const CLI_VERSION = "0.1.4" // what the sign-in says it is, as the CLI does
27
+ const TIMEOUT = 20_000
28
+ const HOUR = 3600
29
+ const WEEK = 7 * 24 * HOUR
30
+
31
+ // The vendor's spending words as magpie's rate, and its quality words as
32
+ // whether the model thinks before it answers.
33
+ const COST = { low: "x0.5", medium: "x1", high: "x2", very_high: "x4" }
34
+ const THINKING = { advanced: true, standard: false }
35
+
36
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
37
+ const text = (v) => (typeof v === "string" && v.trim() ? v.trim() : "")
38
+
39
+ // The runtime key rides model requests; the control key reads the plan. A
40
+ // pasted key is one or the other, so each reader takes what fits it.
41
+ const runtimeKeyOf = (a) => {
42
+ const access = text(a?.access) || text(a?.key)
43
+ return access.startsWith("vela_ctrl_") ? "" : access
44
+ }
45
+ const controlKeyOf = (a) => text(a?.control) || text(a?.metadata?.control) || (text(a?.key).startsWith("vela_ctrl_") ? text(a.key) : "")
46
+
47
+ // authOf keeps a successful sign-in the way magpie saves an oauth one: the
48
+ // two keys, the account they belong to, and refresh "" so one is stored.
49
+ // The keys don't expire, so there is nothing to renew.
50
+ function authOf(user, keys = {}) {
51
+ const access = text(keys.runtimeKey) || text(user?.runtimeKey)
52
+ const control = text(keys.controlKey) || text(user?.controlKey)
53
+ if (!access || !control) return null
54
+ const email = text(user?.email)
55
+ const uid = text(user?.id) || text(user?.appUserId)
56
+ return {
57
+ type: "success",
58
+ refresh: "",
59
+ expires: 0,
60
+ access,
61
+ control,
62
+ ...(email && { accountId: email, email }),
63
+ ...(uid && { uid }),
64
+ }
65
+ }
66
+
67
+ // ---- HTTP --------------------------------------------------------------------
68
+
69
+ async function readJSON(res) {
70
+ const raw = await res.text().catch(() => "")
71
+ try {
72
+ return raw ? JSON.parse(raw) : null
73
+ } catch {
74
+ return { __text: raw }
75
+ }
76
+ }
77
+
78
+ // said() is the vendor's own words, never a page of HTML.
79
+ function said(body, fallback) {
80
+ const raw = body?.error?.message ?? body?.message ?? body?.error ?? body?.__text
81
+ const s = typeof raw === "string" ? raw.trim() : ""
82
+ if (!s || s.startsWith("<")) return fallback
83
+ return s.length > 300 ? s.slice(0, 300) + "…" : s
84
+ }
85
+
86
+ async function api(base, path, { key, body, method = "GET", signal } = {}) {
87
+ const headers = { accept: "application/json", "user-agent": SOURCE }
88
+ if (key) headers.authorization = "Bearer " + key
89
+ if (body !== undefined) headers["content-type"] = "application/json"
90
+ const res = await fetch(base + path, {
91
+ method,
92
+ headers,
93
+ body: body === undefined ? undefined : JSON.stringify(body),
94
+ signal: signal ?? AbortSignal.timeout(TIMEOUT),
95
+ })
96
+ return { status: res.status, ok: res.ok, body: await readJSON(res) }
97
+ }
98
+
99
+ // ---- the sign-in -------------------------------------------------------------
100
+
101
+ // startDevice opens a device authorization: a code, the page that approves
102
+ // it, and the secret the approval is polled with.
103
+ async function startDevice({ signal } = {}) {
104
+ const r = await api(CONTROL, "/api/v1/cli/device-authorizations", {
105
+ method: "POST",
106
+ body: { cliVersion: CLI_VERSION, host: hostname() || "magpie", profile: "prod" },
107
+ signal,
108
+ })
109
+ const d = r.body
110
+ if (!r.ok || !d?.deviceId || !d?.deviceSecret) {
111
+ throw new Error(`Open Design sign-in: the control plane answered ${r.status} (${said(d, "no device authorization")})`)
112
+ }
113
+ return {
114
+ deviceId: String(d.deviceId),
115
+ deviceSecret: String(d.deviceSecret),
116
+ userCode: text(d.userCode),
117
+ url: text(d.activationUrl),
118
+ interval: Number(d.pollIntervalSeconds) > 0 ? Number(d.pollIntervalSeconds) : 2,
119
+ until: Date.parse(d.expiresAt ?? "") || Date.now() + 10 * 60_000,
120
+ }
121
+ }
122
+
123
+ // waitForDevice polls until the page approves, giving the account's two
124
+ // keys; a code that runs out or is refused says so.
125
+ async function waitForDevice(d, { signal, sleep: nap = sleep } = {}) {
126
+ for (;;) {
127
+ if (signal?.aborted) throw new Error("Open Design sign-in: cancelled")
128
+ if (Date.now() > d.until) throw new Error("Open Design sign-in: the code ran out before it was approved")
129
+ await nap((d.interval ?? 2) * 1000)
130
+ let r
131
+ try {
132
+ r = await api(CONTROL, `/api/v1/cli/device-authorizations/${encodeURIComponent(d.deviceId)}/token`, {
133
+ method: "POST",
134
+ body: { deviceSecret: d.deviceSecret },
135
+ signal,
136
+ })
137
+ } catch {
138
+ // a hiccup on the way to the approval is not the sign-in failing
139
+ if (signal?.aborted) throw new Error("Open Design sign-in: cancelled")
140
+ continue
141
+ }
142
+ const auth = authOf(r.body?.user, { controlKey: r.body?.controlKey, runtimeKey: r.body?.runtimeKey })
143
+ if (auth) return auth
144
+ const status = String(r.body?.status ?? "").toLowerCase()
145
+ if (r.status === 404 || ["expired", "canceled", "cancelled", "denied", "rejected"].includes(status)) {
146
+ throw new Error(`Open Design sign-in: the request was ${status || "not found"} — start again`)
147
+ }
148
+ if (r.status === 401) {
149
+ const why = text(r.body?.error)
150
+ 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`)
151
+ }
152
+ // pending, or an answer this plugin doesn't know: wait for the next poll
153
+ }
154
+ }
155
+
156
+ // ---- shaping the readings ----------------------------------------------------
157
+
158
+ // The workspace whose allowance is shown; a personal account has one.
159
+ async function workspaceOf(controlKey, { signal } = {}) {
160
+ const r = await api(CONTROL, "/api/v1/workspaces/current", { key: controlKey, signal })
161
+ if (!r.ok) throw new Error(`the workspaces read answered ${r.status} (${said(r.body, "unauthorized")})`)
162
+ const id = text(r.body?.activeWorkspaceId) || text(r.body?.workspaceId)
163
+ if (!id) throw new Error("the account has no active workspace")
164
+ return { id, tier: text(r.body?.personalMembershipTier) }
165
+ }
166
+
167
+ // credits() shows the plan's credits short: whole below five figures, then
168
+ // thousands, then millions, as a plan's own card rounds them.
169
+ function credits(v) {
170
+ const n = Number(v)
171
+ if (!Number.isFinite(n)) return text(v)
172
+ const whole = Math.round(n)
173
+ const a = Math.abs(whole)
174
+ if (a < 10_000) return String(whole)
175
+ if (a < 1_000_000) {
176
+ const k = whole / 1000
177
+ return (Math.abs(k) >= 100 ? Math.round(k) : Math.round(k * 10) / 10) + "k"
178
+ }
179
+ return Math.round((whole / 1_000_000) * 10) / 10 + "M"
180
+ }
181
+
182
+ function usedPercent(used, limit) {
183
+ const u = Number(used)
184
+ const l = Number(limit)
185
+ if (!Number.isFinite(u) || !Number.isFinite(l) || l <= 0) return null
186
+ return Math.round(Math.max(0, (u / l) * 100) * 10) / 10
187
+ }
188
+
189
+ // The window's name as the vendor's card says it: hours under a day, days
190
+ // above, the week's as "7 days".
191
+ function windowName(seconds) {
192
+ const s = Number(seconds)
193
+ if (!Number.isFinite(s) || s <= 0) return "Allowance"
194
+ const says = (n, one, many) => `${n} ${n === 1 ? one : many}`
195
+ if (s % WEEK === 0) return says((s / WEEK) * 7, "day", "days")
196
+ if (s % (24 * HOUR) === 0) return says(s / (24 * HOUR), "day", "days")
197
+ if (s % HOUR === 0) return says(s / HOUR, "hour", "hours")
198
+ return says(Math.round(s / 60), "minute", "minutes")
199
+ }
200
+
201
+ const money = (v) => {
202
+ const n = Number(v)
203
+ return Number.isFinite(n) ? `$${n.toFixed(2)}` : ""
204
+ }
205
+
206
+ const when = (v) => {
207
+ const t = typeof v === "number" ? (v < 1e11 ? v * 1000 : v) : Date.parse(text(v))
208
+ return Number.isFinite(t) ? new Date(t).toISOString() : undefined
209
+ }
210
+
211
+ // allowances() turns the Design Plan's windows into magpie's, shortest
212
+ // first, as the vendor's card lists them.
213
+ function allowances(plan) {
214
+ const out = []
215
+ for (const w of plan?.windows ?? []) {
216
+ const used = usedPercent(w?.usedCredits, w?.limitCredits)
217
+ if (used === null) continue
218
+ out.push({
219
+ name: windowName(w?.durationSeconds),
220
+ used,
221
+ span: Math.max(0, Number(w?.durationSeconds) || 0),
222
+ resetsAt: when(w?.resetsAt),
223
+ display: `${credits(w?.usedCredits)} / ${credits(w?.limitCredits)} credits`,
224
+ })
225
+ }
226
+ return out.sort((a, b) => a.span - b.span)
227
+ }
228
+
229
+ // thePlan names the subscription the way the dashboard does.
230
+ function thePlan(summary, tier) {
231
+ const t = text(summary?.membershipTier) || text(tier)
232
+ if (!t) return "Open Design"
233
+ return "Design Plan " + t[0].toUpperCase() + t.slice(1)
234
+ }
235
+
236
+ // levelsOf is a model's reasoning levels: the ones models.mjs records as
237
+ // measured against amr-link (#137), where the vendor's capability word
238
+ // misleads both ways — "standard" models took reasoning_effort and thought
239
+ // at it, and GPT-6 Luna took it and never thought. A model the seed doesn't
240
+ // know has none until it is measured too.
241
+ function levelsOf(m) {
242
+ return Array.isArray(m?.efforts) ? m.efforts.filter((e) => typeof e === "string" && e) : []
243
+ }
244
+
245
+ // modelOf turns one model's facts — models.mjs's, or amr-link's catalog
246
+ // read again — into the model magpie shows, as the provider's config has
247
+ // it. A model reasons when it has levels, or else when the vendor calls it
248
+ // "advanced". variants are its levels as @ai-sdk/openai options: magpie
249
+ // shows a model's levels only from its variants, and only when it reasons.
250
+ function modelOf(id, m) {
251
+ const rate = COST[text(m?.cost)]
252
+ const levels = levelsOf(m)
253
+ const thinking = levels.length > 0 || (THINKING[text(m?.capability)] ?? !!m?.reasoning)
254
+ const context = Number(m?.context)
255
+ const output = Number(m?.output)
256
+ const input = Array.isArray(m?.input) ? m.input.filter((x) => typeof x === "string" && x !== "text") : []
257
+ return {
258
+ id,
259
+ name: text(m?.name) || id,
260
+ attachment: true,
261
+ tool_call: true,
262
+ reasoning: thinking,
263
+ ...(levels.length && { variants: Object.fromEntries(levels.map((e) => [e, { reasoningEffort: e }])) }),
264
+ ...(rate && { rate }),
265
+ limit: {
266
+ context: Number.isFinite(context) && context > 0 ? context : 200_000,
267
+ output: Number.isFinite(output) && output > 0 ? output : 32_000,
268
+ },
269
+ modalities: { input: ["text", ...input], output: ["text"] },
270
+ }
271
+ }
272
+
273
+ // KINDS are the kinds of input and output OpenCode's capabilities name.
274
+ const KINDS = ["text", "image", "audio", "video", "pdf"]
275
+ const kinds = (list) => Object.fromEntries(KINDS.map((k) => [k, list.includes(k)]))
276
+
277
+ // servedOf is modelOf's model as provider.models hands it back: OpenCode's
278
+ // model, not the config's. magpie reads a listed model's thinking from
279
+ // capabilities.reasoning and its kinds from capabilities.input, so a config
280
+ // shape there (reasoning: true beside no capabilities) listed every model a
281
+ // signed-in account has as one that doesn't reason, with no levels (#137).
282
+ function servedOf(id, m) {
283
+ const c = modelOf(id, m)
284
+ return {
285
+ id,
286
+ name: c.name,
287
+ api: { id, url: LINK, npm: NPM },
288
+ status: "active",
289
+ headers: {},
290
+ options: {},
291
+ cost: { input: 0, output: 0, cache: { read: 0, write: 0 } },
292
+ limit: c.limit,
293
+ capabilities: {
294
+ temperature: true,
295
+ reasoning: c.reasoning,
296
+ attachment: c.attachment,
297
+ toolcall: c.tool_call,
298
+ input: kinds(c.modalities.input),
299
+ output: kinds(c.modalities.output),
300
+ interleaved: false,
301
+ },
302
+ release_date: "",
303
+ variants: c.variants ?? {},
304
+ ...(c.rate && { rate: c.rate }),
305
+ }
306
+ }
307
+
308
+ // facts() is amr-link's catalog entry in the seed's own shape.
309
+ function facts(m) {
310
+ const meta = m?.metadata ?? {}
311
+ const input = Array.isArray(m?.architecture?.input_modalities)
312
+ ? m.architecture.input_modalities.filter((x) => typeof x === "string" && x !== "text")
313
+ : []
314
+ return {
315
+ context: Number(meta.context_limit),
316
+ output: Number(meta.context_budget),
317
+ input,
318
+ cost: text(meta.cost),
319
+ capability: text(meta.capability),
320
+ }
321
+ }
322
+
323
+ // seed() is what the provider has before anyone signs in, from models.mjs.
324
+ function seed() {
325
+ return Object.fromEntries(Object.entries(MODELS).map(([id, m]) => [id, modelOf(id, m)]))
326
+ }
327
+
328
+ // modelsOf() shapes amr-link's live catalog as magpie's models: the list an
329
+ // account's plan entitles it to right now, as provider.models gives them. A
330
+ // model the seed knows keeps its name and its measured levels; the catalog
331
+ // carries ids only.
332
+ function modelsOf(catalog) {
333
+ const out = {}
334
+ for (const m of catalog?.data ?? []) {
335
+ const id = text(m?.id)
336
+ if (!id) continue
337
+ out[id] = servedOf(id, { ...facts(m), name: MODELS[id]?.name ?? id, efforts: MODELS[id]?.efforts })
338
+ }
339
+ return out
340
+ }
341
+
342
+ // ---- the plugin --------------------------------------------------------------
343
+
344
+ export const OpenDesignAuthPlugin = async () => {
345
+ // the account's workspace, one read for a while
346
+ const workspaces = new Map()
347
+ const workspace = async (controlKey) => {
348
+ const had = workspaces.get(controlKey)
349
+ if (had && Date.now() - had.at < 10 * 60_000) return had.id
350
+ const { id } = await workspaceOf(controlKey)
351
+ workspaces.set(controlKey, { id, at: Date.now() })
352
+ return id
353
+ }
354
+
355
+ // usage is magpie's own hook: the plan, the wallet, and the Design Plan's
356
+ // 5-hour and 7-day allowance, as the dashboard shows them. The control
357
+ // plane doesn't take an API key, so an API key sign-in has no allowance
358
+ // to read; an account sign-in does. Each reading keeps the sign-in
359
+ // (signIn "kept"), as the account's keys neither lapse nor renew.
360
+ const usage = async (getAuth) => {
361
+ const a = await getAuth().catch(() => null)
362
+ const controlKey = controlKeyOf(a)
363
+ if (!controlKey) {
364
+ return { windows: [], error: "Signed in with an API key: the Design Plan allowance needs the account sign-in.", signIn: "kept" }
365
+ }
366
+ const signal = AbortSignal.timeout(30_000)
367
+ try {
368
+ const id = await workspace(controlKey)
369
+ const preflight = await api(CONTROL, `/api/v1/workspaces/${encodeURIComponent(id)}/billing/preflight`, { key: controlKey, signal })
370
+ if (preflight.status === 401 || preflight.status === 403) {
371
+ return { windows: [], error: "Open Design refused the account's sign-in — sign in again.", signIn: "expired" }
372
+ }
373
+ if (!preflight.ok) throw new Error(`the Design Plan read answered ${preflight.status} (${said(preflight.body, "no reading")})`)
374
+ // the summary takes a timeZone, but nothing read here depends on it
375
+ // (only its own updatedAt and usageCount do), so none is sent
376
+ const summary = await api(CONTROL, "/api/v1/billing/summary", { key: controlKey, signal })
377
+ const plan = preflight.body?.codingPlan ?? null
378
+ const out = {
379
+ plan: thePlan(summary.ok ? summary.body : null, ""),
380
+ user: text(a?.email) || text(a?.accountId),
381
+ balance: money(preflight.body?.balanceUsd ?? (summary.ok ? summary.body?.balanceUsd : "")),
382
+ windows: allowances(plan),
383
+ signIn: "kept",
384
+ }
385
+ if (summary.ok) {
386
+ const until = when(summary.body?.subscriptionCurrentPeriodEnd)
387
+ if (until) out.until = until
388
+ if (text(summary.body?.subscriptionStatus)) out.renew = summary.body?.subscriptionCancelAtPeriodEnd ? "off" : "auto"
389
+ }
390
+ if (plan && plan.eligible === false) {
391
+ out.error = "This account has no Design Plan allowance: its requests draw on the wallet balance."
392
+ }
393
+ return out
394
+ } catch (e) {
395
+ return { windows: [], error: `Open Design usage: ${e?.message ?? e}`, signIn: "kept" }
396
+ }
397
+ }
398
+
399
+ return {
400
+ config: async (cfg) => {
401
+ cfg.provider ??= {}
402
+ const was = cfg.provider[ID] ?? {}
403
+ cfg.provider[ID] = {
404
+ name: "Open Design",
405
+ npm: NPM,
406
+ api: LINK,
407
+ ...was,
408
+ models: { ...seed(), ...(was.models ?? {}) },
409
+ }
410
+ },
411
+ // the plan decides which models an account gets, so the list is read
412
+ // per account, at that account's runtime key
413
+ provider: {
414
+ id: ID,
415
+ async models(provider, { auth } = {}) {
416
+ const key = runtimeKeyOf(auth)
417
+ if (!key) return provider.models
418
+ const r = await api(LINK, "/models", { key })
419
+ if (r.status === 401 || r.status === 403) {
420
+ throw Object.assign(new Error(`Open Design refused the account's key (${said(r.body, "unauthorized")}) — sign in again`), { signIn: "expired" })
421
+ }
422
+ if (!r.ok) return provider.models // magpie keeps the list it had
423
+ const models = modelsOf(r.body)
424
+ return Object.keys(models).length ? models : provider.models
425
+ },
426
+ },
427
+ auth: {
428
+ provider: ID,
429
+ usage,
430
+ loader: async (getAuth) => {
431
+ const key = runtimeKeyOf(await getAuth().catch(() => null))
432
+ if (!key) return {}
433
+ return { baseURL: LINK, apiKey: key }
434
+ },
435
+ methods: [
436
+ {
437
+ type: "oauth",
438
+ label: "Open Design account",
439
+ async authorize() {
440
+ const d = await startDevice()
441
+ return {
442
+ url: d.url,
443
+ instructions: d.userCode
444
+ ? `Approve the CLI sign-in on the page that opens (code ${d.userCode}). It finishes here by itself.`
445
+ : "Approve the CLI sign-in on the page that opens. It finishes here by itself.",
446
+ method: "auto",
447
+ async callback() {
448
+ try {
449
+ return await waitForDevice(d)
450
+ } catch (e) {
451
+ return { type: "failed", error: e?.message ?? String(e) }
452
+ }
453
+ },
454
+ }
455
+ },
456
+ },
457
+ {
458
+ // magpie's own key prompt: the key it saves is taken as it is, so
459
+ // a key that isn't right is the vendor's own answer to say
460
+ type: "api",
461
+ label: "Open Design API key",
462
+ placeholder: "sk-amr-…",
463
+ },
464
+ ],
465
+ },
466
+ }
467
+ }
468
+
469
+ // _internal is what the tests read through; magpie calls every exported
470
+ // function as a plugin, so only the plugin itself is exported bare.
471
+ export const _internal = { authOf, allowances, controlKeyOf, credits, modelsOf, money, runtimeKeyOf, said, thePlan, usedPercent, waitForDevice, windowName, when, workspaceOf }
package/models.mjs ADDED
@@ -0,0 +1,25 @@
1
+ // The models an account is offered before anyone has signed in — the seed
2
+ // magpie and OpenCode read for the provider. Regenerate with
3
+ // `bun refresh-models.mjs` (beside this seed): it
4
+ // reads amr-link's catalog at the signed-in account's key, which is the same
5
+ // list a signed-in account is given again on every listing.
6
+ //
7
+ // name: what the model is called; context/output: its token limits; input:
8
+ // the non-text modalities it takes; cost and capability: the vendor's own
9
+ // words, which the plugin turns into magpie's rate and thinking flags;
10
+ // efforts: the reasoning levels amr-link was seen to take and think at,
11
+ // measured, not read (#137), so a refresh keeps them.
12
+
13
+ export const MODELS = {
14
+ "claude-haiku-5.5": { name: "Claude Haiku 5.5", context: 1000000, output: 132000, input: ["image", "file"], cost: "low", capability: "standard", efforts: ["low", "high"] },
15
+ "deepseek-v4-flash": { name: "DeepSeek V4 Flash", context: 1048000, output: 232000, cost: "medium", capability: "standard", efforts: ["low", "high"] },
16
+ "deepseek-v4-flash-vision-exp": { name: "DeepSeek V4 Flash Vision (exp)", context: 1048000, output: 232000, input: ["image"], cost: "medium", capability: "standard", efforts: ["low", "high"] },
17
+ "deepseek-v4-pro": { name: "DeepSeek V4 Pro", context: 1048000, output: 232000, cost: "high", capability: "advanced", efforts: ["low", "high"] },
18
+ "deepseek-v4.1-flash": { name: "DeepSeek V4.1 Flash", context: 1048000, output: 232000, input: ["image"], cost: "low", capability: "advanced", efforts: ["low", "high"] },
19
+ "glm-5.3-flash": { name: "GLM 5.3 Flash", context: 1048000, output: 232000, input: ["image", "video"], cost: "low", capability: "advanced", efforts: ["low", "high"] },
20
+ "glm-5.3-flashx": { name: "GLM 5.3 FlashX", context: 1000000, output: 232000, input: ["image", "file", "video"], cost: "medium", capability: "advanced", efforts: ["low", "high"] },
21
+ "gpt-6-luna": { name: "GPT-6 Luna", context: 1050000, output: 304000, input: ["image", "file"], cost: "low", capability: "standard", efforts: [] },
22
+ "kimi-k2.7-code": { name: "Kimi K2.7 Code", context: 262000, output: 262000, input: ["image"], cost: "medium", capability: "advanced", efforts: ["low", "high"] },
23
+ "mimo-v2.6-flash": { name: "MiMo V2.6 Flash", context: 1048000, output: 232000, input: ["image", "audio", "video"], cost: "low", capability: "standard", efforts: ["low", "high"] },
24
+ "mimo-v2.6-pro": { name: "MiMo V2.6 Pro", context: 1048000, output: 232000, input: ["image", "audio", "video"], cost: "medium", capability: "advanced", efforts: ["low", "high"] },
25
+ }
package/package.json CHANGED
@@ -1,6 +1,29 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-opendesign-auth",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.5",
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",
5
+ "type": "module",
6
+ "main": "./index.mjs",
7
+ "files": [
8
+ "index.mjs",
9
+ "models.mjs",
10
+ "refresh-models.mjs",
11
+ "README.md"
12
+ ],
13
+ "keywords": [
14
+ "opencode",
15
+ "opencode-plugin",
16
+ "magpie",
17
+ "opendesign"
18
+ ],
19
+ "license": "MIT",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/magpie-community/plugins.git",
23
+ "directory": "packages/opendesign"
24
+ },
25
+ "magpie": {
26
+ "icon": "https://open-design.ai/favicon.svg"
27
+ },
28
+ "exports": "./index.mjs"
29
+ }
@@ -0,0 +1,107 @@
1
+ // Regenerates models.mjs — the models the provider offers before anyone has
2
+ // signed in — from amr-link's live catalog, which is the account's own list
3
+ // (it is what the plugin reads for a signed-in account too).
4
+ //
5
+ // bun refresh-models.mjs # key from magpie's sign-in
6
+ // OPENDESIGN_KEY=sk-amr-… bun refresh-models.mjs
7
+ //
8
+ // The key is the account's runtime key: magpie keeps it in plugin-auth.json
9
+ // after `magpie plugin login opendesign`, and it is never printed or written
10
+ // anywhere but the Authorization header. A name already in models.mjs is
11
+ // kept — the catalog carries ids, not names.
12
+ //
13
+ // magpie runs a plugin host per command, so `magpie plugin login` has to have
14
+ // finished before this reads the key it saved.
15
+
16
+ import { existsSync, readFileSync, writeFileSync } from "node:fs"
17
+ import { homedir } from "node:os"
18
+ import { dirname, join } from "node:path"
19
+ import { fileURLToPath, pathToFileURL } from "node:url"
20
+
21
+ // the seed this writes, beside the script: the package root here, and the
22
+ // package root when npm installs it
23
+ const HERE = dirname(fileURLToPath(import.meta.url))
24
+ const TARGET = join(HERE, "models.mjs")
25
+ const API = "https://amr-link.open-design.ai/v1"
26
+
27
+ if (!existsSync(TARGET)) {
28
+ console.error("no models.mjs beside this script")
29
+ process.exit(1)
30
+ }
31
+
32
+ const magpieKey = () => {
33
+ const dir = process.env.XDG_CONFIG_HOME || join(homedir(), ".config")
34
+ try {
35
+ const auth = JSON.parse(readFileSync(join(dir, "magpie", "plugin-auth.json"), "utf8")).opendesign
36
+ return auth?.access || auth?.key || ""
37
+ } catch {
38
+ return ""
39
+ }
40
+ }
41
+
42
+ const key = (process.env.OPENDESIGN_KEY || "").trim() || magpieKey()
43
+ if (!key) {
44
+ console.error("No key: sign in with `magpie plugin login opendesign`, or set OPENDESIGN_KEY=sk-amr-…")
45
+ process.exit(1)
46
+ }
47
+
48
+ const res = await fetch(`${API}/models`, { headers: { authorization: `Bearer ${key}` } })
49
+ if (!res.ok) {
50
+ console.error(`amr-link answered ${res.status}: ${(await res.text()).slice(0, 200)}`)
51
+ process.exit(1)
52
+ }
53
+ const body = await res.json()
54
+ const catalog = (body?.data ?? []).filter((m) => typeof m?.id === "string" && m.id.trim())
55
+ if (!catalog.length) {
56
+ console.error("amr-link listed no models")
57
+ process.exit(1)
58
+ }
59
+
60
+ // names already chosen are kept, and so are the measured reasoning levels:
61
+ // the catalog has ids only, and says nothing of efforts
62
+ let before = {}
63
+ try {
64
+ ;({ MODELS: before } = await import(pathToFileURL(TARGET).href))
65
+ } catch {}
66
+
67
+ const input = (m) => {
68
+ const said = Array.isArray(m?.architecture?.input_modalities) ? m.architecture.input_modalities : []
69
+ return said.filter((x) => typeof x === "string" && x !== "text")
70
+ }
71
+ const lines = []
72
+ for (const m of catalog) {
73
+ const id = m.id.trim()
74
+ const meta = m.metadata ?? {}
75
+ const facts = []
76
+ const context = Number(meta.context_limit)
77
+ const output = Number(meta.context_budget)
78
+ if (Number.isFinite(context) && context > 0) facts.push(`context: ${context}`)
79
+ if (Number.isFinite(output) && output > 0) facts.push(`output: ${output}`)
80
+ const extra = input(m)
81
+ if (extra.length) facts.push(`input: [${extra.map((x) => JSON.stringify(x)).join(", ")}]`)
82
+ if (typeof meta.cost === "string") facts.push(`cost: ${JSON.stringify(meta.cost)}`)
83
+ if (typeof meta.capability === "string") facts.push(`capability: ${JSON.stringify(meta.capability)}`)
84
+ const efforts = before[id]?.efforts
85
+ if (Array.isArray(efforts)) facts.push(`efforts: [${efforts.map((x) => JSON.stringify(x)).join(", ")}]`)
86
+ const name = before[id]?.name ?? id
87
+ lines.push(` ${JSON.stringify(id)}: { name: ${JSON.stringify(name)}${facts.length ? ", " + facts.join(", ") : ""} },`)
88
+ }
89
+
90
+ const header = `// The models an account is offered before anyone has signed in — the seed
91
+ // magpie and OpenCode read for the provider. Regenerate with
92
+ // \`bun refresh-models.mjs\` (beside this seed): it
93
+ // reads amr-link's catalog at the signed-in account's key, which is the same
94
+ // list a signed-in account is given again on every listing.
95
+ //
96
+ // name: what the model is called; context/output: its token limits; input:
97
+ // the non-text modalities it takes; cost and capability: the vendor's own
98
+ // words, which the plugin turns into magpie's rate and thinking flags;
99
+ // efforts: the reasoning levels amr-link was seen to take and think at,
100
+ // measured, not read (#137), so a refresh keeps them.
101
+
102
+ export const MODELS = {
103
+ ${lines.join("\n")}
104
+ }
105
+ `
106
+ writeFileSync(TARGET, header)
107
+ console.log(`${TARGET}: ${lines.length} models`)