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

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