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

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,122 @@
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; a model whose vendor tier is `advanced` is
64
+ marked as one that reasons.
65
+
66
+ `models.mjs` is the seed the provider has *before* anyone signs in. Refresh
67
+ it from the live catalog with:
68
+
69
+ ```bash
70
+ magpie plugin login opendesign # once, so the key is on hand
71
+ bun refresh-models.mjs # or OPENDESIGN_KEY=sk-amr-… bun …
72
+ ```
73
+
74
+ The script keeps the names already chosen — the catalog carries ids only —
75
+ and reads nothing else: no secret is written to the file or printed.
76
+
77
+ Requests go to the **Responses** API (`@ai-sdk/openai` at
78
+ `https://amr-link.open-design.ai/v1`), which is what an Open Design API key
79
+ page recommends for Codex-style clients and what keeps thinking intact.
80
+
81
+ ## Where the sign-in is kept
82
+
83
+ magpie's `plugin-auth.json` (mode 600), as an oauth account:
84
+ `{ type: "oauth", access: <runtime key>, control: <control key>, accountId:
85
+ <email>, uid: <account id> }`. Neither key expires, so there is nothing to
86
+ renew and `refresh` is empty.
87
+
88
+ ## Use
89
+
90
+ ```
91
+ magpie plugin # opendesign (Open Design, 11 models) signed in
92
+ magpie provider test opendesign
93
+ magpie quota # opendesign · Design Plan Go · 5h 32% ↻3h
94
+ ```
95
+
96
+ ### Replacing a custom provider
97
+
98
+ The plugin signs in to the provider id `opendesign`. A **custom provider**
99
+ of that same id (Providers → the host and key by hand) takes the id first,
100
+ so the plugin's provider is then listed as `opendesign-plugin`, with no
101
+ models of its own. Delete the custom provider — `magpie provider rm
102
+ opendesign` — and the plugin's provider takes the plain id, so agent
103
+ configs pointing at `opendesign/<model>` keep working, now with the
104
+ allowance card.
105
+
106
+ ## The allowance in routing
107
+
108
+ The windows are gating windows (magpie's `aside` is left off), so magpie's
109
+ own routing reads them like any subscription's:
110
+
111
+ * a window magpie reads as used up makes the account count as used up, so
112
+ routing groups skip it and a direct call to `opendesign/<model>` is refused
113
+ with a 429 until that window renews;
114
+ * `magpie provider account-cap opendesign <account> [percent|off]` holds the
115
+ account at a share of each window, and `--window "5 hours" 70` caps one
116
+ window alone, which is how to leave headroom instead of spending the plan
117
+ to the last credit.
118
+
119
+ Since Open Design falls back to the wallet balance once the Design Plan
120
+ allowance is out, an exhausted window holds the account rather than spending
121
+ the wallet. Set the account to spend its credits, or cap the windows, to
122
+ choose which of the two magpie does.
package/index.mjs ADDED
@@ -0,0 +1,421 @@
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
+ // modelOf turns one model's facts — models.mjs's, or amr-link's catalog
237
+ // read again — into the model magpie shows.
238
+ function modelOf(id, m) {
239
+ const rate = COST[text(m?.cost)]
240
+ const thinking = THINKING[text(m?.capability)]
241
+ const context = Number(m?.context)
242
+ const output = Number(m?.output)
243
+ const input = Array.isArray(m?.input) ? m.input.filter((x) => typeof x === "string" && x !== "text") : []
244
+ return {
245
+ id,
246
+ name: text(m?.name) || id,
247
+ attachment: true,
248
+ tool_call: true,
249
+ reasoning: thinking ?? !!m?.reasoning,
250
+ ...(rate && { rate }),
251
+ limit: {
252
+ context: Number.isFinite(context) && context > 0 ? context : 200_000,
253
+ output: Number.isFinite(output) && output > 0 ? output : 32_000,
254
+ },
255
+ modalities: { input: ["text", ...input], output: ["text"] },
256
+ }
257
+ }
258
+
259
+ // facts() is amr-link's catalog entry in the seed's own shape.
260
+ function facts(m) {
261
+ const meta = m?.metadata ?? {}
262
+ const input = Array.isArray(m?.architecture?.input_modalities)
263
+ ? m.architecture.input_modalities.filter((x) => typeof x === "string" && x !== "text")
264
+ : []
265
+ return {
266
+ context: Number(meta.context_limit),
267
+ output: Number(meta.context_budget),
268
+ input,
269
+ cost: text(meta.cost),
270
+ capability: text(meta.capability),
271
+ }
272
+ }
273
+
274
+ // seed() is what the provider has before anyone signs in, from models.mjs.
275
+ function seed() {
276
+ return Object.fromEntries(Object.entries(MODELS).map(([id, m]) => [id, modelOf(id, m)]))
277
+ }
278
+
279
+ // modelsOf() shapes amr-link's live catalog as magpie's models: the list an
280
+ // account's plan entitles it to right now, in the seed's shape. A model the
281
+ // seed knows keeps its name; the catalog carries ids only.
282
+ function modelsOf(catalog) {
283
+ const out = {}
284
+ for (const m of catalog?.data ?? []) {
285
+ const id = text(m?.id)
286
+ if (!id) continue
287
+ out[id] = modelOf(id, { ...facts(m), name: MODELS[id]?.name ?? id })
288
+ }
289
+ return out
290
+ }
291
+
292
+ // ---- the plugin --------------------------------------------------------------
293
+
294
+ export const OpenDesignAuthPlugin = async () => {
295
+ // the account's workspace, one read for a while
296
+ const workspaces = new Map()
297
+ const workspace = async (controlKey) => {
298
+ const had = workspaces.get(controlKey)
299
+ if (had && Date.now() - had.at < 10 * 60_000) return had.id
300
+ const { id } = await workspaceOf(controlKey)
301
+ workspaces.set(controlKey, { id, at: Date.now() })
302
+ return id
303
+ }
304
+
305
+ // usage is magpie's own hook: the plan, the wallet, and the Design Plan's
306
+ // 5-hour and 7-day allowance, as the dashboard shows them. The control
307
+ // plane doesn't take an API key, so an API key sign-in has no allowance
308
+ // to read; an account sign-in does. Each reading keeps the sign-in
309
+ // (signIn "kept"), as the account's keys neither lapse nor renew.
310
+ const usage = async (getAuth) => {
311
+ const a = await getAuth().catch(() => null)
312
+ const controlKey = controlKeyOf(a)
313
+ if (!controlKey) {
314
+ return { windows: [], error: "Signed in with an API key: the Design Plan allowance needs the account sign-in.", signIn: "kept" }
315
+ }
316
+ const signal = AbortSignal.timeout(30_000)
317
+ try {
318
+ const id = await workspace(controlKey)
319
+ const preflight = await api(CONTROL, `/api/v1/workspaces/${encodeURIComponent(id)}/billing/preflight`, { key: controlKey, signal })
320
+ if (preflight.status === 401 || preflight.status === 403) {
321
+ return { windows: [], error: "Open Design refused the account's sign-in — sign in again.", signIn: "expired" }
322
+ }
323
+ if (!preflight.ok) throw new Error(`the Design Plan read answered ${preflight.status} (${said(preflight.body, "no reading")})`)
324
+ // the summary takes a timeZone, but nothing read here depends on it
325
+ // (only its own updatedAt and usageCount do), so none is sent
326
+ const summary = await api(CONTROL, "/api/v1/billing/summary", { key: controlKey, signal })
327
+ const plan = preflight.body?.codingPlan ?? null
328
+ const out = {
329
+ plan: thePlan(summary.ok ? summary.body : null, ""),
330
+ user: text(a?.email) || text(a?.accountId),
331
+ balance: money(preflight.body?.balanceUsd ?? (summary.ok ? summary.body?.balanceUsd : "")),
332
+ windows: allowances(plan),
333
+ signIn: "kept",
334
+ }
335
+ if (summary.ok) {
336
+ const until = when(summary.body?.subscriptionCurrentPeriodEnd)
337
+ if (until) out.until = until
338
+ if (text(summary.body?.subscriptionStatus)) out.renew = summary.body?.subscriptionCancelAtPeriodEnd ? "off" : "auto"
339
+ }
340
+ if (plan && plan.eligible === false) {
341
+ out.error = "This account has no Design Plan allowance: its requests draw on the wallet balance."
342
+ }
343
+ return out
344
+ } catch (e) {
345
+ return { windows: [], error: `Open Design usage: ${e?.message ?? e}`, signIn: "kept" }
346
+ }
347
+ }
348
+
349
+ return {
350
+ config: async (cfg) => {
351
+ cfg.provider ??= {}
352
+ const was = cfg.provider[ID] ?? {}
353
+ cfg.provider[ID] = {
354
+ name: "Open Design",
355
+ npm: NPM,
356
+ api: LINK,
357
+ ...was,
358
+ models: { ...seed(), ...(was.models ?? {}) },
359
+ }
360
+ },
361
+ // the plan decides which models an account gets, so the list is read
362
+ // per account, at that account's runtime key
363
+ provider: {
364
+ id: ID,
365
+ async models(provider, { auth } = {}) {
366
+ const key = runtimeKeyOf(auth)
367
+ if (!key) return provider.models
368
+ const r = await api(LINK, "/models", { key })
369
+ if (r.status === 401 || r.status === 403) {
370
+ throw Object.assign(new Error(`Open Design refused the account's key (${said(r.body, "unauthorized")}) — sign in again`), { signIn: "expired" })
371
+ }
372
+ if (!r.ok) return provider.models // magpie keeps the list it had
373
+ const models = modelsOf(r.body)
374
+ return Object.keys(models).length ? models : provider.models
375
+ },
376
+ },
377
+ auth: {
378
+ provider: ID,
379
+ usage,
380
+ loader: async (getAuth) => {
381
+ const key = runtimeKeyOf(await getAuth().catch(() => null))
382
+ if (!key) return {}
383
+ return { baseURL: LINK, apiKey: key }
384
+ },
385
+ methods: [
386
+ {
387
+ type: "oauth",
388
+ label: "Open Design account",
389
+ async authorize() {
390
+ const d = await startDevice()
391
+ return {
392
+ url: d.url,
393
+ instructions: d.userCode
394
+ ? `Approve the CLI sign-in on the page that opens (code ${d.userCode}). It finishes here by itself.`
395
+ : "Approve the CLI sign-in on the page that opens. It finishes here by itself.",
396
+ method: "auto",
397
+ async callback() {
398
+ try {
399
+ return await waitForDevice(d)
400
+ } catch (e) {
401
+ return { type: "failed", error: e?.message ?? String(e) }
402
+ }
403
+ },
404
+ }
405
+ },
406
+ },
407
+ {
408
+ // magpie's own key prompt: the key it saves is taken as it is, so
409
+ // a key that isn't right is the vendor's own answer to say
410
+ type: "api",
411
+ label: "Open Design API key",
412
+ placeholder: "sk-amr-…",
413
+ },
414
+ ],
415
+ },
416
+ }
417
+ }
418
+
419
+ // _internal is what the tests read through; magpie calls every exported
420
+ // function as a plugin, so only the plugin itself is exported bare.
421
+ export const _internal = { authOf, allowances, controlKeyOf, credits, modelsOf, money, runtimeKeyOf, said, thePlan, usedPercent, waitForDevice, windowName, when, workspaceOf }
package/models.mjs ADDED
@@ -0,0 +1,23 @@
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
+
11
+ export const MODELS = {
12
+ "claude-haiku-5.5": { name: "Claude Haiku 5.5", context: 1000000, output: 132000, input: ["image", "file"], cost: "low", capability: "standard" },
13
+ "deepseek-v4-flash": { name: "DeepSeek V4 Flash", context: 1048000, output: 232000, cost: "medium", capability: "standard" },
14
+ "deepseek-v4-flash-vision-exp": { name: "DeepSeek V4 Flash Vision (exp)", context: 1048000, output: 232000, input: ["image"], cost: "medium", capability: "standard" },
15
+ "deepseek-v4-pro": { name: "DeepSeek V4 Pro", context: 1048000, output: 232000, cost: "high", capability: "advanced" },
16
+ "deepseek-v4.1-flash": { name: "DeepSeek V4.1 Flash", context: 1048000, output: 232000, input: ["image"], cost: "low", capability: "advanced" },
17
+ "glm-5.3-flash": { name: "GLM 5.3 Flash", context: 1048000, output: 232000, input: ["image", "video"], cost: "low", capability: "advanced" },
18
+ "glm-5.3-flashx": { name: "GLM 5.3 FlashX", context: 1000000, output: 232000, input: ["image", "file", "video"], cost: "medium", capability: "advanced" },
19
+ "gpt-6-luna": { name: "GPT-6 Luna", context: 1050000, output: 304000, input: ["image", "file"], cost: "low", capability: "standard" },
20
+ "kimi-k2.7-code": { name: "Kimi K2.7 Code", context: 262000, output: 262000, input: ["image"], cost: "medium", capability: "advanced" },
21
+ "mimo-v2.6-flash": { name: "MiMo V2.6 Flash", context: 1048000, output: 232000, input: ["image", "audio", "video"], cost: "low", capability: "standard" },
22
+ "mimo-v2.6-pro": { name: "MiMo V2.6 Pro", context: 1048000, output: 232000, input: ["image", "audio", "video"], cost: "medium", capability: "advanced" },
23
+ }
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.4",
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,102 @@
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: the catalog has ids only
61
+ let before = {}
62
+ try {
63
+ ;({ MODELS: before } = await import(pathToFileURL(TARGET).href))
64
+ } catch {}
65
+
66
+ const input = (m) => {
67
+ const said = Array.isArray(m?.architecture?.input_modalities) ? m.architecture.input_modalities : []
68
+ return said.filter((x) => typeof x === "string" && x !== "text")
69
+ }
70
+ const lines = []
71
+ for (const m of catalog) {
72
+ const id = m.id.trim()
73
+ const meta = m.metadata ?? {}
74
+ const facts = []
75
+ const context = Number(meta.context_limit)
76
+ const output = Number(meta.context_budget)
77
+ if (Number.isFinite(context) && context > 0) facts.push(`context: ${context}`)
78
+ if (Number.isFinite(output) && output > 0) facts.push(`output: ${output}`)
79
+ const extra = input(m)
80
+ if (extra.length) facts.push(`input: [${extra.map((x) => JSON.stringify(x)).join(", ")}]`)
81
+ if (typeof meta.cost === "string") facts.push(`cost: ${JSON.stringify(meta.cost)}`)
82
+ if (typeof meta.capability === "string") facts.push(`capability: ${JSON.stringify(meta.capability)}`)
83
+ const name = before[id]?.name ?? id
84
+ lines.push(` ${JSON.stringify(id)}: { name: ${JSON.stringify(name)}${facts.length ? ", " + facts.join(", ") : ""} },`)
85
+ }
86
+
87
+ const header = `// The models an account is offered before anyone has signed in — the seed
88
+ // magpie and OpenCode read for the provider. Regenerate with
89
+ // \`bun refresh-models.mjs\` (beside this seed): it
90
+ // reads amr-link's catalog at the signed-in account's key, which is the same
91
+ // list a signed-in account is given again on every listing.
92
+ //
93
+ // name: what the model is called; context/output: its token limits; input:
94
+ // the non-text modalities it takes; cost and capability: the vendor's own
95
+ // words, which the plugin turns into magpie's rate and thinking flags.
96
+
97
+ export const MODELS = {
98
+ ${lines.join("\n")}
99
+ }
100
+ `
101
+ writeFileSync(TARGET, header)
102
+ console.log(`${TARGET}: ${lines.length} models`)