@magpie-community/opencode-opendesign-auth 0.1.16 → 0.1.17

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.
Files changed (3) hide show
  1. package/README.md +220 -0
  2. package/index.mjs +740 -10
  3. package/package.json +5 -2
package/README.md CHANGED
@@ -254,3 +254,223 @@ Since Open Design falls back to the wallet balance once the Design Plan
254
254
  allowance is out, an exhausted window holds the account rather than spending
255
255
  the wallet. Set the account to spend its credits, or cap the windows, to
256
256
  choose which of the two magpie does.
257
+
258
+ ## Reset cards
259
+
260
+ A reset card clears the plan's usage windows once; the answer to a spend names
261
+ the windows it cleared, and that is what is reported. The account earns cards
262
+ from the invite campaign (open-design.ai/cloud/reset: a friend's first paid
263
+ subscription within 48 hours of registering gives both sides one) and from the
264
+ vendor's own grants. A card stops being usable 30 days after it was issued.
265
+
266
+ The plugin reads the cards the account can still spend — the ones the control
267
+ plane lists as available and whose expiry has not passed — and shows how many it
268
+ holds, and when the soonest one runs out, on the account's allowance card. The
269
+ count is shown even when it is none: magpie renders it as "0 resets", and an
270
+ account that holds no card is better told that than shown nothing, which reads
271
+ as a plugin that has no such feature. A card read that fails reports no count at
272
+ all, so a failed read never looks like an empty account.
273
+
274
+ On a magpie that shows card actions (v0.1.5169 and later) the card always carries
275
+ **Get reset cards**, which opens open-design.ai/cloud/reset — what a card is, and
276
+ how one is earned — and spends nothing. When the account holds a card the card
277
+ also carries **Use a reset card**, which magpie asks you to confirm before
278
+ running. `--yes` on the command below skips that question, so the command is the
279
+ one place a card can be spent without being asked.
280
+
281
+ magpie does not localize a card action, and hands a plugin no locale to localize
282
+ by, so each label and confirm carries both languages in one string, English
283
+ first and the Chinese after a "·".
284
+
285
+ Spending goes to `POST /api/v1/reset-cards/{cardId}/use` with the workspace
286
+ whose windows it clears. The card spent is the one that runs out first, so none
287
+ that lasts longer goes before it.
288
+
289
+ The operation id is the whole of the retry safety, and it outlives the click
290
+ that started it — and the host that ran it. magpie runs one plugin host per
291
+ `magpie quota action` while the window's host lives on, so the three values are
292
+ also kept in `opendesign-reset-pending.json` in magpie's own state directory,
293
+ `~/.magpie/opendesign/` — not in the project. The `directory` a host hands a
294
+ plugin is the directory that host was started in, so a record kept there would
295
+ land in whatever repository the reader happened to be in, and the command
296
+ line's directory is usually not the window's (the vendor's console keeps the
297
+ same three in `sessionStorage`, for the same reason).
298
+ That file is read at the start of every click, not once when the plugin is
299
+ created: a long-lived host would otherwise miss, and then overwrite, what a
300
+ command line's host wrote. A lock file beside it makes one spend at a time true
301
+ across both, and it is one lock for the whole file, not one for each account:
302
+ that file holds every account's entries, and a write by one account rewrites all
303
+ of it, so while any spend holds the lock every other click is refused — another
304
+ account's included — rather than queued behind it.
305
+
306
+ A card cannot be given back, so the rules about what a lost answer means are
307
+ deliberately blunt:
308
+
309
+ * a spend that gets no answer is asked again at the same id — never a new one,
310
+ which would spend a second card to clear windows already cleared;
311
+ * a click that follows an unresolved spend asks `GET /api/v1/reset-operations/{id}`
312
+ first. `state: "used"` naming this card, operation and workspace is the reset
313
+ having landed; a 404 is the control plane having no record of it, which is the
314
+ one reading that allows the same spend to be asked again, at that same id;
315
+ * a refusal the control plane means (400, 401, 402, 403, 404, 409, 422) is
316
+ final when it answers the *first* ask of a fresh spend, and clears what was
317
+ kept. A refusal to a re-ask or a resume is not final: a 409 there may be the
318
+ vendor saying "that card is already used" about the very operation being
319
+ asked, so it is settled by the operation record instead;
320
+ * anything else — a dropped connection, a gateway 5xx, a record still settling,
321
+ a body in a shape this plugin does not know — leaves the outcome unknown, and
322
+ it is reported as unknown. The card may already be spent, so it is never
323
+ reported as refused, and the next click resumes that same spend rather than
324
+ starting another;
325
+ * a record that cannot be read, or cannot be written, stops the click before
326
+ anything is spent, and the message names the file. Only "there is no file"
327
+ means an account has nothing pending;
328
+ * a record holding an entry this plugin cannot place — one missing its ids, its
329
+ card id, its operation id or its workspace — also stops the click before
330
+ anything is spent, and leaves the file exactly as it is. Dropping such an
331
+ entry would erase the only record of a spend that may already have landed, and
332
+ filling the missing part in from the account's current cards would ask a
333
+ *different* card at the old operation id, which spends a second card.
334
+
335
+ Only an answer that says `state: "used"` **and** names this card, this operation
336
+ and this workspace is a success; the vendor's console checks the same four
337
+ things. A click reads that success from two places only: the answer to its own
338
+ spend, or the operation record read at the start of the click. It never decides
339
+ "settled" from a record consulted after a refusal, because a wrong guess there
340
+ is what spends the next card. The cost is one extra click when an answer was
341
+ lost: that click reports unconfirmed, and the click after it reads the record.
342
+ That read settles the operation; it re-asks the same card only when the control
343
+ plane never received it, and it never reaches for a different card.
344
+
345
+ One spend runs at a time, across the window's host and a command line's, so two
346
+ clicks cannot both spend a card. A second click inside the same host, for the
347
+ same account, is handed the first click's own result instead of starting
348
+ anything, so it answers without a second spend. Every other overlap — another
349
+ host, or another account in the same host — is told at once that another reset
350
+ is running: it does not wait for the lock and it does not run once the lock is
351
+ free, because by then the holder has settled and emptied the record, and a click
352
+ that ran afterwards would read that emptiness as "nothing pending" and pick a
353
+ second card. A lock left by a host that died is taken over once it is older than
354
+ three times a click's own time budget. An entry is dropped once it
355
+ settles, and nothing is dropped on age — an old record is the one thing that
356
+ stops a spend whose answer was lost from being repeated, so getting rid of one
357
+ is a deliberate act, not a timer. The record names an account by every id its
358
+ sign-in answers to, plus a hash of its key; no key is ever written to disk.
359
+
360
+ ```
361
+ magpie quota action opendesign use-reset
362
+ magpie quota action opendesign/<account> use-reset # when the provider holds more than one account
363
+ ```
364
+
365
+ Nothing is spent on a timer, on a reading, or on a request: only when the **Use a
366
+ reset card** button (or the command above) is run. **Get reset cards** just opens
367
+ a page, and spends nothing. A signing in with an API key is told it needs the
368
+ account sign-in, since the control plane takes no API key.
369
+
370
+ Two things this has not been checked against, because the account it was written
371
+ on held no card: a spend that really lands, and the exact body
372
+ `/api/v1/reset-operations/{id}` answers. The shapes above are the ones the
373
+ vendor's console reads. If the real body is a different shape, every click will
374
+ report unconfirmed and keep the record — it would rather stop and be looked at
375
+ than read an unknown body as "not spent" and spend another card. Deleting that
376
+ account's entry from `opendesign-reset-pending.json` clears it, but check the
377
+ account first: the entry may be the record of a card that really was spent, and
378
+ once it is gone the next click has nothing left to stop it spending another.
379
+
380
+ One known limitation, and it can spend a second card. A record is found by the
381
+ names a sign-in answers to, and a pasted control key is known only by a hash of
382
+ itself. Sign the same OpenDesign account in once through OAuth (which gives an
383
+ email or account id) and once by pasting a different control key under a second
384
+ magpie account, and the two have no name in common: a spend whose answer was
385
+ lost under one is not seen from the other, and a click there spends the next
386
+ card. The same blind spot covers another OS user, a different home directory and
387
+ WSL, because the record lives in one user's own directory. The file holds no
388
+ plain key: the account names, the card, workspace and operation ids, and the
389
+ first 16 hex digits of a hash.
390
+
391
+ ## 中文
392
+
393
+ 重置卡可以清空一次 Design Plan 的用量窗口,具体清了哪几个由接口返回的
394
+ `windows` 决定,本插件照实转述,不替它下结论。卡来自邀请活动
395
+ (open-design.ai/cloud/reset:好友注册后 48 小时内完成首次付费订阅,双方各得
396
+ 一张)以及厂商自己的发放;发卡后 30 天失效。
397
+
398
+ 账号卡片上会显示还有几张可用、最早一张什么时候到期。一张都没有时也会显示
399
+ `0 resets`,并保留 **Get reset cards · 获取重置卡** 这个按钮,点了打开
400
+ open-design.ai/cloud/reset,说明重置卡是什么、怎么获得,不会花掉任何卡;读到
401
+ 卡列表失败时则完全不显示张数,免得和“确实没有”混成一件事。
402
+
403
+ 有卡时同一张卡上会多一个 **Use a reset card · 用一张重置卡** 按钮,点了先弹确认。
404
+ `--yes` 会跳过这个确认,所以命令行是唯一能不问就用掉卡的地方。
405
+
406
+ 花卡请求发到 `POST /api/v1/reset-cards/{cardId}/use`,带上要清空的那个工作区。
407
+ 用掉的永远是最早过期的那张,免得先花掉能放更久的。
408
+
409
+ 重试安全全靠 `operationId`,而且它活得比一次点击、也比跑它的宿主久。
410
+ magpie 每跑一次 `magpie quota action` 都是一个独立的插件宿主进程,而窗口里的宿主
411
+ 是常驻的,所以 `cardId`、`operationId`、`workspaceId` 三个值还会写到 magpie 自己的
412
+ 状态目录 `~/.magpie/opendesign/opendesign-reset-pending.json`,**不写进项目目录**:
413
+ 宿主交给插件的 `directory` 就是它启动时的工作目录,写在那里会落进用户当时碰巧打开的
414
+ 仓库里,而命令行的工作目录通常跟窗口的不一样(官方控制台存在 sessionStorage,理由
415
+ 一样)。这个文件**每次点击开始时都会重读**,不是插件创建时读一次——常驻宿主否则就
416
+ 会看不到命令行宿主写进去的记录,回写时还会把它整个覆盖掉。旁边另有一个锁文件,
417
+ 它是整个文件一把锁、不是每个账号一把:这个文件装着所有账号的记录,改一个账号就会
418
+ 重写整份,所以只要有一笔在跑,别的点击(包括另一个账号的)都会被直接拒绝,而不是
419
+ 排队等着。
420
+
421
+ 卡花掉就退不回来,所以「答复丢了算什么」这件事上的规矩故意定得很笨:
422
+
423
+ * 没收到答复的花卡请求,会用**同一个** id 再问一次,绝不新开一个——新开就等于
424
+ 再花一张卡去清已经清过的窗口;
425
+ * 上一次悬着没结算时再点,会先读 `GET /api/v1/reset-operations/{id}`。返回
426
+ `state: "used"` 且卡、操作、工作区三项都对得上,就是已经生效;返回 404 表示控
427
+ 制面没有这笔记录,这是**唯一**允许用同一个 id 重发的情形;
428
+ * 控制面明确拒绝(400、401、402、403、404、409、422)只在它回答**第一次**发出的
429
+ 新花卡请求时算终局,会清掉记录。重发或续跑时收到的拒绝不算终局:那里的 409 很
430
+ 可能就是厂商在说「这张卡已经被用掉了」,指的正是这笔操作,所以要改由操作记录来
431
+ 判定;
432
+ * 其余情况——连接断开、网关 5xx、记录还没结算、返回形状对不上——一律当作「结果
433
+ 未知」,如实报告,不会说成「被拒绝」,因为卡可能已经花掉了。下一次点击会续上同
434
+ 一笔,不会另起一笔;
435
+ * 记录读不出来、或者写不进去,都会在花卡之前停下,并在报错里给出文件路径。只有
436
+ 「文件不存在」才等于「这个账号没有悬着的记录」;
437
+ * 记录里有一条本插件认不出来的条目——缺了身份、卡号、操作号、工作区里任意一项——
438
+ 同样在花卡之前停下,而且**文件原样不动**。丢掉这种条目会抹掉一笔可能已经落地的
439
+ 记录;用账号当前的卡去补全更糟:那张卡的命运正是未知的,补上的会是**另一张**卡,
440
+ 却沿用旧的操作号,于是又花掉一张。
441
+
442
+ 只有同时满足 `state: "used"` **且** `cardId`、`operationId`、`workspaceId` 三项
443
+ 都对得上,才算成功(官方控制台校验的也是这四项)。一次点击只在两个地方认定成功:
444
+ 它自己那笔花卡请求的回答,或者点击开头读到的操作记录。**它绝不在拒绝之后回头补
445
+ 读记录来判定已结算**——在那里猜错一次,下一次点击就会花掉第二张卡。代价是答复丢
446
+ 失时要多点一次:那一次报「未确认」,再下一次读记录结算,全程不多花卡。
447
+
448
+ 同一时间只允许一笔在跑,跨窗口宿主和命令行宿主都成立,所以两次点击不会各花一张
449
+ 卡。同一个宿主里、同一个账号的第二次点击,直接拿到第一次的结果,不另起一笔;其余
450
+ 的重叠——换一个宿主,或者在同一个宿主里换一个账号——都会**当场**被告知还有一笔在
451
+ 进行,既不排队,也不花卡。排队是行不通的:等锁释放时,那一笔已经把记录结算清空,
452
+ 排队进来的点击会把空读成「没有悬着的记录」,于是再花一张。宿主进程死掉留下的锁,
453
+ 只要老过三次点击的时间预算就会被接管。记录在结算后删除,且**不会因为过期而自动
454
+ 丢弃**——一条旧记录正是阻止「答复丢失的那笔被重复花掉」的唯一凭据,所以清掉它必须
455
+ 是人主动做的事,不能交给定时器。记录里的账号名用这家登录方式能提供的全部身份(id、
456
+ 邮箱、uid)再加上密钥的哈希;磁盘上不会出现密钥本身。
457
+
458
+ ```
459
+ magpie quota action opendesign use-reset
460
+ magpie quota action opendesign/<账号> use-reset # 这个供应商下有多个账号时
461
+ ```
462
+
463
+ 不会因为定时、读用量或任何请求自动花卡,只有点 **用一张重置卡** 或敲上面这条
464
+ 命令时才会花。**获取重置卡** 只是打开一个页面,不花卡。用 API key 登录的账号会
465
+ 被告知需要账号登录,因为控制面不接受 API key。
466
+
467
+ 有两件事没有验证过,因为写这个插件的账号手上没有卡:一次真正成功的花卡,以及
468
+ `/api/v1/reset-operations/{id}` 的真实响应体。上面的形状是从官方控制台读出来的。
469
+ 如果真实返回体是另一种形状,插件会一直报「未确认」并保留记录——它宁可卡在这里让
470
+ 人去查,也不会把读不懂的当「没花掉」再花一张。要恢复,删掉
471
+ `opendesign-reset-pending.json` 里对应那条即可——但删之前先去控制台核对:那条记录
472
+ 可能就对应一张**确实已经用掉**的卡,删掉之后,下一次点击就没有东西拦着它再花一张
473
+ 了。
474
+
475
+
476
+ 另有一条已知限制,它会真的多花一张卡。记录是按「这次登录有哪几个名字」去找的,而粘贴的控制密钥只有它自己的哈希当名字。同一个 OpenDesign 账号先用 OAuth 登录(有邮箱或账号 id),再用另一把控制密钥登进第二个 magpie 账号,两边名字没有交集——在一边丢了答复的那一笔,另一边看不见,点下去就花掉下一张。换一个操作系统用户、换一个 home 目录、或者走 WSL,也是同一个盲区,因为记录只存在某个用户自己的目录里。文件里没有任何明文密钥:存的是账号名、卡号、工作区号、操作号,以及一段哈希的前 16 位。
package/index.mjs CHANGED
@@ -12,7 +12,10 @@
12
12
  // keeps its own sign-in in ~/.amr/config.json, a different (machine-issued)
