@magpie-community/opencode-opendesign-auth 0.1.15 → 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.
- package/README.md +287 -2
- package/index.mjs +776 -16
- package/package.json +7 -2
- package/video.mjs +545 -0
package/index.mjs
CHANGED
|
@@ -12,17 +12,22 @@
|
|
|
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" }
|
|
19
22
|
|
|
20
23
|
import { MODELS } from "./models.mjs"
|
|
21
24
|
import { RATES } from "./rates.mjs"
|
|
25
|
+
import { handleVideoFetch, videoConfigModels, videoModels, videoPath, withFallbackVideos } from "./video.mjs"
|
|
22
26
|
|
|
23
27
|
const ID = "opendesign"
|
|
24
28
|
const CONTROL = "https://amr-api.open-design.ai"
|
|
25
29
|
const LINK = "https://amr-link.open-design.ai/v1"
|
|
30
|
+
const MEDIA = "https://amr-link.open-design.ai/api/v1/media"
|
|
26
31
|
// WHICH API each model is asked on: magpie reads the protocol off the AI SDK
|
|
27
32
|
// package a model declares (its api.npm) — "@ai-sdk/openai" is the Responses
|
|
28
33
|
// API, "@ai-sdk/anthropic" Anthropic's messages, the compatible package chat
|
|
@@ -60,7 +65,21 @@ const alsoOf = (id) => Object.values(WIRE).filter((w) => w !== wireOf(id))
|
|
|
60
65
|
// with an x-api-key. signFor reads the API off the request's path.
|
|
61
66
|
const MESSAGES = /\/messages(\/count_tokens)?\/?$/
|
|
62
67
|
const signFor = (key) => async (input, init = {}) => {
|
|
63
|
-
const
|
|
68
|
+
const req = input instanceof Request ? input : null
|
|
69
|
+
const url = req ? req.url : String(input)
|
|
70
|
+
if (videoPath(url)) {
|
|
71
|
+
const signal = init.signal ?? req?.signal
|
|
72
|
+
if (signal?.aborted) throw signal.reason ?? new Error("The operation was aborted")
|
|
73
|
+
let body = init.body
|
|
74
|
+
if (body === undefined && req && req.method !== "GET" && req.method !== "HEAD") body = Buffer.from(await req.clone().arrayBuffer())
|
|
75
|
+
const media = await handleVideoFetch(url, {
|
|
76
|
+
method: init.method ?? req?.method ?? "GET",
|
|
77
|
+
body,
|
|
78
|
+
headers: init.headers ?? req?.headers,
|
|
79
|
+
signal,
|
|
80
|
+
}, { key, idempotencyKey: new Headers(init.headers ?? req?.headers).get("idempotency-key") ?? undefined })
|
|
81
|
+
if (media) return media
|
|
82
|
+
}
|
|
64
83
|
const h = new Headers(init.headers ?? (input instanceof Request ? input.headers : undefined))
|
|
65
84
|
let path = ""
|
|
66
85
|
try {
|
|
@@ -211,7 +230,16 @@ function authOf(user, keys = {}) {
|
|
|
211
230
|
// ---- HTTP --------------------------------------------------------------------
|
|
212
231
|
|
|
213
232
|
async function readJSON(res) {
|
|
214
|
-
|
|
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)
|
|
215
243
|
try {
|
|
216
244
|
return raw ? JSON.parse(raw) : null
|
|
217
245
|
} catch {
|
|
@@ -219,14 +247,23 @@ async function readJSON(res) {
|
|
|
219
247
|
}
|
|
220
248
|
}
|
|
221
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
|
+
|
|
222
257
|
// said() is the vendor's own words, never a page of HTML.
|
|
223
258
|
function said(body, fallback) {
|
|
224
259
|
const raw = body?.error?.message ?? body?.message ?? body?.error ?? body?.__text
|
|
225
|
-
const s = typeof raw === "string" ? raw.trim() : ""
|
|
260
|
+
const s = typeof raw === "string" ? scrub(raw.trim()) : ""
|
|
226
261
|
if (!s || s.startsWith("<")) return fallback
|
|
227
262
|
return s.length > 300 ? s.slice(0, 300) + "…" : s
|
|
228
263
|
}
|
|
229
264
|
|
|
265
|
+
const MAX_BODY = 1 << 20
|
|
266
|
+
|
|
230
267
|
async function api(base, path, { key, body, method = "GET", signal } = {}) {
|
|
231
268
|
const headers = { accept: "application/json", "user-agent": SOURCE }
|
|
232
269
|
if (key) headers.authorization = "Bearer " + key
|
|
@@ -338,6 +375,20 @@ function usedPercent(used, limit) {
|
|
|
338
375
|
|
|
339
376
|
// The window's name as the vendor's card says it: hours under a day, days
|
|
340
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
|
+
|
|
341
392
|
function windowName(seconds) {
|
|
342
393
|
const s = Number(seconds)
|
|
343
394
|
if (!Number.isFinite(s) || s <= 0) return "Allowance"
|
|
@@ -538,9 +589,472 @@ function modelsOf(catalog) {
|
|
|
538
589
|
return out
|
|
539
590
|
}
|
|
540
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
|
+
|
|
541
1040
|
// ---- the plugin --------------------------------------------------------------
|
|
542
1041
|
|
|
543
|
-
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
|
+
|
|
544
1058
|
// the account's workspace, one read for a while
|
|
545
1059
|
const workspaces = new Map()
|
|
546
1060
|
const workspace = async (controlKey) => {
|
|
@@ -560,16 +1074,16 @@ export const OpenDesignAuthPlugin = async () => {
|
|
|
560
1074
|
const a = await getAuth().catch(() => null)
|
|
561
1075
|
const controlKey = controlKeyOf(a)
|
|
562
1076
|
if (!controlKey) {
|
|
563
|
-
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" }
|
|
564
1078
|
}
|
|
565
1079
|
const signal = AbortSignal.timeout(30_000)
|
|
566
1080
|
try {
|
|
567
1081
|
const id = await workspace(controlKey)
|
|
568
1082
|
const preflight = await api(CONTROL, `/api/v1/workspaces/${encodeURIComponent(id)}/billing/preflight`, { key: controlKey, signal })
|
|
569
1083
|
if (preflight.status === 401 || preflight.status === 403) {
|
|
570
|
-
return { windows: [], error: "Open Design refused the account
|
|
1084
|
+
return { windows: [], error: "Open Design refused the account sign-in — sign in again. · Open Design 拒绝了这个账号的登录,请重新登录。", signIn: "expired" }
|
|
571
1085
|
}
|
|
572
|
-
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})`)
|
|
573
1087
|
// the summary takes a timeZone, but nothing read here depends on it
|
|
574
1088
|
// (only its own updatedAt and usageCount do), so none is sent
|
|
575
1089
|
const summary = await api(CONTROL, "/api/v1/billing/summary", { key: controlKey, signal })
|
|
@@ -587,11 +1101,242 @@ export const OpenDesignAuthPlugin = async () => {
|
|
|
587
1101
|
if (text(summary.body?.subscriptionStatus)) out.renew = summary.body?.subscriptionCancelAtPeriodEnd ? "off" : "auto"
|
|
588
1102
|
}
|
|
589
1103
|
if (plan && plan.eligible === false) {
|
|
590
|
-
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 }]
|
|
591
1149
|
}
|
|
592
1150
|
return out
|
|
593
1151
|
} catch (e) {
|
|
594
|
-
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()
|
|
595
1340
|
}
|
|
596
1341
|
}
|
|
597
1342
|
|
|
@@ -603,8 +1348,14 @@ export const OpenDesignAuthPlugin = async () => {
|
|
|
603
1348
|
// a kept copy's: magpie hands back what the hook last wrote, and a model
|
|
604
1349
|
// kept from an earlier version would otherwise stay on the Responses API
|
|
605
1350
|
// it chose for every model, or on a rate the plan no longer charges
|
|
606
|
-
const
|
|
1351
|
+
const videos = videoConfigModels()
|
|
1352
|
+
const models = { ...seed(), ...videos, ...(was.models ?? {}) }
|
|
607
1353
|
for (const [id, m] of Object.entries(models)) {
|
|
1354
|
+
if (videos[id]) {
|
|
1355
|
+
models[id] = { ...videos[id], ...m, id, tool_call: false, reasoning: false, variants: {}, modalities: { input: ["text", "image"], output: ["video"] }, limit: { context: 0, output: 0 } }
|
|
1356
|
+
delete models[id].also
|
|
1357
|
+
continue
|
|
1358
|
+
}
|
|
608
1359
|
const rate = RATES[id] === undefined ? undefined : "x" + RATES[id]
|
|
609
1360
|
// a kept copy's limit is capped too: an earlier version wrote the
|
|
610
1361
|
// catalog's 232000 for glm-5.3-flash, which amr-link refuses (CAP)
|
|
@@ -627,18 +1378,27 @@ export const OpenDesignAuthPlugin = async () => {
|
|
|
627
1378
|
async models(provider, { auth } = {}) {
|
|
628
1379
|
const key = runtimeKeyOf(auth)
|
|
629
1380
|
if (!key) return provider.models
|
|
630
|
-
const r = await
|
|
1381
|
+
const [r, media] = await Promise.all([
|
|
1382
|
+
api(LINK, "/models", { key }),
|
|
1383
|
+
api(MEDIA, "/models", { key }).catch(() => ({ ok: false, status: 0, body: null })),
|
|
1384
|
+
])
|
|
631
1385
|
if (r.status === 401 || r.status === 403) {
|
|
632
1386
|
throw Object.assign(new Error(`Open Design refused the account's key (${said(r.body, "unauthorized")}) — sign in again`), { signIn: "expired" })
|
|
633
1387
|
}
|
|
634
|
-
|
|
635
|
-
const
|
|
636
|
-
|
|
1388
|
+
const listed = r.ok ? videoModels(r.body) : {}
|
|
1389
|
+
const videos = media.ok ? videoModels(media.body)
|
|
1390
|
+
: media.status === 401 || media.status === 403 ? {}
|
|
1391
|
+
: withFallbackVideos(listed)
|
|
1392
|
+
const previous = Object.fromEntries(Object.entries(provider.models ?? {}).filter(([, model]) => !model.capabilities?.output?.video && !model.modalities?.output?.includes("video")))
|
|
1393
|
+
if (!r.ok) return { ...previous, ...videos } // magpie keeps the chat list it had
|
|
1394
|
+
const models = Object.fromEntries(Object.entries(modelsOf(r.body)).filter(([id]) => !listed[id]))
|
|
1395
|
+
return Object.keys(models).length ? { ...models, ...videos } : { ...previous, ...videos }
|
|
637
1396
|
},
|
|
638
1397
|
},
|
|
639
1398
|
auth: {
|
|
640
1399
|
provider: ID,
|
|
641
1400
|
usage,
|
|
1401
|
+
action,
|
|
642
1402
|
loader: async (getAuth) => {
|
|
643
1403
|
const key = runtimeKeyOf(await getAuth().catch(() => null))
|
|
644
1404
|
if (!key) return {}
|
|
@@ -680,4 +1440,4 @@ export const OpenDesignAuthPlugin = async () => {
|
|
|
680
1440
|
|
|
681
1441
|
// _internal is what the tests read through; magpie calls every exported
|
|
682
1442
|
// function as a plugin, so only the plugin itself is exported bare.
|
|
683
|
-
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 }
|