13
13
  // pair of keys, and this plugin never touches it.
14
14
 
15
- import { hostname } from "node:os"
15
+ import { homedir, hostname } from "node:os"
16
+ import { createHash, randomUUID } from "node:crypto"
17
+ import { mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs"
18
+ import { join } from "node:path"
16
19
 
17
20
  // JSON modules have a default export only, in Bun as in Node
18
21
  import pkg from "./package.json" with { type: "json" }
@@ -227,7 +230,16 @@ function authOf(user, keys = {}) {
227
230
  // ---- HTTP --------------------------------------------------------------------
228
231
 
229
232
  async function readJSON(res) {
230
- const raw = await res.text().catch(() => "")
233
+ // an answer comes from the vendor and may be any size; one megabyte is far
234
+ // past anything this plugin reads, and taking a larger one would stall the
235
+ // host on a body it is going to discard
236
+ if (Number(res.headers?.get?.("content-length") ?? 0) > MAX_BODY) {
237
+ // the body is never read, so it is cancelled rather than left open: an
238
+ // unread body keeps the connection out of the pool until it times out
239
+ await res.body?.cancel?.().catch(() => {})
240
+ return { __text: "" }
241
+ }
242
+ const raw = (await res.text().catch(() => "")).slice(0, MAX_BODY)
231
243
  try {
232
244
  return raw ? JSON.parse(raw) : null
233
245
  } catch {
@@ -235,14 +247,23 @@ async function readJSON(res) {
235
247
  }
236
248
  }
237
249
 
250
+ // Both keys this plugin holds have a fixed prefix, so one the vendor reflects
251
+ // back — in an error body, in a message — is cut here. It is cut before the
252
+ // body is shortened, which would otherwise leave half a key that no longer
253
+ // matches the pattern and would go out as it is.
254
+ const KEY = /(vela_ctrl_|sk-amr-)[A-Za-z0-9_-]+/g
255
+ const scrub = (s) => s.replace(KEY, (_, prefix) => `${prefix}…`)
256
+
238
257
  // said() is the vendor's own words, never a page of HTML.
239
258
  function said(body, fallback) {
240
259
  const raw = body?.error?.message ?? body?.message ?? body?.error ?? body?.__text
241
- const s = typeof raw === "string" ? raw.trim() : ""
260
+ const s = typeof raw === "string" ? scrub(raw.trim()) : ""
242
261
  if (!s || s.startsWith("<")) return fallback
243
262
  return s.length > 300 ? s.slice(0, 300) + "…" : s
244
263
  }
245
264
 
265
+ const MAX_BODY = 1 << 20
266
+
246
267
  async function api(base, path, { key, body, method = "GET", signal } = {}) {
247
268
  const headers = { accept: "application/json", "user-agent": SOURCE }
248
269
  if (key) headers.authorization = "Bearer " + key
@@ -354,6 +375,20 @@ function usedPercent(used, limit) {
354
375
 
355
376
  // The window's name as the vendor's card says it: hours under a day, days
356
377
  // above, the week's as "7 days".
378
+ // the vendor names a window in English ("5 hours"), and the Chinese half of a
379
+ // message reads badly with it spliced in, so the name is translated for that
380
+ // half only. Anything unrecognised is passed through rather than invented.
381
+ function zhName(name) {
382
+ const s = text(name)
383
+ if (!s) return ""
384
+ return s
385
+ .replace(/\bdays?\b/gi, "天")
386
+ .replace(/\bhours?\b/gi, "小时")
387
+ .replace(/\bminutes?\b/gi, "分钟")
388
+ .replace(/\bweeks?\b/gi, "周")
389
+ .replace(/\bmonths?\b/gi, "个月")
390
+ }
391
+
357
392
  function windowName(seconds) {
358
393
  const s = Number(seconds)
359
394
  if (!Number.isFinite(s) || s <= 0) return "Allowance"
@@ -554,9 +589,472 @@ function modelsOf(catalog) {
554
589
  return out
555
590
  }
556
591
 
592
+ // ---- reset cards -------------------------------------------------------------
593
+
594
+ // A reset card clears the Design Plan's usage windows once. The account earns
595
+ // them from the invite campaign (open-design.ai/cloud/reset) and from the
596
+ // vendor's own grants; a card stops being usable 30 days after it was issued.
597
+ // The control plane lists them by tab — "available" is what can still be
598
+ // spent, "history" is every card the account has held, spent ones included.
599
+ //
600
+ // A spend is asked at an operation id this side chooses. The vendor's own
601
+ // console keeps that id beside the card it is for (sessionStorage) and asks
602
+ // the same operation again after a lost answer, which is what makes a retry
603
+ // free: the same id twice is the same spend. This keeps the same three values
604
+ // per account (`pending`, below) and resumes at that id — never at a new one,
605
+ // which would spend a second card to clear windows already cleared.
606
+ const CARDS = "/api/v1/reset-cards"
607
+ const USE_RESET = "use-reset"
608
+
609
+ // The second button, and the only one that is always there: it opens the page
610
+ // that says what a reset card is and how one is earned, so an account holding
611
+ // none is told why rather than shown nothing. It spends nothing — magpie opens
612
+ // the url in the browser and the plugin never touches a card for it.
613
+ const HELP = "reset-cards-help"
614
+ const HELP_URL = "https://open-design.ai/cloud/reset"
615
+
616
+ // The vendor answers a spend and an operation read with one shape: the card,
617
+ // the operation, the workspace, the windows it cleared, and `state`, which is
618
+ // "used" once the reset landed. Nothing else in that body says it worked, so
619
+ // nothing else here is read as success — a status word invented here would
620
+ // turn every real success into "still clearing" the day it disagreed.
621
+ const USED = "used"
622
+
623
+ // A refusal the control plane means to be final: the card is gone, the
624
+ // sign-in is wrong, or that workspace may not be reset. Anything else — a
625
+ // dropped connection, a gateway 5xx, an answer in a shape not above — leaves
626
+ // the outcome unknown, and the operation id is kept for the next attempt.
627
+ const FINAL = [400, 401, 402, 403, 404, 409, 422]
628
+
629
+ // What a read of /reset-operations/{id} can say. The distinction is the whole
630
+ // safety of this feature, and it is not the one that looks obvious:
631
+ //
632
+ // NO_RECORD the control plane has never heard of that operation, so the
633
+ // spend cannot have landed. This is the ONLY reading that
634
+ // licenses asking the spend again at that same id.
635
+ // LANDED the operation is over and it cleared the windows.
636
+ // FAILED_OP the operation is over and it cleared nothing.
637
+ // UNKNOWN_OP everything else: a body this plugin does not know the shape of,
638
+ // an operation still settling, a read that failed, a 401.
639
+ //
640
+ // "Unknown" is not "did not spend". Treating it as "did not spend" is what
641
+ // spends a second card to clear windows the first already cleared, so it must
642
+ // stop the click and keep the record instead.
643
+ const NO_RECORD = "no-record"
644
+ const LANDED = "landed"
645
+ const FAILED_OP = "failed-operation"
646
+ const UNKNOWN_OP = "unknown-operation"
647
+
648
+ // States that mean the operation is over and cleared nothing. Only these, and
649
+ // only on a body that names this very operation, take a record off the disk.
650
+ const FAILED_STATES = new Set(["failed", "error", "canceled", "cancelled", "expired", "rejected"])
651
+
652
+ // A spend is asked again only when no answer came back, and twice more at
653
+ // most: the control plane is what decides whether it landed, and a fourth ask
654
+ // only lengthens the window in which nothing is known.
655
+ const SPEND_TRIES = 3
656
+ const RETRY_GAP = 500
657
+
658
+ // How long one click may take before it reports the outcome as unknown rather
659
+ // than hold the button open. Nothing here re-sends a spend the budget cut off.
660
+ const ACTION_BUDGET = 45_000
661
+
662
+ const signInExpired = () => Object.assign(
663
+ new Error("Open Design refused the account's sign-in — sign in again. · Open Design 拒绝了这个账号的登录,请重新登录。"),
664
+ { signIn: "expired" },
665
+ )
666
+
667
+ // cardsOf reads one tab of the account's cards, and only the ones that can be
668
+ // spent now. A body that is not this endpoint's list is a read that failed,
669
+ // not an account holding none: an empty list is `items: []`, and answering
670
+ // "no cards" for a shape this plugin doesn't know is the one answer it cannot
671
+ // support — it looks exactly like an account that has none, forever.
672
+ async function cardsOf(controlKey, tab, { signal } = {}) {
673
+ const q = `?limit=100${tab ? `&tab=${encodeURIComponent(tab)}` : ""}`
674
+ const r = await api(CONTROL, CARDS + q, { key: controlKey, signal })
675
+ if (r.status === 401 || r.status === 403) throw signInExpired()
676
+ if (!r.ok) throw new Error(`the reset-card read answered ${r.status} (${said(r.body, "no reading")}) · 读取重置卡失败:${r.status}`)
677
+ if (!Array.isArray(r.body?.items)) throw new Error("the reset-card list answered a shape this plugin does not know · 重置卡列表返回的形状本插件无法识别")
678
+ const now = Date.now()
679
+ return r.body.items
680
+ .map((c) => ({
681
+ id: text(c?.id),
682
+ state: text(c?.state),
683
+ label: text(c?.sourceLabel),
684
+ issuedAt: when(c?.issuedAt),
685
+ expiresAt: when(c?.expiresAt),
686
+ }))
687
+ // a card the vendor gives no id for cannot be spent; one that is not
688
+ // "available" — spent from the console, or expired — must not be offered,
689
+ // or the button picks it again on every click and never gets past it
690
+ .filter((c) => c.id && (!c.state || c.state === "available"))
691
+ .filter((c) => !c.expiresAt || Date.parse(c.expiresAt) > now)
692
+ }
693
+
694
+ // cardToSpend is the card a click spends: the one that runs out first, so none
695
+ // that lasts longer goes before it. A card whose expiry can't be read goes
696
+ // last, never first — an unreadable date is not evidence of an early one.
697
+ function cardToSpend(cards) {
698
+ const at = (c) => {
699
+ const t = Date.parse(c?.expiresAt ?? "")
700
+ return Number.isFinite(t) ? t : Infinity
701
+ }
702
+ return [...(cards ?? [])].sort((a, b) => at(a) - at(b))[0] ?? null
703
+ }
704
+
705
+ // spendCard asks the control plane to spend one card at the workspace whose
706
+ // windows it clears, at the operation id it was given. Only an answer that
707
+ // never arrived is asked again, and always at that same id. `tries` is how many
708
+ // times it was asked, which is what tells a refusal to a first ask apart from a
709
+ // refusal to a re-ask: the second is ambiguous, because the vendor may be
710
+ // answering "that card is already used" about the very operation being asked.
711
+ async function spendCard(controlKey, { cardId, workspaceId, operationId, signal, nap = sleep } = {}) {
712
+ const path = `${CARDS}/${encodeURIComponent(cardId)}/use`
713
+ const body = { operationId, workspaceId }
714
+ let r = null
715
+ let tries = 0
716
+ for (let attempt = 1; attempt <= SPEND_TRIES; attempt++) {
717
+ tries = attempt
718
+ try {
719
+ r = await api(CONTROL, path, { key: controlKey, method: "POST", body, signal })
720
+ } catch {
721
+ // a connection that dropped is not an answer: the spend may well have
722
+ // landed, so it is asked again at the same id and never at a new one
723
+ r = null
724
+ }
725
+ if (r && (r.ok || FINAL.includes(r.status))) return { r, tries }
726
+ if (signal?.aborted) break
727
+ if (attempt < SPEND_TRIES) await nap(RETRY_GAP * attempt)
728
+ }
729
+ return { r, tries }
730
+ }
731
+
732
+ // readOperation reads what became of a spend, and says which of the four things
733
+ // above it is. A 401 is the sign-in, not the card: it is reported as unknown
734
+ // because it says nothing about whether the spend landed, and a sign-in that
735
+ // lapsed must not take a card's record with it.
736
+ async function readOperation(controlKey, op, { signal } = {}) {
737
+ let r
738
+ try {
739
+ r = await api(CONTROL, `/api/v1/reset-operations/${encodeURIComponent(op.operationId)}`, { key: controlKey, signal })
740
+ } catch {
741
+ return { kind: UNKNOWN_OP }
742
+ }
743
+ if (r.status === 404) return { kind: NO_RECORD }
744
+ if (r.status === 401 || r.status === 403) return { kind: UNKNOWN_OP, signIn: true }
745
+ if (!r.ok) return { kind: UNKNOWN_OP }
746
+ if (usedBy(r.body, op)) return { kind: LANDED, body: r.body }
747
+ const state = text(r.body?.state).toLowerCase()
748
+ // a terminal failure has to name this operation: a body about some other
749
+ // spend is not evidence that this one failed
750
+ if (FAILED_STATES.has(state) && text(r.body?.operationId) === op.operationId) {
751
+ return { kind: FAILED_OP, body: r.body, state }
752
+ }
753
+ return { kind: UNKNOWN_OP, body: r.body }
754
+ }
755
+
756
+ // usedBy says whether a body is the answer to this spend. The vendor's own
757
+ // console checks the same four things; a body naming another card or another
758
+ // operation is not evidence that this card was spent.
759
+ function usedBy(body, { cardId, operationId, workspaceId }) {
760
+ return text(body?.state) === USED
761
+ && text(body?.cardId) === cardId
762
+ && text(body?.operationId) === operationId
763
+ && text(body?.workspaceId) === workspaceId
764
+ }
765
+
766
+ // magpie shows a card action's label and confirm as they are written — it does
767
+ // not localize them, and it hands a plugin no locale to localize by (the input
768
+ // it passes carries option, options, load, tag, usage, account and cardActions,
769
+ // and nothing else). So both languages go in the one string, English first as
770
+ // the rest of this plugin writes it, and the Chinese after a "·". The label
771
+ // stays inside magpie's 40 characters and the confirm inside its 300.
772
+ const LABEL = "Use a reset card · 用一张重置卡"
773
+ const HELP_LABEL = "Get reset cards · 获取重置卡"
774
+ // shown instead of the spend confirm when a record is still waiting: that
775
+ // click settles it and spends nothing
776
+ const SETTLE = "Settle the reset this account already started: it checks that one card and, only if the control plane never got it, re-asks that same card. · 结算上一笔已开始的重置:只查那一张卡,只有控制面没收到的情形才补发同一张,不换卡。"
777
+
778
+ function confirmText(count, first) {
779
+ const many = count === 1 ? "card" : "cards"
780
+ const ends = first?.expiresAt ? ` The first runs out ${when(first.expiresAt).slice(0, 10)}.` : ""
781
+ const endsZh = first?.expiresAt ? `最早一张 ${when(first.expiresAt).slice(0, 10)} 到期。` : ""
782
+ return `Spend 1 of the ${count} reset ${many} this account holds; it clears the Design Plan's usage windows once, and cannot be undone.${ends}`
783
+ + ` · 将用掉 ${count} 张重置卡中的 1 张,清空一次 Design Plan 用量窗口,不可撤销。${endsZh}`
784
+ }
785
+
786
+ // clearedMessage names the windows the answer says were cleared, rather than
787
+ // asserting which two a card clears: the answer carries them, and a card that
788
+ // cleared something else must not be described as this one.
789
+ function clearedMessage(body) {
790
+ const names = (Array.isArray(body?.windows) ? body.windows : [])
791
+ .map((w) => text(w?.name) || windowName(w?.durationSeconds))
792
+ .filter(Boolean)
793
+ return names.length
794
+ ? `Reset card used: ${names.join(" and ")} cleared. · 重置卡已使用:${names.map(zhName).join("、")} 已清空。`
795
+ : "Reset card used. · 重置卡已使用。"
796
+ }
797
+
798
+ // The three ways a spend can end without a cleared window, each saying whether
799
+ // the card is gone, so a reader knows what to do next.
800
+ const UNCONFIRMED = (where) => `The reset was not confirmed: the card may already be spent. Clicking again checks that same operation, not a new card. Record: ${where} · 结果未确认:这张卡可能已用掉;再点是查同一笔,不花新卡。`
801
+ const FAILED_WORD = {
802
+ failed: ["failed", "失败"], error: ["failed", "失败"], rejected: ["was rejected", "被拒绝"],
803
+ canceled: ["was cancelled", "已被取消"], cancelled: ["was cancelled", "已被取消"], expired: ["expired", "已过期"],
804
+ }
805
+ const failedReset = (state) => {
806
+ const [en, zh] = FAILED_WORD[String(state).toLowerCase()] ?? ["failed", "失败"]
807
+ return new Error(`The reset ${en}: nothing was cleared, and that card is gone. · 重置${zh}:没有清空任何窗口,这张卡已作废。`)
808
+ }
809
+ // the vendor's own sentence is worth keeping, but it is not trusted to be
810
+ // short: magpie cuts a message at 300 characters, and a term that starts at the
811
+ // end of a long one is lost, so it is cut here with room left for the rest
812
+ const refusedReset = (r) => new Error(`the reset was refused · 重置卡被拒绝:${said(r?.body, `answered ${r?.status ?? 0}`).slice(0, 160)}`)
813
+
814
+ // Every name a sign-in answers to, because the record has to be found again by
815
+ // whichever host and whichever sign-in form comes next. The window signs in
816
+ // with an account and the terminal may paste a control key for the same
817
+ // account: one name would miss the other's record, and a missed record is a
818
+ // second card. The key itself is never written; its hash is a name that still
819
+ // matches the same credential next time.
820
+ function accountIdsOf(a, controlKey) {
821
+ const ids = [text(a?.accountId), text(a?.email), text(a?.uid)].filter(Boolean)
822
+ if (controlKey) ids.push("key:" + createHash("sha256").update(controlKey).digest("hex").slice(0, 16))
823
+ return [...new Set(ids)]
824
+ }
825
+
826
+ // Where a spend that was never confirmed is kept. magpie runs one plugin host
827
+ // per `magpie quota action`, and the window's host is long-lived, so two hosts
828
+ // can be looking at the same account at once: an id kept only in memory would
829
+ // be lost between them, and the second click would spend a second card. The
830
+ // vendor's console keeps the same three values in sessionStorage for the same
831
+ // reason this keeps them beside magpie's config.
832
+ //
833
+ // Two rules make the file worth trusting, and both are load-bearing:
834
+ // * a file that cannot be read is NOT an account with nothing pending. Only
835
+ // "there is no file" means that. Anything else stops the spend, because the
836
+ // record is the one thing standing between a lost answer and a second card.
837
+ // * a record that cannot be written stops the spend before the POST, for the
838
+ // same reason in the other direction.
839
+ // Where the record of a spend lives. NOT input.directory: magpie hands a plugin
840
+ // the project directory there (the host falls back to process.cwd()), and a
841
+ // record kept beside a project is a record the next click cannot find the
842
+ // moment it runs from another directory -- which is exactly the case this file
843
+ // exists to survive. Two hosts started anywhere by the same user share this one.
844
+ const STATE_DIR = join(homedir(), ".magpie", "opendesign")
845
+ const PENDING = "opendesign-reset-pending.json"
846
+ const LOCK = "opendesign-reset-pending.lock"
847
+ // a lock this old was left by a host that died, not by one that is spending:
848
+ // it is longer than any single click is allowed to take
849
+ const LOCK_STALE = ACTION_BUDGET * 3
850
+ const LOCK_RECLAIM_BUDGET = 3_000
851
+ // a credential that an earlier build could write where a name belongs
852
+ const KEY_SHAPED = /(vela_ctrl_|sk-amr-)/
853
+ // the vendor refuses an operation id that is not a v4 UUID (400), so a record
854
+ // carrying anything else could never settle: it is treated as damaged
855
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
856
+
857
+ function storeOf(directory) {
858
+ const dir = text(directory)
859
+ const file = dir ? join(dir, PENDING) : ""
860
+ const lockFile = dir ? join(dir, LOCK) : ""
861
+
862
+ const where = () => (file ? file : "no directory")
863
+
864
+ // a spend needs somewhere to keep its record; the directory is made on first
865
+ // use, and one that cannot be made stops the click before anything is spent
866
+ const needFile = () => {
867
+ if (!dir) {
868
+ throw new Error("This plugin has no directory to record a spend in, so nothing was spent. · 本插件没有可写目录记录这次操作,没有花掉任何卡。")
869
+ }
870
+ try {
871
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
872
+ } catch (e) {
873
+ throw new Error(`The directory a reset record needs could not be made, so nothing was spent (${dir}): ${e?.message ?? e} · 无法创建重置记录所需的目录,没有花掉任何卡`)
874
+ }
875
+ }
876
+
877
+ // A record leaves this file only when the control plane settles it. Nothing
878
+ // is dropped on age: an old entry is the one thing that stops a spend whose
879
+ // answer was lost from being repeated, and the way out of a record that can
880
+ // never settle is a human deleting it, not a timer that forgets a card.
881
+ const read = () => {
882
+ needFile()
883
+ let raw
884
+ try {
885
+ raw = readFileSync(file, "utf8")
886
+ } catch (e) {
887
+ if (e?.code === "ENOENT") return []
888
+ throw new Error(`The record of an earlier reset could not be read, so nothing was spent (${where()}): ${e?.message ?? e} · 无法读取上一次重置的记录,没有花掉任何卡`)
889
+ }
890
+ let parsed
891
+ try {
892
+ parsed = JSON.parse(raw)
893
+ } catch {
894
+ throw new Error(`The record of an earlier reset is damaged, so nothing was spent (${where()}). A reset may already have been spent; check the account before deleting the file. · 上一次重置的记录已损坏,没有花掉任何卡。这张卡可能已经用掉,删文件前先确认。`)
895
+ }
896
+ if (!Array.isArray(parsed?.pending)) {
897
+ throw new Error(`The record of an earlier reset is not in the shape this plugin writes, so nothing was spent (${where()}) · 上一次重置的记录格式不符,没有花掉任何卡`)
898
+ }
899
+ const entries = parsed.pending.map((e) => ({
900
+ // every name this sign-in answers to, so a record written by the window
901
+ // is found by the command line, and one written after a sign-in change
902
+ // is still found under the name that did not change
903
+ // Every name this sign-in answers to. A key is never one of them: an
904
+ // earlier build fell back to writing the control key itself here, and a
905
+ // credential is not a name, so it is dropped and the entry is judged on
906
+ // whatever is left.
907
+ ids: (Array.isArray(e?.ids) ? e.ids : [e?.account])
908
+ .map(text)
909
+ .filter((id) => id && !KEY_SHAPED.test(id)),
910
+ cardId: text(e?.cardId),
911
+ operationId: text(e?.operationId),
912
+ workspaceId: text(e?.workspaceId),
913
+ at: Number(e?.at ?? 0),
914
+ }))
915
+ // An entry this plugin cannot place is not an entry it may drop, nor one it
916
+ // may fill in. Dropping it erases the only record of a spend that may have
917
+ // landed. Filling a missing card id from the account's current cards is
918
+ // worse: the card whose fate is unknown is the one that was asked about, so
919
+ // a substitute is a DIFFERENT card asked at the old operation id, and it
920
+ // gets spent. Every part has to be there.
921
+ const broken = entries.find((e) => !e.ids.length || !e.cardId || !e.workspaceId || !UUID.test(e.operationId))
922
+ if (broken) {
923
+ throw new Error(`The record of an earlier reset has an entry this plugin cannot place, so nothing was spent (${where()}). A reset may already have been spent: check the account before deleting that entry · 上一次重置的记录里有一条无法识别,没有花掉任何卡(${where()})。这张卡可能已经用掉,删掉那条之前请先去控制台核对`)
924
+ }
925
+ return entries
926
+ }
927
+
928
+ const write = (entries) => {
929
+ needFile()
930
+ // A name nobody can predict, created with `wx` so a symlink planted at it is
931
+ // refused rather than followed. 0600 keeps the account names and card ids to
932
+ // their owner on POSIX; on Windows the mode is ignored and the protection is
933
+ // whatever ACL the directory already carries.
934
+ const tmp = `${file}.${process.pid}.${randomUUID()}.tmp`
935
+ try {
936
+ writeFileSync(tmp, JSON.stringify({ pending: entries }, null, 1), { flag: "wx", mode: 0o600 })
937
+ renameSync(tmp, file)
938
+ } catch (e) {
939
+ try { unlinkSync(tmp) } catch {}
940
+ throw new Error(`The record of this reset could not be written, so nothing was spent (${where()}): ${e?.message ?? e} · 无法写入这次重置的记录,没有花掉任何卡`)
941
+ }
942
+ }
943
+
944
+ // Reclaiming moves a lock only if it is old, and confirms afterwards that it
945
+ // moved the one it judged old. Two hosts that both decide a lock is stale
946
+ // cannot both unlink it: the rename is atomic and only one wins, so the other
947
+ // finds nothing to take and goes back to waiting.
948
+ // Is the lock held by a host that may still be spending? One answer, one
949
+ // meaning: a lock younger than the stale bar is live, and a live lock is
950
+ // never taken.
951
+ const lockIsLive = () => {
952
+ try {
953
+ return Date.now() - statSync(lockFile).mtimeMs <= LOCK_STALE
954
+ } catch (e) {
955
+ // only "there is no lock" means no lock is live. A permission or handle
956
+ // problem is not evidence that nobody is spending, and taking it as that
957
+ // would let this host reclaim a lock that is in use.
958
+ if (e?.code === "ENOENT") return false
959
+ throw e
960
+ }
961
+ }
962
+
963
+ // Take a lock whose holder is demonstrably gone. It reports nothing: the
964
+ // caller simply tries to create its own again, and whether that worked is
965
+ // answered by the create, not by this.
966
+ const reclaimStale = () => {
967
+ try {
968
+ if (Date.now() - statSync(lockFile).mtimeMs <= LOCK_STALE) return
969
+ } catch {
970
+ return // it went away by itself
971
+ }
972
+ const aside = `${lockFile}.${process.pid}.${randomUUID()}`
973
+ try {
974
+ renameSync(lockFile, aside)
975
+ } catch {
976
+ return
977
+ }
978
+ let give = false
979
+ try {
980
+ // a rename keeps the mtime, so a fresh lock grabbed by mistake admits it
981
+ give = Date.now() - statSync(aside).mtimeMs <= LOCK_STALE
982
+ } catch {}
983
+ if (give) {
984
+ // put a live lock back if the slot is free. When it is not, the copy is
985
+ // left alone rather than deleted: deleting it would destroy the only
986
+ // record of which host held that lock.
987
+ try { writeFileSync(lockFile, readFileSync(aside, "utf8"), { flag: "wx", mode: 0o600 }) } catch { return }
988
+ }
989
+ try { unlinkSync(aside) } catch {}
990
+ }
991
+
992
+ // The lock is what makes "one spend at a time" true across the window's host
993
+ // and a command line's; an in-process flag only ever covers one of them. It is
994
+ // one lock for the file rather than one per account, because the file it
995
+ // guards is one file, and a write by one account rewrites all of it.
996
+ const lock = async () => {
997
+ needFile()
998
+ // what the lock holds is what makes it ours: a reclaim followed by a
999
+ // release must be able to tell "still mine" from "someone else's by now"
1000
+ const mine = `${process.pid} ${randomUUID()}`
1001
+ const deadline = Date.now() + LOCK_RECLAIM_BUDGET
1002
+ for (;;) {
1003
+ try {
1004
+ writeFileSync(lockFile, mine, { flag: "wx", mode: 0o600 })
1005
+ const held = () => {
1006
+ try { return readFileSync(lockFile, "utf8") === mine } catch { return false }
1007
+ }
1008
+ return {
1009
+ held,
1010
+ release: () => {
1011
+ // deleting unconditionally would delete a lock another host has
1012
+ // taken since, and let a third one in on top of it
1013
+ if (held()) { try { unlinkSync(lockFile) } catch {} }
1014
+ },
1015
+ }
1016
+ } catch (e) {
1017
+ if (e?.code !== "EEXIST") {
1018
+ throw new Error(`The lock a reset needs could not be taken, so nothing was spent (${lockFile}): ${e?.message ?? e} · 无法取得重置所需的锁,没有花掉任何卡`)
1019
+ }
1020
+ }
1021
+ // A lock that is not stale belongs to a spend happening right now, so it
1022
+ // is refused rather than waited for. Waiting is how one intent becomes
1023
+ // two: the moment it is released the record is settled and empty, and a
1024
+ // queued click would read that emptiness as "nothing pending" and pick a
1025
+ // second card. Only a lock whose holder is gone is taken.
1026
+ if (lockIsLive()) {
1027
+ throw new Error("Another reset is running, so nothing was spent. · 还有一笔重置正在进行,没有花掉任何卡。")
1028
+ }
1029
+ reclaimStale()
1030
+ if (Date.now() > deadline) {
1031
+ throw new Error("Another reset is running, so nothing was spent. · 还有一笔重置正在进行,没有花掉任何卡。")
1032
+ }
1033
+ await sleep(100)
1034
+ }
1035
+ }
1036
+
1037
+ return { read, write, lock, where }
1038
+ }
1039
+
557
1040
  // ---- the plugin --------------------------------------------------------------
558
1041
 
559
- export const OpenDesignAuthPlugin = async () => {
1042
+ export const OpenDesignAuthPlugin = async (input) => {
1043
+ // magpie's own switch: it is true only where a card action is shown and run.
1044
+ // An older magpie, and OpenCode, leave it out — and then usage lists none,
1045
+ // and action refuses rather than spend a card no one was asked about.
1046
+ const cardActions = Boolean(input?.magpie?.cardActions)
1047
+
1048
+
1049
+ // The record of a spend is read from disk inside every click, never once at
1050
+ // construction: the window's host outlives many clicks, and a command line's
1051
+ // host is a different process entirely, so a copy taken when this one started
1052
+ // would miss (and then overwrite) what the other had written.
1053
+ const store = storeOf(text(input?.stateDirectory) || STATE_DIR)
1054
+ // one spend at a time per account, within this host. Across hosts the lock
1055
+ // file does the same job; this only saves the round trip.
1056
+ const running = new Map()
1057
+
560
1058
  // the account's workspace, one read for a while
561
1059
  const workspaces = new Map()
562
1060
  const workspace = async (controlKey) => {
@@ -576,16 +1074,16 @@ export const OpenDesignAuthPlugin = async () => {
576
1074
  const a = await getAuth().catch(() => null)
577
1075
  const controlKey = controlKeyOf(a)
578
1076
  if (!controlKey) {
579
- return { windows: [], error: "Signed in with an API key: the Design Plan allowance needs the account sign-in.", signIn: "kept" }
1077
+ return { windows: [], error: "Signed in with an API key: the Design Plan allowance needs the account sign-in. · 用 API key 登录时读不到 Design Plan 额度,需要改成账号登录。", signIn: "kept" }
580
1078
  }
581
1079
  const signal = AbortSignal.timeout(30_000)
582
1080
  try {
583
1081
  const id = await workspace(controlKey)
584
1082
  const preflight = await api(CONTROL, `/api/v1/workspaces/${encodeURIComponent(id)}/billing/preflight`, { key: controlKey, signal })
585
1083
  if (preflight.status === 401 || preflight.status === 403) {
586
- return { windows: [], error: "Open Design refused the account's sign-in — sign in again.", signIn: "expired" }
1084
+ return { windows: [], error: "Open Design refused the account sign-in — sign in again. · Open Design 拒绝了这个账号的登录,请重新登录。", signIn: "expired" }
587
1085
  }
588
- if (!preflight.ok) throw new Error(`the Design Plan read answered ${preflight.status} (${said(preflight.body, "no reading")})`)
1086
+ if (!preflight.ok) throw new Error(`the Design Plan read answered ${preflight.status} (${said(preflight.body, "no reading")}) · 读取 Design Plan 额度失败(${preflight.status})`)
589
1087
  // the summary takes a timeZone, but nothing read here depends on it
590
1088
  // (only its own updatedAt and usageCount do), so none is sent
591
1089
  const summary = await api(CONTROL, "/api/v1/billing/summary", { key: controlKey, signal })
@@ -603,11 +1101,242 @@ export const OpenDesignAuthPlugin = async () => {
603
1101
  if (text(summary.body?.subscriptionStatus)) out.renew = summary.body?.subscriptionCancelAtPeriodEnd ? "off" : "auto"
604
1102
  }
605
1103
  if (plan && plan.eligible === false) {
606
- out.error = "This account has no Design Plan allowance: its requests draw on the wallet balance."
1104
+ out.error = "This account has no Design Plan allowance: its requests draw on the wallet balance. · 这个账号没有 Design Plan 额度,请求走钱包余额。"
1105
+ }
1106
+ // The count is what the list holds, not the campaign's
1107
+ // `usage.remainingSuccessfulUses`: that counter tracks the six
1108
+ // invite-earned uses and does not move for a card the vendor granted
1109
+ // (measured: a card from `pool_admin_targeted_reset_v1` was spent on
1110
+ // 2026-11-30 and the counter still read 0 of 6). Showing it as the card
1111
+ // count would say "none used" to an account that used one.
1112
+ //
1113
+ // A reading that worked is reported even when it holds no card: magpie
1114
+ // renders `count: 0` as "0 resets" (measured), and an account that has
1115
+ // none is better told so, with the page that explains how one is earned,
1116
+ // than shown nothing at all. A reading that failed reports nothing here,
1117
+ // so the line is absent rather than a made-up zero — the two cases must
1118
+ // not look the same.
1119
+ const cards = await cardsOf(controlKey, "available", { signal }).catch(() => null)
1120
+ if (cards) {
1121
+ const first = cardToSpend(cards)
1122
+ out.resets = { count: cards.length, ...(first?.expiresAt && { until: first.expiresAt }) }
1123
+ }
1124
+ // the page button is offered whether or not the card read worked: it
1125
+ // spends nothing, and a read that failed is exactly when a reader wants
1126
+ // to be told what a card is and where they come from
1127
+ // A spend whose answer was lost leaves a record, and the click that
1128
+ // settles it is this same action. When the card it names was the last
1129
+ // one, the vendor now lists no cards at all -- so the button has to come
1130
+ // from the record, not from the count, or the only way to settle it is
1131
+ // to edit the file by hand.
1132
+ let carried = null
1133
+ try {
1134
+ const ids = accountIdsOf(a, controlKey)
1135
+ carried = store.read().find((e) => e.ids.some((id) => ids.includes(id))) ?? null
1136
+ } catch (e) {
1137
+ // a record this plugin cannot read is reported when a click runs, not
1138
+ // here -- but saying nothing at all would leave the card looking as if
1139
+ // nothing were wrong, so the reason is put on the card as well
1140
+ out.error = scrub(String(e?.message ?? e)).slice(0, 300)
1141
+ }
1142
+ if (cardActions) {
1143
+ const use = carried
1144
+ ? { id: USE_RESET, label: LABEL, confirm: SETTLE }
1145
+ : cards?.length
1146
+ ? { id: USE_RESET, label: LABEL, confirm: confirmText(cards.length, cardToSpend(cards)) }
1147
+ : null
1148
+ out.actions = [...(use ? [use] : []), { id: HELP, label: HELP_LABEL }]
607
1149
  }
608
1150
  return out
609
1151
  } catch (e) {
610
- return { windows: [], error: `Open Design usage: ${e?.message ?? e}`, signIn: "kept" }
1152
+ return { windows: [], error: `Open Design usage: ${scrub(String(e?.message ?? e))}`, signIn: "kept", ...(cardActions ? { actions: [{ id: HELP, label: HELP_LABEL }] } : {}) }
1153
+ }
1154
+ }
1155
+
1156
+ // action is magpie's own hook: the button on the usage card runs it, and
1157
+ // only when the user clicks it — never on a timer, a reading, or a request.
1158
+ // Spending a card is the one thing that changes anything, and the card it
1159
+ // spends is read here rather than carried from the reading that drew the
1160
+ // button: a card can be spent elsewhere between the two, and the id must be
1161
+ // one the account still holds. The other button only opens a page.
1162
+ const action = async (getAuth, provider, { id, signal } = {}) => {
1163
+ if (id === HELP) return { url: HELP_URL }
1164
+ if (id !== USE_RESET) throw new Error(`Open Design has no card action called ${id} · Open Design 没有这个卡片操作`)
1165
+ // the button is only drawn where magpie runs card actions. A call from
1166
+ // anywhere else — an older magpie, OpenCode, another module importing this
1167
+ // one — is refused here rather than spend a card no one was asked about.
1168
+ if (!cardActions) throw new Error("This magpie does not run card actions; nothing was spent. · 这个 magpie 不运行卡片操作,没有花掉任何卡。")
1169
+ const a = await getAuth().catch(() => null)
1170
+ const controlKey = controlKeyOf(a)
1171
+ if (!controlKey) throw new Error("Spending a reset card needs the account sign-in; an API key has no plan to reset. · 用重置卡需要账号登录,API key 没有可重置的套餐。")
1172
+ const ids = accountIdsOf(a, controlKey)
1173
+ // one spend at a time per account within this host: a double-click gets the
1174
+ // first one's answer rather than a second card. Across hosts the lock file
1175
+ // does the same job.
1176
+ const key = ids.join("|")
1177
+ if (running.has(key)) return running.get(key)
1178
+ const run = spend(controlKey, ids, { signal })
1179
+ running.set(key, run)
1180
+ try {
1181
+ return await run
1182
+ } finally {
1183
+ running.delete(key)
1184
+ }
1185
+ }
1186
+
1187
+ // spend is one click's whole spend: resume what an earlier click left, or pick
1188
+ // a card and ask. Two invariants carry the safety of this, both because a
1189
+ // spent card cannot be given back:
1190
+ //
1191
+ // 1. A click reads success from exactly two places — the answer the control
1192
+ // plane gave to this click's own POST, or an operation record read at the
1193
+ // very start of the click, which is how the click after a lost answer
1194
+ // finds out the earlier one landed. It never reads success from an
1195
+ // operation record consulted after a refusal: a 409 to a re-ask may be
1196
+ // the control plane saying "that card is used" about this very
1197
+ // operation, and a click that took it as either success or failure would
1198
+ // be acting on a guess about a card that may be gone.
1199
+ // 2. Only NO_RECORD — the control plane never having heard of the operation
1200
+ // — licenses spending a different card. A record this plugin cannot read,
1201
+ // or one still settling, keeps the record and reports the outcome as
1202
+ // unknown. "Unknown" is not "did not spend": treating it as that is
1203
+ // exactly what spends a second card on the next click.
1204
+ //
1205
+ // The record goes to disk before the POST, so a host that never sees the
1206
+ // answer can still learn what became of that operation afterwards.
1207
+ const spend = async (controlKey, ids, { signal } = {}) => {
1208
+ const budget = AbortSignal.timeout(ACTION_BUDGET)
1209
+ // where `any` is missing the caller's cancel counts for more than the
1210
+ // budget: a click the user stopped must stop, even at the cost of the
1211
+ // deadline
1212
+ const bound = (() => {
1213
+ if (!signal) return budget
1214
+ if (typeof AbortSignal.any === "function") return AbortSignal.any([signal, budget])
1215
+ // an older runtime composes the two by hand rather than dropping one:
1216
+ // losing the caller's cancel hangs on a click the user stopped, and
1217
+ // losing the budget hangs on a control plane that never answers
1218
+ const both = new AbortController()
1219
+ const stop = () => both.abort()
1220
+ for (const s of [signal, budget]) s.addEventListener?.("abort", stop, { once: true })
1221
+ return both.signal
1222
+ })()
1223
+
1224
+ const { held, release } = await store.lock()
1225
+ try {
1226
+ const mine = (e) => e.ids.some((id) => ids.includes(id))
1227
+
1228
+ // Every write re-reads the file. The snapshot below is a moment old, and
1229
+ // rewriting the whole file from it would drop an entry another host wrote
1230
+ // in between — including one for another account, whose next click would
1231
+ // then spend a second card.
1232
+ const set = (op) => {
1233
+ // the lock is what makes rewriting this file safe. A host that has lost
1234
+ // it -- reclaimed as stale by someone else -- must not write, or it
1235
+ // would erase the record of the host that holds it now.
1236
+ if (!held()) {
1237
+ throw new Error("Another reset took over this account's record, so nothing was spent. · 另一笔重置接管了这条记录,没有花掉任何卡。")
1238
+ }
1239
+ const rest = store.read().filter((e) => !mine(e))
1240
+ store.write(op ? [...rest, op] : rest)
1241
+ }
1242
+ // a settle that cannot be written must not turn a landed reset into an
1243
+ // error: the card is already gone and the record still says so, so the
1244
+ // next click settles it from there
1245
+ const settled = () => { try { set(null) } catch {} }
1246
+
1247
+ // read inside the lock and inside the click: the window's host and a
1248
+ // command line's are different processes, and a copy taken at start-up
1249
+ // would neither see what the other wrote nor keep it when writing back
1250
+ const held_ = store.read().filter(mine)
1251
+ if (held_.length > 1) {
1252
+ throw new Error(`The record of an earlier reset has two entries for this account, so nothing was spent (${store.where()}) · 上一次重置的记录里同一个账号有两条待定,没有花掉任何卡`)
1253
+ }
1254
+ const carried = held_[0] ?? null
1255
+
1256
+ // what became of a spend an earlier click started and never learned the
1257
+ // end of. Only NO_RECORD sends this click on to ask that same operation
1258
+ // again; a record it cannot read stops the click, because the card may
1259
+ // already be gone and only the control plane can say otherwise.
1260
+ if (carried) {
1261
+ const seen = await readOperation(controlKey, carried, { signal: bound })
1262
+ if (seen.kind === LANDED) {
1263
+ settled()
1264
+ return { message: clearedMessage(seen.body) }
1265
+ }
1266
+ if (seen.kind === FAILED_OP) {
1267
+ settled()
1268
+ throw failedReset(seen.state)
1269
+ }
1270
+ if (seen.kind === UNKNOWN_OP) {
1271
+ // a lapsed sign-in says nothing about the card, so the record stays
1272
+ if (seen.signIn) throw signInExpired()
1273
+ throw new Error(UNCONFIRMED(store.where()))
1274
+ }
1275
+ // NO_RECORD: it never landed. The same operation is asked again, at
1276
+ // that same id, and never at a different card.
1277
+ }
1278
+
1279
+ // the workspace is read again here rather than taken from usage's cache:
1280
+ // this id is the target of something that cannot be undone, and an
1281
+ // account's active workspace can change between two readings. A resumed
1282
+ // spend keeps the workspace it was started at, because an answer is only
1283
+ // this spend's if the workspace matches.
1284
+ const workspaceId = carried?.workspaceId || (await workspaceOf(controlKey, { signal: bound })).id
1285
+ // a resumed spend re-asks the card the record names whether or not the
1286
+ // vendor still lists it: the vendor is the one that knows if it is spent,
1287
+ // and asking about it is the only way to find out
1288
+ const cardId = carried?.cardId || cardToSpend(await cardsOf(controlKey, "available", { signal: bound }))?.id
1289
+ if (!cardId) throw new Error("This account has no reset card to spend. · 这个账号没有可用的重置卡。")
1290
+
1291
+ const operationId = carried?.operationId || randomUUID()
1292
+ // a resume adds this sign-in's names to the record, never replaces
1293
+ // them: dropping an alias here is what makes the record an orphan after
1294
+ // the next sign-in change, and an orphan is a second card
1295
+ const op = { ids: [...new Set([...ids, ...(carried?.ids ?? [])])], cardId, operationId, workspaceId, at: Date.now() }
1296
+ // on disk BEFORE the POST: a host that loses the answer has to be able to
1297
+ // find this operation afterwards, and a record that cannot be written
1298
+ // means no other host could either, so the spend does not happen at all
1299
+ set(op)
1300
+
1301
+ const { r, tries } = await spendCard(controlKey, { cardId, workspaceId, operationId, signal: bound })
1302
+
1303
+ // the sign-in, not the card: the spend was refused before it ran, but the
1304
+ // record is about the card, and signing in again must not lose it
1305
+ if (r?.status === 401 || r?.status === 403) throw signInExpired()
1306
+
1307
+ // the answer to this click's own POST: the one place a POST settles
1308
+ if (r?.ok && usedBy(r.body, op)) {
1309
+ settled()
1310
+ return { message: clearedMessage(r.body) }
1311
+ }
1312
+
1313
+ // A refusal to the first ask of a fresh spend is the answer: that card was
1314
+ // already used before this click touched it, so nothing is owed. On a
1315
+ // re-ask or a resume it is ambiguous instead — the vendor may be answering
1316
+ // "that card is already used" about this very operation — so it is left to
1317
+ // the operation record, and only a record that reports the operation over
1318
+ // takes it away.
1319
+ if (r && FINAL.includes(r.status) && tries === 1 && !carried) {
1320
+ settled()
1321
+ throw refusedReset(r)
1322
+ }
1323
+
1324
+ const seen = await readOperation(controlKey, op, { signal: bound })
1325
+ // Only an operation the control plane says is over, and names, clears the
1326
+ // record. A 404 does NOT, here: the same 404 is what a wrong path, a
1327
+ // gateway rule, or a read that has not caught up would answer, and
1328
+ // clearing on it is exactly how one click spends two cards.
1329
+ if (seen.kind === FAILED_OP) {
1330
+ settled()
1331
+ throw failedReset(seen.state)
1332
+ }
1333
+ // LANDED is deliberately not success here either: the next click reads
1334
+ // this record at its start and settles it, and this click reports what it
1335
+ // honestly knows, which is that the answer never arrived.
1336
+ if (seen.signIn) throw signInExpired()
1337
+ throw new Error(UNCONFIRMED(store.where()))
1338
+ } finally {
1339
+ release()
611
1340
  }
612
1341
  }
613
1342
 
@@ -669,6 +1398,7 @@ export const OpenDesignAuthPlugin = async () => {
669
1398
  auth: {
670
1399
  provider: ID,
671
1400
  usage,
1401
+ action,
672
1402
  loader: async (getAuth) => {
673
1403
  const key = runtimeKeyOf(await getAuth().catch(() => null))
674
1404
  if (!key) return {}
@@ -710,4 +1440,4 @@ export const OpenDesignAuthPlugin = async () => {
710
1440
 
711
1441
  // _internal is what the tests read through; magpie calls every exported
712
1442
  // function as a plugin, so only the plugin itself is exported bare.
713
- export const _internal = { authOf, signFor, plainThinkingSse, allowances, controlKeyOf, credits, modelsOf, money, rateOf, runtimeKeyOf, said, startDevice, thePlan, usedPercent, waitForDevice, windowName, when, workspaceOf }
1443
+ export const _internal = { accountIdsOf, authOf, signFor, plainThinkingSse, allowances, cardToSpend, cardsOf, clearedMessage, controlKeyOf, credits, modelsOf, money, readOperation, rateOf, runtimeKeyOf, said, scrub, spendCard, startDevice, thePlan, usedBy, usedPercent, waitForDevice, windowName, when, workspaceOf }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-opendesign-auth",
3
- "version": "0.1.16",
4
- "description": "Open Design Cloud (Design Plan) in OpenCode and magpie: the account's device sign-in, chat and native video models, and the plan's 5-hour and 7-day allowance",
3
+ "version": "0.1.17",
4
+ "description": "Open Design Cloud (Design Plan) in OpenCode and magpie: the account's device sign-in, chat and native video models, the plan's 5-hour and 7-day allowance, and its reset cards",
5
5
  "type": "module",
6
6
  "main": "./opencode.mjs",
7
7
  "files": [
@@ -30,5 +30,8 @@
30
30
  "name": "Open Design",
31
31
  "icon": "https://open-design.ai/favicon.svg"
32
32
  },
33
+ "scripts": {
34
+ "test": "bun test"
35
+ },
33
36
  "exports": { ".": "./opencode2.mjs" }
34
37
  }