@jianmu-plugins/opencode-workbuddy-auth 0.0.0-stage → 0.2.34

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/index.mjs ADDED
@@ -0,0 +1,4776 @@
1
+ // OpenCode provider plugins for WorkBuddy's plans, Tencent's two builds of
2
+ // WorkBuddy (CodeBuddy's desktop agent):
3
+ // - workbuddy: the China build, copilot.tencent.com
4
+ // - workbuddy-ai: the international build, www.workbuddy.ai
5
+ // A WorkBuddy account signs in in the browser (Tencent's page, polled for
6
+ // the token as WorkBuddy's desktop app does) or is taken from WorkBuddy
7
+ // desktop's own sign-in. Its chats are chat completions at <endpoint>/v2,
8
+ // streamed only, with WorkBuddy's headers: a request whose User-Agent isn't
9
+ // WorkBuddy/<version> is refused (error 10085). Each build's headers are
10
+ // those of its current desktop app (see SITES' app, cli and appName).
11
+
12
+ import { createHash, randomBytes } from "node:crypto"
13
+ import { closeSync, createReadStream, openSync, readFileSync, readdirSync, readSync, statSync } from "node:fs"
14
+ import { homedir } from "node:os"
15
+ import { dirname, isAbsolute, join } from "node:path"
16
+ import { createGunzip, gzipSync } from "node:zlib"
17
+
18
+ const POLL_MS = 1000
19
+ const SIGN_IN_MS = 5 * 60 * 1000
20
+ const EARLY_MS = 60 * 1000 // a token this close to its end is refreshed before a request
21
+ const LEAD_MS = 5 * 60 * 1000 // and this close, magpie renews it ahead of time (auth.refresh)
22
+ const KEEP_RENEWED_MS = 60 * 1000 // how long a refresh's result answers for the old refresh token
23
+
24
+ // [id, name, context, efforts, output]
25
+ //
26
+ // output is the config's maxOutputTokens, where a config read from the site
27
+ // gave it (testdata/config-561.json, config-efforts.json); without it magpie
28
+ // fills in models.dev's, which for deepseek-v4.1-flash is 384000 where
29
+ // WorkBuddy's own config says 128000 (sayagoodbyeplz on Discord). A model
30
+ // with none here is left to models.dev, as before.
31
+ const CN_MODELS = [
32
+ ["auto", "Auto", 168000],
33
+ ["hy4-preview-f", "Hy4 preview", 1000000, ["high"]],
34
+ ["hy3", "Hy3", 192000, ["low", "high"]],
35
+ ["hy3-x", "Hy3-X", 192000, ["low", "high"]],
36
+ ["deepseek-v4.1-flash", "Deepseek-V4.1-Flash", 1000000, ["none", "low", "high", "max"], 128000],
37
+ ["glm-5.3", "GLM-5.3", 1000000, ["low", "high", "max"]],
38
+ ["glm-5.3-flash", "GLM-5.3-Flash", 1000000, ["low", "high", "max"], 131072],
39
+ ["glm-5.2", "GLM-5.2", 1000000, ["high", "xhigh"]],
40
+ ["glm-5.1", "GLM-5.1", 200000],
41
+ ["glm-5v-turbo", "GLM-5v-Turbo", 200000],
42
+ ["minimax-m3", "MiniMax-M3", 512000],
43
+ ["kimi-k3-1", "Kimi-K3", 1000000, ["low", "high", "xhigh"]],
44
+ ["kimi-k2.7", "Kimi-K2.7-Code", 256000],
45
+ ["kimi-k2.6", "Kimi-K2.6", 256000],
46
+ ["deepseek-v4-pro", "Deepseek-V4-Pro", 1000000, ["none", "high", "xhigh"], 128000],
47
+ ]
48
+
49
+ const AI_MODELS = [
50
+ ["default-model", "Default", 176000, undefined, 24000],
51
+ ["fast-model", "Fast", 200000, undefined, 32000],
52
+ ["balanced-model", "Balanced", 256000],
53
+ ["primary-model", "Primary", 272000, undefined, 72000],
54
+ ["deep-model", "Deep", 176000],
55
+ ["gpt-5.5", "GPT-5.5", 1000000],
56
+ ["gpt-5.4", "GPT-5.4", 272000],
57
+ ["gpt-5.3-codex", "GPT-5.3-Codex", 272000],
58
+ ["gemini-3.1-pro", "Gemini-3.1-Pro", 400000],
59
+ ["gemini-3.5-flash", "Gemini-3.5-Flash", 1000000, undefined, 65536],
60
+ ["glm-5.3", "GLM-5.3", 1000000, ["low", "high", "max"]],
61
+ ["glm-5.2", "GLM-5.2", 1000000, ["high", "xhigh"], 48000],
62
+ ["hy3", "Hy3", 192000, ["low", "high"], 64000],
63
+ ["kimi-k3", "Kimi-K3", 1000000, undefined, 32000],
64
+ ["kimi-k2.6", "Kimi-K2.6", 256000],
65
+ ["minimax-m3", "MiniMax-M3", 512000],
66
+ ]
67
+
68
+ const SITES = {
69
+ workbuddy: {
70
+ id: "workbuddy",
71
+ name: "WorkBuddy",
72
+ endpoint: "https://copilot.tencent.com",
73
+ authID: "workbuddy-desktop",
74
+ platform: "workbuddy",
75
+ ai: false,
76
+ // the desktop app the requests are WorkBuddy's own client's of: its
77
+ // version, its bundled CLI's (@genie/agent-cli), and the CLI's
78
+ // product.json applicationName. Read from WorkBuddy 5.9.3.42398134,
79
+ // the update feed's current build on 2026-10-28.
80
+ app: "5.9.3",
81
+ cli: "2.165.0",
82
+ appName: "WorkBuddy",
83
+ // 5.9's CLI says on each chat where the agent runs; the desktop's own
84
+ // is "local-agent" (X-Agent-Runtime, absent in 5.8)
85
+ runtime: "local-agent",
86
+ // where this build's API keys are made (see keyAccount)
87
+ keys: "https://www.workbuddy.cn/profile/keys",
88
+ models: CN_MODELS,
89
+ // it serves the Claude models on Anthropic's Messages API too (see
90
+ // nativeOf)
91
+ messages: true,
92
+ },
93
+ "workbuddy-ai": {
94
+ id: "workbuddy-ai",
95
+ name: "WorkBuddy AI",
96
+ endpoint: "https://www.workbuddy.ai",
97
+ authID: "workbuddy-desktop-ai",
98
+ platform: "workbuddy-ai",
99
+ ai: true,
100
+ // WorkBuddy AI 5.9.3.42398134, its update feed's current build on
101
+ // 2026-10-29 (see the China build's): the same CLI as the China
102
+ // build's 5.9.3, byte for byte but for product.json, and the same
103
+ // Electron (37.10.3); its desktop puts agentRuntime local-agent in the
104
+ // prompt meta as the China build's does
105
+ app: "5.9.3",
106
+ cli: "2.165.0",
107
+ appName: "workbuddy-ai",
108
+ runtime: "local-agent",
109
+ keys: "https://www.workbuddy.ai/profile/keys",
110
+ models: AI_MODELS,
111
+ // models whose images WorkBuddy AI drops though its config says they
112
+ // take them (see textOnly)
113
+ noImages: /^glm-/,
114
+ },
115
+ }
116
+
117
+ // A model's context is its config's maxInputTokens, on both sites. 0.2.7
118
+ // capped deepseek-v4.1-flash at 100000 on copilot.tencent.com from one
119
+ // report's error ("prompt is too long: 100001 tokens > 100000 maximum"),
120
+ // and it was wrong: on 2026-10-31 China Free-plan accounts of three other
121
+ // users took 110,041 to 992,389-token prompts on it there, the whole prompt
122
+ // read (needles recalled), and the vendor's own refusal of 1,157,831 named
123
+ // 1048576 as the maximum (plugins#561). The cap made every client compact at
124
+ // 100k. Where a prompt really is too long, WorkBuddy's 400 says "prompt is
125
+ // too long" and goes to the client as it came (explained), which magpie
126
+ // reads as the context overflowing (context_length_exceeded): the agent is
127
+ // told to compact, and the account isn't rested for it.
128
+
129
+ // OFF_TAKEN are models that turn thinking off for reasoning_effort "none"
130
+ // though the config says onlyReasoning (so WorkBuddy's own client offers no
131
+ // off switch): deepseek-v4.1-flash, and the same model under its paid id.
132
+ // Measured 2026-10-31 on www.workbuddy.ai: "none" answered 200 with 0
133
+ // reasoning tokens on both, where "low" thought 1221 and 1127; and on the
134
+ // China build by the reporter of plugins#563 (0 reasoning tokens, a 30-item
135
+ // prompt in 14s instead of 50s). Without the level magpie sends "low" for
136
+ // a client's "none".
137
+ const OFF_TAKEN = new Set(["deepseek-v4.1-flash", "deepseek-v4.1-flash-sg"])
138
+
139
+ // textOnly says whether site drops the images sent to model, whatever its
140
+ // config says. On 2026-10-13, with a real WorkBuddy AI account (Yirasumi on
141
+ // Discord), www.workbuddy.ai's /v3/config marked every model
142
+ // supportsImages: true, but a chat to glm-5.3-flash, glm-5.3 or glm-5.2
143
+ // came back saying "[System reminder: the current model does not support
144
+ // images. Content filtered. ...]": the server had taken the image out.
145
+ // Its other models (deepseek-v4.1-flash, kimi, gemini, grok, gpt) read
146
+ // them, and WorkBuddy (China)'s glm-5.3-flash does too, so this is WorkBuddy
147
+ // AI's GLM models alone. Said text-only, magpie's image-describing model
148
+ // reads the image for them; a user who said the model takes images keeps
149
+ // their own answer (magpie's settings, over what this list says).
150
+ function textOnly(site, model) {
151
+ return !!site.noImages?.test(model)
152
+ }
153
+
154
+ const NPM = "@ai-sdk/openai-compatible"
155
+ const hex = () => randomBytes(16).toString("hex")
156
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
157
+ const api = (site) => site.endpoint + "/v2"
158
+
159
+ // MESSAGES is the API SDK package for Anthropic's Messages shape, which
160
+ // WorkBuddy serves the Claude models on, beside its chat completions:
161
+ // <endpoint>/v1/messages. Those models are Anthropic's own, and their
162
+ // thinking is asked for the way Anthropic asks it (thinking.type adaptive
163
+ // with output_config.effort), which the chat endpoint has no field for: a
164
+ // chat carries reasoning_effort alone, and WorkBuddy's chat endpoint gives
165
+ // the same answer at every level, so an agent that picked max got no more
166
+ // than one that picked low. See nativeOf.
167
+ const NPM_MESSAGES = "@ai-sdk/anthropic"
168
+ const apiMessages = (site) => site.endpoint + "/v1"
169
+
170
+ // nativeOf is whether site serves model on Messages rather than chat: a
171
+ // Claude model, on a site that serves Messages at all (site.messages).
172
+ // Measured 2026-10-24 on WorkBuddy's China build, each model of
173
+ // /v3/config's cli agent asked on /v1/messages: claude-opus-5.5,
174
+ // claude-sonnet-5.5, claude-opus-5 and claude-opus-4.8-1m answered in
175
+ // Anthropic's stream; glm-5.3 and deepseek-v4.1-flash answered 500, gpt-5.5
176
+ // and kimi-k3-1 400. An account may still be refused a Claude model it has
177
+ // no entitlement for (11158), which is the account's, not the endpoint's.
178
+ // WorkBuddy AI (www.workbuddy.ai) has no such route: /v1/messages,
179
+ // /v2/messages and /v1/messages?beta=true are all "404 Route Not Found"
180
+ // there, whatever the model, so its models stay on chat, a Claude one too
181
+ // should it list one.
182
+ function nativeOf(site, model) {
183
+ return site?.messages === true && /^claude-/i.test(String(model ?? ""))
184
+ }
185
+
186
+ // ---- WorkBuddy's API ------------------------------------------------------
187
+
188
+ class WBError extends Error {
189
+ constructor(message, code, status, said) {
190
+ super(message)
191
+ this.code = code
192
+ this.status = status
193
+ this.said = said // as magpie's built-in (wbCall) worded it
194
+ }
195
+ }
196
+
197
+ // call makes a request of WorkBuddy's plugin API, which answers
198
+ // {code, msg, data}; a code but 0 is an error.
199
+ async function call(site, method, path, headers = {}, body) {
200
+ const res = await fetch(site.endpoint + path, {
201
+ method,
202
+ headers: {
203
+ "Content-Type": "application/json",
204
+ Accept: "application/json",
205
+ "User-Agent": "WorkBuddy/" + site.app,
206
+ ...headers,
207
+ },
208
+ body: body === undefined ? undefined : JSON.stringify(body),
209
+ signal: AbortSignal.timeout(30000),
210
+ })
211
+ const text = await res.text()
212
+ let env = {}
213
+ try {
214
+ env = JSON.parse(text)
215
+ } catch {}
216
+ const code = Number.parseInt(env.code, 10) || 0
217
+ if (!res.ok) {
218
+ const why = env.msg || env.message || env.error?.message || text.slice(0, 200) || res.statusText
219
+ const said = code ? env.msg || `error ${code}` : env.msg || statusText(res.status)
220
+ throw new WBError(`${site.name}: ${why} (HTTP ${res.status}${env.code ? ", code " + env.code : ""})`, env.code, res.status, said)
221
+ }
222
+ if (env.code) throw new WBError(`${site.name}: ${env.msg || "error"} (${env.code})`, env.code, res.status, env.msg || `error ${code}`)
223
+ return env.data
224
+ }
225
+
226
+ function domainOf(site, a) {
227
+ return a.domain || new URL(api(site)).host
228
+ }
229
+
230
+ // CLOUD_HOSTED are the hosts of WorkBuddy's cloud-hosted enterprises, as
231
+ // WorkBuddy's own product.json lists them (cloudHostedDomain, read from
232
+ // WorkBuddy 5.5.6 and WorkBuddy AI): <enterprise>.sso.copilot.tencent.com,
233
+ // <enterprise>.copilot.qq.com, <enterprise>.sso.codebuddy.cn. Such an
234
+ // account's sign-in names that host as its domain, and WorkBuddy's client
235
+ // serves it there: the cloud-hosted product has no endpoint of its own, and
236
+ // the client sets the enterprise's endpoint in its place
237
+ // (applyEnterpriseEndpoint). Tencent's own iOA host
238
+ // (tencent.sso.copilot.tencent.com) matches the pattern but is served at
239
+ // copilot.tencent.com (product.ioa.json), as the client checks iOA first.
240
+ const CLOUD_HOSTED = [/^[a-z0-9-]+\.sso\.copilot\.tencent\.com$/, /^[a-z0-9-]+\.copilot\.qq\.com$/, /^[a-z0-9-]+\.sso\.codebuddy\.cn$/]
241
+ const IOA = new Set(["tencent.sso.copilot.tencent.com", "tencent.sso.codebuddy.cn"])
242
+
243
+ // endpointOf is where a's requests go: its enterprise's own host for a
244
+ // cloud-hosted enterprise's account, else the site's endpoint. Before
245
+ // 0.2.32 every account was sent to the site's endpoint, which a
246
+ // cloud-hosted enterprise's token isn't valid at.
247
+ function endpointOf(site, a) {
248
+ const d = typeof a?.domain === "string" ? a.domain.trim().toLowerCase() : ""
249
+ if (!d || IOA.has(d) || a?.source === "key") return site.endpoint
250
+ return CLOUD_HOSTED.some((r) => r.test(d)) ? "https://" + d : site.endpoint
251
+ }
252
+
253
+ // at is site with a's endpoint (endpointOf): the same site when that is
254
+ // the site's own.
255
+ const atHosts = new Map()
256
+ function at(site, a) {
257
+ const end = endpointOf(site, a)
258
+ if (end === site.endpoint) return site
259
+ const key = site.id + "\n" + end
260
+ let s = atHosts.get(key)
261
+ if (!s) atHosts.set(key, (s = { ...site, endpoint: end }))
262
+ return s
263
+ }
264
+
265
+ // moved is url sent to a's endpoint instead of the site's, when they differ.
266
+ function moved(site, a, url) {
267
+ const end = endpointOf(site, a)
268
+ if (end === site.endpoint || !url.startsWith(site.endpoint + "/")) return url
269
+ return end + url.slice(site.endpoint.length)
270
+ }
271
+
272
+ // merge takes a token WorkBuddy gave (sign-in or refresh) into the
273
+ // stored sign-in, times given as at-ms or in-seconds.
274
+ function merge(a, got) {
275
+ const now = Date.now()
276
+ const out = { ...a, access: got.accessToken }
277
+ if (got.refreshToken) out.refresh = got.refreshToken
278
+ if (got.domain) out.domain = got.domain
279
+ if (got.tokenType) out.tokenType = got.tokenType
280
+ if (got.expiresAt > 0) out.expires = got.expiresAt
281
+ else if (got.expiresIn > 0) out.expires = now + got.expiresIn * 1000
282
+ if (got.refreshExpiresAt > 0) out.refreshExpiresAt = got.refreshExpiresAt
283
+ else if (got.refreshExpiresIn > 0) out.refreshExpiresAt = now + got.refreshExpiresIn * 1000
284
+ return out
285
+ }
286
+
287
+ function stale(a) {
288
+ return !!a.expires && Date.now() >= a.expires - EARLY_MS
289
+ }
290
+
291
+ // renewing is each refresh under way, by site and the refresh token it
292
+ // spends; renewed is what each gave, kept a minute so one that read the
293
+ // old refresh token after it was spent (magpie's auth.refresh, a request)
294
+ // takes that rather than spending it again.
295
+ const renewing = new Map()
296
+ const renewed = new Map()
297
+
298
+ function refreshable(a) {
299
+ return !!a.refresh && !(a.refreshExpiresAt && Date.now() >= a.refreshExpiresAt)
300
+ }
301
+
302
+ // renew spends a's refresh token, once: those who come while it runs, or
303
+ // within KEEP_RENEWED_MS of it, get what it gave. save keeps the result.
304
+ function renew(site, a, save) {
305
+ const key = site.id + "\n" + a.refresh
306
+ const done = renewed.get(key)
307
+ if (done && Date.now() - done.at < KEEP_RENEWED_MS) return Promise.resolve(merged(a, done.next))
308
+ let r = renewing.get(key)
309
+ if (!r) {
310
+ r = (async () => {
311
+ const got = await call(at(site, a), "POST", "/v2/plugin/auth/token/refresh", {
312
+ "X-Refresh-Token": a.refresh,
313
+ "X-Auth-Refresh-Source": "plugin",
314
+ "X-Domain": domainOf(site, a),
315
+ ...enterpriseHeaders(a),
316
+ }, {})
317
+ if (!got?.accessToken) throw Object.assign(new Error("WorkBuddy gave no refreshed token"), { bare: true })
318
+ const next = merge(a, got)
319
+ renewed.set(key, { next, at: Date.now() })
320
+ await save?.(next)
321
+ return next
322
+ })().finally(() => renewing.delete(key))
323
+ renewing.set(key, r)
324
+ }
325
+ return r.then((next) => merged(a, next))
326
+ }
327
+
328
+ // merged is a with the tokens another's refresh gave over it.
329
+ function merged(a, next) {
330
+ const out = { ...a }
331
+ for (const k of TOKEN_FIELDS) if (k in next) out[k] = next[k]
332
+ return out
333
+ }
334
+ const TOKEN_FIELDS = ["access", "refresh", "expires", "refreshExpiresAt", "domain", "tokenType"]
335
+
336
+ // fresh is the sign-in with an access token that isn't about to end:
337
+ // refreshed (and saved) when it is. A refresh that fails, or a refresh
338
+ // token that has ended, leaves the access token there is. Its failures
339
+ // are worded as the built-in's (wbFresh), "WorkBuddy" on both sites.
340
+ async function fresh(site, client, a) {
341
+ if (!stale(a)) return a
342
+ if (!refreshable(a)) {
343
+ if (a.access) return a
344
+ throw new Error("this WorkBuddy account is signed out; sign in again")
345
+ }
346
+ try {
347
+ return await renew(site, a, async (next) => {
348
+ try {
349
+ await client?.auth?.set?.({ path: { id: site.id }, body: next })
350
+ } catch {}
351
+ })
352
+ } catch (e) {
353
+ if (a.access) return a
354
+ if (e?.bare) throw e
355
+ throw new Error(`WorkBuddy token refresh: ${e?.said ?? e?.message ?? e}`)
356
+ }
357
+ }
358
+
359
+ // refreshed is what magpie's auth.refresh gives for a browser sign-in:
360
+ // the fields a refresh changed, nothing when there's nothing to renew.
361
+ // magpie saves them itself.
362
+ async function refreshed(site, auth) {
363
+ if (auth?.type !== "oauth" || auth.source === "desktop" || !auth.access || !auth.refresh) return undefined
364
+ // a refresh token that has ended is said plainly, never as signIn
365
+ // "expired": the built-in never marked a WorkBuddy account
366
+ if (!refreshable(auth)) throw new Error("this WorkBuddy account is signed out; sign in again")
367
+ let next
368
+ try {
369
+ next = await renew(site, auth)
370
+ } catch (e) {
371
+ if (e?.bare) throw e
372
+ throw new Error(`WorkBuddy token refresh: ${e?.said ?? e?.message ?? e}`)
373
+ }
374
+ const out = {}
375
+ for (const k of TOKEN_FIELDS) if (k in next && next[k] !== auth[k]) out[k] = next[k]
376
+ return Object.keys(out).length ? out : undefined
377
+ }
378
+
379
+ // sign sets on headers what WorkBuddy's desktop app sends with a chat: the
380
+ // account's own, the client's, and the attribution WorkBuddy's usage list
381
+ // shows as the client that asked (使用端). The chat's ids — the
382
+ // conversation's, the turn's, the message's — are attend's below.
383
+ //
384
+ // WorkBuddy's own client sends the whole of this on both builds
385
+ // (application-manifest.js: X-Agent-Purpose "conversation", X-IDE-Name/Type
386
+ // "WorkBuddy", X-IDE-Version, X-Product "SaaS"); a chat without them is
387
+ // counted under no client at all, which is the empty 使用端 a request shows
388
+ // when only some of the group is there. The gate below used to give the China
389
+ // build none of the client's headers, so every China-build request was
390
+ // attribution-less.
391
+ function sign(site, a, headers) {
392
+ headers.set("Authorization", "Bearer " + a.access)
393
+ headers.set("X-User-Id", a.uid ?? "")
394
+ if (a.source === "key") {
395
+ // the key's own header, and no X-Domain: a key's session has none
396
+ headers.set("X-API-Key", a.key)
397
+ headers.delete("X-Domain")
398
+ } else {
399
+ headers.delete("X-API-Key")
400
+ headers.set("X-Domain", domainOf(site, a))
401
+ }
402
+ headers.set("X-Product", "SaaS")
403
+ headers.set("X-IDE-Type", "WorkBuddy")
404
+ headers.set("User-Agent", cliAgent(site))
405
+ headers.set("X-Requested-With", "XMLHttpRequest")
406
+ headers.set("X-Agent-Intent", "craft")
407
+ headers.set("X-Agent-Purpose", "conversation")
408
+ headers.set("X-IDE-Name", "WorkBuddy")
409
+ headers.set("X-IDE-Version", site.app)
410
+ for (const [k, v] of Object.entries(enterpriseHeaders(a))) headers.set(k, v)
411
+ }
412
+
413
+ // cliAgent is the User-Agent WorkBuddy's desktop CLI sends its API calls
414
+ // (a chat, the product config) with: UserAgentHttpInterceptor's
415
+ // buildUserAgent puts the platform (CLIENT_INFO_PLATFORM "WorkBuddy", at
416
+ // the app's version) first, then the CLI's applicationName at the same
417
+ // version, then CLIENT_INFO_USER_AGENT_EXTENSION, "CLI/<its version>".
418
+ function cliAgent(site) {
419
+ return `WorkBuddy/${site.app} ${site.appName}/${site.app} CLI/${site.cli}`
420
+ }
421
+
422
+ // OPENAI_SDK and NODE are what the CLI's chats go out through: the OpenAI
423
+ // SDK it bundles (openai 6.25.0) and the Node its Electron runs it on
424
+ // (Electron 37.10.3, ELECTRON_RUN_AS_NODE).
425
+ const OPENAI_SDK = "6.25.0"
426
+ const NODE = "v22.21.1"
427
+ const SDK_OS = { darwin: "MacOS", win32: "Windows", linux: "Linux", freebsd: "FreeBSD", openbsd: "OpenBSD", android: "Android" }
428
+ const SDK_ARCH = { x64: "x64", arm64: "arm64", arm: "arm", ia32: "x32", x32: "x32" }
429
+
430
+ // chatHeaders sets on a chat what WorkBuddy's CLI adds to its model
431
+ // requests alone (axiosToFetchAdapter, both builds): the agent type
432
+ // (resolveModelCallAgentType, "main" for the conversation's own agent),
433
+ // the runtime where a build sends one, and the OpenAI SDK's own headers,
434
+ // which the CLI's fetch passes on. Its client has a 1200s timeout and
435
+ // no retries of its own.
436
+ function chatHeaders(site, headers) {
437
+ headers.set("X-Agent-Type", "main")
438
+ if (site.runtime) headers.set("X-Agent-Runtime", site.runtime)
439
+ else headers.delete("X-Agent-Runtime")
440
+ headers.set("Accept", "application/json")
441
+ headers.set("X-Stainless-Retry-Count", "0")
442
+ headers.set("X-Stainless-Timeout", "1200")
443
+ headers.set("X-Stainless-Lang", "js")
444
+ headers.set("X-Stainless-Package-Version", OPENAI_SDK)
445
+ headers.set("X-Stainless-OS", SDK_OS[process.platform] ?? (process.platform ? `Other:${process.platform}` : "Unknown"))
446
+ headers.set("X-Stainless-Arch", SDK_ARCH[process.arch] ?? (process.arch ? `other:${process.arch}` : "unknown"))
447
+ headers.set("X-Stainless-Runtime", "node")
448
+ headers.set("X-Stainless-Runtime-Version", NODE)
449
+ }
450
+
451
+ // keyAccount is the account an API key (OpenCode's {type: "api", key}) is
452
+ // sent as, the way WorkBuddy's own CLI sends one (@tencent-ai/codebuddy-code
453
+ // 2.177.0, CODEBUDDY_API_KEY): its API-key sign-in is a session whose access
454
+ // token is the key and whose uid is "anonymous_" and the key's last eight
455
+ // characters (ACC_USER_ID unset), personal, with no domain and no
456
+ // enterprise; and its model requests carry the key twice, X-API-Key and
457
+ // Authorization: Bearer (getCustomHeaders). Its requests go to the build's
458
+ // own host, the one its other sign-ins use: for the China build that is
459
+ // copilot.tencent.com, the CLI's own endpoint for that build
460
+ // (CODEBUDDY_INTERNET_ENVIRONMENT=internal, product.internal.json), and the
461
+ // same API as www.workbuddy.cn, where the keys are made (the CLI's
462
+ // CN_SAAS_CORE_API_FRONT_DOORS); for the international build,
463
+ // www.workbuddy.ai (the CLI's own default, www.codebuddy.ai, is CodeBuddy's,
464
+ // not WorkBuddy's). Nothing renews a key.
465
+ function keyAccount(auth) {
466
+ const key = typeof auth?.key === "string" ? auth.key.trim() : ""
467
+ if (!key) return null
468
+ return { key, access: key, uid: "anonymous_" + key.slice(-8), source: "key" }
469
+ }
470
+
471
+ // remoteConfig says whether WorkBuddy's own CLI asks /v3/config for the
472
+ // account's models with this key: only for keys that start ck_ or pt_
473
+ // (shouldLoadRemoteConfig); any other key keeps the built-in list.
474
+ const remoteConfig = (key) => /^(ck_|pt_)/.test(key)
475
+
476
+ // enterpriseHeaders names the enterprise (team) an account signed in as, as
477
+ // WorkBuddy's own client does on every request it makes for that account
478
+ // (its auth interceptor: X-Enterprise-Id and X-Tenant-Id, both the
479
+ // account's enterpriseId). Without them WorkBuddy answers as the personal
480
+ // account: /v3/config lists the personal plan's models and not the
481
+ // enterprise's (#75). A personal account has none and sends none.
482
+ function enterpriseHeaders(a) {
483
+ const id = typeof a?.enterpriseId === "string" ? a.enterpriseId.trim() : ""
484
+ return id ? { "X-Enterprise-Id": id, "X-Tenant-Id": id } : {}
485
+ }
486
+
487
+ // enterpriseOf is the enterprise the account a sign-in gave belongs to,
488
+ // { id, name }: the one /login/account names, else, for an account that
489
+ // isn't personal, the one WorkBuddy's account list has for it — the same
490
+ // choice WorkBuddy's own client makes (mergeCurrentAccountDetails): the
491
+ // uid's only entry of that type, or the only one it last signed in to. None
492
+ // found is personal ({ id: "" }).
493
+ //
494
+ // Which account that is was chosen on WorkBuddy's sign-in page: after a
495
+ // phone sign-in it lists the person's accounts (personal, a team,
496
+ // 「WorkBuddy 教育公益版」…) and binds the one picked to the sign-in's state
497
+ // (POST /console/login/enterprise/<id>?state=…), so the token and
498
+ // /login/account this plugin reads by that state are the chosen account's.
499
+ async function enterpriseOf(site, a, who) {
500
+ const name = (x) => (typeof x?.enterpriseName === "string" ? x.enterpriseName.trim() : "")
501
+ const own = typeof who?.enterpriseId === "string" ? who.enterpriseId.trim() : ""
502
+ const type = String(who?.type ?? "").trim().toLowerCase()
503
+ if (!own && (!type || type === "personal")) return { id: "", name: "" }
504
+ // a name /login/account leaves out is the account list's, as the
505
+ // client merges the two
506
+ if (own && name(who)) return { id: own, name: name(who) }
507
+ let list
508
+ try {
509
+ list = await call(at(site, a), "GET", "/v2/plugin/accounts", {
510
+ Authorization: "Bearer " + a.access,
511
+ "X-Domain": domainOf(site, a),
512
+ })
513
+ } catch {
514
+ return { id: own, name: "" }
515
+ }
516
+ const mine = (list?.accounts ?? []).filter((x) => x?.uid === who.uid && typeof x.enterpriseId === "string" && x.enterpriseId.trim())
517
+ if (own) return { id: own, name: name(mine.find((x) => x.enterpriseId.trim() === own)) }
518
+ const same = mine.filter((x) => String(x.type ?? "").trim().toLowerCase() === type)
519
+ const last = mine.filter((x) => x.lastLogin)
520
+ const pick = same.length === 1 ? same[0] : last.length === 1 ? last[0] : mine.length === 1 ? mine[0] : undefined
521
+ return pick ? { id: pick.enterpriseId.trim(), name: name(pick) } : { id: "", name: "" }
522
+ }
523
+
524
+ // accountName is what magpie lists an account a sign-in gave as: the
525
+ // person's name, and for an enterprise (team, education) account the
526
+ // enterprise's too. One person's personal account and their enterprise one
527
+ // share the uid and the nickname, and magpie's plugin host keeps one
528
+ // account per name and uid (settle in host.js): named alike, signing in to
529
+ // 「WorkBuddy 教育公益版」 took the place of the same person's personal
530
+ // account, and the two could never be in one pool. An enterprise WorkBuddy
531
+ // names no name for is told by the end of its id.
532
+ function accountName(who, ent) {
533
+ const person = who?.nickname || who?.phoneNumber || who?.uid || ""
534
+ if (!ent?.id) return person
535
+ const team = ent.name || `enterprise ${ent.id.slice(-6)}`
536
+ return person ? `${person} · ${team}` : team
537
+ }
538
+
539
+ // WorkBuddy's own client names each chat to its gateway four ways: the
540
+ // conversation it belongs to, the user send (turn) it answers, the message
541
+ // itself, and the request that carried it. Its backend counts a user send as
542
+ // one request by X-Conversation-Request-ID: a chat carrying a new one every
543
+ // time is counted on its own, so one send that takes several steps — a tool
544
+ // call answered and sent again, a retry — shows up
545
+ // in the usage detail as many requests. The ids below are made from what
546
+ // names the conversation and the turn, so every step of one send carries the
547
+ // same turn id and the user's next message carries another, as WorkBuddy's
548
+ // own client does.
549
+
550
+ // SESSION carries the conversation magpie (or OpenCode) names a request by,
551
+ // from the chat.headers hook to the loader's fetch. It goes no further.
552
+ const SESSION = "x-magpie-workbuddy-session"
553
+
554
+ // SALT is what the ids are derived with, so an id says nothing of the words
555
+ // it was made from. New in each process, as WorkBuddy's own ids are one
556
+ // conversation's own within a run.
557
+ const SALT = randomBytes(16).toString("hex")
558
+
559
+ // idFor is the 32 hex digits WorkBuddy's own ids are made of, made of a
560
+ // name of the thing the id is for (a turn, a conversation) and what names it.
561
+ // key is a string, or the pieces it is made of: the digest is the same
562
+ // either way, and a key made of a 45 MiB message is never joined into one
563
+ // string to be hashed (plugins#461). Each piece goes to the hash whole:
564
+ // Bun reads a one-byte string's bytes in place, where a piece cut into
565
+ // slices was measured costing a copy of each slice.
566
+ function idFor(kind, key) {
567
+ const h = createHash("sha256").update(`${SALT}|${kind}|`)
568
+ // a surrogate pair's first half ending one piece waits for the next, as
569
+ // the joined key would hold the pair together
570
+ let held = ""
571
+ for (let piece of typeof key === "string" ? [key] : key) {
572
+ if (held) piece = held + piece
573
+ held = ""
574
+ const c = piece.charCodeAt(piece.length - 1)
575
+ if (c >= 0xd800 && c <= 0xdbff) {
576
+ held = piece.slice(-1)
577
+ piece = piece.slice(0, -1)
578
+ }
579
+ h.update(piece)
580
+ }
581
+ if (held) h.update(held)
582
+ return h.digest("hex").slice(0, 32)
583
+ }
584
+
585
+ // signatureOf is a message content's signature: its text, and a digest of
586
+ // every part that isn't text (an image, a file), so a turn of images alone is
587
+ // a turn of its own too. A tool result's part — carried in a user message by
588
+ // clients of Anthropic's shape — is left out: it is not what the user said,
589
+ // and it changes with every step of the send.
590
+ function signatureOf(content) {
591
+ return signatureParts(content).join("")
592
+ }
593
+
594
+ // signatureParts is signatureOf in the pieces it is joined from, none empty
595
+ function signatureParts(content) {
596
+ if (typeof content === "string") return content ? [content] : []
597
+ if (!Array.isArray(content)) return []
598
+ const out = []
599
+ for (const part of content) {
600
+ const type = part?.type ?? ""
601
+ if (type === "" || type === "text") {
602
+ if (typeof part?.text === "string" && part.text) out.push(part.text)
603
+ } else if (type !== "tool_result" && type !== "tool-result") {
604
+ out.push(`[${type}:${createHash("sha256").update(JSON.stringify(part)).digest("hex").slice(0, 8)}]`)
605
+ }
606
+ }
607
+ return out
608
+ }
609
+
610
+ // answeredBefore is whether msgs[i] answers the message before it — a tool's
611
+ // result, or an assistant's calls — rather than carrying the user's own
612
+ // words. A client that sends a tool result's images in a user message (pi's
613
+ // "Attached image(s) from tool result:") puts that message right after the
614
+ // result, and a turn keyed on it would be a turn of its own on every step.
615
+ //
616
+ // Anthropic's Messages shape says the same another way: a tool's result is a
617
+ // tool_result block in a user message, after an assistant message of
618
+ // tool_use blocks. Such a user message answers too, whatever text sits
619
+ // beside the results (Claude Code puts a reminder there, a user's words typed
620
+ // mid-task go there as well), and so does one right after it, as a chat's
621
+ // does after role "tool". Messages that are neither the user's nor the
622
+ // assistant's (Claude Code's role "system" ones, which carry a turn's
623
+ // effort, its environment and its token count between the steps) stand
624
+ // between them without changing which message answers.
625
+ function answeredBefore(msgs, i) {
626
+ if (hasBlock(msgs[i], "tool_result")) return true
627
+ let j = i - 1
628
+ while (j >= 0 && msgs[j]?.role === "system") j--
629
+ const prev = msgs[j]
630
+ if (prev === null || typeof prev !== "object") return false
631
+ if (prev.role === "tool") return true
632
+ if (prev.role === "user" && hasBlock(prev, "tool_result")) return true
633
+ if (prev.role !== "assistant") return false
634
+ if (Array.isArray(prev.tool_calls) && prev.tool_calls.length > 0) return true
635
+ return hasBlock(prev, "tool_use")
636
+ }
637
+
638
+ // hasBlock is whether message m's content holds a block of type.
639
+ function hasBlock(m, type) {
640
+ return Array.isArray(m?.content) && m.content.some((p) => p?.type === type)
641
+ }
642
+
643
+ // turnKey names the user send a chat answers: the body's last user message
644
+ // that is the user's own, by its place and its signature. Every step of one
645
+ // send repeats it; the user's next message changes it. "" for a chat whose
646
+ // last such message has nothing signable in it (an empty message) or which
647
+ // has none at all: the caller then makes a fresh id for that request, as
648
+ // before these were derived at all.
649
+ function turnKey(chat) {
650
+ return turnParts(chat).join("")
651
+ }
652
+
653
+ // turnParts is turnKey in pieces (idFor takes them): [] for ""
654
+ function turnParts(chat) {
655
+ const msgs = Array.isArray(chat?.messages) ? chat.messages : []
656
+ for (let i = msgs.length - 1; i >= 0; i--) {
657
+ if (msgs[i]?.role !== "user" || answeredBefore(msgs, i)) continue
658
+ const sig = signatureParts(msgs[i].content)
659
+ return sig.length ? [`u${i}:`, ...sig] : []
660
+ }
661
+ return []
662
+ }
663
+
664
+ // conversationKey names the conversation a chat belongs to: the session
665
+ // magpie or OpenCode names (its chat.headers hook), else the chat's first
666
+ // user message, which every later turn of it repeats. "" when neither names
667
+ // one — a body that isn't a chat, or one with no user message in it — and no
668
+ // conversation id is sent then: a made-up one would be a conversation of the
669
+ // request's own, which is what fragments the usage detail in the first place.
670
+ function conversationKey(chat, session) {
671
+ return conversationParts(chat, session).join("")
672
+ }
673
+
674
+ // conversationParts is conversationKey in pieces (idFor takes them): [] for ""
675
+ function conversationParts(chat, session) {
676
+ if (session) return [`session:${session}`]
677
+ const msgs = Array.isArray(chat?.messages) ? chat.messages : []
678
+ for (const m of msgs) {
679
+ if (m?.role !== "user") continue
680
+ const sig = signatureParts(m.content)
681
+ if (sig.length) return ["first:", ...sig]
682
+ }
683
+ return []
684
+ }
685
+
686
+ // isMessages says whether a request is an Anthropic Messages one, which
687
+ // site serves the Claude models natively: its URL ends at /messages or at
688
+ // the counting endpoint beside it (/v1/messages/count_tokens, which the
689
+ // chat route's rewrites would otherwise turn into a chat), or (a body is
690
+ // all there is to go on) its system is Anthropic's blocks rather than a
691
+ // chat's string, and its tools carry input_schema where a chat's carry a
692
+ // function's parameters. A chat's own tools can look either way, so the URL
693
+ // decides when there is one.
694
+ function isMessages(url, body) {
695
+ const path = (() => {
696
+ try {
697
+ return new URL(String(url ?? "")).pathname
698
+ } catch {
699
+ return ""
700
+ }
701
+ })()
702
+ if (path) return /\/messages(\/count_tokens)?$/.test(path)
703
+ const b = chatOf(body)
704
+ if (!b) return false
705
+ if (Array.isArray(b.system)) return true
706
+ const tools = Array.isArray(b.tools) ? b.tools : []
707
+ return tools.some((t) => t && typeof t === "object" && "input_schema" in t && !t.function)
708
+ }
709
+
710
+ // withoutUnsigned is a Messages body without the thinking blocks that carry
711
+ // no signature, or whose signature WorkBuddy doesn't take.
712
+ //
713
+ // A conversation that began elsewhere — on WorkBuddy's chat route, whose
714
+ // thinking comes back unsigned, or on any other provider — and goes on here
715
+ // carries such blocks in its history, and WorkBuddy refuses the whole request
716
+ // for one of them when another assistant message holds a signed block:
717
+ // 11159 "Invalid `signature` in `thinking` block. The block is bound to a
718
+ // different conversation" (or the same wrapped in 11133). Seen 2026-10-24 in
719
+ // real Claude Code sessions moved onto this route mid-way: every request of
720
+ // two of them refused, each attempt alike, until the session ended. Replayed
721
+ // the same day, with a real account (20+ runs each):
722
+ //
723
+ // unsigned thinking alone, no signed block anywhere ....... 200
724
+ // one unsigned-only assistant message + a signed one ...... 11159
725
+ // that message with the unsigned block taken out .......... 200
726
+ // unsigned and signed blocks in the SAME message .......... 200
727
+ // thinking.block_binding.prefix_mismatch_behavior=drop_block ... 11159
728
+ //
729
+ // So what binds a signed block is the history it sits in, and a message that
730
+ // is thinking alone can't be part of it; whether that thinking is signed
731
+ // makes no difference (a signed block alone is accepted too). The signature
732
+ // itself isn't checked for where it came from: a block keeping a signature
733
+ // of an unrelated turn, of another model (sonnet-5.5's on opus-5.5), or
734
+ // another account's answers 200, while a truncated or altered one is 11159.
735
+ // What WorkBuddy checks is that it reads as a signature.
736
+ //
737
+ // A block with no signature can't be verified by the model anyway, so
738
+ // nothing it could use is lost. A message whose only block that was gets an
739
+ // empty text block: measured the same day, that history still answers 200
740
+ // with a signed turn after it (three runs), where the unsigned block itself
741
+ // answers 11159 (three runs), and Anthropic's API refuses an empty text
742
+ // block — 200 here means WorkBuddy takes it. The signed blocks, this
743
+ // route's own, go back as they came, as Anthropic asks. A body without
744
+ // unsigned thinking is body itself, byte for byte.
745
+ function withoutUnsigned(body) {
746
+ const b = chatOf(body)
747
+ return unsignedOn(b) ? JSON.stringify(b) : body
748
+ }
749
+
750
+ // unsignedOn makes withoutUnsigned's change to a body's object; true when it made one
751
+ function unsignedOn(b) {
752
+ const msgs = b?.messages
753
+ if (!Array.isArray(msgs)) return false
754
+ let changed = false
755
+ for (const m of msgs) {
756
+ if (m?.role !== "assistant" || !Array.isArray(m.content)) continue
757
+ const kept = m.content.filter((p) => !(p?.type === "thinking" && !p.signature))
758
+ if (kept.length === m.content.length) continue
759
+ changed = true
760
+ m.content = kept.length ? kept : [{ type: "text", text: "" }]
761
+ }
762
+ return changed
763
+ }
764
+
765
+ // withoutSignedThinking is a Messages body without any thinking block at
766
+ // all, for a refusal saying a signature is not one WorkBuddy made (see the
767
+ // retry in the loader). An assistant message left with nothing gets an
768
+ // empty text block, as withoutUnsigned leaves it. null for a body with no
769
+ // thinking block to drop: the retry would send the same request again.
770
+ function withoutSignedThinking(body) {
771
+ const b = chatOf(body)
772
+ const msgs = b?.messages
773
+ if (!Array.isArray(msgs)) return null
774
+ let dropped = 0
775
+ for (const m of msgs) {
776
+ if (m?.role !== "assistant" || !Array.isArray(m.content)) continue
777
+ const kept = m.content.filter((p) => p?.type !== "thinking")
778
+ if (kept.length === m.content.length) continue
779
+ dropped += m.content.length - kept.length
780
+ m.content = kept.length ? kept : [{ type: "text", text: "" }]
781
+ }
782
+ return dropped ? JSON.stringify(b) : null
783
+ }
784
+
785
+ // chatOf is a chat's body as the object it is, null for one that isn't: a
786
+ // body that isn't text (bytes), or isn't JSON at all.
787
+ // bodyString is a body given as bytes, as text; anything else is null.
788
+ function bodyString(body) {
789
+ if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) return new TextDecoder().decode(body)
790
+ return null
791
+ }
792
+
793
+ function chatOf(body) {
794
+ if (typeof body !== "string") return null
795
+ try {
796
+ const b = JSON.parse(body)
797
+ return b !== null && typeof b === "object" ? b : null
798
+ } catch {
799
+ return null
800
+ }
801
+ }
802
+
803
+ // sessionOf takes the session a chat.headers hook named off the headers,
804
+ // with the header: it goes no further than here. Its length is capped as
805
+ // magpie's own session ids are, the id below being derived from it anyway.
806
+ function sessionOf(headers) {
807
+ const s = String(headers.get(SESSION) ?? "").trim()
808
+ headers.delete(SESSION)
809
+ return s.slice(0, 128)
810
+ }
811
+
812
+ // attend sets a chat's ids on the headers its request goes to WorkBuddy
813
+ // with: the message's (each request its own, as the client makes them), the
814
+ // turn's (one user send, whatever it takes), and the conversation's. A header
815
+ // already there — the caller's own, or another plugin's — is kept, and the
816
+ // message and request ids are the same one, as WorkBuddy's client has them.
817
+ //
818
+ // who is the account the chat goes as (scopeOf). The ids are that account's
819
+ // own: WorkBuddy's client runs as one account, so one conversation or turn
820
+ // never shows up under two. Without it, one magpie session spread over a
821
+ // group of accounts sent the same X-Conversation-ID and
822
+ // X-Conversation-Request-ID under every account's X-User-Id.
823
+ function attend(headers, body, session, who = "") {
824
+ return attendChat(headers, chatOf(body), session, who)
825
+ }
826
+
827
+ // attendChat is attend with the chat read already. It returns what reattend
828
+ // needs to set the ids again for another account once the chat itself is
829
+ // let go: the ids it set itself (not the caller's), and the digests of what
830
+ // names the turn and the conversation, which are never sent as they are.
831
+ function attendChat(headers, chat, session, who = "") {
832
+ const conv = conversationParts(chat, session)
833
+ const turn = turnParts(chat)
834
+ const ids = {
835
+ set: [],
836
+ // a turn is a conversation's own: two conversations whose user message
837
+ // reads the same are still two sends, not one
838
+ turn: turn.length ? idFor("turn", [...conv, "|", ...turn]) : "",
839
+ conv: conv.length ? idFor("conversation", conv) : "",
840
+ }
841
+ return setIds(headers, ids, who)
842
+ }
843
+
844
+ // setIds sets the message's id, and the turn's and conversation's for the
845
+ // account who, where the caller set none.
846
+ function setIds(headers, ids, who) {
847
+ const msg = hex()
848
+ headers.set("X-Conversation-Message-ID", msg)
849
+ headers.set("X-Request-ID", msg)
850
+ const set = []
851
+ const own = (kind, base) => (who ? idFor(kind, [`account:${who}`, "|", base]) : base)
852
+ if (!headers.has("X-Conversation-Request-ID")) {
853
+ headers.set("X-Conversation-Request-ID", ids.turn ? own("turn", ids.turn) : hex())
854
+ set.push("X-Conversation-Request-ID")
855
+ }
856
+ if (ids.conv && !headers.has("X-Conversation-ID")) {
857
+ headers.set("X-Conversation-ID", own("conversation", ids.conv))
858
+ set.push("X-Conversation-ID")
859
+ }
860
+ return { ...ids, set }
861
+ }
862
+
863
+ // scopeOf names the account a chat goes as for attend: its uid, its
864
+ // enterprise, and for a key account the key (only ever hashed).
865
+ function scopeOf(a) {
866
+ return `${a?.uid ?? ""}|${a?.enterpriseId ?? ""}|${a?.source === "key" ? a.key ?? "" : ""}`
867
+ }
868
+
869
+ // reattend sets a chat's ids again for the account it is now sent as, when
870
+ // that is another account than the one they were set for.
871
+ function reattend(headers, ids, was, now) {
872
+ if (was === now) return ids
873
+ for (const h of ids.set) headers.delete(h)
874
+ return setIds(headers, ids, now)
875
+ }
876
+
877
+ // FLAGGED are the words WorkBuddy refuses a chat for, "Illegal API
878
+ // invocation from an unapproved channel" (magpie #182), each with words
879
+ // that say the same and pass: tried one by one against both builds with
880
+ // the requests Claude Code 2.1.280 and Codex 0.159.2 send. WorkBuddy reads
881
+ // every message, not only the system prompt (Claude Code puts its main
882
+ // branch in the first user message), and pays no mind to case. Claude
883
+ // Code's billing header means nothing to WorkBuddy's models and goes.
884
+ const FLAGGED = [
885
+ [/x-anthropic-billing-header:[^\n]*\n?/gi, ""],
886
+ [/You are Claude Code, Anthropic['’]s official CLI for Claude/gi, "You are Claude Code, Anthropic's CLI for Claude"],
887
+ [/Main branch \(you will usually use this for PRs\)/gi, "Main branch (usually the base for PRs)"],
888
+ [/(?<!the )Codex CLI is an open source project led by OpenAI\./gi, "The Codex CLI is an open source project led by OpenAI."],
889
+ // DeepSeek Harness (DSH) opens its system prompt with this line, which
890
+ // WorkBuddy refuses as 11128 (magpie-community/plugins#279; the same
891
+ // refusal traced in smart-open/TraeWorkAssistant#125). WorkBuddy matches
892
+ // the line whole and exactly, so a comma is enough to pass: measured on
893
+ // 2026-10-30 against copilot.tencent.com, one account, streamed, the line
894
+ // as DSH writes it answered 400 code 11128 and the same line with the
895
+ // comma answered 200. Saying it in another agent's terms passed too, but
896
+ // took the harness's own name out of the only line that says which agent
897
+ // runs here, and that name is what the rest of the prompt refers back to.
898
+ [/You are an AI agent powered by DeepSeek Harness\.?/gi, "You are an AI agent, powered by DeepSeek Harness."],
899
+ // A line WorkBuddy refuses in a long DeepSeek Harness chat, measured 400
900
+ // then 200 with this wording by tearslee (magpie-community/plugins#291). The
901
+ // model can quote it back into an assistant message, which the move to
902
+ // the user's instructions can't reach, so it is reworded in every message.
903
+ [/Web GUI whose URL the runtime context names\.\s+When the user refers/gi, "Web GUI whose URL the runtime context names. The interface, when the user refers"],
904
+ ]
905
+
906
+ function unflagged(text) {
907
+ for (const [re, to] of FLAGGED) text = text.replace(re, to)
908
+ return text
909
+ }
910
+
911
+ // unflag puts FLAGGED's words in place in every message of a chat, and
912
+ // leaves out a text that had nothing else (the billing header's system
913
+ // block). It says whether it changed anything.
914
+ function unflag(messages) {
915
+ let changed = false
916
+ for (let i = messages.length - 1; i >= 0; i--) {
917
+ const m = messages[i]
918
+ if (typeof m?.content === "string") {
919
+ const t = unflagged(m.content)
920
+ if (t === m.content) continue
921
+ changed = true
922
+ if (t.trim() || m.role !== "system") m.content = t
923
+ else messages.splice(i, 1)
924
+ } else if (Array.isArray(m?.content)) {
925
+ const parts = []
926
+ let here = false
927
+ for (const p of m.content) {
928
+ const t = typeof p?.text === "string" ? unflagged(p.text) : null
929
+ if (t === null || t === p.text) {
930
+ parts.push(p)
931
+ continue
932
+ }
933
+ here = true
934
+ if (t.trim()) parts.push({ ...p, text: t })
935
+ }
936
+ if (!here) continue
937
+ changed = true
938
+ if (parts.length || m.role !== "system") m.content = parts
939
+ else messages.splice(i, 1)
940
+ }
941
+ }
942
+ return changed
943
+ }
944
+
945
+ // withSystem gives a chat that doesn't open with a system message
946
+ // WorkBuddy's default one, as its app does, takes FLAGGED's words out of it,
947
+ // and applies the request spellings WorkBuddy's chat endpoint accepts. The
948
+ // OpenAI-compatible client normally uses max_completion_tokens and may call a
949
+ // reasoning prompt developer; WorkBuddy's endpoint takes max_tokens and
950
+ // system instead.
951
+ // An earlier turn's thinking goes back as `reasoning`, the field WorkBuddy's
952
+ // own client (CodeBuddy's agents converter) sets on an assistant message.
953
+ // WorkBuddy drops `reasoning_content`, which Grok Build, DeepSeek-style
954
+ // clients and magpie's own replies use: measured 2026-10-27 on
955
+ // www.workbuddy.ai, a codeword in reasoning_content reached none of
956
+ // kimi-k2.6, kimi-k3, glm-5.3, deepseek-v4.1-flash and minimax-m3, while
957
+ // the same words as `reasoning` reached kimi-k2.6 and minimax-m3.
958
+ // OpenRouter-style reasoning_details are read for their text the same way.
959
+ function reasoningOf(m) {
960
+ if (typeof m.reasoning_content === "string" && m.reasoning_content) return m.reasoning_content
961
+ if (Array.isArray(m.reasoning_details)) {
962
+ const text = m.reasoning_details.map((d) => (typeof d?.text === "string" ? d.text : typeof d?.summary === "string" ? d.summary : "")).join("")
963
+ if (text) return text
964
+ }
965
+ return ""
966
+ }
967
+
968
+ function asReasoning(messages) {
969
+ let changed = false
970
+ for (const m of messages) {
971
+ if (m?.role !== "assistant" || (m.reasoning_content === undefined && m.reasoning_details === undefined)) continue
972
+ const text = reasoningOf(m)
973
+ if (text && !(typeof m.reasoning === "string" && m.reasoning)) m.reasoning = text
974
+ delete m.reasoning_content
975
+ delete m.reasoning_details
976
+ changed = true
977
+ }
978
+ return changed
979
+ }
980
+
981
+ function withSystem(body) {
982
+ // a body magpie or OpenCode hands over as bytes is read as the text it is
983
+ if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) body = new TextDecoder().decode(body)
984
+ if (typeof body !== "string") return body
985
+ try {
986
+ const b = JSON.parse(body)
987
+ return systemOn(b) ? JSON.stringify(b) : body
988
+ } catch {
989
+ return body
990
+ }
991
+ }
992
+
993
+ // systemOn makes withSystem's changes to a chat's object; true when it made any
994
+ function systemOn(b) {
995
+ if (!Array.isArray(b?.messages) || !b.messages.length) return false
996
+ let changed = unflag(b.messages)
997
+ if (b.max_completion_tokens !== undefined) {
998
+ if (b.max_tokens === undefined) b.max_tokens = b.max_completion_tokens
999
+ delete b.max_completion_tokens
1000
+ changed = true
1001
+ }
1002
+ for (const m of b.messages) {
1003
+ if (m?.role !== "developer") continue
1004
+ m.role = "system"
1005
+ changed = true
1006
+ }
1007
+ if (asReasoning(b.messages)) changed = true
1008
+ if (b.messages[0]?.role !== "system") {
1009
+ b.messages.unshift({ role: "system", content: "You are a helpful assistant." })
1010
+ changed = true
1011
+ }
1012
+ return changed
1013
+ }
1014
+
1015
+ // WorkBuddy's channel check reads the system and assistant messages only:
1016
+ // tried on 2026-10-21 with real accounts on both builds (glm-5.3,
1017
+ // deepseek-v4.1-flash, gpt-5.5), each refused line was served in the user's
1018
+ // message, a tool's result and a user message's parts, and refused again in
1019
+ // the system or an assistant message. It matches a known line whole and
1020
+ // exactly (one extra space lets it through), so FLAGGED only ever knows the
1021
+ // lines met so far, and another agent's opening line is refused until one is
1022
+ // added (Wing on Discord, 10-21, with an agent we couldn't name).
1023
+ //
1024
+ // systemAsUser is body with its system prompt read to the model as the
1025
+ // first thing the user says, in INSTRUCTIONS' tags, and WorkBuddy's default
1026
+ // system prompt first, as both builds want a system message there (11128
1027
+ // "first message is not system prompt"). A system message later in the chat
1028
+ // becomes the user's where it stands. null when there's nothing to move.
1029
+ const DEFAULT_SYSTEM = "You are a helpful assistant."
1030
+ const INSTRUCTIONS = ["<instructions>\n", "\n</instructions>"]
1031
+
1032
+ function textOf(content) {
1033
+ if (typeof content === "string") return content
1034
+ if (!Array.isArray(content)) return ""
1035
+ return content.map((p) => (typeof p?.text === "string" ? p.text : "")).filter(Boolean).join("\n")
1036
+ }
1037
+
1038
+ // systemKey is the text of a chat's system messages, which a chat refused
1039
+ // once is known by: the same agent's next chat goes with systemAsUser at once
1040
+ function systemKey(body) {
1041
+ return systemKeyOf(chatOf(body))
1042
+ }
1043
+
1044
+ function systemKeyOf(chat) {
1045
+ const msgs = chat?.messages
1046
+ if (!Array.isArray(msgs)) return ""
1047
+ const key = msgs.filter((m) => m?.role === "system").map((m) => textOf(m.content)).join("\n")
1048
+ return key.trim() === DEFAULT_SYSTEM ? "" : key
1049
+ }
1050
+
1051
+ function systemAsUser(body) {
1052
+ const b = chatOf(body)
1053
+ return systemAsUserOn(b) ? JSON.stringify(b) : null
1054
+ }
1055
+
1056
+ // systemAsUserOn makes systemAsUser's move on a chat's object; false when
1057
+ // there's nothing to move
1058
+ function systemAsUserOn(b) {
1059
+ const msgs = b?.messages
1060
+ if (!Array.isArray(msgs)) return false
1061
+ let i = 0
1062
+ const lead = []
1063
+ for (; i < msgs.length && msgs[i]?.role === "system"; i++) lead.push(textOf(msgs[i].content))
1064
+ const said = lead.join("\n\n").trim()
1065
+ const rest = msgs.slice(i).map((m) => (m?.role === "system" ? { ...m, role: "user" } : m))
1066
+ const moved = said && said !== DEFAULT_SYSTEM
1067
+ if (!moved && rest.every((m, k) => m === msgs[i + k])) return false
1068
+ if (moved) {
1069
+ const text = INSTRUCTIONS[0] + said + INSTRUCTIONS[1]
1070
+ const u = rest.findIndex((m) => m?.role === "user")
1071
+ if (u < 0) rest.unshift({ role: "user", content: text })
1072
+ else if (typeof rest[u].content === "string") rest[u] = { ...rest[u], content: text + "\n\n" + rest[u].content }
1073
+ else if (Array.isArray(rest[u].content)) rest[u] = { ...rest[u], content: [{ type: "text", text }, ...rest[u].content] }
1074
+ else rest[u] = { ...rest[u], content: text }
1075
+ }
1076
+ b.messages = [{ role: "system", content: DEFAULT_SYSTEM }, ...rest]
1077
+ return true
1078
+ }
1079
+
1080
+ // OPENERS are the shapes in which an agent's opening says which harness it
1081
+ // runs in, as a vendor may have fingerprinted one. A vendor matches a refused
1082
+ // line whole and exactly — one extra space passes it, as FLAGGED's note above
1083
+ // has it — so the same line with one more comma passes while still saying
1084
+ // what it said. Measured 2026-10-30 against copilot.tencent.com, one account,
1085
+ // streamed, deepseek-v4.1-flash at max: DeepSeek Harness's opener answered
1086
+ // 400 code 11128 as written, and 200 with the comma, the harness's name still
1087
+ // in it; a suffix in its place (…Harness Desktop., …Harness CLI.) changed
1088
+ // nothing, so it is the line's shape the vendor knows, not the product alone.
1089
+ const OPENERS = [
1090
+ [/(\bYou are (?:an?|the)\s[^\n.,]{0,60}?\b(?:agent|assistant))\s+(powered by|running on|running in|built on|based on)\b/gi, "$1, $2"],
1091
+ ]
1092
+
1093
+ function opened(text) {
1094
+ for (const [re, to] of OPENERS) text = text.replace(re, to)
1095
+ return text
1096
+ }
1097
+
1098
+ // commaPaused is body with OPENERS' comma set in its system and assistant
1099
+ // messages — the two WorkBuddy reads (REFUSED.md). The user's messages and
1100
+ // tools' results are not among them: a comma in a message the vendor never
1101
+ // matches changes what someone said without changing what was refused, and
1102
+ // the user's own words come back altered. It is tried before systemAsUser,
1103
+ // which takes the system prompt out of the slot an agent's instructions are
1104
+ // read in. null when there was nothing to set a comma in.
1105
+ //
1106
+ // The two roles are read off the message's own role: a message with no role,
1107
+ // or one of another kind, is left as it is. roles, when given, collects the
1108
+ // roles the comma went into — the caller uses it to tell a comma that made a
1109
+ // chat pass in its system prompt from one that only set an assistant
1110
+ // message's (commaSystems).
1111
+ const PAUSED_ROLES = new Set(["system", "assistant"])
1112
+
1113
+ function commaPaused(body, roles) {
1114
+ const b = chatOf(body)
1115
+ return commaPausedOn(b, roles) ? JSON.stringify(b) : null
1116
+ }
1117
+
1118
+ // commaPausedOn makes commaPaused's change on a chat's object, in place; false
1119
+ // when there was nothing to set a comma in. commaPaused is this on a body, and
1120
+ // the first send of a system prompt whose comma passed is this too
1121
+ // (commaSystems), so the two can never drift apart.
1122
+ function commaPausedOn(b, roles) {
1123
+ const msgs = b?.messages
1124
+ if (!Array.isArray(msgs)) return false
1125
+ let changed = false
1126
+ for (const m of msgs) {
1127
+ if (!PAUSED_ROLES.has(m?.role)) continue
1128
+ let mine = false
1129
+ if (typeof m.content === "string") {
1130
+ const t = opened(m.content)
1131
+ if (t !== m.content) {
1132
+ m.content = t
1133
+ mine = true
1134
+ }
1135
+ } else if (Array.isArray(m.content)) {
1136
+ for (const p of m.content) {
1137
+ if (typeof p?.text !== "string") continue
1138
+ const t = opened(p.text)
1139
+ if (t === p.text) continue
1140
+ p.text = t
1141
+ mine = true
1142
+ }
1143
+ }
1144
+ // a message whose parts held no opening of their own is not changed, and
1145
+ // is not reported as one that was
1146
+ if (!mine) continue
1147
+ changed = true
1148
+ roles?.add(m.role)
1149
+ }
1150
+ return changed
1151
+ }
1152
+
1153
+ // normalizeToolChoice converts the object form emitted by OpenAI clients to
1154
+ // WorkBuddy's string form. It runs after fitted(), so a named choice follows a
1155
+ // tool name that was made safe for WorkBuddy.
1156
+ function normalizeToolChoice(body) {
1157
+ if (typeof body !== "string") return body
1158
+ try {
1159
+ const b = JSON.parse(body)
1160
+ return toolChoiceOn(b) ? JSON.stringify(b) : body
1161
+ } catch {
1162
+ return body
1163
+ }
1164
+ }
1165
+
1166
+ // toolChoiceOn makes normalizeToolChoice's change to a chat's object; true
1167
+ // when it made one (a string choice other than none is WorkBuddy's already)
1168
+ function toolChoiceOn(b) {
1169
+ if (!b || typeof b !== "object" || Array.isArray(b) || !("tool_choice" in b)) return false
1170
+ const choice = b.tool_choice
1171
+ if (typeof choice === "string") {
1172
+ if (choice.trim().toLowerCase() !== "none") return false
1173
+ delete b.tool_choice
1174
+ delete b.tools
1175
+ delete b.functions
1176
+ return true
1177
+ }
1178
+ if (!choice || typeof choice !== "object" || Array.isArray(choice)) {
1179
+ delete b.tool_choice
1180
+ return true
1181
+ }
1182
+ const type = typeof choice.type === "string" ? choice.type.trim().toLowerCase() : ""
1183
+ if (type === "none") {
1184
+ delete b.tool_choice
1185
+ delete b.tools
1186
+ delete b.functions
1187
+ } else if (type === "auto" || type === "required") {
1188
+ b.tool_choice = type
1189
+ } else if (type === "function") {
1190
+ const fn = choice.function && typeof choice.function === "object" && !Array.isArray(choice.function)
1191
+ ? choice.function
1192
+ : undefined
1193
+ const name = typeof fn?.name === "string" ? fn.name.trim() : ""
1194
+ b.tool_choice = name || "auto"
1195
+ } else {
1196
+ delete b.tool_choice
1197
+ }
1198
+ return true
1199
+ }
1200
+
1201
+ // ---- tools WorkBuddy takes ----------------------------------------------------
1202
+
1203
+ // WorkBuddy AI answers 400 code 11133 "Invalid request parameters" (the
1204
+ // model provider rejected them) to a chat whose tools it can't pass on to
1205
+ // the model (wyh on magpie's Discord: ZCode and DeepSeek Harness on
1206
+ // deepseek-v4.1-flash). Tried on the owner's account, 2026-10-08: DeepSeek
1207
+ // turns away each of the shapes below, and Kimi, GPT, Gemini and GLM some
1208
+ // of them; MiniMax none. fitTools gives each a shape every model takes.
1209
+ // A tool's name may hold letters, digits, _ and -; another character
1210
+ // (". : / space", CJK) is refused.
1211
+ const NAME_OK = /^[A-Za-z0-9_-]+$/
1212
+
1213
+ // safeName is name with each character WorkBuddy refuses as _, kept apart
1214
+ // from the names in taken.
1215
+ function safeName(name, taken) {
1216
+ const base = String(name).replace(/[^A-Za-z0-9_-]/g, "_") || "tool"
1217
+ let n = base
1218
+ for (let i = 2; taken.has(n); i++) n = `${base}_${i}`
1219
+ taken.add(n)
1220
+ return n
1221
+ }
1222
+
1223
+ // NUL_ESCAPE finds a regex's \0 (the NUL character), stepping over each \\
1224
+ // (a backslash) so that a \\0 is left; \01 is an octal escape, also left.
1225
+ const NUL_ESCAPE = /\\\\|\\0(?![0-9])/g
1226
+
1227
+ // fitSchema mends a schema in place, at every depth: a pattern's \0, which
1228
+ // DeepSeek's validator says is "not a 'regex'", is \u0000, which matches
1229
+ // the same (magpie's gateway does this for DeepSeek's own API,
1230
+ // deepseekToolPatterns); a tuple's items (a list) become one schema any of
1231
+ // them fits. It reports whether it changed anything.
1232
+ function fitSchema(s, depth = 0) {
1233
+ if (!s || typeof s !== "object" || depth > 64) return false
1234
+ let changed = false
1235
+ if (Array.isArray(s)) {
1236
+ for (const v of s) if (fitSchema(v, depth + 1)) changed = true
1237
+ return changed
1238
+ }
1239
+ if (typeof s.pattern === "string" && s.pattern.includes("\\0")) {
1240
+ const p = s.pattern.replace(NUL_ESCAPE, (m) => (m === "\\\\" ? m : "\\u0000"))
1241
+ if (p !== s.pattern) {
1242
+ s.pattern = p
1243
+ changed = true
1244
+ }
1245
+ }
1246
+ if (s.pattern === "^[^\\uD800-\\uDFFF]*$") {
1247
+ delete s.pattern
1248
+ changed = true
1249
+ }
1250
+ if (Array.isArray(s.items)) {
1251
+ const list = s.items.filter((v) => v && typeof v === "object")
1252
+ s.items = list.length === 0 ? {} : list.length === 1 ? list[0] : { anyOf: list }
1253
+ delete s.additionalItems
1254
+ changed = true
1255
+ }
1256
+ for (const v of Object.values(s)) if (fitSchema(v, depth + 1)) changed = true
1257
+ return changed
1258
+ }
1259
+
1260
+ // Kimi (kimi-k3-1) answers 11133 too, to the tools of an MCP server or a
1261
+ // plugin (clearmann, #122). Tried on the owner's account, 2026-10-14, each
1262
+ // alone in an otherwise plain chat: Kimi turns away an enum with no type
1263
+ // (["a","b"] as much as [1,"a",null]), an empty enum, an enum whose type
1264
+ // lists two types besides null, a schema that is true or false where a
1265
+ // schema goes (properties.x: true, items: true), a required that isn't a
1266
+ // list, and a type it doesn't know ("any", "String"). It takes an enum
1267
+ // typed T or [T, "null"], an anyOf of such enums, {"not": {}}, {}, and
1268
+ // additionalProperties: true or false. fitShape gives each the shape it
1269
+ // takes, meaning the same: none of it narrows or widens what a call may
1270
+ // hold, except an empty enum (which nothing fits) is left out.
1271
+ const TYPES = new Set(["string", "number", "integer", "boolean", "object", "array", "null"])
1272
+
1273
+ // SUB_ONE are the keywords whose value is a schema, SUB_LIST a list of
1274
+ // schemas, SUB_MAP a map of names to schemas. additionalProperties and
1275
+ // unevaluatedProperties are left as they are when true or false.
1276
+ const SUB_ONE = ["items", "additionalItems", "unevaluatedItems", "contains", "not", "if", "then", "else", "propertyNames", "additionalProperties", "unevaluatedProperties"]
1277
+ const SUB_LIST = ["anyOf", "oneOf", "allOf", "prefixItems"]
1278
+ const SUB_MAP = ["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"]
1279
+ const BOOL_OK = new Set(["additionalProperties", "unevaluatedProperties"])
1280
+
1281
+ // valueType is the JSON Schema type of an enum's value.
1282
+ function valueType(v) {
1283
+ if (v === null) return "null"
1284
+ if (Array.isArray(v)) return "array"
1285
+ if (typeof v === "number") return Number.isInteger(v) ? "integer" : "number"
1286
+ return typeof v
1287
+ }
1288
+
1289
+ // fitEnum gives s's enum a type: the one its values have, or that and
1290
+ // "null"; values of several types are an anyOf of an enum for each. It
1291
+ // reports whether it changed anything.
1292
+ function fitEnum(s) {
1293
+ if (!("enum" in s)) return false
1294
+ if (!Array.isArray(s.enum) || s.enum.length === 0) {
1295
+ delete s.enum
1296
+ return true
1297
+ }
1298
+ const listed = Array.isArray(s.type) ? s.type : typeof s.type === "string" ? [s.type] : []
1299
+ if (listed.filter((t) => t !== "null").length === 1) return false
1300
+ const byType = new Map()
1301
+ for (const v of s.enum) {
1302
+ const t = valueType(v)
1303
+ if (!byType.has(t)) byType.set(t, [])
1304
+ byType.get(t).push(v)
1305
+ }
1306
+ if (byType.has("integer") && byType.has("number")) {
1307
+ byType.get("number").push(...byType.get("integer"))
1308
+ byType.delete("integer")
1309
+ }
1310
+ const hasNull = byType.delete("null")
1311
+ if (byType.size <= 1) {
1312
+ const [t] = byType.keys()
1313
+ const want = t === undefined ? "null" : hasNull ? [t, "null"] : t
1314
+ if (JSON.stringify(want) === JSON.stringify(s.type)) return false
1315
+ s.type = want
1316
+ return true
1317
+ }
1318
+ const split = [...byType].map(([t, vs]) => ({ type: t, enum: vs }))
1319
+ if (hasNull) split.push({ type: "null" })
1320
+ delete s.enum
1321
+ delete s.type
1322
+ if (Array.isArray(s.anyOf)) s.allOf = [...(Array.isArray(s.allOf) ? s.allOf : []), { anyOf: split }]
1323
+ else s.anyOf = split
1324
+ return true
1325
+ }
1326
+
1327
+ // subSchema is v, a schema found under key, as an object Kimi takes: true
1328
+ // is {}, false is {"not": {}}.
1329
+ function subSchema(v, key) {
1330
+ if (typeof v !== "boolean" || BOOL_OK.has(key)) return v
1331
+ return v ? {} : { not: {} }
1332
+ }
1333
+
1334
+ // fitShape mends s, a schema, and each schema under it, in place (see
1335
+ // TYPES above); a name under properties is never read as a keyword. It
1336
+ // reports whether it changed anything.
1337
+ function fitShape(s, depth = 0) {
1338
+ if (!s || typeof s !== "object" || Array.isArray(s) || depth > 64) return false
1339
+ let changed = false
1340
+ if ("type" in s) {
1341
+ const list = (Array.isArray(s.type) ? s.type : [s.type]).map((t) => (typeof t === "string" ? t.toLowerCase() : t)).filter((t) => TYPES.has(t))
1342
+ const uniq = [...new Set(list)]
1343
+ const want = uniq.length === 0 ? undefined : uniq.length === 1 ? uniq[0] : uniq
1344
+ if (JSON.stringify(want) !== JSON.stringify(s.type)) {
1345
+ if (want === undefined) delete s.type
1346
+ else s.type = want
1347
+ changed = true
1348
+ }
1349
+ }
1350
+ if ("required" in s && !Array.isArray(s.required)) {
1351
+ delete s.required
1352
+ changed = true
1353
+ } else if (Array.isArray(s.required) && s.required.some((k) => typeof k !== "string")) {
1354
+ s.required = s.required.filter((k) => typeof k === "string")
1355
+ changed = true
1356
+ }
1357
+ if (fitEnum(s)) changed = true
1358
+ for (const k of SUB_ONE) {
1359
+ if (!(k in s)) continue
1360
+ const v = subSchema(s[k], k)
1361
+ if (v !== s[k]) {
1362
+ s[k] = v
1363
+ changed = true
1364
+ }
1365
+ if (fitShape(v, depth + 1)) changed = true
1366
+ }
1367
+ for (const k of SUB_LIST) {
1368
+ if (!Array.isArray(s[k])) continue
1369
+ s[k].forEach((v0, i) => {
1370
+ const v = subSchema(v0, k)
1371
+ if (v !== v0) {
1372
+ s[k][i] = v
1373
+ changed = true
1374
+ }
1375
+ if (fitShape(v, depth + 1)) changed = true
1376
+ })
1377
+ }
1378
+ for (const k of SUB_MAP) {
1379
+ const m = s[k]
1380
+ if (!m || typeof m !== "object" || Array.isArray(m)) continue
1381
+ for (const [name, v0] of Object.entries(m)) {
1382
+ const v = subSchema(v0, k)
1383
+ if (v !== v0) {
1384
+ m[name] = v
1385
+ changed = true
1386
+ }
1387
+ if (fitShape(v, depth + 1)) changed = true
1388
+ }
1389
+ }
1390
+ return changed
1391
+ }
1392
+
1393
+ // localRef is the schema a local $ref in root names ("#/$defs/x",
1394
+ // "#/definitions/x"), or s itself.
1395
+ function localRef(root, s) {
1396
+ const ref = s?.$ref
1397
+ if (typeof ref !== "string" || !ref.startsWith("#/")) return s
1398
+ let at = root
1399
+ for (const k of ref.slice(2).split("/")) at = at?.[k.replaceAll("~1", "/").replaceAll("~0", "~")]
1400
+ return at && typeof at === "object" ? at : s
1401
+ }
1402
+
1403
+ // objectRoot makes a tool's parameters an object at the root, as magpie's
1404
+ // gateway does for xAI (provider.ObjectRoot): allOf's branches are merged
1405
+ // whole; of anyOf's and oneOf's object branches the properties are merged
1406
+ // and a field each requires stays required. A root with no type, or an
1407
+ // empty one, is an object. It reports whether it changed anything.
1408
+ function objectRoot(ps, root = ps, depth = 0) {
1409
+ const unions = ["allOf", "anyOf", "oneOf"].filter((k) => Array.isArray(ps[k]))
1410
+ if (ps.type === "object" && !unions.length) return false
1411
+ const props = ps.properties && typeof ps.properties === "object" ? ps.properties : {}
1412
+ const required = Array.isArray(ps.required) ? [...ps.required] : []
1413
+ for (const b0 of ps.allOf ?? []) {
1414
+ let b = localRef(root, b0)
1415
+ if (!b || typeof b !== "object") continue
1416
+ if (depth < 8 && ["allOf", "anyOf", "oneOf"].some((k) => Array.isArray(b[k]))) objectRoot((b = structuredClone(b)), root, depth + 1)
1417
+ for (const [k, v] of Object.entries(b.properties ?? {})) if (!(k in props)) props[k] = v
1418
+ if (Array.isArray(b.required)) required.push(...b.required)
1419
+ }
1420
+ const branches = []
1421
+ for (const key of ["anyOf", "oneOf"]) {
1422
+ for (const b0 of ps[key] ?? []) {
1423
+ let b = localRef(root, b0)
1424
+ if (!b || typeof b !== "object") continue
1425
+ if (depth < 8 && ["allOf", "anyOf", "oneOf"].some((k) => Array.isArray(b[k]))) objectRoot((b = structuredClone(b)), root, depth + 1)
1426
+ if (b.type !== "object" && !b.properties) continue
1427
+ branches.push(b)
1428
+ }
1429
+ }
1430
+ const from = new Map()
1431
+ for (const b of branches) {
1432
+ for (const [k, v] of Object.entries(b.properties ?? {})) {
1433
+ if (k in props) continue
1434
+ const seen = from.get(k) ?? []
1435
+ if (!seen.some((x) => JSON.stringify(x) === JSON.stringify(v))) seen.push(v)
1436
+ from.set(k, seen)
1437
+ }
1438
+ }
1439
+ for (const [k, list] of from) props[k] = list.length === 1 ? list[0] : { anyOf: list }
1440
+ if (branches.length) {
1441
+ for (const k of Object.keys(branches[0].properties ?? {})) {
1442
+ if (branches.every((b) => Array.isArray(b.required) && b.required.includes(k))) required.push(k)
1443
+ }
1444
+ }
1445
+ for (const k of unions) delete ps[k]
1446
+ ps.type = "object"
1447
+ ps.properties = props
1448
+ const req = [...new Set(required)].filter((k) => typeof k === "string" && k in props)
1449
+ if (req.length) ps.required = req
1450
+ else delete ps.required
1451
+ return true
1452
+ }
1453
+
1454
+ // Kimi (kimi-k3.1-pro) answers 400 "Invalid request parameters" to a oneOf
1455
+ // that has no type, at the root of a $ref's target or deeper, even when every
1456
+ // branch is an object (congee949, #378: dsh's REA tools, on workbuddy and
1457
+ // workbuddy-ai alike; a "type": "object" beside it is taken). typeUnions gives
1458
+ // such a oneOf type "object" when each branch is typed object itself or
1459
+ // through a chain of local $refs, and changes nothing else: a union of other
1460
+ // or mixed types, an anyOf, or a $ref that is missing, external or circular
1461
+ // is left as it came. It reports whether it changed anything.
1462
+ function typeUnions(s, root = s, depth = 0) {
1463
+ if (!s || typeof s !== "object" || Array.isArray(s) || depth > 64) return false
1464
+ let changed = false
1465
+ if (!("type" in s) && Array.isArray(s.oneOf) && s.oneOf.length && s.oneOf.every((b) => objectBranch(root, b))) {
1466
+ s.type = "object"
1467
+ changed = true
1468
+ }
1469
+ for (const k of SUB_ONE) if (typeUnions(s[k], root, depth + 1)) changed = true
1470
+ for (const k of SUB_LIST) for (const v of Array.isArray(s[k]) ? s[k] : []) if (typeUnions(v, root, depth + 1)) changed = true
1471
+ for (const k of SUB_MAP) {
1472
+ const m = s[k]
1473
+ if (!m || typeof m !== "object" || Array.isArray(m)) continue
1474
+ for (const v of Object.values(m)) if (typeUnions(v, root, depth + 1)) changed = true
1475
+ }
1476
+ return changed
1477
+ }
1478
+
1479
+ // objectBranch says whether b is typed object, itself or where its local
1480
+ // $refs lead; a $ref seen before on the way is a cycle, and not.
1481
+ function objectBranch(root, b, seen = []) {
1482
+ if (!b || typeof b !== "object" || Array.isArray(b)) return false
1483
+ if ("type" in b) return b.type === "object"
1484
+ if (typeof b.$ref !== "string" || seen.includes(b.$ref) || seen.length > 16) return false
1485
+ const t = localRef(root, b)
1486
+ return t !== b && objectBranch(root, t, [...seen, b.$ref])
1487
+ }
1488
+
1489
+ // fitTools mends b's function tools in place: their parameters (fitSchema,
1490
+ // fitShape, objectRoot) and names. It reports whether it changed anything,
1491
+ // and the names it gave, each to the name the client knows (ours), so that the
1492
+ // model's calls are named back. A call in the chat's history is named as
1493
+ // its tool now is.
1494
+ function fitTools(b) {
1495
+ const names = new Map()
1496
+ if (!Array.isArray(b?.tools) || !b.tools.length) return { changed: false, names }
1497
+ let changed = false
1498
+ const taken = new Set()
1499
+ for (const t of b.tools) {
1500
+ const n = t?.function?.name
1501
+ if (typeof n === "string" && NAME_OK.test(n)) taken.add(n)
1502
+ }
1503
+ const theirs = new Map()
1504
+ for (const t of b.tools) {
1505
+ const fn = t?.type === "function" || t?.function ? t.function : null
1506
+ if (!fn || typeof fn !== "object") continue
1507
+ if (typeof fn.name === "string" && !NAME_OK.test(fn.name)) {
1508
+ const safe = safeName(fn.name, taken)
1509
+ names.set(safe, fn.name)
1510
+ theirs.set(fn.name, safe)
1511
+ fn.name = safe
1512
+ changed = true
1513
+ }
1514
+ if (fn.parameters === undefined) continue
1515
+ if (!fn.parameters || typeof fn.parameters !== "object" || Array.isArray(fn.parameters)) {
1516
+ fn.parameters = { type: "object", properties: {} }
1517
+ changed = true
1518
+ continue
1519
+ }
1520
+ if (fitSchema(fn.parameters)) changed = true
1521
+ if (fitShape(fn.parameters)) changed = true
1522
+ if (typeUnions(fn.parameters)) changed = true
1523
+ if (objectRoot(fn.parameters)) changed = true
1524
+ }
1525
+ if (theirs.size && Array.isArray(b.messages)) {
1526
+ for (const m of b.messages) {
1527
+ for (const c of Array.isArray(m?.tool_calls) ? m.tool_calls : []) {
1528
+ const safe = theirs.get(c?.function?.name)
1529
+ if (safe) c.function.name = safe
1530
+ }
1531
+ if (m?.role === "tool" && theirs.has(m.name)) m.name = theirs.get(m.name)
1532
+ }
1533
+ }
1534
+ const choice = b.tool_choice?.function
1535
+ if (choice && theirs.has(choice.name)) choice.name = theirs.get(choice.name)
1536
+ return { changed, names }
1537
+ }
1538
+
1539
+ // fitted is a chat body with its tools mended (fitTools), and the names
1540
+ // given its tools, each to the client's own; a body that isn't a chat is
1541
+ // as it was.
1542
+ function fitted(body) {
1543
+ if (typeof body !== "string") return { body, names: new Map() }
1544
+ try {
1545
+ const b = JSON.parse(body)
1546
+ const { changed, names } = fitTools(b)
1547
+ return { body: changed ? JSON.stringify(b) : body, names }
1548
+ } catch {
1549
+ return { body, names: new Map() }
1550
+ }
1551
+ }
1552
+
1553
+ // GROWTH_SEND is the growth event WorkBuddy's client puts in a chat's own
1554
+ // body for the user's send (Events.ChatRequestSend).
1555
+ const GROWTH_SEND = "chat_request_send"
1556
+
1557
+ // withGrowth gives a WorkBuddy AI chat the extra_vars its own client sends
1558
+ // (magpie-community/plugins#691): `growthEvent`, a JSON string holding an
1559
+ // array of growth events, and `initiator: "user"`. WorkBuddy AI 5.6.2's CLI
1560
+ // (codebuddy-lite-wb.mjs, reportChatRequestSendTelemetry) builds the
1561
+ // chat_request_send event as {eventCode, id: the conversation's id, extra:
1562
+ // {inputLength, requestModelId, requestModelName, mode, command, expertId}}
1563
+ // and, when its growth flag is on, sends it in the chat body
1564
+ // (appendGrowthEvent into providerData.extra_vars) instead of reporting it
1565
+ // on /v2/report; a 5.9.4 capture (#691) carries it there, with initiator
1566
+ // "user". Nothing proves WorkBuddy reads it for the daily credit; it is the
1567
+ // only per-chat activity mark the client sends with the chat itself.
1568
+ //
1569
+ // Built from the chat alone: inputLength is the length of the user's last
1570
+ // own message (its text, as the CLI's getInputLength counts it), the model
1571
+ // is the chat's, its name the site's table's (else the id), mode "craft"
1572
+ // (the X-Agent-Intent it is sent with) and no command. conv is the chat's
1573
+ // X-Conversation-ID; with none, nothing is added. An event the caller put
1574
+ // there is kept; was is the conversation id an earlier call gave the event
1575
+ // for, whose event this one replaces (the chat sent as another account).
1576
+ // true when the chat changed.
1577
+ function withGrowth(site, chat, conv, was = "") {
1578
+ if (!site.ai || !conv || !chat || typeof chat !== "object" || !Array.isArray(chat.messages)) return false
1579
+ const vars = chat.extra_vars !== null && typeof chat.extra_vars === "object" && !Array.isArray(chat.extra_vars) ? chat.extra_vars : {}
1580
+ let events = []
1581
+ if (typeof vars.growthEvent === "string" && vars.growthEvent.trim()) {
1582
+ try {
1583
+ const v = JSON.parse(vars.growthEvent)
1584
+ events = Array.isArray(v) ? v : [v]
1585
+ } catch {}
1586
+ }
1587
+ if (was) events = events.filter((e) => !(e?.eventCode === GROWTH_SEND && e?.id === was))
1588
+ const model = typeof chat.model === "string" ? chat.model : ""
1589
+ const event = {
1590
+ eventCode: GROWTH_SEND,
1591
+ id: conv,
1592
+ extra: {
1593
+ inputLength: inputLengthOf(chat.messages),
1594
+ requestModelId: model,
1595
+ requestModelName: site.models.find((m) => m[0] === model)?.[1] ?? model,
1596
+ mode: "craft",
1597
+ command: "",
1598
+ },
1599
+ }
1600
+ if (!events.some((e) => e?.eventCode === GROWTH_SEND && e?.id === conv)) events.push(event)
1601
+ chat.extra_vars = { ...vars, growthEvent: JSON.stringify(events), initiator: vars.initiator ?? "user" }
1602
+ return true
1603
+ }
1604
+
1605
+ // regrown is a chat body given for conversation was given its growth event
1606
+ // for conv instead (withGrowth); null when it can't be read or isn't one.
1607
+ function regrown(site, b, was, conv) {
1608
+ const chat = chatOf(typeof b === "string" ? b : bodyString(b))
1609
+ return chat && withGrowth(site, chat, conv, was) ? JSON.stringify(chat) : null
1610
+ }
1611
+
1612
+ // withVars is a chat body, as text, with extra_vars set as its last field
1613
+ // and every byte it had kept: the vars go in before the object's closing
1614
+ // brace. For a chat that names no extra_vars of its own (withGrowth).
1615
+ function withVars(body, vars) {
1616
+ if (typeof body !== "string") return body
1617
+ const i = body.lastIndexOf("}")
1618
+ if (i < 0) return body
1619
+ const open = /\{\s*$/.test(body.slice(0, i))
1620
+ return body.slice(0, i) + (open ? "" : ",") + '"extra_vars":' + JSON.stringify(vars) + "}" + body.slice(i + 1)
1621
+ }
1622
+
1623
+ // inputLengthOf is the length of the chat's last user message that is the
1624
+ // user's own (not a tool's result): its text, as WorkBuddy's CLI counts a
1625
+ // user input (TelemetryUtils.getInputLength); 0 when there is none.
1626
+ function inputLengthOf(msgs) {
1627
+ for (let i = msgs.length - 1; i >= 0; i--) {
1628
+ if (msgs[i]?.role !== "user" || answeredBefore(msgs, i)) continue
1629
+ const c = msgs[i].content
1630
+ if (typeof c === "string") return c.length
1631
+ if (!Array.isArray(c)) return 0
1632
+ return c.reduce((n, p) => n + ((p?.type ?? "text") === "text" && typeof p?.text === "string" ? p.text.length : 0), 0)
1633
+ }
1634
+ return 0
1635
+ }
1636
+
1637
+ // gzipped is a chat's body compressed, as WorkBuddy's own client sends its
1638
+ // model requests: its CLI's GzipRequestProcessor (WorkBuddy 5.9.3, CLI
1639
+ // 2.165.0, on both builds) gzips each POST's body and sets
1640
+ // Content-Encoding: gzip when the product's RequestBodyGzip feature is on,
1641
+ // which both builds' product.json turn on and /v3/config (merged over it)
1642
+ // doesn't turn off. Sent as plain JSON, a long agent conversation went up
1643
+ // whole on every step: runmiNeverstop on X saw 2.89 GB up to
1644
+ // copilot.tencent.com against 258 MB down. Measured 2026-10-28 on
1645
+ // www.workbuddy.ai: a gzipped chat answers as the plain one does. A
1646
+ // Messages request (Claude on the China build) goes as it came: that route
1647
+ // wasn't tried gzipped. Only a chat completion goes gzipped (isCompletion):
1648
+ // WorkBuddy's images API reads its body as plain JSON, and magpie's drawing
1649
+ // (/v2/images/generations, /v2/images/edits) is sent through this same
1650
+ // fetch; gzipped it answered 400 11101 "invalid character '\x1f'" (iwinux on
1651
+ // Discord, 0.1.43). null when the body isn't sent gzipped.
1652
+ function gzipped(completion, b) {
1653
+ if (!completion) return null
1654
+ if (typeof b === "string") return gzipSync(Buffer.from(b))
1655
+ if (b instanceof ArrayBuffer || ArrayBuffer.isView(b)) return gzipSync(b)
1656
+ return null
1657
+ }
1658
+
1659
+ // prepared is a request's body read once for every change the loader makes
1660
+ // to it and everything it reads off it (plugins#461): a long chat, 45 MiB
1661
+ // of history, was parsed six times on its way, once by each step, and
1662
+ // written out again whole by normalizeToolChoice even when nothing changed.
1663
+ // chat is the parsed body, changed whether any step changed it; the caller
1664
+ // writes it out once, when it did. Each step is the one its own function
1665
+ // above makes, in the same order.
1666
+ function prepared(body, native) {
1667
+ if (!native && (body instanceof ArrayBuffer || ArrayBuffer.isView(body))) body = new TextDecoder().decode(body)
1668
+ const none = { body, chat: null, names: new Map(), changed: false }
1669
+ if (typeof body !== "string") return none
1670
+ let chat
1671
+ try {
1672
+ chat = JSON.parse(body)
1673
+ } catch {
1674
+ return none
1675
+ }
1676
+ if (chat === null || typeof chat !== "object") return none
1677
+ if (native) return { body, chat, names: new Map(), changed: unsignedOn(chat) }
1678
+ try {
1679
+ let changed = systemOn(chat)
1680
+ const fit = fitTools(chat)
1681
+ if (fit.changed) changed = true
1682
+ if (toolChoiceOn(chat)) changed = true
1683
+ return { body, chat, names: fit.names, changed }
1684
+ } catch {
1685
+ // a shape a step can't take: the steps one by one, each keeping the
1686
+ // body as it was when it can't, as they always have
1687
+ const fit = fitted(withSystem(body))
1688
+ const out = normalizeToolChoice(fit.body)
1689
+ return { body: out, chat: chatOf(out), names: fit.names, changed: false }
1690
+ }
1691
+ }
1692
+
1693
+ // namedBack gives the model's calls in a chat answer (one JSON body, or an
1694
+ // SSE stream's chunks) the names the client gave its tools.
1695
+ function namedBack(v, names) {
1696
+ let changed = false
1697
+ for (const c of Array.isArray(v?.choices) ? v.choices : []) {
1698
+ for (const at of [c?.message, c?.delta]) {
1699
+ for (const tc of Array.isArray(at?.tool_calls) ? at.tool_calls : []) {
1700
+ const ours = names.get(tc?.function?.name)
1701
+ if (ours) {
1702
+ tc.function.name = ours
1703
+ changed = true
1704
+ }
1705
+ }
1706
+ }
1707
+ }
1708
+ return changed
1709
+ }
1710
+
1711
+ // renamed is res with namedBack on its body, read as it comes.
1712
+ function renamed(res, names) {
1713
+ if (!names.size || !res.body) return res
1714
+ const headers = new Headers(res.headers)
1715
+ headers.delete("content-length")
1716
+ headers.delete("content-encoding")
1717
+ const json = /json/i.test(res.headers.get("content-type") ?? "")
1718
+ if (json) {
1719
+ const out = res.text().then((text) => {
1720
+ try {
1721
+ const v = JSON.parse(text)
1722
+ return namedBack(v, names) ? JSON.stringify(v) : text
1723
+ } catch {
1724
+ return text
1725
+ }
1726
+ })
1727
+ return out.then((text) => new Response(text, { status: res.status, statusText: res.statusText, headers }))
1728
+ }
1729
+ const dec = new TextDecoder()
1730
+ const enc = new TextEncoder()
1731
+ let rest = ""
1732
+ const line = (l) => {
1733
+ const m = /^data:\s?(.*)$/.exec(l)
1734
+ if (!m || m[1] === "[DONE]") return l
1735
+ try {
1736
+ const v = JSON.parse(m[1])
1737
+ return namedBack(v, names) ? `data: ${JSON.stringify(v)}` : l
1738
+ } catch {
1739
+ return l
1740
+ }
1741
+ }
1742
+ const body = res.body.pipeThrough(
1743
+ new TransformStream({
1744
+ transform(chunk, ctl) {
1745
+ rest += dec.decode(chunk, { stream: true })
1746
+ const lines = rest.split("\n")
1747
+ rest = lines.pop()
1748
+ if (lines.length) ctl.enqueue(enc.encode(lines.map(line).join("\n") + "\n"))
1749
+ },
1750
+ flush(ctl) {
1751
+ rest += dec.decode()
1752
+ if (rest) ctl.enqueue(enc.encode(line(rest)))
1753
+ },
1754
+ }),
1755
+ )
1756
+ return new Response(body, { status: res.status, statusText: res.statusText, headers })
1757
+ }
1758
+
1759
+ // FILTER_SAYS is the text WorkBuddy's safety filter puts in a reply it ends
1760
+ // with finish_reason "content_filter": deepseek-v4.1-flash on
1761
+ // copilot.tencent.com reasoned, said this, and ended content_filter with
1762
+ // no output tokens counted (itspig, plugins #540).
1763
+ const FILTER_SAYS = ["Sorry, I can't respond to this question."]
1764
+
1765
+ // filterSaid tells whether text said so far may still be FILTER_SAYS, with
1766
+ // white space on either side: copilot.tencent.com sends it as
1767
+ // "\nSorry, I can't respond to this question.\n" (itspig, plugins #540).
1768
+ // Text that is only white space so far may still be it; text that goes on
1769
+ // past it is not.
1770
+ const filterSaid = (text) => {
1771
+ const t = text.replace(/’/g, "'").trim()
1772
+ return FILTER_SAYS.some((s) => s.startsWith(t))
1773
+ }
1774
+
1775
+ // unsaid is a streamed chat whose reply WorkBuddy's filter refused with its
1776
+ // text (FILTER_SAYS) and finish_reason content_filter, with the text taken
1777
+ // out: a reply that says nothing before content_filter is the refusal magpie
1778
+ // asks the group's next member for, where a 200 that said something is an
1779
+ // answer the agent fails on ("The model refused to complete the request",
1780
+ // plugins #540). Only text that is still the filter's is held, so any other
1781
+ // reply's first words go as they come, and one that only begins like it is
1782
+ // let through at its first word that isn't, or at its end.
1783
+ function unsaid(res) {
1784
+ if (!res.body || !/event-stream/i.test(res.headers.get("content-type") ?? "")) return res
1785
+ const headers = new Headers(res.headers)
1786
+ headers.delete("content-length")
1787
+ headers.delete("content-encoding")
1788
+ const dec = new TextDecoder()
1789
+ const enc = new TextEncoder()
1790
+ let rest = ""
1791
+ let open = true // the reply may still be the filter's
1792
+ let said = ""
1793
+ let held = [] // events held while it may be
1794
+ const chunkOf = (ev) => {
1795
+ const m = /^data:\s?(.*)$/m.exec(ev)
1796
+ if (!m || m[1] === "[DONE]") return null
1797
+ try {
1798
+ const v = JSON.parse(m[1])
1799
+ return v && typeof v === "object" ? v : null
1800
+ } catch {
1801
+ return null
1802
+ }
1803
+ }
1804
+ // without is ev with the filter's text taken out, or "" when nothing
1805
+ // else is in it
1806
+ const without = (ev) => {
1807
+ const v = chunkOf(ev)
1808
+ const c = v?.choices?.[0]
1809
+ if (!c?.delta || typeof c.delta.content !== "string") return ev
1810
+ delete c.delta.content
1811
+ const left = Object.keys(c.delta).filter((k) => k !== "role")
1812
+ if (!left.length && c.finish_reason == null && v.usage == null) return ""
1813
+ return `data: ${JSON.stringify(v)}`
1814
+ }
1815
+ const event = (ev) => {
1816
+ if (!open) return [ev]
1817
+ const c = chunkOf(ev)?.choices?.[0]
1818
+ const text = typeof c?.delta?.content === "string" ? c.delta.content : ""
1819
+ const finish = c?.finish_reason
1820
+ // copilot.tencent.com sends "tool_calls": [] on every delta, text
1821
+ // too: only a list with a call in it is one
1822
+ const calls = c?.delta?.tool_calls
1823
+ if ((Array.isArray(calls) ? calls.length > 0 : calls) || (text && !filterSaid(said + text))) {
1824
+ open = false
1825
+ const out = [...held, ev]
1826
+ held = []
1827
+ return out
1828
+ }
1829
+ said += text
1830
+ if (finish === "content_filter" && said) {
1831
+ open = false
1832
+ const out = [...held, ev].map(without).filter(Boolean)
1833
+ held = []
1834
+ return out
1835
+ }
1836
+ if (finish) {
1837
+ open = false
1838
+ const out = [...held, ev]
1839
+ held = []
1840
+ return out
1841
+ }
1842
+ if (!said) return [ev] // reasoning, the role, before any text
1843
+ held.push(ev)
1844
+ return []
1845
+ }
1846
+ const body = res.body.pipeThrough(
1847
+ new TransformStream({
1848
+ transform(chunk, ctl) {
1849
+ rest = (rest + dec.decode(chunk, { stream: true })).replace(/\r\n/g, "\n")
1850
+ const evs = rest.split("\n\n")
1851
+ rest = evs.pop()
1852
+ const out = evs.flatMap(event)
1853
+ if (out.length) ctl.enqueue(enc.encode(out.map((e) => e + "\n\n").join("")))
1854
+ },
1855
+ flush(ctl) {
1856
+ rest += dec.decode()
1857
+ const out = held.map((e) => e + "\n\n").join("") + rest
1858
+ held = []
1859
+ if (out) ctl.enqueue(enc.encode(out))
1860
+ },
1861
+ }),
1862
+ )
1863
+ return new Response(body, { status: res.status, statusText: res.statusText, headers })
1864
+ }
1865
+
1866
+ // ---- signing in -------------------------------------------------------------
1867
+
1868
+ // poll asks path until WorkBuddy answers with data, retrying the codes
1869
+ // that mean "not yet".
1870
+ async function poll(site, path, headers, retry, deadline) {
1871
+ for (;;) {
1872
+ if (Date.now() > deadline) throw new Error(`${site.name} sign-in timed out`)
1873
+ try {
1874
+ const data = await call(site, "GET", path, headers)
1875
+ if (data && Object.keys(data).length) return data
1876
+ } catch (e) {
1877
+ if (!(retry.includes(e.code) || e.status === 408 || e.status === 429)) throw e
1878
+ }
1879
+ await sleep(POLL_MS)
1880
+ }
1881
+ }
1882
+
1883
+ async function browserSignIn(site) {
1884
+ const state = await call(site, "POST", `/v2/plugin/auth/state?platform=${encodeURIComponent(site.platform)}`, {
1885
+ "X-No-Authorization": "true",
1886
+ "X-No-User-Id": "true",
1887
+ "X-No-Enterprise-Id": "true",
1888
+ "X-No-Department-Info": "true",
1889
+ }, {})
1890
+ if (!state?.state || !state?.authUrl) throw new Error(`${site.name} gave no sign-in page`)
1891
+ const url = new URL(state.authUrl)
1892
+ if (url.protocol !== "https:") throw new Error(`${site.name}'s sign-in page isn't https`)
1893
+ // the desktop app's own version, as WorkBuddy desktop opens it
1894
+ // (openAuthUrl: version = CLIENT_INFO_PLUGIN_VERSION, the app's version).
1895
+ // The China build's page hides 企业微信 (WeCom) for a version under 5.8.0
1896
+ // (its signin-callback chunk: platform workbuddy and version >= "5.8.0"),
1897
+ // so the 2.0.0 sent before offered no WeCom sign-in (shenyebuwu on Discord)
1898
+ url.searchParams.set("version", site.app)
1899
+ url.searchParams.set("loginSessionId", hex())
1900
+ return {
1901
+ url: url.toString(),
1902
+ instructions: `Sign in to ${site.name} in the browser; this finishes by itself.`,
1903
+ method: "auto",
1904
+ async callback() {
1905
+ try {
1906
+ const deadline = Date.now() + SIGN_IN_MS
1907
+ const q = encodeURIComponent(state.state)
1908
+ const token = await poll(site, `/v2/plugin/auth/token?state=${q}`, {}, [11217], deadline)
1909
+ if (!token.accessToken) return { type: "failed", error: `${site.name} sent back no token` }
1910
+ let a = merge({}, token)
1911
+ const who = await poll(site, `/v2/plugin/login/account?state=${q}`, {
1912
+ Authorization: "Bearer " + a.access,
1913
+ "X-Domain": domainOf(site, a),
1914
+ "X-No-User-Id": "true",
1915
+ "X-No-Enterprise-Id": "true",
1916
+ }, [12151], deadline)
1917
+ a.uid = who.uid ?? ""
1918
+ const ent = await enterpriseOf(site, a, who)
1919
+ a.enterpriseId = ent.id
1920
+ return success(site, a, accountName(who, ent))
1921
+ } catch (e) {
1922
+ return { type: "failed", error: e.message }
1923
+ }
1924
+ },
1925
+ }
1926
+ }
1927
+
1928
+ function success(site, a, name) {
1929
+ return {
1930
+ type: "success",
1931
+ refresh: a.refresh ?? "",
1932
+ access: a.access,
1933
+ expires: a.expires ?? 0,
1934
+ accountId: name || site.name,
1935
+ uid: a.uid ?? "",
1936
+ domain: a.domain ?? "",
1937
+ ...(a.enterpriseId ? { enterpriseId: a.enterpriseId } : {}),
1938
+ ...(a.refreshExpiresAt ? { refreshExpiresAt: a.refreshExpiresAt } : {}),
1939
+ ...(a.tokenType ? { tokenType: a.tokenType } : {}),
1940
+ }
1941
+ }
1942
+
1943
+ // desktopFile is where WorkBuddy's desktop app keeps its sign-in.
1944
+ function desktopFile(site) {
1945
+ const home = homedir()
1946
+ const base =
1947
+ process.platform === "darwin" ? join(home, "Library", "Application Support", "CodeBuddyExtension")
1948
+ : process.platform === "win32" ? join(home, "AppData", "Local", "CodeBuddyExtension")
1949
+ : join(home, ".local", "share", "CodeBuddyExtension")
1950
+ return join(base, "Data", "Public", "auth", site.authID + ".info")
1951
+ }
1952
+
1953
+ // readDesktop is WorkBuddy desktop's sign-in as the app keeps it now, null
1954
+ // for none (or tokens the app keeps encrypted, which can't be read).
1955
+ function readDesktop(site) {
1956
+ try {
1957
+ const f = JSON.parse(readFileSync(desktopFile(site), "utf8"))
1958
+ const t = f?.auth ?? {}
1959
+ if (typeof t.accessToken !== "string" || !t.accessToken || !f?.account?.uid) return null
1960
+ const now = Date.now()
1961
+ const acct = f.account
1962
+ return {
1963
+ access: t.accessToken,
1964
+ refresh: typeof t.refreshToken === "string" ? t.refreshToken : "",
1965
+ expires: t.expiresAt > 0 ? t.expiresAt : t.expiresIn > 0 ? now + t.expiresIn * 1000 : 0,
1966
+ refreshExpiresAt: t.refreshExpiresAt > 0 ? t.refreshExpiresAt : t.refreshExpiresIn > 0 ? now + t.refreshExpiresIn * 1000 : 0,
1967
+ domain: typeof t.domain === "string" ? t.domain : "",
1968
+ tokenType: typeof t.tokenType === "string" ? t.tokenType : "",
1969
+ uid: acct.uid,
1970
+ ...(typeof acct.enterpriseId === "string" && acct.enterpriseId.trim() ? { enterpriseId: acct.enterpriseId.trim() } : {}),
1971
+ name: acct.nickname || acct.phoneNumber || acct.uid,
1972
+ // what the errors below say to do goes by it: sign in to the app again
1973
+ source: "desktop",
1974
+ }
1975
+ } catch {
1976
+ return null
1977
+ }
1978
+ }
1979
+
1980
+ // notDesktop says why there is no desktop sign-in to use: WorkBuddy 5.6
1981
+ // and later seal its tokens at rest ({$wbEncrypted: 1, envelope}), which
1982
+ // only the app itself opens (plugins#18), so the browser sign-in is the way;
1983
+ // else the app isn't signed in.
1984
+ function notDesktop(site) {
1985
+ try {
1986
+ const t = JSON.parse(readFileSync(desktopFile(site), "utf8"))?.auth ?? {}
1987
+ if (t.accessToken?.$wbEncrypted || t.refreshToken?.$wbEncrypted)
1988
+ return `${site.name} desktop keeps its sign-in encrypted (WorkBuddy 5.6 and later), which magpie can't read; sign in with "${site.name} account (browser)" instead`
1989
+ } catch {}
1990
+ return `${site.name} desktop isn't signed in`
1991
+ }
1992
+
1993
+ // desktopSignIn uses the account WorkBuddy desktop is signed in to: nothing
1994
+ // is copied (a copied refresh token would be the app's and the plugin's
1995
+ // both, and the first to use it would sign the other out); its file is
1996
+ // read each time, as the app keeps it.
1997
+ function desktopSignIn(site) {
1998
+ return {
1999
+ url: "",
2000
+ instructions: `Uses the account ${site.name} desktop is signed in to.`,
2001
+ method: "auto",
2002
+ async callback() {
2003
+ const d = readDesktop(site)
2004
+ if (!d) return { type: "failed", error: notDesktop(site) }
2005
+ return { type: "success", refresh: "", access: "", expires: 0, source: "desktop", accountId: d.name || site.name, uid: d.uid }
2006
+ },
2007
+ }
2008
+ }
2009
+
2010
+ // ---- accounts from a file (magpie's auth.import) ------------------------------
2011
+
2012
+ // IMPORT_FROM says which files magpie's "Import accounts from a file…"
2013
+ // takes for site (marchen_cc on X: there was no way to bring a WorkBuddy
2014
+ // sign-in in from its JSON). Importing renews the sign-in, as signing in
2015
+ // does, so the app the file came from is signed out of that account.
2016
+ function importFrom(site) {
2017
+ const file = site.authID + ".info"
2018
+ return {
2019
+ en: `Choose ${site.name} desktop's sign-in file (${file}, in CodeBuddyExtension/Data/Public/auth), or a copy of a sign-in (JSON with its access and refresh tokens). Each account's sign-in is renewed with ${site.name} before it is added, so the app or tool the file came from is signed out of it and has to sign in again.`,
2020
+ froms: {
2021
+ zh: `选择 ${site.name} 桌面版的登录文件(${file},在 CodeBuddyExtension/Data/Public/auth 下),或一份登录凭证(含 access 和 refresh token 的 JSON)。每个账号都会先向 ${site.name} 续期登录再添加,所以文件来源的应用或工具会退出该账号,需要重新登录。`,
2022
+ "zh-TW": `選擇 ${site.name} 桌面版的登入檔(${file},在 CodeBuddyExtension/Data/Public/auth 下),或一份登入憑證(含 access 和 refresh token 的 JSON)。每個帳號都會先向 ${site.name} 續期登入再加入,所以檔案來源的應用或工具會登出該帳號,需要重新登入。`,
2023
+ ja: `${site.name} デスクトップのサインインファイル(${file}、CodeBuddyExtension/Data/Public/auth 内)か、サインイン情報のコピー(access と refresh トークンを含む JSON)を選んでください。各アカウントは追加の前に ${site.name} でサインインを更新するため、ファイルの元のアプリやツールはそのアカウントからサインアウトされ、再サインインが必要になります。`,
2024
+ de: `Wähle die Anmeldedatei von ${site.name} Desktop (${file}, in CodeBuddyExtension/Data/Public/auth) oder eine Kopie einer Anmeldung (JSON mit Access- und Refresh-Token). Die Anmeldung jedes Kontos wird vor dem Hinzufügen bei ${site.name} erneuert, daher wird die App oder das Tool, aus dem die Datei stammt, von diesem Konto abgemeldet und muss sich neu anmelden.`,
2025
+ },
2026
+ }
2027
+ }
2028
+
2029
+ const str = (v) => (typeof v === "string" ? v.trim() : "")
2030
+ const sealed = (v) => !!(v && typeof v === "object" && v.$wbEncrypted)
2031
+ // plain is an account a file names with only its plain words: WorkBuddy 5.6
2032
+ // and later seal the nickname too ({ $wbEncrypted }), which isn't a name
2033
+ const plain = (who) => who && { ...who, nickname: str(who.nickname), phoneNumber: str(who.phoneNumber), uid: str(who.uid) }
2034
+ const atMs = (at, inSec, now) => (Number(at) > 0 ? Number(at) : Number(inSec) > 0 ? now + Number(inSec) * 1000 : 0)
2035
+
2036
+ // signInsIn are the sign-ins a file's text holds, as found: WorkBuddy
2037
+ // desktop's .info ({ auth, account }), a plugin's or OpenCode's auth.json
2038
+ // entry ({ access, refresh, expires, uid, domain, enterpriseId, … }, by
2039
+ // itself, in a map or a list), or tokens named as OAuth names them
2040
+ // (accessToken/refreshToken, access_token/refresh_token). Each is
2041
+ // { a, who, sealed? }: a the sign-in, who the account the file names (or
2042
+ // null). Nothing is asked of WorkBuddy here.
2043
+ function signInsIn(text) {
2044
+ let v
2045
+ try {
2046
+ v = JSON.parse(text)
2047
+ } catch {
2048
+ return [{ error: "not JSON" }]
2049
+ }
2050
+ const out = []
2051
+ const now = Date.now()
2052
+ const seen = new Set()
2053
+ const walk = (o, depth) => {
2054
+ if (!o || typeof o !== "object" || depth > 4 || seen.has(o)) return
2055
+ seen.add(o)
2056
+ if (Array.isArray(o)) return o.forEach((x) => walk(x, depth + 1))
2057
+ // the desktop app's file: its tokens under auth, the account beside
2058
+ if (o.auth && typeof o.auth === "object" && ("accessToken" in o.auth || "refreshToken" in o.auth)) {
2059
+ const t = o.auth
2060
+ if (sealed(t.accessToken) || sealed(t.refreshToken)) return out.push({ sealed: true })
2061
+ const acct = o.account && typeof o.account === "object" ? o.account : null
2062
+ return out.push({
2063
+ a: {
2064
+ access: str(t.accessToken), refresh: str(t.refreshToken),
2065
+ expires: atMs(t.expiresAt, t.expiresIn, now), refreshExpiresAt: atMs(t.refreshExpiresAt, t.refreshExpiresIn, now),
2066
+ domain: str(t.domain), tokenType: str(t.tokenType),
2067
+ ...(str(acct?.enterpriseId) ? { enterpriseId: str(acct.enterpriseId) } : {}),
2068
+ },
2069
+ who: str(acct?.uid) ? plain(acct) : null,
2070
+ })
2071
+ }
2072
+ const access = o.access ?? o.accessToken ?? o.access_token
2073
+ const refresh = o.refresh ?? o.refreshToken ?? o.refresh_token
2074
+ if (sealed(access) || sealed(refresh)) return out.push({ sealed: true })
2075
+ if (str(access) || str(refresh)) {
2076
+ const uid = str(o.uid)
2077
+ return out.push({
2078
+ a: {
2079
+ access: str(access), refresh: str(refresh),
2080
+ expires: atMs(o.expires ?? o.expiresAt, o.expiresIn ?? o.expires_in, now),
2081
+ refreshExpiresAt: atMs(o.refreshExpiresAt, o.refreshExpiresIn ?? o.refresh_expires_in, now),
2082
+ domain: str(o.domain), tokenType: str(o.tokenType ?? o.token_type),
2083
+ ...(str(o.enterpriseId) ? { enterpriseId: str(o.enterpriseId) } : {}),
2084
+ },
2085
+ who: uid ? { uid, nickname: str(o.nickname) || str(o.accountId) } : null,
2086
+ })
2087
+ }
2088
+ for (const x of Object.values(o)) walk(x, depth + 1)
2089
+ }
2090
+ walk(v, 0)
2091
+ return out.length ? out : [{ error: "no WorkBuddy sign-in in it" }]
2092
+ }
2093
+
2094
+ // otherSite says the site a sign-in's domain belongs to when it isn't
2095
+ // site: a China build's sign-in brought into WorkBuddy AI, or the other way.
2096
+ function otherSite(site, a) {
2097
+ const d = str(a.domain).toLowerCase()
2098
+ if (!d) return ""
2099
+ const cn = /(^|\.)(codebuddy\.cn|tencent\.com|qq\.com)$/.test(d)
2100
+ const ai = /(^|\.)workbuddy\.ai$/.test(d)
2101
+ if (site.ai && cn) return SITES.workbuddy.name
2102
+ if (!site.ai && ai) return SITES["workbuddy-ai"].name
2103
+ return ""
2104
+ }
2105
+
2106
+ // importSignIns checks each sign-in texts hold with WorkBuddy, as signing
2107
+ // in does, and gives each as a sign-in result: renewed with its refresh
2108
+ // token (an access token alone is kept while it lasts), and the account
2109
+ // looked up — the one the file names, else the one WorkBuddy's account
2110
+ // list has it signed in to.
2111
+ async function importSignIns(site, texts) {
2112
+ const results = []
2113
+ for (const text of texts) {
2114
+ for (const got of signInsIn(text)) {
2115
+ if (got.error) { results.push({ type: "failed", error: got.error }); continue }
2116
+ if (got.sealed) {
2117
+ results.push({ type: "failed", error: `${site.name} desktop keeps this sign-in encrypted (WorkBuddy 5.6 and later), which magpie can't read; sign in with "${site.name} account (browser)" instead` })
2118
+ continue
2119
+ }
2120
+ let a = got.a
2121
+ const name0 = got.who ? accountName(got.who, null) : ""
2122
+ try {
2123
+ const other = otherSite(site, a)
2124
+ if (other) throw new Error(`this is a ${other} sign-in; import it under ${other}`)
2125
+ if (refreshable(a)) a = await renew(site, a)
2126
+ else if (!a.access || stale(a)) throw new Error(`the sign-in has ended; sign in to ${site.name} again where it came from`)
2127
+ let who = got.who
2128
+ if (!who?.uid) {
2129
+ const list = await call(at(site, a), "GET", "/v2/plugin/accounts", { Authorization: "Bearer " + a.access, "X-Domain": domainOf(site, a), ...enterpriseHeaders(a) })
2130
+ const all = (list?.accounts ?? []).filter((x) => x?.uid)
2131
+ const ent = a.enterpriseId
2132
+ const pick = ent ? all.filter((x) => str(x.enterpriseId) === ent) : all.filter((x) => x.lastLogin)
2133
+ who = plain(pick.length === 1 ? pick[0] : all.length === 1 ? all[0] : null)
2134
+ if (!who) throw new Error(`${site.name} didn't say whose sign-in this is`)
2135
+ }
2136
+ a.uid = who.uid
2137
+ const ent = await enterpriseOf(site, a, who)
2138
+ if (ent.id) a.enterpriseId = ent.id
2139
+ results.push(success(site, a, accountName(who, ent)))
2140
+ } catch (e) {
2141
+ results.push({ type: "failed", error: e?.message ?? String(e), ...(name0 ? { accountId: name0 } : {}) })
2142
+ }
2143
+ }
2144
+ }
2145
+ return results
2146
+ }
2147
+
2148
+ // desktopHeld is what a desktop sign-in was renewed to here, by site and
2149
+ // account: kept in memory only, never written where the app keeps it.
2150
+ const desktopHeld = new Map()
2151
+
2152
+ // current is the sign-in a stored auth names, fresh: WorkBuddy desktop's,
2153
+ // read where it keeps it, or one kept here.
2154
+ async function current(site, client, auth) {
2155
+ if (auth?.source !== "desktop") return fresh(site, client, auth)
2156
+ const d = readDesktop(site)
2157
+ if (!d) throw new Error(notDesktop(site))
2158
+ const k = site.id + "|" + d.uid
2159
+ const h = desktopHeld.get(k)
2160
+ const a = await fresh(site, null, h && h.expires >= d.expires ? h : d)
2161
+ desktopHeld.set(k, a)
2162
+ return a
2163
+ }
2164
+
2165
+ // ---- allowance ----------------------------------------------------------------
2166
+
2167
+ // STATUS_TEXT is Go's http.StatusText, which magpie's built-in said a
2168
+ // refused meter call with; a status Go has no words for is "HTTP <n>", so
2169
+ // the card always has an error.
2170
+ const STATUS_TEXT = {
2171
+ 100: "Continue", 101: "Switching Protocols", 102: "Processing", 103: "Early Hints",
2172
+ 200: "OK", 201: "Created", 202: "Accepted", 203: "Non-Authoritative Information", 204: "No Content", 205: "Reset Content",
2173
+ 206: "Partial Content", 207: "Multi-Status", 208: "Already Reported", 226: "IM Used",
2174
+ 300: "Multiple Choices", 301: "Moved Permanently", 302: "Found", 303: "See Other", 304: "Not Modified", 305: "Use Proxy",
2175
+ 307: "Temporary Redirect", 308: "Permanent Redirect",
2176
+ 400: "Bad Request", 401: "Unauthorized", 402: "Payment Required", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed",
2177
+ 406: "Not Acceptable", 407: "Proxy Authentication Required", 408: "Request Timeout", 409: "Conflict", 410: "Gone",
2178
+ 411: "Length Required", 412: "Precondition Failed", 413: "Request Entity Too Large", 414: "Request URI Too Long",
2179
+ 415: "Unsupported Media Type", 416: "Requested Range Not Satisfiable", 417: "Expectation Failed", 418: "I'm a teapot",
2180
+ 421: "Misdirected Request", 422: "Unprocessable Entity", 423: "Locked", 424: "Failed Dependency", 425: "Too Early",
2181
+ 426: "Upgrade Required", 428: "Precondition Required", 429: "Too Many Requests", 431: "Request Header Fields Too Large",
2182
+ 451: "Unavailable For Legal Reasons",
2183
+ 500: "Internal Server Error", 501: "Not Implemented", 502: "Bad Gateway", 503: "Service Unavailable", 504: "Gateway Timeout",
2184
+ 505: "HTTP Version Not Supported", 506: "Variant Also Negotiates", 507: "Insufficient Storage", 508: "Loop Detected",
2185
+ 510: "Not Extended", 511: "Network Authentication Required",
2186
+ }
2187
+ const statusText = (n) => STATUS_TEXT[n] || `HTTP ${n}`
2188
+
2189
+ // meterAsked is the billing API's reply to path, asked with a's sign-in.
2190
+ function meterAsked(site, a, path, body = {}, signal = AbortSignal.timeout(20000)) {
2191
+ return fetch(endpointOf(site, a) + path, {
2192
+ method: "POST",
2193
+ headers: { "Content-Type": "application/json", Accept: "application/json", "User-Agent": "WorkBuddy/" + site.app,
2194
+ Authorization: "Bearer " + a.access, "X-User-Id": a.uid ?? "", "X-Domain": domainOf(site, a), "X-Product": "SaaS",
2195
+ "X-IDE-Type": "WorkBuddy", ...enterpriseHeaders(a) },
2196
+ body: JSON.stringify(body),
2197
+ signal,
2198
+ })
2199
+ }
2200
+
2201
+ // EDGE_READS is how much of a request WorkBuddy's front door (APISIX, on
2202
+ // both sites) reads before it answers a sign-in it refuses. A refused
2203
+ // request with a longer body gets no answer at all: the connection is
2204
+ // reset, and the chat fails as "ECONNRESET: The socket connection was
2205
+ // closed unexpectedly", which says nothing of the sign-in (wyp on Discord,
2206
+ // 2026-10-15: a Claude Code session past 2 MiB failed on every turn).
2207
+ // Measured on 2026-10-15 on www.workbuddy.ai and copilot.tencent.com: a
2208
+ // body of 2097152 bytes with a refused token got 401, one of 2097153 a
2209
+ // reset; with an accepted token 20 MB went through.
2210
+ const EDGE_READS = 2 * 1024 * 1024
2211
+
2212
+ const byteLength = (b) =>
2213
+ typeof b === "string" ? Buffer.byteLength(b) : b instanceof ArrayBuffer || ArrayBuffer.isView(b) ? b.byteLength : 0
2214
+
2215
+ // unanswered is what a chat whose fetch failed with err comes to: a chat
2216
+ // past EDGE_READS that the connection was reset on is asked about at the
2217
+ // billing API, which answers a refused sign-in with its 401 whatever the
2218
+ // size. A 401 there is the chat's own answer, said as one; anything else
2219
+ // leaves err as it was, as does a smaller chat, which the front door
2220
+ // answers itself. The chat isn't sent again.
2221
+ async function unanswered(site, a, body, err, signal) {
2222
+ if (signal?.aborted || err?.name === "AbortError" || err?.name === "TimeoutError") throw err
2223
+ const size = byteLength(body)
2224
+ if (size <= EDGE_READS) throw err
2225
+ // the billing API isn't asked with a key: what it answers one is unknown
2226
+ if (a.source === "key") throw err
2227
+ let status = 0
2228
+ let challenge = ""
2229
+ try {
2230
+ const res = await meterAsked(site, a, "/billing/meter/get-user-resource-summary", {}, AbortSignal.timeout(20000))
2231
+ status = res.status
2232
+ challenge = res.headers.get("www-authenticate") ?? ""
2233
+ await res.body?.cancel()
2234
+ } catch {
2235
+ throw err
2236
+ }
2237
+ if (status !== 401) throw err
2238
+ const mb = (size / (1024 * 1024)).toFixed(1)
2239
+ const note = `It closes the connection on a refused request over 2 MiB (this one was ${mb} MiB) instead of answering, which is why it read as ECONNRESET.`
2240
+ const message =
2241
+ `${site.name} refused this account's sign-in (401). ${note} ` +
2242
+ (a.source === "desktop" ? `Sign in to ${site.name} desktop again.` : `Sign in to ${site.name} again in magpie.`)
2243
+ // the billing API's challenge goes with it: it says whether the token
2244
+ // itself was refused (invalidToken), as the chat's own 401 would have
2245
+ const headers = { "content-type": "application/json", ...(challenge ? { "www-authenticate": challenge } : {}) }
2246
+ const res = new Response(JSON.stringify({ error: { message, type: "authentication_error", code: 401 } }), {
2247
+ status: 401,
2248
+ statusText: "Unauthorized",
2249
+ headers,
2250
+ })
2251
+ edgeNotes.set(res, note)
2252
+ return res
2253
+ }
2254
+
2255
+ // edgeNotes is what unanswered's 401s say of the reset, for signedOut to
2256
+ // say again when the sign-in can't be renewed.
2257
+ const edgeNotes = new WeakMap()
2258
+
2259
+ // ---- a refused sign-in ----------------------------------------------------------
2260
+
2261
+ // invalidToken says res is WorkBuddy refusing the access token itself. Its
2262
+ // front door (APISIX, on both sites) answers a token it doesn't take with
2263
+ // 401 and WWW-Authenticate: Bearer realm="copilot", error="invalid_token",
2264
+ // on a chat (streamed or not) and on the billing API alike; measured on
2265
+ // www.workbuddy.ai on 2026-10-23 with a real account's token cut short,
2266
+ // and with "garbage". (Its /v3/config answers 200 to any token, so the
2267
+ // models list never meets a 401.) A 401 without it is not taken as the
2268
+ // sign-in's: WorkBuddy answers some paths with a bare 401 to an accepted
2269
+ // sign-in (magpie's check-in, モモコ on Discord).
2270
+ const invalidToken = (res) => res?.status === 401 && /invalid_token/i.test(res.headers.get("www-authenticate") ?? "")
2271
+
2272
+ // refreshRefused says e is WorkBuddy turning the refresh token itself
2273
+ // away: HTTP 401 with code 12153, "refresh token failed:400 Bad Request:
2274
+ // invalid_grant: Invalid refresh token" for a spent or unknown one, or
2275
+ // "10000:token format error" (measured 2026-10-23). Anything else (a 5xx,
2276
+ // a timeout) says nothing of the sign-in.
2277
+ const refreshRefused = (e) => e instanceof WBError && (e.status === 401 || /invalid_grant/i.test(e.message))
2278
+
2279
+ // reissued is the sign-in to send a request WorkBuddy refused a's access
2280
+ // token for (401) once more with, before that token's time: WorkBuddy can
2281
+ // refuse one long before it ends (a browser sign-in's lasts as long as
2282
+ // its refresh token, about 340 days), and renewing only by time left such
2283
+ // an account refused on every request for months. It is
2284
+ // { a }: a sign-in with another access token, to send the request with
2285
+ // once more;
2286
+ // { why, kind }: none to be had, why, and of what kind: "refresh
2287
+ // refused" (WorkBuddy turned the refresh token away too), "nothing to
2288
+ // renew with" (no refresh token, or one past its end), or "unknown"
2289
+ // (the refresh failed for another reason, the desktop's token is the
2290
+ // one refused).
2291
+ // began is the access token the request read at its start: a stored one
2292
+ // that isn't it was saved since by someone else (magpie's renewal,
2293
+ // another of its processes), and is taken rather than renewing again.
2294
+ //
2295
+ // A desktop sign-in is the app's: its file is read again, and what was
2296
+ // renewed here (desktopHeld) is let go, but its refresh token is never
2297
+ // spent for a refusal, which would sign the app itself out (see
2298
+ // desktopSignIn).
2299
+ async function reissued(site, client, getAuth, a, began) {
2300
+ if (a.source === "desktop") {
2301
+ desktopHeld.delete(site.id + "|" + a.uid)
2302
+ const d = readDesktop(site)
2303
+ if (!d) return { why: notDesktop(site), kind: "unknown" }
2304
+ if (d.access !== a.access) {
2305
+ desktopHeld.set(site.id + "|" + d.uid, d)
2306
+ return { a: d }
2307
+ }
2308
+ return { why: `${site.name} desktop's own sign-in is the one refused`, kind: "unknown" }
2309
+ }
2310
+ const newer = async () => {
2311
+ const now = await getAuth().catch(() => null)
2312
+ return now?.type === "oauth" && now.source !== "desktop" && now.access && now.access !== began && now.access !== a.access ? now : null
2313
+ }
2314
+ const saved = await newer()
2315
+ if (saved) return { a: saved }
2316
+ if (!refreshable(a)) return { why: a.refresh ? "its refresh token has ended" : "there is no refresh token to renew it with", kind: "nothing to renew with" }
2317
+ try {
2318
+ const next = await renew(site, a, async (n) => {
2319
+ try {
2320
+ await client?.auth?.set?.({ path: { id: site.id }, body: n })
2321
+ } catch {}
2322
+ })
2323
+ return next.access !== a.access ? { a: next } : { why: "renewing it gave the same token", kind: "unknown" }
2324
+ } catch (e) {
2325
+ if (refreshRefused(e)) {
2326
+ // spent by someone else, who saved what it gave
2327
+ const saved = await newer()
2328
+ if (saved) return { a: saved }
2329
+ return { why: `it refused the refresh token too (${e.said ?? e.message})`, kind: "refresh refused" }
2330
+ }
2331
+ return { why: `renewing it failed: ${e?.said ?? e?.message ?? e}`, kind: "unknown" }
2332
+ }
2333
+ }
2334
+
2335
+ // gone says whether a sign-in reissued (r) couldn't renew is gone, on
2336
+ // WorkBuddy's word: it turned the refresh token away, or refused the access
2337
+ // token itself (tokenRefused, invalidToken) with none to renew it with. A
2338
+ // desktop sign-in never is: the app's file is read on each request, and
2339
+ // signing in to the app again is all it takes.
2340
+ const gone = (a, r, tokenRefused) =>
2341
+ a.source !== "desktop" && (r.kind === "refresh refused" || (r.kind === "nothing to renew with" && !!tokenRefused))
2342
+
2343
+ // refusedText says WorkBuddy refused a's sign-in, why it wasn't renewed,
2344
+ // and what to do.
2345
+ function refusedText(site, a, why, note) {
2346
+ return (
2347
+ `${site.name} refused this account's sign-in (401)${why ? "; " + why : ""}. ${note ? note + " " : ""}` +
2348
+ (a.source === "desktop"
2349
+ ? `Sign in to ${site.name} desktop again; magpie reads its sign-in on the next request.`
2350
+ : `Sign in to it again in magpie: Providers → ${site.name} → this account's Sign in again.`)
2351
+ )
2352
+ }
2353
+
2354
+ // keyRefused is the answer to a request WorkBuddy refused an API key for
2355
+ // (401): a key isn't renewed, so it says to check the key. Marked expired
2356
+ // only on WorkBuddy's word that the token itself is refused (invalidToken).
2357
+ function keyRefused(site, expired, note) {
2358
+ const message = `${site.name} refused this API key (401). ${note ? note + " " : ""}Check the key at ${site.keys}, then add it again in magpie: Providers → ${site.name}.`
2359
+ return new Response(JSON.stringify({ error: { message, type: "authentication_error", code: 401 } }), {
2360
+ status: 401,
2361
+ statusText: "Unauthorized",
2362
+ headers: { "content-type": "application/json", "X-Magpie-Sign-In": expired ? "expired" : "kept" },
2363
+ })
2364
+ }
2365
+
2366
+ // signedOut is the answer to a request WorkBuddy refused this account's
2367
+ // sign-in for, renewed or not: a 401 that says so and what to do, which
2368
+ // WorkBuddy's own (an HTML page, its {code, msg}) doesn't. expired marks
2369
+ // the account in magpie (X-Magpie-Sign-In), out of routing and "sign in
2370
+ // again" on its row, till it is signed in again; else it is kept.
2371
+ function signedOut(site, a, why, expired, note) {
2372
+ const message = refusedText(site, a, why, note)
2373
+ return new Response(JSON.stringify({ error: { message, type: "authentication_error", code: 401 } }), {
2374
+ status: 401,
2375
+ statusText: "Unauthorized",
2376
+ headers: { "content-type": "application/json", "X-Magpie-Sign-In": expired ? "expired" : "kept" },
2377
+ })
2378
+ }
2379
+
2380
+ // meter asks the billing API as magpie's built-in did, its errors said
2381
+ // the same: WorkBuddy's message, else its code, else the HTTP status.
2382
+ async function meter(site, a, path, body = {}) {
2383
+ const res = await meterAsked(site, a, path, body)
2384
+ const raw = await res.text()
2385
+ let env = {}
2386
+ let parsed = true
2387
+ try {
2388
+ env = JSON.parse(raw) ?? {}
2389
+ } catch {
2390
+ parsed = false
2391
+ }
2392
+ if (res.ok && !parsed) {
2393
+ const unreadable = raw.trim().slice(0, 120) || "(empty)"
2394
+ throw Object.assign(new Error(`unreadable reply ${unreadable}`), { status: res.status, code: 0, unreadable: true })
2395
+ }
2396
+ const code = Number.parseInt(env.code, 10) || 0
2397
+ // the status, the code and whether the token itself was refused go with
2398
+ // it, for usage's one renewal on a 401 (reissued) and check-in's outcomes
2399
+ const said = { status: res.status, code }
2400
+ if (!res.ok) said.invalidToken = invalidToken(res)
2401
+ const err = (message) => Object.assign(new Error(message), said)
2402
+ if (!res.ok) {
2403
+ if (code) throw err(env.msg || `error ${code}`)
2404
+ if (env.msg) throw err(env.msg)
2405
+ throw err(statusText(res.status))
2406
+ }
2407
+ if (code) throw err(env.msg || `error ${code}`)
2408
+ return env.data ?? null
2409
+ }
2410
+
2411
+ // checkinOf claims the account's daily credits. China has the /v2 meter;
2412
+ // after the activity status names an active, unchecked day. Transient
2413
+ // upstream failures are asked again twice (the bounded retry quota-hub
2414
+ // observed on the billing endpoint; callers may shorten the waits for a
2415
+ // test).
2416
+ async function checkinOf(site, a, { waits = [0, 0] } = {}) {
2417
+ let status
2418
+ try {
2419
+ status = await meter(site, a, "/v2/billing/meter/checkin-activity-status")
2420
+ } catch (e) {
2421
+ if (e?.code === 1001) return { outcome: "done" }
2422
+ // a reply WorkBuddy sent is the day's failed answer; only a request
2423
+ // that got no answer leaves as a throw, for magpie's offline backoff
2424
+ if (e?.status !== undefined || e?.code !== undefined) return { outcome: "failed", message: e.message }
2425
+ throw e
2426
+ }
2427
+ if (!status?.active) return { outcome: "inactive" }
2428
+ if (status.today_checked_in ?? status.todayCheckedIn) {
2429
+ // today_credit is what today actually gave, the built-in's word for a
2430
+ // day already in; daily_credit is the day's grant
2431
+ const credit = Number(status.today_credit ?? status.daily_credit)
2432
+ return { outcome: "done", ...(Number.isFinite(credit) && credit > 0 ? { credit } : {}) }
2433
+ }
2434
+ const paths = ["/v2/billing/meter/daily-checkin"]
2435
+ for (let attempt = 0; ; attempt++) {
2436
+ let i = 0
2437
+ while (i < paths.length) {
2438
+ try {
2439
+ const got = await meter(site, a, paths[i++])
2440
+ // the claim's own answer, as the built-in hands it on: the credit
2441
+ // and streak it granted and what it said, for the card
2442
+ const credit = Number(got?.credit)
2443
+ const streak = Number(got?.streak_days)
2444
+ return {
2445
+ outcome: "claimed",
2446
+ ...(Number.isFinite(credit) && credit > 0 ? { credit } : {}),
2447
+ ...(Number.isFinite(streak) && streak > 0 ? { streak } : {}),
2448
+ ...(got?.message ? { message: String(got.message) } : {}),
2449
+ }
2450
+ } catch (e) {
2451
+ if (e?.code === 1001) return { outcome: "done" }
2452
+ if (e?.code === 1002) return { outcome: "ineligible", message: e.message }
2453
+ if (e?.code === 1003) return { outcome: "inactive", message: e.message }
2454
+ if (e?.status === 401) {
2455
+ try {
2456
+ await meter(site, a, "/billing/meter/get-user-resource-summary")
2457
+ } catch {
2458
+ throw e
2459
+ }
2460
+ return { outcome: "ineligible", message: "WorkBuddy's check-in takes WorkBuddy's own app" }
2461
+ }
2462
+ if (e?.unreadable) return { outcome: "failed", message: `check-in: ${e.message}` }
2463
+ const transient = e?.status >= 500 || e?.code === 10000
2464
+ if (transient && attempt < waits.length) {
2465
+ await new Promise((r) => setTimeout(r, waits[attempt]))
2466
+ break
2467
+ }
2468
+ // a reply WorkBuddy sent is the day's failed answer; only a request
2469
+ // that got no answer leaves as a throw, for magpie's offline backoff
2470
+ if (e?.status !== undefined || e?.code !== undefined) return { outcome: "failed", message: e.message }
2471
+ throw e
2472
+ }
2473
+ }
2474
+ }
2475
+ }
2476
+
2477
+ // capacity is a capacity the billing API sends, as a string ("438.88")
2478
+ // or now and then a number; empty is 0.
2479
+ function capacity(v) {
2480
+ if (v == null || v === "") return 0
2481
+ if (typeof v === "number") return v
2482
+ const s = String(v)
2483
+ const n = Number(s)
2484
+ if (s.trim() !== s || Number.isNaN(n)) throw new Error(`strconv.ParseFloat: parsing ${JSON.stringify(s)}: invalid syntax`)
2485
+ return n
2486
+ }
2487
+
2488
+ // compact is a count as magpie says one: whole, else to two places.
2489
+ const compact = (n) => (Number.isInteger(n) ? String(n) : n.toFixed(2).replace(/0+$/, "").replace(/\.$/, ""))
2490
+
2491
+ // The window WorkBuddy rate limits deepseek-v4.1-flash by, which its credit
2492
+ // meter does not show: WorkBuddy AI measured at about 1e8 over ten days, the
2493
+ // China build at about 2e8 on 2026-11-02 (see CN_ESTIMATED_WINDOWS).
2494
+ //
2495
+ // A free account's usage() reports only the credits window, so a plan with
2496
+ // 160 credits untouched reads 0% while chats to deepseek-v4.1-flash are
2497
+ // already refused: the model has a token allowance of its own, counted
2498
+ // apart from credits, and nothing the vendor answers with reports it. The
2499
+ // refusal is the only place it appears, and only as a time:
2500
+ //
2501
+ // 429 usage exceeds frequency limit, but don't worry, your usage will
2502
+ // reset at 2026-10-20 19:47:41 UTC+8, alternatively, you can switch to
2503
+ // the other models to continue using it.
2504
+ //
2505
+ // The China build (copilot.tencent.com) says the same in its own words:
2506
+ //
2507
+ // 429 WorkBuddy: 您的使用量已超出频率限制,将在 2026-11-02 19:17:02
2508
+ // UTC+8 重置,您也可以切换其他模型继续使用。
2509
+ //
2510
+ // Measured on a free plan over ten days (one account, deepseek-v4.1-flash
2511
+ // only), counting in + cache_read + out:
2512
+ //
2513
+ // 10-15 15:40 → 100,183,315 429 10-18 19:52 → 92,792,962 429
2514
+ // 10-16 16:48 → 99,971,831 429 10-19 19:47 → 98,201,537 429
2515
+ // 10-14 15:38 → 71,687,717 lapsed
2516
+ //
2517
+ // so the cap is per account per 24 hours at about 1e8 tokens, the largest
2518
+ // value that still answered being 100,183,315. Three things about it are
2519
+ // easy to get wrong and were all checked:
2520
+ //
2521
+ // - cache_read counts. In + out alone is 20× smaller (0.75M–3.9M a
2522
+ // window) and never comes near the cap.
2523
+ // - the window is fixed, not sliding: peak trailing-24h over the same
2524
+ // data is 172.85M, which a sliding window would have held to 1e8.
2525
+ // - the reset a refusal names is the window's start + 24h exactly, and
2526
+ // the start is the first request answered after the previous window
2527
+ // ended — not the reset instant. Gaps of 6, 68, 80 and 182 minutes
2528
+ // were seen between a reset and the next request, each opening the new
2529
+ // window.
2530
+ //
2531
+ // The China build was measured after that, on 2026-11-02: two Free-plan
2532
+ // accounts on copilot.tencent.com, both spending the machine's ledger only
2533
+ // on this model, were refused at 200,389,043 and 200,485,923 tokens counted
2534
+ // the same way. Its cap sits at about 2e8 — and its refusals name the reset
2535
+ // in Chinese (将在 … UTC+8 重置), which windowReset reads as well.
2536
+ //
2537
+ // deepseek-v4.1-flash-sg is the same model under its paid id (the product
2538
+ // config's ModelRateLimitCap.lines[0] names it as paidId to this freeId,
2539
+ // allowPaidSwitch: true) and draws on the same window: it was refused in
2540
+ // the same windows, to the second, with about 0.01M tokens of its own.
2541
+ // Both ids are named in models: magpie matches a plugin window's models
2542
+ // against a model id exactly, folding only an @size suffix
2543
+ // (internal/provider/plugin_usage.go, idSetOf), so one id alone leaves the
2544
+ // other unrestricted.
2545
+ //
2546
+ // The window is read two ways, and a refusal wins:
2547
+ //
2548
+ // - the sum (in + cache_read + out) of this machine's rows, which holds
2549
+ // until the account is first refused. The ledger is this machine's
2550
+ // only, so an account also used on another machine or through another
2551
+ // client reads short: 92.8M read as "93%" on one refused at 92,792,962,
2552
+ // the rest of its spending being elsewhere.
2553
+ // - a refusal whose named reset is still ahead, which makes the window
2554
+ // full whatever the sum says. That is the one exact signal there is,
2555
+ // and routing must not pass over it either.
2556
+ //
2557
+ // So the sum is an estimate, and it is shown, not routed on: its card is set
2558
+ // aside (aside: true), which magpie draws beside the account and never counts
2559
+ // as its allowance. Only a refusal's card stops the model. The estimate used
2560
+ // to stop it as well, and it read a paid China account at 99% of a cap it had
2561
+ // never been refused at, with 2,457 credits left (XiaoFeiyu9, plugins#641):
2562
+ // the cap is two accounts' measurement, the ledger is one machine's, and
2563
+ // neither is the vendor's word for this account. Nothing is lost by waiting
2564
+ // for that word: magpie's gateway reads the refusal's reset ("将在 … 重置",
2565
+ // "reset at …") and its "switch to the other models", and rests this model
2566
+ // alone, on this account alone, until the time the vendor named.
2567
+ //
2568
+ // The ledger is magpie's own, in magpie's config folder (appdir.Config()):
2569
+ // the folder the plugin host runs in, which is the portable data folder
2570
+ // when magpie runs portable, $XDG_CONFIG_HOME/magpie when that is set, and
2571
+ // ~/.config/magpie otherwise. No endpoint reports the window; a ledger that
2572
+ // cannot be read yields no window rather than a made-up one.
2573
+
2574
+ // A window: the build's ledger rows it counts (provider and model), the cap
2575
+ // it reports against, and how its card reads. Two builds, two sets of
2576
+ // windows: the same phone number can be signed in to both, and their ledgers
2577
+ // stay apart — one build's spending must not fill the other's window.
2578
+ //
2579
+ // The China caps are measured on this machine from the vendor's own
2580
+ // refusals, never the vendor's word, and each is an estimate: 2e8 for
2581
+ // deepseek-v4.1-flash (two accounts refused at 200.39M and 200.49M on
2582
+ // 2026-11-02), with the card saying so (`~` and "(est.)"). The card is
2583
+ // shown only — set aside, plugins#641 — so a cap that goes stale costs a
2584
+ // wrong percentage, never a wrongly rested model; the first refusal of a
2585
+ // window pins the card full at the reset the vendor names.
2586
+ //
2587
+ // One entry per model, and only models that have been measured: a guessed
2588
+ // cap would read wrong every day. Add an entry when another model's window
2589
+ // is measured; remove one when the vendor stops applying it.
2590
+ const CN_ESTIMATED_WINDOWS = [
2591
+ {
2592
+ provider: "workbuddy",
2593
+ model: "deepseek-v4.1-flash",
2594
+ aliases: ["deepseek-v4.1-flash-sg"],
2595
+ cap: 2e8,
2596
+ name: "deepseek-v4.1-flash tokens (est.)",
2597
+ short: "~200M",
2598
+ // no unit: the name already says tokens, and magpie's narrow account
2599
+ // cards cut a unit short ("tok…") beside the nine-digit numbers
2600
+ unit: "",
2601
+ },
2602
+ ]
2603
+ // WorkBuddy AI's window keeps the name it shipped with: there the model is
2604
+ // served at x0.00, so "Free model tokens" is what it is.
2605
+ const FREE_WINDOW_AI = {
2606
+ provider: "workbuddy-ai",
2607
+ model: "deepseek-v4.1-flash",
2608
+ aliases: ["deepseek-v4.1-flash-sg"],
2609
+ cap: 1e8,
2610
+ name: "Free model tokens",
2611
+ short: "100M",
2612
+ unit: "tokens",
2613
+ }
2614
+ const FREE_WINDOW_SPAN = 24 * 3600 * 1000
2615
+ // The lead: how far back of an edge the read goes on. A chain read from a row
2616
+ // that opens a window needs the window the span makes of the rows above it,
2617
+ // so the rows kept reach a day past the edge — the window opening at the
2618
+ // request after it, minutes to hours into that day, whatever the first row
2619
+ // after the edge falls on.
2620
+ const FREE_WINDOW_LEAD = 86400 * 1000
2621
+ // A gap this long between two of this account's answered rows ends every
2622
+ // window before it, so the later row opens one: the window holding the
2623
+ // earlier row began at most 24h before it, and so ended 24h after it at the
2624
+ // latest. This is one of the two edges the ledger itself spells out.
2625
+ const FREE_WINDOW_GAP = FREE_WINDOW_SPAN
2626
+ // the model a window is counted for is its spec's `model`; `aliases` are the
2627
+ // ids that share the window (-sg is the same model under its paid id), and
2628
+ // both are named in the card's models so magpie's exact match finds them
2629
+
2630
+ // windowOffset is the UTC offset a refusal spells out, in minutes, from
2631
+ // "UTC+8", "UTC+08:00", "UTC-5" or "GMT+8". null when it spells out none,
2632
+ // which is not the same as +08:00: an offset guessed wrong puts the reset
2633
+ // hours from where it is, so a reset that cannot be placed is not used as
2634
+ // an edge at all.
2635
+ function windowOffset(text) {
2636
+ const m = /\b(?:UTC|GMT)\s*([+-])\s*(\d{1,2})(?::?(\d{2}))?\b/i.exec(String(text ?? ""))
2637
+ if (!m) return null
2638
+ const min = Number(m[2]) * 60 + Number(m[3] ?? 0)
2639
+ if (min > 14 * 60) return null
2640
+ return m[1] === "-" ? -min : min
2641
+ }
2642
+
2643
+ // windowReset is the instant a refusal names, or NaN when it names none or
2644
+ // names it in an offset that cannot be read. Both builds name it — WorkBuddy
2645
+ // AI in its English "will reset at …", the China build in its Chinese
2646
+ // "将在 … 重置" — with the time in the same shape, so the two patterns share
2647
+ // the group numbering and the offset below reads the "UTC+8" either way.
2648
+ function windowReset(text) {
2649
+ const s = String(text ?? "")
2650
+ const at =
2651
+ /reset at (\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2}):(\d{2})/.exec(s) ||
2652
+ /将在\s*(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2}):(\d{2})/.exec(s)
2653
+ if (!at) return NaN
2654
+ const off = windowOffset(s)
2655
+ if (off === null) return NaN
2656
+ return Date.UTC(+at[1], +at[2] - 1, +at[3], +at[4], +at[5], +at[6]) - off * 60000
2657
+ }
2658
+
2659
+ // resetOf is the vendor reset a row names, whether its words spell it out or
2660
+ // a routing trace handed it as the instant itself.
2661
+ function resetOf(row) {
2662
+ const said = windowReset(row?.err)
2663
+ if (Number.isFinite(said)) return said
2664
+ const until = Number(row?.restUntil)
2665
+ return Number.isFinite(until) ? until : NaN
2666
+ }
2667
+
2668
+ function windowModel(model, win) {
2669
+ return typeof model === "string" && (model.startsWith(win.model) || win.aliases.some((alias) => model.startsWith(alias)))
2670
+ }
2671
+
2672
+ // freeWindowOf is the window account is in now, from rows (magpie's usage
2673
+ // records), or null when it has lapsed — the next request opens a new one.
2674
+ // now is passed in so the reading is testable; win is the build's window
2675
+ // (which build's rows count, what cap they fill), AI by default.
2676
+ //
2677
+ // The window is a chain: it begins at the first request answered after the
2678
+ // previous one ended, so where this window began depends on every window
2679
+ // before it. A window ends at a refusal's reset when the ledger holds one,
2680
+ // and otherwise a day after it began. readLedgerTail (which see) stops on
2681
+ // both, so that these rows read the same as the whole ledger.
2682
+ function freeWindowOf(rows, account, now = Date.now(), win = FREE_WINDOW_AI) {
2683
+ const mine = (Array.isArray(rows) ? rows : []).filter(
2684
+ (r) =>
2685
+ r?.provider === win.provider &&
2686
+ r.providerAccount === account &&
2687
+ typeof r.model === "string" &&
2688
+ windowModel(r.model, win) &&
2689
+ r.t,
2690
+ )
2691
+ if (!mine.length) return null
2692
+
2693
+ const at = (r) => {
2694
+ const t = Date.parse(r.t)
2695
+ return Number.isFinite(t) ? t : 0
2696
+ }
2697
+ const counted = (r) => (r.in ?? 0) + (r.cache_read ?? 0) + (r.out ?? 0)
2698
+ // two rows a day apart: the first of them opened a window that has ended by
2699
+ // the second. Written as a function so that no minifier folds the
2700
+ // subtraction into the comparison.
2701
+ const apart = (a, b) => a - b >= FREE_WINDOW_SPAN
2702
+
2703
+ // a refusal names the end of the window it refused in
2704
+ const edges = []
2705
+ for (const r of mine) {
2706
+ if (Number(r.status) !== 429) continue
2707
+ const t = resetOf(r)
2708
+ if (Number.isFinite(t)) edges.push(t)
2709
+ }
2710
+ edges.sort((a, b) => a - b)
2711
+
2712
+ const answered = mine.filter((r) => Number(r.status) === 200 && at(r) > 0).sort((a, b) => at(a) - at(b))
2713
+ if (!answered.length) return null
2714
+
2715
+ const head = (from) => {
2716
+ let start = null
2717
+ let used = 0
2718
+ let edge = 0 // the refusals already read
2719
+ for (let i = from; i < answered.length; i++) {
2720
+ const r = answered[i]
2721
+ const t = at(r)
2722
+ // every refusal this row's window ended at closes it
2723
+ while (edge < edges.length && edges[edge] <= t) {
2724
+ start = null
2725
+ used = 0
2726
+ edge++
2727
+ }
2728
+ if (start === null) start = t
2729
+ else if (apart(t, start)) {
2730
+ start = t
2731
+ used = 0
2732
+ }
2733
+ used += counted(r)
2734
+ }
2735
+ return start === null ? null : { start, used }
2736
+ }
2737
+
2738
+ // The rows may begin before the window now: readLedgerTail goes a day past
2739
+ // the edge it stops at, so the run of rows that opens a window can start a
2740
+ // day after the first row kept. That window opens at a row with no answered
2741
+ // row of this account's within a day before it — where the chain is read
2742
+ // from. Read from the first row kept, the chain would begin shifted, a day
2743
+ // early: every window after it, the card with it.
2744
+ let w = null
2745
+ for (let i = 0; i < answered.length; i++) {
2746
+ if (i && !apart(at(answered[i]), at(answered[i - 1]))) continue
2747
+ const h = head(i)
2748
+ if (h === null) continue
2749
+ if (h.start + FREE_WINDOW_SPAN <= now) continue // lapsed before now
2750
+ w = h
2751
+ break
2752
+ }
2753
+ const start = w?.start
2754
+ const used = w?.used
2755
+ if (!(start > 0)) return null
2756
+
2757
+ const end = start + FREE_WINDOW_SPAN
2758
+ if (now >= end) return null // lapsed: nothing is exhausted, a new window opens on the next request
2759
+
2760
+ const card = (amount, resetsAt, refused) => ({
2761
+ name: win.name,
2762
+ used: Math.min(100, (100 * amount) / win.cap),
2763
+ amount,
2764
+ limit: win.cap,
2765
+ unit: win.unit,
2766
+ display: `${tokensShort(amount)} / ${win.short}`,
2767
+ resetsAt: new Date(resetsAt).toISOString(),
2768
+ span: FREE_WINDOW_SPAN / 1000,
2769
+ // the window's own model and the ids that share it, so magpie's exact
2770
+ // match finds every id it limits
2771
+ models: [win.model, ...win.aliases],
2772
+ // the ledger's sum is an estimate, shown and set aside; the vendor's
2773
+ // refusal is the one that stops the model (see the window above)
2774
+ ...(refused ? { refused: true } : { aside: true }),
2775
+ })
2776
+
2777
+ // A refusal still in force is exact: the account is spending this window
2778
+ // from elsewhere too, so the sum undercounts it, and the refusal is the
2779
+ // answer the vendor would give again. Its reset is the window's end,
2780
+ // named by the vendor rather than derived from start.
2781
+ let live = null
2782
+ for (const r of mine) {
2783
+ if (Number(r.status) !== 429) continue
2784
+ const t = resetOf(r)
2785
+ if (!Number.isFinite(t) || t <= now || t <= start) continue
2786
+ if (live === null || t > live) live = t
2787
+ }
2788
+ if (live !== null) return card(win.cap, live, true)
2789
+
2790
+ return card(used, end, false)
2791
+ }
2792
+
2793
+ // tokensShort says a token count small: 11.9M, 812k. The credits card's
2794
+ // compact() (2 decimals, credited to credits) reads a token count badly.
2795
+ function tokensShort(n) {
2796
+ if (n >= 1e6) return `${(n / 1e6).toFixed(1)}M`
2797
+ if (n >= 1e3) return `${Math.round(n / 1e3)}k`
2798
+ return String(Math.round(n))
2799
+ }
2800
+
2801
+ // ledgerParsed is the rows read last and what they were read for: the file's
2802
+ // fingerprint, the account and the instant. A file that has not changed hands
2803
+ // back the rows already parsed rather than reading and decoding them again.
2804
+ //
2805
+ // Reading the ledger whole was 48 ms on 2026-10-21 (10.3 MiB, 17925 lines:
2806
+ // 6.4 ms to read, 32.8 ms to JSON.parse, 8 ms to find the window), spent
2807
+ // synchronously on the plugin host's thread every time a panel opened or a
2808
+ // card was asked about, which is what made the free-token window feel slow
2809
+ // beside the credits, whose reading is a network call and so blocks nothing.
2810
+ // A heavy ledger runs to hundreds of MiB, so the read starts at the end.
2811
+ //
2812
+ // The key carries the account because the rows are this account's: one
2813
+ // account's read must not answer for another's. A read for an earlier instant
2814
+ // keeps all the rows a read for a later one would — the bounds are only
2815
+ // further back, and an edge is the same time in either — so the rows held
2816
+ // over answer for the later one too: freeWindowOf is what decides with its
2817
+ // own now.
2818
+ let ledgerParsed = null
2819
+
2820
+ // routingParsed is the WorkBuddy refusals read from a routing file, keyed by
2821
+ // that file, provider and model. The
2822
+ // usage ledger beside it changes on every request; the routing files need not
2823
+ // be read — least of all the gzip days — merely because usage did.
2824
+ const routingParsed = new Map()
2825
+ const routingReads = { count: 0 }
2826
+
2827
+ // ledgerBad is the number of whole lines the ledger last had that could
2828
+ // not be decoded, and the file it was read from, so that a ledger read
2829
+ // once and read again is complained about once, not on every panel open.
2830
+ let ledgerBad = { key: "", count: 0 }
2831
+
2832
+ // freeWindowLedger is the ledgers looked for, in magpie's own folder order
2833
+ // (appdir.Config()): the plugin host runs in that folder — the portable
2834
+ // data folder when magpie runs portable, $XDG_CONFIG_HOME/magpie when that
2835
+ // is set, ~/.config/magpie otherwise — so its cwd answers first; the other
2836
+ // two are named as well, for a plugin asked outside the host. The first
2837
+ // readable ledger wins: a stale copy in a folder magpie does not use must
2838
+ // not hide the live one.
2839
+ //
2840
+ // $XDG_CONFIG_HOME counts only when it is absolute, as appdir.rooted has it:
2841
+ // an empty or relative value is not where magpie keeps its ledger.
2842
+ function freeWindowLedger(cwd = process.cwd(), env = process.env, home = homedir()) {
2843
+ const dirs = [cwd]
2844
+ if (env.XDG_CONFIG_HOME && isAbsolute(env.XDG_CONFIG_HOME)) dirs.push(join(env.XDG_CONFIG_HOME, "magpie"))
2845
+ if (home) dirs.push(join(home, ".config", "magpie"))
2846
+ return dirs.map((d) => join(d, "usage.jsonl"))
2847
+ }
2848
+
2849
+ // freeWindowRouting is the trace files a window can need, from the same root
2850
+ // as the ledger. Magpie writes one plain file a day and gzips the days before,
2851
+ // so only the local dates a 24h window and its lead can reach are named:
2852
+ // three, from the day two days back through today. A busy day goes on past
2853
+ // 256 MB in numbered files (2026-11-13.1.jsonl, magpie 5d93f6b3), each
2854
+ // gzipped in turn, and every one of them is that day's too (#1077).
2855
+ function freeWindowRouting(base, now = Date.now()) {
2856
+ const days = new Set()
2857
+ for (let at = new Date(now); days.size < 3; at.setDate(at.getDate() - 1)) {
2858
+ days.add(`${at.getFullYear()}-${String(at.getMonth() + 1).padStart(2, "0")}-${String(at.getDate()).padStart(2, "0")}`)
2859
+ }
2860
+ let names
2861
+ try {
2862
+ names = readdirSync(join(base, "routing"))
2863
+ } catch {
2864
+ return []
2865
+ }
2866
+ const found = []
2867
+ for (const day of days) {
2868
+ const of = []
2869
+ for (const name of names) {
2870
+ const m = /^(?:\.(\d+))?\.jsonl(\.gz)?$/.exec(name.startsWith(day) ? name.slice(day.length) : "")
2871
+ if (m) of.push({ name, n: Number(m[1] ?? 0), gz: m[2] ? 1 : 0 })
2872
+ }
2873
+ of.sort((a, b) => a.n - b.n || a.gz - b.gz)
2874
+ for (const { name } of of) found.push(join(base, "routing", name))
2875
+ }
2876
+ return found
2877
+ }
2878
+
2879
+ // restIdentity reads the gateway rest key's exact shape,
2880
+ // workbuddy@<account>/<model>: the provider must be this build's whole name,
2881
+ // the model starts at the last slash, and the account is everything before it,
2882
+ // so an account may itself contain @ or /.
2883
+ function restIdentity(rest, win) {
2884
+ if (typeof rest?.key !== "string") return null
2885
+ if (!rest.key.startsWith(win.provider + "@")) return null
2886
+ const tail = rest.key.slice(win.provider.length + 1)
2887
+ const modelAt = tail.lastIndexOf("/")
2888
+ if (modelAt <= 0 || modelAt === tail.length - 1) return null
2889
+ const model = tail.slice(modelAt + 1)
2890
+ return windowModel(model, win) ? { account: tail.slice(0, modelAt), model } : null
2891
+ }
2892
+
2893
+ // routingRefusals turns a routing trace's failed WorkBuddy attempts into the
2894
+ // same shape as a usage row, so freeWindowOf can read the vendor reset an
2895
+ // ordinary usage read never saw. An attempt is named either by order[]'s who
2896
+ // or, when the gateway rest carries a reset, by rest.key's account and model;
2897
+ // keyed accounts are compared case-insensitively, and an order's spelling is
2898
+ // kept. Where both name different accounts the attempt is left out rather
2899
+ // than guessed onto one of them.
2900
+ function routingRefusals(win, text) {
2901
+ const rows = []
2902
+ for (const line of text.split("\n")) routingRefusal(win, line, rows)
2903
+ return rows
2904
+ }
2905
+
2906
+ // routingRefusal adds one trace line's refusals to rows. Only a line that
2907
+ // names a 429 and this build is decoded.
2908
+ function routingRefusal(win, line, rows) {
2909
+ if (!/"status"\s*:\s*429/.test(line)) return
2910
+ if (!line.includes(win.provider)) return
2911
+ let event
2912
+ try {
2913
+ event = JSON.parse(line)
2914
+ } catch {
2915
+ return
2916
+ }
2917
+ const orders = Array.isArray(event?.order) ? event.order : []
2918
+ const named = new Map()
2919
+ const ambiguous = new Set()
2920
+ for (const order of orders) {
2921
+ if (order?.provider !== undefined && order.provider !== win.provider) continue
2922
+ if (typeof order.id !== "string" || typeof order.who !== "string") continue
2923
+ if (ambiguous.has(order.id)) continue
2924
+ const was = named.get(order.id)
2925
+ if (was === undefined) named.set(order.id, order.who)
2926
+ else if (was.toLowerCase() !== order.who.toLowerCase()) {
2927
+ named.delete(order.id)
2928
+ ambiguous.add(order.id)
2929
+ }
2930
+ }
2931
+ for (const attempt of Array.isArray(event?.tries) ? event.tries : []) {
2932
+ if (Number(attempt?.status) !== 429) continue
2933
+ if (attempt.provider !== undefined && attempt.provider !== win.provider) continue
2934
+ if (!windowModel(attempt.model, win)) continue
2935
+ const error = typeof attempt.error === "string" ? attempt.error : typeof attempt.error?.message === "string" ? attempt.error.message : ""
2936
+ const keyed = restIdentity(attempt.rest, win)
2937
+ let reset = windowReset(error)
2938
+ let restUntil = NaN
2939
+ if (!Number.isFinite(reset)) {
2940
+ restUntil = keyed && attempt.rest.by === "resets" ? Date.parse(typeof attempt.rest.until === "string" ? attempt.rest.until : "") : NaN
2941
+ if (Number.isFinite(restUntil)) reset = restUntil
2942
+ }
2943
+ if (!Number.isFinite(reset)) continue
2944
+ const ordered = named.get(String(attempt.id ?? ""))
2945
+ if (ordered !== undefined && keyed && ordered.toLowerCase() !== keyed.account.toLowerCase()) continue
2946
+ const account = ordered ?? keyed?.account
2947
+ if (typeof account !== "string" || !account) continue
2948
+ const keyedOnly = ordered === undefined
2949
+ rows.push({
2950
+ provider: win.provider,
2951
+ providerAccount: account,
2952
+ model: attempt.model,
2953
+ t: attempt.start ?? event?.time,
2954
+ status: 429,
2955
+ err: error,
2956
+ ...(keyedOnly ? { keyedOnly: true } : {}),
2957
+ ...(Number.isFinite(windowReset(error)) ? {} : { restUntil }),
2958
+ })
2959
+ }
2960
+ }
2961
+
2962
+ // ROUTING_LINE_MAX is the longest trace line read; a longer one is passed
2963
+ // over. A refusal's line is a few KiB, and the longest line of a 520 MB day
2964
+ // was 88 KiB (#1077).
2965
+ const ROUTING_LINE_MAX = 4 << 20
2966
+
2967
+ // routingLines calls each with every whole line of a routing trace, from
2968
+ // byte `from` of a plain file on, unzipped as it is read when compressed.
2969
+ // Only a chunk and one line are ever held, never the file: a busy day's .gz
2970
+ // unzipped to 520 MB, and reading it whole took the plugin host past 1 GB
2971
+ // on a 2 GB machine, where the kernel killed it and every request in flight
2972
+ // with it (#1077). It resolves to the offset just past a plain file's last
2973
+ // newline, where a later read goes on: a last line with none yet may be
2974
+ // half written. A .gz's last line is passed whole, as magpie's own reader
2975
+ // takes it. A read that fails part way resolves to how far it got, the
2976
+ // lines before kept.
2977
+ async function routingLines(path, compressed, from, each) {
2978
+ let offset = from
2979
+ let line = [] // the pieces of the line being read, while it fits
2980
+ let lineBytes = 0
2981
+ const add = (piece) => {
2982
+ if (lineBytes + piece.length <= ROUTING_LINE_MAX) line.push(piece)
2983
+ else line = null
2984
+ lineBytes += piece.length
2985
+ }
2986
+ const done = () => {
2987
+ if (line && lineBytes) each(Buffer.concat(line, lineBytes).toString("utf8"))
2988
+ offset += lineBytes
2989
+ line = []
2990
+ lineBytes = 0
2991
+ }
2992
+ const file = createReadStream(path, compressed ? undefined : { start: from })
2993
+ const stream = compressed ? file.pipe(createGunzip()) : file
2994
+ if (compressed) file.on("error", (e) => stream.destroy(e))
2995
+ try {
2996
+ for await (const chunk of stream) {
2997
+ let start = 0
2998
+ for (let nl = chunk.indexOf(10); nl !== -1; nl = chunk.indexOf(10, start)) {
2999
+ add(chunk.subarray(start, nl))
3000
+ done()
3001
+ offset++
3002
+ start = nl + 1
3003
+ }
3004
+ if (start < chunk.length) add(chunk.subarray(start))
3005
+ }
3006
+ if (compressed) done()
3007
+ } catch {
3008
+ file.destroy()
3009
+ stream.destroy()
3010
+ }
3011
+ return offset
3012
+ }
3013
+
3014
+ // routingReading is the reads under way, so that two usage reads at once
3015
+ // read a trace once.
3016
+ const routingReading = new Map()
3017
+
3018
+ async function readRoutingRefusals(path, compressed, win) {
3019
+ let st
3020
+ try {
3021
+ st = statSync(path)
3022
+ } catch {
3023
+ return []
3024
+ }
3025
+ const key = `${path}|${win.provider}|${win.model}`
3026
+ const held = routingParsed.get(key)
3027
+ const fingerprint = `${st.mtimeMs}:${st.size}`
3028
+ if (held?.fingerprint === fingerprint) return held.rows
3029
+ const going = routingReading.get(key)
3030
+ if (going) return going
3031
+ const read = (async () => {
3032
+ routingReads.count++
3033
+ // magpie only appends to a day's plain file, so one that has grown is
3034
+ // read on from where the last read stopped; one that shrank or kept its
3035
+ // size was written anew, and is read whole
3036
+ const grown = !compressed && held && held.ino === st.ino && st.size > held.size
3037
+ const rows = grown ? [...held.rows] : []
3038
+ const offset = await routingLines(path, compressed, grown ? held.offset : 0, (line) => routingRefusal(win, line, rows))
3039
+ routingParsed.set(key, { key, path, fingerprint, size: st.size, ino: st.ino, offset, rows })
3040
+ return rows
3041
+ })()
3042
+ routingReading.set(key, read)
3043
+ try {
3044
+ return await read
3045
+ } finally {
3046
+ routingReading.delete(key)
3047
+ }
3048
+ }
3049
+
3050
+ async function routingRefusalRows(path, compressed, now, account, win = FREE_WINDOW_AI, text) {
3051
+ const parsed = text === undefined ? await readRoutingRefusals(path, compressed, win) : routingRefusals(win, text)
3052
+ const rows = []
3053
+ const oldest = now - 2 * FREE_WINDOW_SPAN
3054
+ for (const attempt of parsed) {
3055
+ const t = Date.parse(attempt.t)
3056
+ if (!Number.isFinite(t) || t < oldest || t > now) continue
3057
+ if (attempt.providerAccount.toLowerCase() !== account.toLowerCase()) continue
3058
+ rows.push({ ...attempt, providerAccount: attempt.keyedOnly ? account : attempt.providerAccount })
3059
+ }
3060
+ return rows
3061
+ }
3062
+
3063
+ // freeWindowRows reads magpie's usage ledger for account, oldest row first.
3064
+ // null when no ledger can be read: the window is then left unknown rather
3065
+ // than guessed.
3066
+ //
3067
+ // The ledger is appended to a line at a time, so a read that lands while a
3068
+ // call is being written can catch that line half-written. Only the last
3069
+ // line can be torn that way (everything before it was written whole), and
3070
+ // only it is passed over in silence. A whole line in the middle that won't
3071
+ // decode is a real fault — a truncated file, a writer that lost a record —
3072
+ // and is said aloud, because passing it over quietly is how a window goes
3073
+ // missing with nothing to point at: on 2026-10-21 a restart caught the
3074
+ // ledger mid-write, the one row holding the free window's start was
3075
+ // dropped without a word, and the panel showed no window at all until the
3076
+ // next read happened to succeed.
3077
+ async function freeWindowRows(account, now = Date.now(), cwd = process.cwd(), env = process.env, home = homedir(), win = FREE_WINDOW_AI) {
3078
+ if (!account) return null
3079
+ let found = null
3080
+ for (const path of freeWindowLedger(cwd, env, home)) {
3081
+ try {
3082
+ const st = statSync(path)
3083
+ if (!st.size) continue
3084
+ found = { path, st }
3085
+ break
3086
+ } catch {}
3087
+ }
3088
+ if (!found) return null
3089
+ const { path, st } = found
3090
+ // size and mtime both move when a call is appended, which is the only
3091
+ // way this ledger is written; one rewritten in place (a rotation or a
3092
+ // compaction) moves mtime even when its size lands the same.
3093
+ const file = path + "|" + st.mtimeMs + ":" + st.size
3094
+ // the key carries the account, the build and the model: one account's
3095
+ // rows are its own, the two builds' chains over one ledger must not
3096
+ // answer for each other (the same phone number can be signed in to both),
3097
+ // and two windows of one build count different models
3098
+ const key = file + "|" + win.provider + "|" + win.model + "|" + account
3099
+ let got
3100
+ if (ledgerParsed?.key === key) {
3101
+ got = ledgerParsed
3102
+ } else {
3103
+ try {
3104
+ got = readLedgerTail(path, st, now, undefined, account, win)
3105
+ } catch {
3106
+ return null
3107
+ }
3108
+ if (got.bad && ledgerBad.key !== file) {
3109
+ ledgerBad = { key: file, count: got.bad }
3110
+ console.error(
3111
+ `workbuddy: ${got.bad} whole line${got.bad === 1 ? "" : "s"} of ${path} could not be decoded ` +
3112
+ `(not the last line, so not a write in progress); the free-token window may read short`,
3113
+ )
3114
+ }
3115
+ ledgerParsed = { key, rows: got.rows }
3116
+ }
3117
+ const routes = freeWindowRouting(dirname(path), now)
3118
+ const current = new Set(routes)
3119
+ for (const [key, held] of routingParsed) if (!current.has(held.path)) routingParsed.delete(key)
3120
+ const refused = []
3121
+ for (const route of routes) refused.push(...(await routingRefusalRows(route, route.endsWith(".gz"), now, account, win)))
3122
+ const rows = [...got.rows, ...refused].sort((a, b) => Date.parse(a.t) - Date.parse(b.t))
3123
+ return rows
3124
+ }
3125
+
3126
+ // LEDGER_T is where a row's time sits: "t" is among the first keys
3127
+ // usage.Record writes, within this many bytes of the line's start, so every
3128
+ // line's time is read without decoding the line — most of a ledger's lines
3129
+ // belong to another provider, or to this account and out of reach.
3130
+ const LEDGER_T = /"t"\s*:\s*"([^"]{10,64})"/
3131
+
3132
+ // LEDGER_ACCOUNT finds the account a line was written under, before the line
3133
+ // is decoded. usage.Record writes providerAccount second.
3134
+ const LEDGER_ACCOUNT = /"providerAccount"\s*:\s*"([^"]{0,256})"/
3135
+
3136
+ // rowTime is the instant a line is written at, from that "t", or NaN.
3137
+ function rowTime(line) {
3138
+ const m = LEDGER_T.exec(line)
3139
+ return m ? Date.parse(m[1]) : NaN
3140
+ }
3141
+
3142
+ // LEDGER_REPORTED finds what a client reported: POST /v1/magpie/usage/requests
3143
+ // (#1874) appends a client's own calls to the same ledger, with the time the
3144
+ // client gives them, and a past time is kept on purpose so history can be
3145
+ // backfilled (docs/integrating.md). Such a row is written at the end of the
3146
+ // file and dated anywhere, so it says nothing about where the file's own
3147
+ // records have got to — magpie's index leaves it out of firstOwn for the same
3148
+ // reason (log_index.go). It never carries providerAccount, being not in
3149
+ // ingestFields, so it is never a row of this account either.
3150
+ const LEDGER_REPORTED = /"source"\s*:\s*"reported"/
3151
+
3152
+ // rowReported is whether a line is one a client reported rather than one
3153
+ // magpie wrote when it happened.
3154
+ function rowReported(line) {
3155
+ return LEDGER_REPORTED.test(line)
3156
+ }
3157
+
3158
+ // rowAccount is the account a line was written under, or null when the line
3159
+ // names none (another record, or one cut short).
3160
+ function rowAccount(line) {
3161
+ const m = LEDGER_ACCOUNT.exec(line)
3162
+ if (!m) return null
3163
+ try {
3164
+ return JSON.parse(`"${m[1]}"`)
3165
+ } catch {
3166
+ return null
3167
+ }
3168
+ }
3169
+
3170
+ // ofAccount is whether a row belongs to the chain read for account: this
3171
+ // account's own row of the window's model, either id. A refusal of another
3172
+ // account's, of the other build, or of another model says nothing about
3173
+ // where this chain opens.
3174
+ function ofAccount(row, account, win = FREE_WINDOW_AI) {
3175
+ return (
3176
+ row?.provider === win.provider &&
3177
+ row.providerAccount === account &&
3178
+ typeof row.model === "string" &&
3179
+ windowModel(row.model, win)
3180
+ )
3181
+ }
3182
+
3183
+ // readLedgerTail decodes the ledger from its end backwards, and stops where
3184
+ // the chain of account's own rows can still be read from. chunks is a test's
3185
+ // way of counting reads; nothing else passes it.
3186
+ //
3187
+ // Why it cannot stop at 48h: the window is a chain — each one starts at the
3188
+ // first request answered after the previous one ended — so where the window
3189
+ // now began depends on every window before it. A first row that is not an
3190
+ // edge opens the window in the middle of a real one and every window after
3191
+ // it is shifted: 4% on an account two hours from its cap, or 100% on one
3192
+ // still served, which routing would then pass over. So the read goes back
3193
+ // until the rows it keeps read the window now as the whole ledger does:
3194
+ //
3195
+ // - a refusal of this account's, whose reset can be read: the window it
3196
+ // named ended there, and the next request opened another;
3197
+ // - a gap of 24h or more between two of this account's answered rows: the
3198
+ // window holding the earlier one has ended by then, and the later one
3199
+ // opens one;
3200
+ // - and with neither, it reads to the file's start, where the chain has no
3201
+ // earlier window to be shifted by.
3202
+ //
3203
+ // Each edge is passed by a day (FREE_WINDOW_LEAD), the window opening at the
3204
+ // request after it, minutes to hours into the day.
3205
+ //
3206
+ // Two bounds keep that from being a whole file on every poll, and neither
3207
+ // depends on how busy the account is:
3208
+ //
3209
+ // - the ledger is appended in time order, so a line whose time is under the
3210
+ // edge — of whatever provider, of whatever account — ends the read;
3211
+ // - a read that is past now - 24h with no answered free-model row of this
3212
+ // account has nothing to report: the window has lapsed, and freeWindowOf
3213
+ // says null. It stops there rather than going on to the edges.
3214
+ //
3215
+ // Every line's time is read from its "t" before the line is decoded, so a
3216
+ // line of another provider or account costs one match and no JSON.parse.
3217
+ //
3218
+ // What is not covered: magpie's providerAccount is the account's label, and a
3219
+ // label two accounts share gets its slot added to it (pluginLabels,
3220
+ // plugin_accounts.go). The label then no longer equals the accountId rows are
3221
+ // written under, no row is found for this account at all, and the card
3222
+ // reports no free window.
3223
+ function readLedgerTail(path, st, now, chunks, account, win = FREE_WINDOW_AI) {
3224
+ const CHUNK = 1 << 16
3225
+ const lapsed = now - FREE_WINDOW_SPAN // a read past this holds no window now
3226
+ const fd = openSync(path, "r")
3227
+ try {
3228
+ // a ledger whose last byte ends a line has no line being written
3229
+ let tornEnd = false
3230
+ if (st.size > 0) {
3231
+ const one = Buffer.allocUnsafe(1)
3232
+ readSync(fd, one, 0, 1, st.size - 1)
3233
+ tornEnd = one[0] !== 0x0a
3234
+ }
3235
+ const rev = [] // the rows kept, latest first
3236
+ let bad = 0
3237
+ let pos = st.size
3238
+ let carry = ""
3239
+ let firstPass = true
3240
+ let stop = false
3241
+ const edge = pinning() // where this account's own rows read so far say the chain is read from
3242
+ let reach = 0 // the row below which nothing is kept: 0 until an edge is found
3243
+ let answered = false // whether an answered free-model row of it is read
3244
+
3245
+ while (pos > 0 && !stop) {
3246
+ const len = Math.min(CHUNK, pos)
3247
+ pos -= len
3248
+ const buf = Buffer.allocUnsafe(len)
3249
+ readSync(fd, buf, 0, len, pos)
3250
+ if (chunks) chunks(1)
3251
+ const lines = (buf.toString("utf8") + carry).split("\n")
3252
+ carry = lines.shift() // its first line is begun in an earlier chunk
3253
+ for (let i = lines.length - 1; i >= 0 && !stop; i--) {
3254
+ const line = lines[i]
3255
+ if (!line.trim()) continue
3256
+ const t = rowTime(line)
3257
+ // Under an edge or the bound, by time alone: nothing below it can be
3258
+ // kept, whatever wrote it — but a line a client reported is dated
3259
+ // where the client's call happened, not where the file has got to.
3260
+ const dated = Number.isFinite(t) && !rowReported(line)
3261
+ if (dated && reach && t < reach) {
3262
+ stop = true
3263
+ break
3264
+ }
3265
+ // A day back with nothing of this account's answered and no edge in
3266
+ // reach: no window is being spent now, and nothing below can open one
3267
+ if (dated && !reach && !answered && t < lapsed) {
3268
+ stop = true
3269
+ break
3270
+ }
3271
+ // Another provider's or another account's line: nothing else to see
3272
+ if (!line.includes(account) || rowAccount(line) !== account) continue
3273
+ let row
3274
+ try {
3275
+ row = JSON.parse(line)
3276
+ } catch {
3277
+ // the last line may be a call still being written, and is passed
3278
+ // over; anything before it is a fault worth saying
3279
+ if (!(firstPass && tornEnd && i === lines.length - 1)) bad++
3280
+ continue
3281
+ }
3282
+ if (!ofAccount(row, account, win)) continue
3283
+ rev.push(row)
3284
+ if (Number(row.status) === 200) answered = true
3285
+ if (!reach) reach = edge(row)
3286
+ }
3287
+ firstPass = false
3288
+ }
3289
+ // the file's first line, with no newline before it: kept only when the
3290
+ // read ran to the file's start
3291
+ if (!stop && pos === 0 && carry.trim() && carry.includes(account) && rowAccount(carry) === account) {
3292
+ const t = rowTime(carry)
3293
+ if (!reach || !Number.isFinite(t) || t >= reach) {
3294
+ try {
3295
+ const row = JSON.parse(carry)
3296
+ if (ofAccount(row, account, win)) rev.push(row)
3297
+ } catch {
3298
+ bad++
3299
+ }
3300
+ }
3301
+ }
3302
+ return { rows: rev.reverse(), bad }
3303
+ } finally {
3304
+ closeSync(fd)
3305
+ }
3306
+ }
3307
+
3308
+ // pinned is where the chain of account's own rows (latest first) is read
3309
+ // from: the time below which nothing is kept. 0 while the rows say nothing
3310
+ // about it yet, and the read then goes to the file's start.
3311
+ //
3312
+ // A row whose time cannot be read is passed over rather than ending the
3313
+ // chain there: one corrupt line used to cut it wherever it sat.
3314
+ function pinned(rows, account) {
3315
+ const at = (r) => Date.parse(r?.t)
3316
+ const apart = (a, b) => a - b >= FREE_WINDOW_GAP
3317
+ // A refusal names where a window ended, and the next request opened
3318
+ // another. The loop walks oldest to newest and overwrites `denied`, so the
3319
+ // one kept is the *newest* readable refusal in the chain, not the earliest:
3320
+ // a later refusal is nearer to now, and its reset is the tighter bound on
3321
+ // where the chain can be read from. A refusal whose reset has already been
3322
+ // passed by a newer one therefore loses, which is what we want — the old
3323
+ // `reset < newest` test that used to guard this is gone, the overwrite does
3324
+ // the same job and keeps the latest.
3325
+ let denied = null
3326
+ for (let i = rows.length - 1; i >= 0; i--) {
3327
+ const reset = Number(rows[i]?.status) === 429 ? resetOf(rows[i]) : NaN
3328
+ if (Number.isFinite(reset)) denied = reset
3329
+ }
3330
+ if (denied !== null) return denied - FREE_WINDOW_LEAD
3331
+ // A day's gap between two answered rows ended every window before it, and
3332
+ // the day before the later row is where the span's reading of the rows
3333
+ // above it begins. The rows come latest first, so each is compared with the
3334
+ // one read before it — the row after it in time, `later`.
3335
+ let later = null
3336
+ for (let i = rows.length - 1; i >= 0; i--) {
3337
+ const r = rows[i]
3338
+ const t = at(r)
3339
+ if (!Number.isFinite(t)) continue
3340
+ if (Number(r.status) !== 200) continue
3341
+ if (later === null) {
3342
+ later = t
3343
+ continue
3344
+ }
3345
+ if (apart(t, later)) return later - FREE_WINDOW_LEAD
3346
+ later = t
3347
+ }
3348
+ // no edge among these rows: the read goes on to the file's start, which is
3349
+ // the whole ledger — the only place a chain needs nothing before it
3350
+ return 0
3351
+ }
3352
+
3353
+ // pinning is pinned read a row at a time: it is handed the account's own
3354
+ // rows latest first, as readLedgerTail reads them, and answers each with what
3355
+ // pinned would answer for every row handed so far — in constant time.
3356
+ //
3357
+ // readLedgerTail used to call pinned on its whole chain after each row, and
3358
+ // pinned walks the chain, so a chain with no edge in it cost the square of
3359
+ // its rows: 10.5 s for 16,000 rows on mote, a minute and more for an account
3360
+ // a server spends on all day (a call a minute is 43,000 rows in a month).
3361
+ // That ran on the plugin host's one thread at every usage read, and the
3362
+ // ledger changes with every call, so nothing held it over: the host sat at
3363
+ // 99% CPU and every session through it stalled (xmoon76 on Discord, the
3364
+ // China build's window being read since 0.2.12).
3365
+ //
3366
+ // It holds because the rows only ever grow at their oldest end, and pinned
3367
+ // was asked only while it answered 0 — no readable refusal and no day's gap
3368
+ // among the rows so far — so the one new thing a row can bring is:
3369
+ //
3370
+ // - a refusal with a readable reset: the newest such is the first read,
3371
+ // and pinned answers it whatever else the rows hold, once a row that is
3372
+ // not a refusal follows (readLedgerTail asked pinned for those alone);
3373
+ // - a day's gap between it and the oldest answered row before it, the only
3374
+ // pair of answered rows not already looked at. pinned answers that with
3375
+ // the older row of the pair, this one.
3376
+ function pinning() {
3377
+ let denied = null // the newest readable refusal's reset
3378
+ let oldest = null // the oldest answered row's time so far
3379
+ return (row) => {
3380
+ const status = Number(row?.status)
3381
+ if (status === 429) {
3382
+ if (denied === null) {
3383
+ const reset = resetOf(row)
3384
+ if (Number.isFinite(reset)) denied = reset
3385
+ }
3386
+ return 0
3387
+ }
3388
+ if (denied !== null) return denied - FREE_WINDOW_LEAD
3389
+ if (status !== 200) return 0
3390
+ const t = Date.parse(row?.t)
3391
+ if (!Number.isFinite(t)) return 0
3392
+ if (oldest !== null && oldest - t >= FREE_WINDOW_GAP) return t - FREE_WINDOW_LEAD
3393
+ oldest = t
3394
+ return 0
3395
+ }
3396
+ }
3397
+
3398
+ // _internal is where these are handed to a test: magpie's host calls every
3399
+ // exported function of a plugin as one of its own factories (host.js,
3400
+ // servers()), so freeWindowRows et al. must not be exports of the plugin.
3401
+
3402
+ // usageOf is the account's credits, from its resource summary: the plan's
3403
+ // credits used against what the cycle grants, as magpie's built-in said —
3404
+ // the count itself too (amount of limit, in credits), for magpie to say it
3405
+ // as used or left beside the share (magpie#659). The free plan is said as a
3406
+ // plan: "Free" alone beside the account read as the model being free, and
3407
+ // routing as preferring it for that (#337).
3408
+ //
3409
+ // A package with no CycleTotalCapacity has no denominator: it is sent as
3410
+ // magpie's balance-shaped window (#3950), {balance, unit} with no used,
3411
+ // limit or aside, and routing ranks it by what is left. A literal "0" total
3412
+ // is still a total, not a wallet: it stays on the old path, so a lapsed or
3413
+ // placeholder package adds nothing. A literal "0" remainder is a reading
3414
+ // of nothing left, not an absent field; only a package with no
3415
+ // CycleRemainCapacity at all leaves the window out. TotalCredits is not a
3416
+ // fallback: an account with no packages at all keeps its unknown allowance,
3417
+ // as before, so its free models are not skipped.
3418
+ //
3419
+ // The plan's own credits and the rest are two windows (akic404 on
3420
+ // Discord): summed, the gifted and activity packages' credits used long
3421
+ // ago put the card at most of its allowance on the first day of the
3422
+ // month, and the plan's pace line said nothing. "Credits" is the plan's
3423
+ // base credits and "Extra credits" every other kind, as WorkBuddy's own
3424
+ // usage panel breaks them down (Jiabubu on Discord: a plan's bonus and
3425
+ // bought credits were nowhere on the card). The summary's CreditGroups
3426
+ // say it in WorkBuddy's words: plan_base ("Plan Base Credits") is the
3427
+ // plan's, plan_bonus, addon ("Top-up Credits") and benefit ("Platform
3428
+ // Reward Credits") are extra. A summary without them is split by code as
3429
+ // the client's resolveCreditGroup does (PLAN_CODES, see planCodes). A
3430
+ // summary with only one kind keeps the one "Credits" window, as before.
3431
+ //
3432
+ // Neither of the two stops the account: WorkBuddy serves it while any
3433
+ // credits are left, of either kind. Both are set aside, and the account's
3434
+ // whole is a third window, "Total credits", which stops it (totalOf).
3435
+ // Before, the one that stopped it was the plan's until its credits were
3436
+ // spent and the extra one's after, so magpie's Routing page said the
3437
+ // plan's "500 / 500" alone on one account and the extra credits on
3438
+ // another, and an account at 90% of its plan's credits was kept for last
3439
+ // with its extra ones untouched (ferock on Discord, 0.2.22).
3440
+ function usageOf(sum, plan, site) {
3441
+ const out = { plan: plan || (sum?.IsPaidUser ? "Pro" : "Free plan"), windows: [] }
3442
+ const { plan: mine, extra, left, bags } = kindsOf(sum, site)
3443
+ if (mine.total > 0 && extra.total > 0) {
3444
+ const credits = creditWindow("Credits", mine), more = creditWindow("Extra credits", extra)
3445
+ out.windows.push(credits, more, totalOf(credits, more))
3446
+ } else {
3447
+ const total = mine.total + extra.total, used = mine.used + extra.used
3448
+ if (total > 0) out.windows.push(creditWindow("Credits", { used, total }))
3449
+ }
3450
+ const total = mine.total + extra.total
3451
+ if (bags > 0 && (total === 0 || left > 0)) out.windows.push({ name: "Prepaid credits", balance: left, display: `${compact(left)} credits`, unit: "credits" })
3452
+ return out
3453
+ }
3454
+
3455
+ // creditWindow is a window of credits used of a total.
3456
+ const creditWindow = (name, { used, total }) => ({ name, used: (100 * used) / total, display: `${compact(used)} / ${compact(total)}`, amount: used, limit: total, unit: "credits" })
3457
+
3458
+ // totalOf is the account's whole credits, the plan's and the extra ones,
3459
+ // as the window that stops it, and sets the two aside (see usageOf). It
3460
+ // renews with the plan's (its cycle, resetsAt and span), and says the
3461
+ // soonest of the two to lapse (runsOutAt, runsOut), as routing reads no
3462
+ // window set aside.
3463
+ function totalOf(plan, extra) {
3464
+ plan.aside = extra.aside = true
3465
+ const w = creditWindow("Total credits", { used: plan.amount + extra.amount, total: plan.limit + extra.limit })
3466
+ if (plan.resetsAt) w.resetsAt = plan.resetsAt
3467
+ if (plan.span) w.span = plan.span
3468
+ const at = (x) => (x.runsOutAt ? Date.parse(x.runsOutAt) : 0)
3469
+ const [a, b] = [at(plan), at(extra)]
3470
+ const soon = a > 0 && (!(b > 0) || a <= b) ? plan : b > 0 ? extra : null
3471
+ if (soon) Object.assign(w, { runsOutAt: soon.runsOutAt, runsOut: soon.runsOut + (a > 0 && a === b ? extra.runsOut : 0) })
3472
+ return w
3473
+ }
3474
+
3475
+ // kindsOf is the summary's credits, the plan's and the extra ones (see
3476
+ // usageOf), and what is left in its packages with no total (a prepaid
3477
+ // balance).
3478
+ function kindsOf(sum, site) {
3479
+ const ofPlan = planCodes(sum, site)
3480
+ const kinds = { plan: { total: 0, used: 0 }, extra: { total: 0, used: 0 }, left: 0, bags: 0 }
3481
+ const hasTotal = (p) => p?.CycleTotalCapacity != null && p.CycleTotalCapacity !== ""
3482
+ const add = (k, p) => ((k.total += capacity(p.CycleTotalCapacity)), (k.used += capacity(p?.CycleUsedCapacity)))
3483
+ const groups = (Array.isArray(sum?.CreditGroups) ? sum.CreditGroups : []).filter(hasTotal)
3484
+ for (const g of groups) add(kinds[g?.Kind === "plan_base" ? "plan" : "extra"], g)
3485
+ for (const p of sum?.Packages ?? []) {
3486
+ if (hasTotal(p)) {
3487
+ if (!groups.length) add(kinds[ofPlan(p?.PackageCode) ? "plan" : "extra"], p)
3488
+ } else if (p?.CycleRemainCapacity != null && p.CycleRemainCapacity !== "") {
3489
+ kinds.left += capacity(p.CycleRemainCapacity)
3490
+ kinds.bags++
3491
+ }
3492
+ }
3493
+ return kinds
3494
+ }
3495
+
3496
+ // listedExtra is the extra credits of the detail lists (packagesOf) that
3497
+ // the summary doesn't list at all, as WorkBuddy's own usage panel counts
3498
+ // them (jiabubu on Discord, magpie 0.1.2774, a China-site free account:
3499
+ // magpie's card read "0 / 500" alone, while the panel shows the extra
3500
+ // kinds beside the plan's). The panel's groups come from the detail
3501
+ // lists, not the summary (buildCreditGroups over fetchUserResources' paid
3502
+ // and free lists), and leave out a package past its end; a slice package
3503
+ // (CapacityType 4) counts the day's slice, as resolveResourceCapacity
3504
+ // does. null when there are none with credits.
3505
+ function listedExtra(sum, packages, site, now = Date.now()) {
3506
+ const summed = new Set((sum?.Packages ?? []).map((p) => p?.PackageCode))
3507
+ const codes = site?.ai ? [...EXTRA_CODES, ...EXTRA_AI] : EXTRA_CODES
3508
+ let total = 0, left = 0, at = 0, lapsing = 0
3509
+ for (const p of packages ?? []) {
3510
+ const code = p?.PackageCode
3511
+ if (!codes.includes(code) || summed.has(code)) continue
3512
+ const end = endOf(p)
3513
+ if (end > 0 && end <= now) continue
3514
+ const slice = String(p?.CapacityType) === SLICE ? p?.SlicePeriodUsageDetails?.[0] : null
3515
+ const of = (v) => { const n = Number(v); return Number.isFinite(n) && n > 0 ? n : 0 }
3516
+ const t = of(slice ? slice.SlicePeriodCapacitySizePrecise : p?.CycleCapacitySizePrecise)
3517
+ const l = Math.min(t, of(slice ? slice.SlicePeriodCapacityRemainPrecise : p?.CycleCapacityRemainPrecise))
3518
+ if (!(t > 0)) continue
3519
+ total += t
3520
+ left += l
3521
+ if (l > 0 && end > 0 && !slice) {
3522
+ if (!at || end < at) at = end, lapsing = l
3523
+ else if (end === at) lapsing += l
3524
+ }
3525
+ }
3526
+ if (!(total > 0)) return null
3527
+ return { total, used: total - left, ...(at ? { runsOutAt: new Date(at).toISOString(), runsOut: lapsing } : {}) }
3528
+ }
3529
+
3530
+ // enterpriseUsageOf is an enterprise (team) account's credits, from
3531
+ // /billing/meter/get-enterprise-user-usage, the meter WorkBuddy's own usage
3532
+ // page (www.workbuddy.cn/profile/usage) reads for one (magpie #1904,
3533
+ // CnsMaple): the resource summary answers such an account with no
3534
+ // packages at all. It counts the cycle's credits flat — credit used of
3535
+ // limitNum — and when the cycle began and resets (UTC+8). null when it
3536
+ // grants none.
3537
+ function enterpriseUsageOf(u) {
3538
+ const limit = capacity(u?.limitNum)
3539
+ if (!(limit > 0)) return null
3540
+ const used = capacity(u?.credit)
3541
+ const w = { name: "Credits", used: (100 * used) / limit, display: `${compact(used)} / ${compact(limit)}`, amount: used, limit, unit: "credits" }
3542
+ const at = (v) => (typeof v === "string" && /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(v.trim()) ? Date.parse(v.trim().replace(" ", "T") + "+08:00") : 0)
3543
+ const reset = at(u?.cycleResetTime), start = at(u?.cycleStartTime)
3544
+ if (reset > 0) w.resetsAt = new Date(reset).toISOString()
3545
+ if (reset > start && start > 0) w.span = (reset - start) / 1000
3546
+ return w
3547
+ }
3548
+
3549
+ // spareFree has the credits windows not count the models that cost none
3550
+ // (notModels): a model at x0.00 draws no credits, and with the credits
3551
+ // used up WorkBuddy still serves it (deepseek-v4.1-flash at 560 / 560,
3552
+ // magpie-community/plugins#138, hheei). Counted, the window at 100% put
3553
+ // the account last, and behind every other, for its free models too. A
3554
+ // model free only some hours (a night promotion) is not free here, as in
3555
+ // the list (priceOf). A list that can't be read leaves the windows as they
3556
+ // are: every model counted, as before.
3557
+ async function spareFree(site, a, windows) {
3558
+ if (!windows.length) return windows
3559
+ let free = []
3560
+ try {
3561
+ free = (await liveModels(site, a)).filter((m) => m.free).map((m) => m.id)
3562
+ } catch {}
3563
+ if (free.length) for (const w of windows) w.notModels = free
3564
+ return windows
3565
+ }
3566
+
3567
+ // The packages' codes, as WorkBuddy's own client lists them when it asks
3568
+ // for each package's credits (its COMMODITY_CODES): the API refuses a
3569
+ // detail list without them (10001 "PackageCodes required").
3570
+ const CODE = (n, s) => `TCACA_code_${n}_${s}`
3571
+ const PAID_CODES = [CODE("002", "AkiJS3ZHF5"), CODE("005", "maRGyrHhw1"), CODE("003", "FAnt7lcmRT"), CODE("023", "4xbGhMrE6q"),
3572
+ CODE("026", "BaESVICNoi"), CODE("027", "0FCGVA6vSa"), CODE("043", "6oIkxT7Z0S"), CODE("009", "0XmEQc2xOf"), CODE("038", "OhvqZtiPKr"), CODE("036", "lupO5WgNdG")]
3573
+ const DAILY_CODE = CODE("001", "PqouKr6QWV")
3574
+ const FREE_CODES = [DAILY_CODE, CODE("008", "cfWoLwvjU4"), CODE("035", "ArVxJcGDsm"), CODE("006", "DbXS0lrypC"), CODE("039", "KRcQj7wUat"),
3575
+ CODE("040", "mi9rCYg46x"), CODE("007", "nzdH5h4Nl0"), CODE("028", "NtpWi0jzXs"), CODE("037", "WxOD3MpI2o"), CODE("029", "6wCGEWquYy"),
3576
+ CODE("030", "BjSt89qTvr")]
3577
+ // a slice package (CapacityType 4) is refreshed each day: its credits are
3578
+ // lost at the same midnight on every account, so they tell none apart
3579
+ const SLICE = "4"
3580
+
3581
+ // PLAN_CODES are the plan's base credits, as WorkBuddy's client (WorkBuddy
3582
+ // AI 5.9.4) groups them in its usage panel (resolveCreditGroup's
3583
+ // planBase): Pro monthly, Pro monthly plus, Pro yearly, youth, advanced,
3584
+ // flagship, buddyOneVip, the international free plan (freeMonIntl), the
3585
+ // Pro trials, and on the China build alone the free plan's monthly base
3586
+ // (freeMon, 套餐基础积分). The plan's bonus (bonus28; bonusIntl, "Plan
3587
+ // Bonus Quota") comes back each cycle too, but the client says it apart
3588
+ // (planBonus), as it does the credit packs (009, 036, 038: addon) and
3589
+ // activity, bonus29/30 and gift (benefit).
3590
+ const PLAN_CODES = [CODE("002", "AkiJS3ZHF5"), CODE("005", "maRGyrHhw1"), CODE("003", "FAnt7lcmRT"), CODE("023", "4xbGhMrE6q"),
3591
+ CODE("026", "BaESVICNoi"), CODE("027", "0FCGVA6vSa"), CODE("043", "6oIkxT7Z0S"), CODE("035", "ArVxJcGDsm"),
3592
+ CODE("039", "KRcQj7wUat"), CODE("040", "mi9rCYg46x")]
3593
+ const FREE_MON = CODE("008", "cfWoLwvjU4")
3594
+
3595
+ // EXTRA_CODES are the kinds of extra credits WorkBuddy's own usage panel
3596
+ // shows beside the plan's base (WorkBuddy 5.5.6, the China build's
3597
+ // resolveCreditGroup): the plan's bonus (bonus28, bonusIntl), top-ups
3598
+ // (extra 009, extra38 038, extraIntl 036) and platform rewards (activity
3599
+ // 007, bonus29, bonus30), and on WorkBuddy AI the free month (008) and
3600
+ // gift (006) too. The China build puts gift in no group, so it shows none.
3601
+ const EXTRA_CODES = [CODE("028", "NtpWi0jzXs"), CODE("037", "WxOD3MpI2o"), CODE("009", "0XmEQc2xOf"), CODE("038", "OhvqZtiPKr"),
3602
+ CODE("036", "lupO5WgNdG"), CODE("007", "nzdH5h4Nl0"), CODE("029", "6wCGEWquYy"), CODE("030", "BjSt89qTvr")]
3603
+ const EXTRA_AI = [FREE_MON, CODE("006", "DbXS0lrypC")]
3604
+
3605
+ // planCodes says whether a package of the summary is the plan's own: one
3606
+ // of PLAN_CODES on that site, or the subscription the summary names.
3607
+ function planCodes(sum, site) {
3608
+ const sub = sum?.SubscriptionPackageCode
3609
+ return (code) => !!code && (code === sub || PLAN_CODES.includes(code) || (!site?.ai && code === FREE_MON))
3610
+ }
3611
+
3612
+ // beijing is WorkBuddy's own time ("2026-10-13 00:39:27" is UTC+8, as its
3613
+ // DeductionEndTime for the same package says).
3614
+ const beijing = (ms) => new Date(ms + 8 * 3600_000).toISOString().slice(0, 19).replace("T", " ")
3615
+
3616
+ // packagesOf is every package of the account with credits, paid and free,
3617
+ // as WorkBuddy's client asks for them: active and used-up (Status 0, 3),
3618
+ // up to 10 pages of 200.
3619
+ async function packagesOf(site, a, now = Date.now()) {
3620
+ const day = beijing(now).slice(0, 10)
3621
+ const lists = [
3622
+ ["/billing/meter/get-user-resource-paid-packages", { PackageCodes: PAID_CODES, NeedRenewInfo: true }],
3623
+ ["/billing/meter/get-user-resource-free-packages", { PackageCodes: FREE_CODES, SlicePeriodStartTime: day + " 00:00:00", SlicePeriodEndTime: day + " 23:59:59" }],
3624
+ ]
3625
+ const out = []
3626
+ for (const [path, extra] of lists) {
3627
+ for (let page = 1; page <= 10; page++) {
3628
+ const d = await meter(site, a, path, { PageNumber: page, PageSize: 200, Status: [0, 3], ...extra })
3629
+ const got = d?.Accounts ?? []
3630
+ out.push(...got)
3631
+ if (got.length < 200 || out.length >= (d?.TotalCount ?? 0)) break
3632
+ }
3633
+ }
3634
+ return out
3635
+ }
3636
+
3637
+ // endOf is when a package's credits are lost: its DeductionEndTime, else
3638
+ // ExpiredTime, else the cycle's end (UTC+8), as WorkBuddy's client reads it.
3639
+ function endOf(p) {
3640
+ const ms = Number(p?.DeductionEndTime)
3641
+ if (ms > 0) return ms
3642
+ for (const v of [p?.ExpiredTime, p?.CycleEndTime]) {
3643
+ if (typeof v !== "string" || !v.trim()) continue
3644
+ const t = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(v.trim()) ? Date.parse(v.trim().replace(" ", "T") + "+08:00") : Date.parse(v)
3645
+ if (t > 0) return t
3646
+ }
3647
+ return 0
3648
+ }
3649
+
3650
+ // runsOutOf is the soonest moment credits left in one of the account's
3651
+ // packages are lost, and how many (cdredfox on X): smart routing spends
3652
+ // the account whose credits expire first. Only packages the summary
3653
+ // counts, with credits left, and not the daily slice; null when none.
3654
+ // only narrows it to the packages of one window (the split's, usageOf).
3655
+ //
3656
+ // A reward the summary doesn't list but the detail lists do (a daily
3657
+ // check-in's credits, each with its own end) is counted too when site is
3658
+ // given, as WorkBuddy's own panel counts them (see listedExtra): the
3659
+ // account serves them like any others, so an account whose check-in
3660
+ // credits lapse first is spent first (cdredfox on X).
3661
+ function runsOutOf(sum, packages, now = Date.now(), only = () => true, site = null) {
3662
+ const counted = new Set((sum?.Packages ?? []).map((p) => p?.PackageCode))
3663
+ if (site) for (const c of site.ai ? [...EXTRA_CODES, ...EXTRA_AI] : EXTRA_CODES) counted.add(c)
3664
+ let at = 0, amount = 0
3665
+ for (const p of packages ?? []) {
3666
+ if (!counted.has(p?.PackageCode) || !only(p?.PackageCode) || p?.PackageCode === DAILY_CODE || String(p?.CapacityType) === SLICE) continue
3667
+ const left = capacity(p?.CycleCapacityRemainPrecise ?? p?.CycleCapacityRemain)
3668
+ const end = endOf(p)
3669
+ if (!(left > 0) || end <= now) continue
3670
+ if (!at || end < at) at = end, amount = left
3671
+ else if (end === at) amount += left
3672
+ }
3673
+ return at ? { runsOutAt: new Date(at).toISOString(), runsOut: amount } : null
3674
+ }
3675
+
3676
+ // cycleOf is when the plan's credits start again, as WorkBuddy's own client
3677
+ // says it (getCurrentPlan's refreshAt): the cycle end of the package the
3678
+ // summary names as the subscription (SubscriptionPackageCode), in UTC+8,
3679
+ // with how long the cycle is. Without it the card had used credits and no
3680
+ // reset, and magpie said "Not used yet" beside 46% (windy on Discord,
3681
+ // 2026-10-26). null when the subscription isn't in the lists, or its cycle
3682
+ // is over.
3683
+ function cycleOf(sum, packages, now = Date.now()) {
3684
+ const code = sum?.SubscriptionPackageCode
3685
+ const at = (v) => (typeof v === "string" && /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(v.trim()) ? Date.parse(v.trim().replace(" ", "T") + "+08:00") : 0)
3686
+ const of = (p) => {
3687
+ const end = at(p?.CycleEndTime), start = at(p?.CycleStartTime)
3688
+ if (!(end > now)) return null
3689
+ return { resetsAt: new Date(end).toISOString(), ...(start > 0 && start < end ? { span: (end - start) / 1000 } : {}) }
3690
+ }
3691
+ // A summary that does name one goes by it alone: named and not listed, or
3692
+ // its cycle over, is unknown — a paid plan's cycle is its subscription's,
3693
+ // never the slice's (yetone, #415).
3694
+ if (code) {
3695
+ for (const p of packages ?? []) if (p?.PackageCode === code) return of(p)
3696
+ return null
3697
+ }
3698
+ // A free account's summary names no subscription at all: both sites answer
3699
+ // SubscriptionPackageCode "" (copilot.tencent.com and www.workbuddy.ai,
3700
+ // measured 2026-10-26 on eight CN accounts and one AI one), so this
3701
+ // returned null and the card of an account whose credits are being spent
3702
+ // said nothing of when they come back — the one thing cycleOf is for.
3703
+ //
3704
+ // Its plan's own credits are the slice (CapacityType 4): packagesOf's
3705
+ // free list returns a month's plan_base with it, 00:00:00 to 23:59:59
3706
+ // UTC+8, the same cycle on every account on both sites (500 credits on
3707
+ // the CN site, 100 on the international), and its CycleEndTime is when
3708
+ // the plan gives the next month's back. A slice tells no account apart,
3709
+ // which is why runsOutOf keeps it out: which account to spend first is a
3710
+ // different question from when the plan refills.
3711
+ for (const p of packages ?? []) if (String(p?.CapacityType) === SLICE) return of(p)
3712
+ return null
3713
+ }
3714
+
3715
+ // ---- models -----------------------------------------------------------------
3716
+
3717
+ // variants are the reasoning levels as OpenCode gives them to the AI SDK.
3718
+ function variants(efforts) {
3719
+ return Object.fromEntries((efforts ?? []).map((e) => [e, { reasoningEffort: e }]))
3720
+ }
3721
+
3722
+ // configModels is the site's own list as a provider's models, each on the
3723
+ // API it is served on: a Claude model on Messages, the rest on chat.
3724
+ // A model declared here (before an account's list is read, for a key
3725
+ // whose CLI reads no config, or when /v3/config can't be read) takes images
3726
+ // unless textOnly says the site drops them: both sites' configs mark every
3727
+ // model supportsImages (read 2026-11-01), and a chat to WorkBuddy AI's
3728
+ // kimi-k3 with a two-colour PNG named both colours (plugins#572). Declared
3729
+ // text-only, as before, every model read as one that can't see.
3730
+ function configModels(site) {
3731
+ return Object.fromEntries(site.models.map(([id, name, context, efforts, output]) => [id, {
3732
+ name,
3733
+ limit: { context, output: output ?? 0 },
3734
+ tool_call: true,
3735
+ attachment: !textOnly(site, id),
3736
+ modalities: { input: textOnly(site, id) ? ["text"] : ["text", "image"], output: ["text"] },
3737
+ // OpenCode (and magpie's host) read a config model's package and URL
3738
+ // from provider: { npm, api }, not api
3739
+ ...(nativeOf(site, id) ? { provider: { npm: NPM_MESSAGES, api: apiMessages(site) } } : {}),
3740
+ ...(efforts ? { reasoning: true, variants: variants(efforts) } : {}),
3741
+ }]))
3742
+ }
3743
+
3744
+ function modelOf(site, provider, m) {
3745
+ return {
3746
+ id: m.id,
3747
+ providerID: provider.id,
3748
+ name: m.name,
3749
+ api: { id: m.id, url: nativeOf(site, m.id) ? apiMessages(site) : api(site), npm: nativeOf(site, m.id) ? NPM_MESSAGES : NPM },
3750
+ status: "active",
3751
+ headers: {},
3752
+ options: {},
3753
+ cost: { input: 0, output: 0, cache: { read: 0, write: 0 } },
3754
+ limit: { context: m.context ?? 0, output: m.output ?? 0 },
3755
+ capabilities: {
3756
+ temperature: true,
3757
+ reasoning: !!m.efforts?.length,
3758
+ attachment: !!m.images,
3759
+ toolcall: true,
3760
+ input: { text: true, image: !!m.images, audio: false, video: false, pdf: false },
3761
+ output: { text: true, image: false, audio: false, video: false, pdf: false },
3762
+ interleaved: false,
3763
+ },
3764
+ release_date: "",
3765
+ variants: variants(m.efforts),
3766
+ // magpie's own: served at no cost to the plan's credits
3767
+ free: !!m.free,
3768
+ // magpie's own: the credits a request costs, as a multiple (0: none)
3769
+ rate: m.rate ?? 0,
3770
+ // magpie's own: the price before a discount running now (0: none)
3771
+ rateWas: m.rateWas ?? 0,
3772
+ }
3773
+ }
3774
+
3775
+ // liveModels asks WorkBuddy's product config for the plan's models: the
3776
+ // "cli" agent's list, each with its details. The CLI User-Agent picks
3777
+ // WorkBuddy's config (a bare WorkBuddy/<v> gets CodeBuddy IDE's, no cli).
3778
+ // creditsOf reads a model's credits, the multiple WorkBuddy's picker shows
3779
+ // by it: "x0.03", "0" or 0; "x0.00" is free. A rate it can't read (or
3780
+ // none, or an infinite one) is undefined: the model is neither free nor
3781
+ // rated. The same rule as magpie's built-in (wbCredits).
3782
+ function creditsOf(c) {
3783
+ if (c == null || c === "") return undefined
3784
+ const s = String(c).trim().toLowerCase().replace(/\s+credits?$/, "").replace(/^x/, "")
3785
+ const n = Number(s)
3786
+ return s !== "" && Number.isFinite(n) && n >= 0 ? n : undefined
3787
+ }
3788
+
3789
+ // freeCredits says whether a model's credits are none: "x0.00", "0" or 0.
3790
+ // A rate it can't read is not free.
3791
+ function freeCredits(c) {
3792
+ return creditsOf(c) === 0
3793
+ }
3794
+
3795
+ // discountOf reads a promotion's price: its discountedCredits ("0.50x",
3796
+ // "0.00x"), else the factor times the model's own credits.
3797
+ function discountOf(p, base) {
3798
+ const said = creditsOf(String(p.discount?.discountedCredits ?? "").trim().replace(/x$/i, ""))
3799
+ if (said !== undefined) return said
3800
+ const f = Number(p.discount?.factor)
3801
+ return Number.isFinite(f) && f >= 0 && base !== undefined ? base * f : undefined
3802
+ }
3803
+
3804
+ // running says whether a promotion is on at now: enabled, and inside its
3805
+ // validFrom..validUntil. Its daily hours are not looked at here.
3806
+ function running(p, now) {
3807
+ if (!p || p.enabled === false) return false
3808
+ const from = Date.parse(p.schedule?.validFrom ?? "")
3809
+ const until = Date.parse(p.schedule?.validUntil ?? "")
3810
+ return !(from > now) && !(until <= now)
3811
+ }
3812
+
3813
+ // priceOf is a model's price as magpie keeps it, from its credits and the
3814
+ // config's modelPromotions (what WorkBuddy's picker shows as 限时免费,
3815
+ // 夜间免费, 夜间折扣). magpie keeps the list it is given until it asks
3816
+ // again, so a price that holds only some hours of the day (Hy4 preview,
3817
+ // free 23:00–8:00 only) is given as its full price, never as free: a list
3818
+ // asked for at night would otherwise say "free" all day (#121). A discount
3819
+ // for whole days (Step-5-Preview's 独家限免) is the price now, with the
3820
+ // price before it as rateWas.
3821
+ function priceOf(d, promotions, now = Date.now()) {
3822
+ const base = creditsOf(d.credits)
3823
+ const mine = (Array.isArray(promotions) ? promotions : []).filter(
3824
+ (p) => p?.kind === "discount" && Array.isArray(p.modelIds) && p.modelIds.includes(d.id) && running(p, now),
3825
+ )
3826
+ if (mine.some((p) => Array.isArray(p.schedule?.daily) && p.schedule.daily.length)) {
3827
+ // by the hour: the full price, which the credits are unless a night
3828
+ // discount already took them to its own price
3829
+ const night = mine.filter((p) => p.discount && Array.isArray(p.schedule?.daily) && p.schedule.daily.length)
3830
+ if (base === undefined || (base === 0 && night.some((p) => discountOf(p, base) === 0))) return { free: false }
3831
+ return { free: false, rate: base }
3832
+ }
3833
+ const off = mine.filter((p) => p.discount).map((p) => discountOf(p, base)).filter((r) => r !== undefined)
3834
+ if (off.length) {
3835
+ const r = Math.min(...off)
3836
+ return { free: r === 0, rate: r, ...(base !== undefined && base > r ? { rateWas: base } : {}) }
3837
+ }
3838
+ if (base === undefined) return {}
3839
+ return { free: base === 0, rate: base }
3840
+ }
3841
+
3842
+ // effortsOf are the levels a config model takes. Most list them in
3843
+ // reasoning.supportedEfforts; some (fast-model, deepseek-v4.1-flash, kimi-k3,
3844
+ // gemini-3.5-flash … on both sites, plugins#255) say only supportsReasoning
3845
+ // and a default reasoning.effort. Those take low, high and max (each
3846
+ // reasoned under a real account, on four of them) and their own default.
3847
+ const EFFORT_ORDER = ["low", "medium", "high", "xhigh", "max"]
3848
+ function effortsOf(d, site, id) {
3849
+ const said = d.reasoning?.supportedEfforts
3850
+ if (Array.isArray(said) && said.length) {
3851
+ // A Claude model on Messages takes max though the config's list stops
3852
+ // at xhigh: measured 2026-10-24, output_config.effort "max" answered
3853
+ // 200 on each Claude model, and on claude-opus-5.5 with more thinking
3854
+ // than xhigh (11248 thinking tokens against 1999, one run each). How
3855
+ // much more a level gives varies by model and run; what matters here
3856
+ // is that a client picking max reaches the server as max, not xhigh.
3857
+ // On chat max means nothing more (see NPM_MESSAGES), so a model there
3858
+ // keeps what the config says.
3859
+ if (nativeOf(site, id) && !said.includes("max")) return [...said, "max"]
3860
+ return said
3861
+ }
3862
+ if (d.supportsReasoning !== true) return []
3863
+ const own = d.reasoning?.effort
3864
+ const set = new Set(["low", "high", "max", ...(typeof own === "string" && EFFORT_ORDER.includes(own) ? [own] : [])])
3865
+ return EFFORT_ORDER.filter((e) => set.has(e))
3866
+ }
3867
+
3868
+ // isCompletion is whether a request is a chat completion: one to
3869
+ // .../chat/completions, or, with no URL to read, a body holding a chat's
3870
+ // messages. Nothing else the loader's fetch sends (magpie's drawings to
3871
+ // /v2/images/*) is a chat: it goes neither gzipped nor given an effort.
3872
+ function isCompletion(url, chat) {
3873
+ let path = ""
3874
+ try {
3875
+ path = new URL(String(url ?? "")).pathname
3876
+ } catch {}
3877
+ if (path) return /\/chat\/completions$/.test(path)
3878
+ return Array.isArray(chat?.messages)
3879
+ }
3880
+
3881
+ // defaultEffortOf is the level WorkBuddy's own client asks a model for when
3882
+ // the user picked none: its CLI's configureThinkingSettings (WorkBuddy
3883
+ // 5.9.3, CLI 2.165.0) takes the session's effort, else the settings', else
3884
+ // the config's reasoning.defaultEffort, else reasoning.effort, and sends it
3885
+ // as reasoning_effort unless thinking was turned off. A request with no
3886
+ // reasoning_effort is not thinking on WorkBuddy's side: measured 2026-10-28
3887
+ // on www.workbuddy.ai, deepseek-v4.1-flash (defaultEffort "high") answered
3888
+ // with 0 reasoning tokens without one, and thought at low and high
3889
+ // (troilus1011 on X, OpenCode's default variant). A default the model's
3890
+ // levels don't hold is left out, as the CLI clamps it to one they do.
3891
+ function defaultEffortOf(d, efforts) {
3892
+ const own = d.reasoning?.defaultEffort ?? d.reasoning?.effort
3893
+ return typeof own === "string" && efforts.includes(own) ? own : undefined
3894
+ }
3895
+
3896
+ // SMALL_BUDGET is the largest output budget a chat can name and still be
3897
+ // one no client meant to think in: Anthropic's API takes thinking only with
3898
+ // a budget of at least 1024 tokens and a max_tokens above it, so a request
3899
+ // of 1024 or less can't have asked for thinking there, and a client's own
3900
+ // short asks (a session title, a classification) name such budgets. A
3901
+ // default effort spends them on reasoning: itspig (#643) saw 230+ title
3902
+ // requests at max_tokens 64 on deepseek-v4-pro end out=64, reasoning=64,
3903
+ // no text. Measured 2026-11-03 on www.workbuddy.ai, deepseek-v4.1-flash-sg
3904
+ // at its default high: max_tokens 64 ended "length" with 64 reasoning
3905
+ // tokens and no text; without an effort it answered the title.
3906
+ const SMALL_BUDGET = 1024
3907
+
3908
+ // withDefaultEffort gives a chat that names no effort the model's default
3909
+ // (defaultEffortOf), as WorkBuddy's client sends it; true when it did. An
3910
+ // effort the client named, "none" too, goes as it came. A chat whose
3911
+ // max_tokens is SMALL_BUDGET or less is given none: WorkBuddy doesn't
3912
+ // think without one, so its budget goes to the answer.
3913
+ function withDefaultEffort(chat, list) {
3914
+ if (!chat || typeof chat !== "object" || namesEffort(chat)) return false
3915
+ const limit = chat.max_tokens ?? chat.max_completion_tokens
3916
+ if (typeof limit === "number" && limit > 0 && limit <= SMALL_BUDGET) return false
3917
+ const m = list?.find((x) => x.id === chat.model)
3918
+ if (!m?.effort) return false
3919
+ chat.reasoning_effort = m.effort
3920
+ return true
3921
+ }
3922
+
3923
+ // namesEffort is whether a chat names its effort itself, in either spelling
3924
+ function namesEffort(chat) {
3925
+ return chat.reasoning_effort !== undefined || (!!chat.reasoning && typeof chat.reasoning === "object" && chat.reasoning.effort !== undefined)
3926
+ }
3927
+
3928
+ async function liveModels(site, a) {
3929
+ const headers = new Headers()
3930
+ sign(site, a, headers)
3931
+ headers.set("User-Agent", cliAgent(site))
3932
+ headers.set("X-Requested-With", "XMLHttpRequest")
3933
+ headers.set("Accept", "application/json")
3934
+ const res = await fetch(endpointOf(site, a) + "/v3/config", { headers, signal: AbortSignal.timeout(15000) })
3935
+ const env = await res.json().catch(() => ({}))
3936
+ if (!res.ok) throw new Error(`${site.name}'s config: HTTP ${res.status}`)
3937
+ if (env.code) throw new Error(`${site.name}'s config: ${env.msg} (${env.code})`)
3938
+ const cfg = env.data ?? {}
3939
+ const models = Array.isArray(cfg.models) ? cfg.models : []
3940
+ const out = []
3941
+ const seen = new Set()
3942
+ const add = (id, d) => {
3943
+ seen.add(id)
3944
+ const m = { id, name: d?.name || id }
3945
+ if (d) {
3946
+ m.context = d.maxInputTokens
3947
+ m.output = d.maxOutputTokens
3948
+ m.images = d.supportsImages === true && !textOnly(site, id)
3949
+ Object.assign(m, priceOf(d, cfg.modelPromotions))
3950
+ const es = effortsOf(d, site, id)
3951
+ if (es.length) {
3952
+ const canOff = d.reasoning?.canDisableThinking
3953
+ const off = (!d.onlyReasoning && (canOff == null || canOff)) || OFF_TAKEN.has(id)
3954
+ m.efforts = [...(off ? ["none"] : []), ...es]
3955
+ const def = defaultEffortOf(d, es)
3956
+ if (def) m.effort = def
3957
+ }
3958
+ }
3959
+ out.push(m)
3960
+ }
3961
+ let cli = false
3962
+ for (const agent of cfg.agents ?? []) {
3963
+ if (agent.name !== "cli") continue
3964
+ cli = true
3965
+ for (const id of agent.models ?? []) add(id, models.find((x) => x.id === id))
3966
+ }
3967
+ // An enterprise's own models ("custom:<name>|<name>", modelType
3968
+ // "enterprise") come in the config's models, not in the cli agent's
3969
+ // list: WorkBuddy's CLI (as bundled in WorkBuddy 5.5.6, read from its
3970
+ // AgentManager.computeModels) appends every model whose id starts with
3971
+ // "custom:" to the agent's list itself, after the ones the agent names,
3972
+ // in the config's order (plugins#1015). The id is sent as it is, "|" and
3973
+ // all: WorkBuddy serves a chat to it. The CLI
3974
+ // appends models tagged "custom" or "chat" too; those in a desktop's
3975
+ // config are its own local models, with their own url and apiKey, and
3976
+ // aren't WorkBuddy's to serve, so they stay out.
3977
+ if (cli) {
3978
+ for (const d of models) {
3979
+ if (typeof d?.id === "string" && d.id.startsWith("custom:") && !seen.has(d.id)) add(d.id, d)
3980
+ }
3981
+ }
3982
+ // tell apart models the config names alike: deepseek-v4.1-flash and
3983
+ // deepseek-v4.1-flash-sg are both "Deepseek-V4.1-Flash"
3984
+ const first = new Map()
3985
+ for (const m of out) {
3986
+ const id = first.get(m.name)
3987
+ if (id === undefined) {
3988
+ first.set(m.name, m.id)
3989
+ continue
3990
+ }
3991
+ const rest = m.id.startsWith(id + "-") ? m.id.slice(id.length + 1) : ""
3992
+ m.name = `${m.name} (${rest ? rest.toUpperCase() : m.id})`
3993
+ }
3994
+ return out
3995
+ }
3996
+
3997
+ // ---- the plugins --------------------------------------------------------------
3998
+
3999
+ // AFTER_TOOLS_REFUSED is WorkBuddy's 400 code 11153, "the conversation must
4000
+ // end with a user message", which WorkBuddy AI's gemini-3.8-flash answers to a
4001
+ // chat whose tool results are followed by the user's message (#113): Claude
4002
+ // Code's reminders, a user's words sent mid-task, a tool's images, which
4003
+ // magpie hands over in a user message after the results. It does end with a
4004
+ // user message; the same chat with any other message between them is served.
4005
+ // The code is matched whole, as with 14018.
4006
+ const AFTER_TOOLS_REFUSED = /must end with a user message|["']code["']\s*:\s*["']?11153(?![\d.])/i
4007
+
4008
+ // replyAfterTools is a chat ending with tool results then the user's
4009
+ // message(s), with an empty assistant message between them, as if the model
4010
+ // had said nothing after the results. Tried with a real WorkBuddy AI
4011
+ // account on 2026-10-14: gemini-3.8-flash serves it and follows the user's
4012
+ // message as a user's, where folded into the tool's result it was read as
4013
+ // the tool's output and its ask left undone. null for any other chat — one
4014
+ // ending with the assistant's message is a prefill, refused as it is.
4015
+ function replyAfterTools(body) {
4016
+ const b = chatOf(body)
4017
+ return replyAfterToolsOn(b) ? JSON.stringify(b) : null
4018
+ }
4019
+
4020
+ // replyAfterToolsOn makes replyAfterTools's change on a chat's object; false
4021
+ // for a chat it doesn't take
4022
+ function replyAfterToolsOn(b) {
4023
+ const msgs = b?.messages
4024
+ if (!Array.isArray(msgs)) return false
4025
+ let i = msgs.length - 1
4026
+ while (i >= 0 && msgs[i]?.role === "user") i--
4027
+ if (i === msgs.length - 1 || i < 0 || msgs[i]?.role !== "tool") return false
4028
+ msgs.splice(i + 1, 0, { role: "assistant", content: "" })
4029
+ return true
4030
+ }
4031
+
4032
+ // HIDE_DSH is the switch, on unless the user turns it off, that takes
4033
+ // DeepSeek Harness's name out of what it sends (NancyTom on X: an account
4034
+ // used from dsh through magpie was banned, and a reply there had Tencent
4035
+ // recognize dsh's built-in prompt). FLAGGED's comma gets a chat past the
4036
+ // live 11128 check; this is for a check that reads the prompt afterwards.
4037
+ // The lines are dsh 0.2.1's own (@deepseek-ai/dsh-system-prompt and
4038
+ // dsh-harness-dev-context): the opener, the checkout and Web GUI lines in
4039
+ // the system prompt and in the runtime context dsh sends as a user message,
4040
+ // and their earlier wording (LEGACY_SOURCE, LEGACY_WEB_SURFACE). Only the
4041
+ // name in prose goes: lower-case dsh, which names paths (~/.dsh), commands,
4042
+ // URIs (dsh-session:) and skills the agent calls, stays, as does a tool's
4043
+ // result, which is what a file or command said. Case counts, so the name
4044
+ // in an identifier (DSH_HOME) is left too.
4045
+ //
4046
+ // The bare name is taken out only where dsh wrote it: the system prompt and
4047
+ // the tools' descriptions (DSH_PROSE). The user's and the assistant's text
4048
+ // get dsh's own lines alone (DSH_LINES: its runtime context comes as a user
4049
+ // message, and the model can quote a line back); a bare DSH or "DeepSeek
4050
+ // Harness" there is the user's own word. liby233 on Discord: a user asked
4051
+ // for "/root/DSH/Work/OC-182.92.66.95/" word for word and got
4052
+ // "/root/the agent harness/Work/…" back. Even in the system prompt a name
4053
+ // in a path or a file name (/root/DSH/, C:\DSH\, DSH.md) is never prose
4054
+ // (IN_PATH_BEFORE, IN_PATH_AFTER), so a working directory dsh writes there stays as it is.
4055
+ const HIDE_DSH = "hide_dsh"
4056
+ const DSH_LINES = [
4057
+ [/You are an AI agent,? powered by DeepSeek Harness\.?/g, "You are an AI agent."],
4058
+ [/DeepSeek Harness (Web GUI)/g, "$1"],
4059
+ [/DeepSeek Harness (implementation checkout)/g, "agent $1"],
4060
+ [/\bDSH itself\b/g, "the agent itself"],
4061
+ ]
4062
+ // before and after a name, what makes it part of a path, a file's name or
4063
+ // an identifier rather than a word of prose
4064
+ const IN_PATH_BEFORE = String.raw`(?<![\w/\\.~:@-])`
4065
+ const IN_PATH_AFTER = String.raw`(?![\w/\\@-]|\.\w)`
4066
+ const DSH_PROSE = [
4067
+ ...DSH_LINES,
4068
+ [new RegExp(IN_PATH_BEFORE + "([Tt]he )?DeepSeek Harness" + IN_PATH_AFTER, "g"), (_, the) => (the ?? "the ") + "agent harness"],
4069
+ [new RegExp(IN_PATH_BEFORE + "DSH" + IN_PATH_AFTER, "g"), "the agent harness"],
4070
+ ]
4071
+
4072
+ // dshHidden takes the name out of text dsh wrote (the system prompt, a
4073
+ // tool's description); in the user's or the assistant's text (said) only
4074
+ // dsh's own lines are reworded.
4075
+ function dshHidden(text, said = false) {
4076
+ for (const [re, to] of said ? DSH_LINES : DSH_PROSE) text = text.replace(re, to)
4077
+ return text
4078
+ }
4079
+
4080
+ // hideDsh puts dshHidden on the text of a chat's messages (Chat
4081
+ // Completions or Messages: a string, or a part of type text), on Messages'
4082
+ // system, and on the tools' descriptions; true when it changed any.
4083
+ // A tool's result (role tool, or a tool_result part) is left as it came.
4084
+ function hideDsh(chat) {
4085
+ if (!chat || typeof chat !== "object") return false
4086
+ let changed = false
4087
+ const parts = (content, said) => {
4088
+ if (typeof content === "string") {
4089
+ const t = dshHidden(content, said)
4090
+ if (t !== content) changed = true
4091
+ return t
4092
+ }
4093
+ if (!Array.isArray(content)) return content
4094
+ return content.map((p) => {
4095
+ if (!p || typeof p.text !== "string" || (p.type !== undefined && p.type !== "text")) return p
4096
+ const t = dshHidden(p.text, said)
4097
+ if (t === p.text) return p
4098
+ changed = true
4099
+ return { ...p, text: t }
4100
+ })
4101
+ }
4102
+ if (Array.isArray(chat.messages))
4103
+ for (const m of chat.messages)
4104
+ if (m && typeof m === "object" && m.role !== "tool") m.content = parts(m.content, m.role !== "system" && m.role !== "developer")
4105
+ if (chat.system !== undefined) chat.system = parts(chat.system, false)
4106
+ const described = (o) => {
4107
+ if (!o || typeof o !== "object") return
4108
+ if (Array.isArray(o)) return o.forEach(described)
4109
+ for (const k of Object.keys(o)) {
4110
+ if (k === "description" && typeof o[k] === "string") {
4111
+ const t = dshHidden(o[k])
4112
+ if (t !== o[k]) {
4113
+ o[k] = t
4114
+ changed = true
4115
+ }
4116
+ } else described(o[k])
4117
+ }
4118
+ }
4119
+ if (Array.isArray(chat.tools)) described(chat.tools)
4120
+ return changed
4121
+ }
4122
+
4123
+ // FREE_ONLY is the switch that keeps an account off credits (#430): its
4124
+ // list holds only the models WorkBuddy serves at no cost (priceOf's free),
4125
+ // and a request for any other is answered here, never sent. A price that
4126
+ // can't be read is not free, and a list that can't be read sends nothing.
4127
+ const FREE_ONLY = "free_only"
4128
+ // PRICE_TTL is how long a list read for that check is used before it is
4129
+ // read again: a promotion that ends stops counting as free within it.
4130
+ const PRICE_TTL = 60_000
4131
+
4132
+ // notFree is the answer to a request the switch keeps from WorkBuddy. Its
4133
+ // words say the model, not the account, is what is turned away, so magpie
4134
+ // rests that model alone and asks another provider of it; they name no
4135
+ // quota or credit, which would rest the whole account as out of credit.
4136
+ function notFree(site, model, why) {
4137
+ const msg = why
4138
+ ? `${site.name}'s model list couldn't be read (${why}), so whether model ${model || "(none)"} is free is unknown; with "Free models only" on it isn't sent`
4139
+ : `model ${model || "(none)"} is not available while "Free models only" is on: ${site.name} charges for it. Turn the switch off in ${site.name}'s provider settings to use it`
4140
+ return new Response(JSON.stringify({ error: { message: msg, type: "invalid_request_error", code: why ? "free_only_unknown" : "model_not_found" } }), {
4141
+ status: why ? 503 : 404,
4142
+ headers: { "content-type": "application/json", "X-Magpie-Sign-In": "kept" },
4143
+ })
4144
+ }
4145
+
4146
+ function makePlugin(site) {
4147
+ // the models of this site that refused tool results then the user's
4148
+ // message, for this run: their next chats go with replyAfterTools at once
4149
+ const endsAfterTools = new Set()
4150
+ // the system prompts this run WorkBuddy refused as an unapproved channel:
4151
+ // their next chats go with systemAsUser at once, not refused first
4152
+ const refusedSystems = new Set()
4153
+ // the system prompts this run WorkBuddy refused as written and took with
4154
+ // OPENERS' comma: their next chats go with the comma set before the first
4155
+ // send, as a moved one goes moved. Without it every turn of that agent —
4156
+ // and every step of its tool loop — pays a refused round trip first, which
4157
+ // is latency on each request and a pattern of channel refusals on the
4158
+ // account. Bounded as refusedSystems is.
4159
+ const commaSystems = new Set()
4160
+ return async ({ client, magpie }) => {
4161
+ // each account's list as last read, for FREE_ONLY: {at, list}
4162
+ const lists = new Map()
4163
+ const listKey = (a) => `${a.uid ?? ""}|${a.enterpriseId ?? ""}|${a.source === "key" ? a.key : ""}`
4164
+ // listed is the account's live list, read again past PRICE_TTL
4165
+ const listed = async (a, fresh = false) => {
4166
+ const k = listKey(a)
4167
+ const was = lists.get(k)
4168
+ if (!fresh && was && Date.now() - was.at < PRICE_TTL) return was.list
4169
+ const list = await liveModels(site, a)
4170
+ lists.set(k, { at: Date.now(), list })
4171
+ if (lists.size > 64) lists.delete(lists.keys().next().value)
4172
+ return list
4173
+ }
4174
+ // effortList is the list a chat's default effort is read from
4175
+ // (withDefaultEffort): listed's, or null when there is none to read — a
4176
+ // key WorkBuddy's CLI reads no config with (as models does), or a read
4177
+ // that failed within PRICE_TTL, so a config that can't be read costs a
4178
+ // chat one try a minute, not one each
4179
+ const unlisted = new Map()
4180
+ const effortList = async (a) => {
4181
+ if (a.source === "key" && !remoteConfig(a.key)) return null
4182
+ const k = listKey(a)
4183
+ if (Date.now() - (unlisted.get(k) ?? 0) < PRICE_TTL) return null
4184
+ try {
4185
+ return await listed(a)
4186
+ } catch {
4187
+ unlisted.set(k, Date.now())
4188
+ if (unlisted.size > 64) unlisted.delete(unlisted.keys().next().value)
4189
+ return null
4190
+ }
4191
+ }
4192
+ const freeOnly = () => magpie?.option?.(site.id, FREE_ONLY) === true
4193
+ // on by default: magpie hands over the user's value, else the default;
4194
+ // OpenCode, with no magpie, has it on
4195
+ const dshOff = () => magpie?.option?.(site.id, HIDE_DSH) !== false
4196
+ // onlyFree is a list with the switch on: its free models, or a failure
4197
+ // when there are none to tell (magpie then keeps the list it had)
4198
+ const onlyFree = (ms) => {
4199
+ if (!freeOnly()) return ms
4200
+ const free = ms.filter((m) => m.free)
4201
+ if (!free.length) throw new Error(`${site.name} lists no free model, and "Free models only" is on`)
4202
+ return free
4203
+ }
4204
+ return {
4205
+ config: async (config) => {
4206
+ config.provider ??= {}
4207
+ config.provider[site.id] ??= {}
4208
+ const p = config.provider[site.id]
4209
+ p.name ??= site.name
4210
+ p.npm ??= NPM
4211
+ p.api ??= api(site)
4212
+ p.models = { ...configModels(site), ...(p.models ?? {}) }
4213
+ },
4214
+ // the conversation's id, which the chats below carry to WorkBuddy:
4215
+ // magpie's (or OpenCode's) session for this request, when it names one
4216
+ "chat.headers": async (input, output) => {
4217
+ const id = input?.model?.providerID ?? input?.provider?.info?.id
4218
+ if (id !== site.id || !input?.sessionID) return
4219
+ output.headers[SESSION] = String(input.sessionID).slice(0, 128)
4220
+ },
4221
+ provider: {
4222
+ id: site.id,
4223
+ // the account's own list, when it's signed in and WorkBuddy answers;
4224
+ // else the list above
4225
+ async models(provider, { auth }) {
4226
+ if (auth?.type === "api") {
4227
+ // asked as WorkBuddy's own CLI asks with a key (remoteConfig)
4228
+ const a = keyAccount(auth)
4229
+ if (!a || !remoteConfig(a.key)) {
4230
+ if (freeOnly()) throw new Error(`${site.name} lists no prices for this key, and "Free models only" is on`)
4231
+ return provider.models
4232
+ }
4233
+ let ms
4234
+ try {
4235
+ ms = await listed(a, true)
4236
+ } catch (e) {
4237
+ if (freeOnly()) throw e
4238
+ return provider.models
4239
+ }
4240
+ if (!ms.length && !freeOnly()) return provider.models
4241
+ return Object.fromEntries(onlyFree(ms).map((m) => [m.id, modelOf(site, provider, m)]))
4242
+ }
4243
+ if (auth?.type !== "oauth" || !(auth.access || auth.source)) return provider.models
4244
+ let ms
4245
+ try {
4246
+ const a = await current(site, client, auth)
4247
+ ms = await listed(a, true)
4248
+ } catch (e) {
4249
+ // with the switch on, a list without prices would offer models
4250
+ // that cost credits: the failure goes up, and magpie keeps the
4251
+ // list it had
4252
+ if (freeOnly()) throw e
4253
+ return provider.models
4254
+ }
4255
+ if (!ms.length && !freeOnly()) return provider.models
4256
+ return Object.fromEntries(onlyFree(ms).map((m) => [m.id, modelOf(site, provider, m)]))
4257
+ },
4258
+ },
4259
+ auth: {
4260
+ provider: site.id,
4261
+ // magpie renews a browser sign-in LEAD_MS before its end (an hour's
4262
+ // token), once for the account, before its requests, models and
4263
+ // usage ask; the check before each request stays for OpenCode,
4264
+ // which doesn't call this. Desktop's sign-in has no expiry stored
4265
+ // and is renewed as before.
4266
+ refreshLead: LEAD_MS,
4267
+ rotating: true,
4268
+ refresh: (auth) => refreshed(site, auth),
4269
+ // the account's daily check-in: magpie can run it once a day per
4270
+ // account, when its WorkBuddy check-in switch is on; the button in
4271
+ // Settings asks right away. China's meter only: the AI build has no
4272
+ // check-in (#47), so the hook stays off its plugin. Errors leave as
4273
+ // throws, not as failed answers: host.js answers a throwing hook to
4274
+ // magpie as an error, whose wbCheckinFailed keeps the offline words
4275
+ // and magpie's 1-minute backoff, where a returned failed waits the
4276
+ // full 30 minutes (magpie-community/plugins#149). checkinOf returns
4277
+ // an outcome only for answers it read and classified.
4278
+ ...(site.ai ? {} : {
4279
+ async checkin(getAuth) {
4280
+ const auth = await getAuth()
4281
+ // an API key reads no credits (see usage), so it has no day to claim
4282
+ if (auth?.type === "api") return { outcome: "ineligible", message: "check-in needs a signed-in account, not an API key" }
4283
+ if (auth?.type !== "oauth" || !(auth.access || auth.source)) return { outcome: "failed", message: "not signed in" }
4284
+ const a = await current(site, client, auth)
4285
+ return await checkinOf(site, a, { waits: [2000, 4000] })
4286
+ },
4287
+ }),
4288
+ options: [
4289
+ {
4290
+ key: FREE_ONLY,
4291
+ label: "Free models only",
4292
+ description: `Lists only the models ${site.name} serves at no cost, and turns away a request for any other here instead of sending it, so no credits are spent. A model free only at night counts as paid.`,
4293
+ // the same words in magpie's other languages, and that the list
4294
+ // leaves models out while it is on (plugins#590); magpie's own
4295
+ // fields, which an older magpie and OpenCode leave alone
4296
+ labels: { zh: "仅免费模型", "zh-TW": "僅免費模型", ja: "無料モデルのみ", de: "Nur kostenlose Modelle" },
4297
+ descriptions: {
4298
+ zh: `只列出 ${site.name} 免费提供的模型;其他模型的请求在这里就被拒绝、不会发出,因此不消耗积分。只在夜间免费的模型按付费算。`,
4299
+ "zh-TW": `只列出 ${site.name} 免費提供的模型;其他模型的請求在這裡就被拒絕、不會送出,因此不消耗積分。只在夜間免費的模型以付費計。`,
4300
+ ja: `${site.name} が無料で提供するモデルだけを表示し、ほかのモデルへのリクエストは送信せずここで断るので、クレジットを消費しません。夜間だけ無料のモデルは有料として扱います。`,
4301
+ de: `Listet nur die Modelle, die ${site.name} kostenlos anbietet, und weist eine Anfrage an jedes andere hier ab, statt sie zu senden, sodass keine Credits verbraucht werden. Ein Modell, das nur nachts kostenlos ist, gilt als kostenpflichtig.`,
4302
+ },
4303
+ filtersModels: true,
4304
+ },
4305
+ {
4306
+ key: HIDE_DSH,
4307
+ label: "Hide DeepSeek Harness's name",
4308
+ description: `Takes DeepSeek Harness's name out of what it sends to ${site.name}: its opening line, and the lines naming its checkout and Web GUI. Paths, commands and tools stay as they are.`,
4309
+ default: true,
4310
+ labels: { zh: "隐去 DeepSeek Harness 的名字", "zh-TW": "隱去 DeepSeek Harness 的名字", ja: "DeepSeek Harness の名前を伏せる", de: "Namen von DeepSeek Harness ausblenden" },
4311
+ descriptions: {
4312
+ zh: `把 DeepSeek Harness 的名字从发给 ${site.name} 的内容里去掉:开头那句,以及说明它源码目录和 Web GUI 的几行。路径、命令和工具保持不变。`,
4313
+ "zh-TW": `把 DeepSeek Harness 的名字從送給 ${site.name} 的內容裡去掉:開頭那句,以及說明它原始碼目錄和 Web GUI 的幾行。路徑、指令和工具保持不變。`,
4314
+ ja: `${site.name} に送る内容から DeepSeek Harness の名前を外します。冒頭の一文と、チェックアウトや Web GUI を示す行が対象です。パス、コマンド、ツールはそのままです。`,
4315
+ de: `Entfernt den Namen von DeepSeek Harness aus dem, was an ${site.name} gesendet wird: die erste Zeile sowie die Zeilen zu seinem Checkout und seiner Web-GUI. Pfade, Befehle und Tools bleiben unverändert.`,
4316
+ },
4317
+ },
4318
+ ],
4319
+ async loader(getAuth) {
4320
+ const auth = await getAuth()
4321
+ if (auth?.type !== "oauth" && auth?.type !== "api") return {}
4322
+ return {
4323
+ // no baseURL: a model's own api.url says where it is served —
4324
+ // <endpoint>/v2 for a chat, <endpoint>/v1 for a Claude model on
4325
+ // Messages. A provider-wide base would put /messages under /v2.
4326
+ baseURL: "",
4327
+ apiKey: "",
4328
+ async fetch(input, init) {
4329
+ const stored = await getAuth()
4330
+ const keyed = stored?.type === "api" ? keyAccount(stored) : null
4331
+ if (stored?.type !== "oauth" && !keyed) throw new Error(`${site.name} isn't signed in`)
4332
+ let a = keyed ?? (await current(site, client, stored))
4333
+ const req = input instanceof Request ? input : null
4334
+ const headers = new Headers(init?.headers ?? req?.headers)
4335
+ headers.delete("authorization")
4336
+ headers.delete("x-api-key")
4337
+ headers.delete("content-length")
4338
+ const session = sessionOf(headers)
4339
+ sign(site, a, headers)
4340
+ let body = init?.body
4341
+ if (body === undefined && req) body = await req.clone().text()
4342
+ // An Anthropic request goes as the agent sent it: WorkBuddy
4343
+ // serves these models on Messages itself, and the rewrites
4344
+ // below (a default system message, the chat endpoint's
4345
+ // max_tokens spelling, tool shapes, the move of a refused
4346
+ // system prompt) exist for the chat endpoint alone. Claude
4347
+ // Code's own system prompt is taken there as it is — measured
4348
+ // 2026-10-24: the billing line, the "official CLI" line,
4349
+ // Codex's and DeepSeek Harness's openings all answer on
4350
+ // /v1/messages, where a chat is refused 11128.
4351
+ const native = isMessages(req ? req.url : String(input), body)
4352
+ // read once (prepared): nothing below parses the body again on
4353
+ // its way out, and nothing keeps the parsed chat once it is
4354
+ // written (plugins#461)
4355
+ let chat, changed, names
4356
+ ;({ body, chat, changed, names } = prepared(body, native))
4357
+ if (native) names = {}
4358
+ if (dshOff() && hideDsh(chat)) changed = true
4359
+ // the switch is checked before anything is sent: a model not
4360
+ // free, or one whose price can't be read, never reaches
4361
+ // WorkBuddy. The model is read off the chat parsed above; a body
4362
+ // prepared leaves unread (bytes on Messages) is read for it.
4363
+ if (freeOnly()) {
4364
+ const model = (chat ?? chatOf(typeof body === "string" ? body : bodyString(body)))?.model
4365
+ let list
4366
+ try {
4367
+ list = await listed(a)
4368
+ } catch (e) {
4369
+ return notFree(site, model, e?.message ?? String(e))
4370
+ }
4371
+ if (!list.some((m) => m.id === model && m.free)) return notFree(site, model)
4372
+ }
4373
+ // a chat that names no effort is asked at the model's default,
4374
+ // as WorkBuddy's client asks it (withDefaultEffort); with no
4375
+ // list to read (effortList) the chat goes as it came
4376
+ const completion = !native && isCompletion(req ? req.url : input, chat)
4377
+ if (completion && chat && !namesEffort(chat) && withDefaultEffort(chat, await effortList(a))) changed = true
4378
+ chatHeaders(site, headers)
4379
+ let who = scopeOf(a)
4380
+ let ids = attendChat(headers, chat, session, who)
4381
+ // the growth event WorkBuddy AI's client sends with a chat (#691),
4382
+ // for the conversation id the chat goes with
4383
+ let grownFor = ""
4384
+ // a chat nothing else changes has the vars set into its own
4385
+ // bytes (withVars), so it isn't written out again whole for
4386
+ // them (plugins#461); one that named extra_vars is written out
4387
+ const hadVars = !!chat && typeof chat === "object" && Object.hasOwn(chat, "extra_vars")
4388
+ if (completion && withGrowth(site, chat, headers.get("X-Conversation-ID") ?? "")) {
4389
+ if (hadVars) changed = true
4390
+ grownFor = headers.get("X-Conversation-ID")
4391
+ }
4392
+ const post = (b) => {
4393
+ // sent as another account (reattend), the chat's conversation
4394
+ // id is that account's, and so is its growth event's
4395
+ const conv = headers.get("X-Conversation-ID") ?? ""
4396
+ if (grownFor && conv && conv !== grownFor) b = regrown(site, b, grownFor, conv) ?? b
4397
+ // a chat goes gzipped, as WorkBuddy's client sends it
4398
+ // (gzipped); its size on the wire is what unanswered weighs
4399
+ const z = gzipped(completion, b)
4400
+ if (z) headers.set("Content-Encoding", "gzip")
4401
+ else headers.delete("Content-Encoding")
4402
+ return fetch(moved(site, a, String(req ? req.url : input)), { ...init, method: init?.method ?? req?.method, headers, body: z ?? b }).catch((e) => unanswered(site, a, z ?? b, e, init?.signal))
4403
+ }
4404
+ // a 401 is answered once, on whichever try meets it: by a
4405
+ // sign-in with another access token (reissued), the request
4406
+ // sent once more with it, never again after that; else, or
4407
+ // when that is refused too, by signedOut. The body is a
4408
+ // string here (or bytes), which goes again as it is; one that
4409
+ // can't be read twice isn't sent again.
4410
+ //
4411
+ // The account is marked (expired) only on WorkBuddy's word
4412
+ // that the sign-in is gone: it turned the refresh token away,
4413
+ // or refused the access token itself (invalidToken) with none
4414
+ // to renew it with, or refused even the token just renewed. A
4415
+ // desktop sign-in is never marked: the app's file is read on
4416
+ // each request, so signing in to the app again is enough.
4417
+ let renewed = false
4418
+ const ours = new WeakSet() // the answers signedOut gave, passed on as they are
4419
+ const out = (why, expired, res) => {
4420
+ const r = signedOut(site, a, why, expired && a.source !== "desktop", edgeNotes.get(res))
4421
+ ours.add(r)
4422
+ return r
4423
+ }
4424
+ const resendable = (b) => b == null || typeof b === "string" || b instanceof ArrayBuffer || ArrayBuffer.isView(b)
4425
+ const send = async (b) => {
4426
+ const res = await post(b)
4427
+ if (res.status !== 401) return res
4428
+ if (renewed) return out("it refused the token renewed for it too", invalidToken(res), res)
4429
+ // a key isn't renewed: the 401 says the key was refused
4430
+ if (a.source === "key") {
4431
+ const r = keyRefused(site, invalidToken(res), edgeNotes.get(res))
4432
+ ours.add(r)
4433
+ return r
4434
+ }
4435
+ if (!resendable(b)) return res
4436
+ await res.body?.cancel().catch(() => {})
4437
+ const r = await reissued(site, client, getAuth, a, stored.access)
4438
+ if (!r.a) return out(r.why, gone(a, r, invalidToken(res)), res)
4439
+ renewed = true
4440
+ a = r.a
4441
+ sign(site, a, headers)
4442
+ ids = reattend(headers, ids, who, (who = scopeOf(a)))
4443
+ const again = await post(b)
4444
+ if (again.status !== 401) return again
4445
+ return out("it refused the token renewed for it too", invalidToken(again), again)
4446
+ }
4447
+ // a model known to turn tool results then the user's message away
4448
+ // gets the empty reply between them up front (see endsAfterTools)
4449
+ const model = chat?.model
4450
+ // a system prompt WorkBuddy refused before goes as the user's
4451
+ // words at once (see systemAsUser)
4452
+ const sysKey = native ? "" : systemKeyOf(chat)
4453
+ if (sysKey && refusedSystems.has(sysKey) && systemAsUserOn(chat)) changed = true
4454
+ // a system prompt whose comma passed once goes with the comma
4455
+ // set before the first send (see commaSystems), the way one
4456
+ // refused before goes moved above
4457
+ if (sysKey && commaSystems.has(sysKey) && commaPausedOn(chat)) changed = true
4458
+ // shaped is a body as such a model takes it. The first try's
4459
+ // is made on the chat already parsed, after the move above,
4460
+ // as shaped would make it of the body written; a resend with
4461
+ // the system prompt moved (below) is shaped again, and a body
4462
+ // that has the reply already is left as it is.
4463
+ const shaped = (b) => (!native && endsAfterTools.has(model) ? replyAfterTools(b) ?? b : b)
4464
+ if (!native && endsAfterTools.has(model) && replyAfterToolsOn(chat)) changed = true
4465
+ if (changed) body = JSON.stringify(chat)
4466
+ else if (grownFor) body = withVars(body, chat.extra_vars)
4467
+ chat = null
4468
+ let res = await send(body)
4469
+ // a signature WorkBuddy's own signing didn't make — a session
4470
+ // moved here from another provider keeps its thinking blocks,
4471
+ // and a truncated or altered one reads the same way — is 11159
4472
+ // too, and none of them can be told apart from a good one
4473
+ // before sending. The request goes once more without them.
4474
+ // Measured 2026-10-24: another vendor's signature answers 11159
4475
+ // on its own, drop_block notwithstanding; without the block the
4476
+ // same history answers 200. Only when the history holds a
4477
+ // signature that isn't this route's own, so a session on this
4478
+ // route never sends twice.
4479
+ if (native && res.status >= 400) {
4480
+ const text = await res.text()
4481
+ const again = BAD_SIGNATURE.test(text) ? withoutSignedThinking(body) : null
4482
+ if (again) res = await send(again)
4483
+ else res = new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers })
4484
+ }
4485
+ if (res.status === 400 && !native) { let text = await res.text()
4486
+ // the vendor may know a shape of the agent's opening that FLAGGED
4487
+ // doesn't: the same words said with one more comma pass it, and
4488
+ // that is tried before the system prompt is moved out of its slot.
4489
+ // The roles the comma went into are kept: one set in the system
4490
+ // prompt is what its next chats go with, one set in an assistant
4491
+ // message alone says nothing about the next chat's.
4492
+ const roles = new Set()
4493
+ const paused = REFUSED.test(text) ? commaPaused(body, roles) : null
4494
+ if (paused) {
4495
+ body = paused
4496
+ res = await send(shaped(body))
4497
+ if (res.status === 400) text = await res.text()
4498
+ // not refused this time: the comma is what passed the
4499
+ // vendor's check, so this system prompt's next chats go
4500
+ // with it set before the first send
4501
+ else if (sysKey && roles.has("system")) {
4502
+ commaSystems.add(sysKey)
4503
+ if (commaSystems.size > 256) commaSystems.delete(commaSystems.values().next().value)
4504
+ }
4505
+ }
4506
+ const moved = res.status === 400 && REFUSED.test(text) && sysKey && !refusedSystems.has(sysKey) ? systemAsUser(body) : null
4507
+ if (moved) {
4508
+ refusedSystems.add(sysKey)
4509
+ if (refusedSystems.size > 256) refusedSystems.delete(refusedSystems.values().next().value)
4510
+ body = moved
4511
+ res = await send(shaped(body))
4512
+ if (res.status === 400) text = await res.text()
4513
+ }
4514
+ const again = res.status === 400 && !endsAfterTools.has(model) && AFTER_TOOLS_REFUSED.test(text) ? replyAfterTools(body) : null
4515
+ if (again) {
4516
+ endsAfterTools.add(model)
4517
+ res = await send(again)
4518
+ } else if (res.status === 400) {
4519
+ res = new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers })
4520
+ }
4521
+ }
4522
+ if (ours.has(res)) return res
4523
+ // renewed here: a mark the account had comes off
4524
+ return res.status >= 400 ? explained(res) : kept(native ? res : unsaid(await renamed(res, names)), renewed ? "renewed" : "kept")
4525
+ },
4526
+ }
4527
+ },
4528
+ // the account's credits, as magpie's built-in showed them; each
4529
+ // read keeps the sign-in (signIn), as the built-in's neither marked
4530
+ // an account lapsed nor cleared it, but for a 401 (gone, below)
4531
+ async usage(getAuth) {
4532
+ const auth = await getAuth()
4533
+ // WorkBuddy's own CLI reads no credits with a key, and what the
4534
+ // billing API answers one is unknown, so a key's card says so
4535
+ if (auth?.type === "api") return { error: `credits unknown with an API key (WorkBuddy's own client reads none with one); see ${site.keys.replace(/\/profile\/keys$/, "")}`, signIn: "kept" }
4536
+ if (auth?.type !== "oauth" || !(auth.access || auth.source)) return { error: "not signed in", signIn: "kept" }
4537
+ try {
4538
+ let a = await current(site, client, auth)
4539
+ // the meter has no /v2 prefix, on either site
4540
+ const SUMMARY = "/billing/meter/get-user-resource-summary"
4541
+ // a 401 is answered as a chat's is: once, by a sign-in with
4542
+ // another access token, else the card says WorkBuddy refused
4543
+ // the sign-in and what to do; renewed, a mark comes off
4544
+ let said = "kept"
4545
+ let sum
4546
+ try {
4547
+ sum = await meter(site, a, SUMMARY)
4548
+ } catch (e) {
4549
+ if (e?.status !== 401) throw e
4550
+ const r = await reissued(site, client, getAuth, a, auth.access)
4551
+ if (!r.a) return { error: refusedText(site, a, r.why), signIn: gone(a, r, e.invalidToken) ? "expired" : "kept" }
4552
+ a = r.a
4553
+ try {
4554
+ sum = await meter(site, a, SUMMARY)
4555
+ } catch (e) {
4556
+ if (e?.status !== 401) throw e
4557
+ const why = "it refused the token renewed for it too"
4558
+ return { error: refusedText(site, a, why), signIn: a.source !== "desktop" && e.invalidToken ? "expired" : "kept" }
4559
+ }
4560
+ said = "renewed"
4561
+ }
4562
+ const out = usageOf(sum, auth.plan, site)
4563
+ // an enterprise account's summary has no packages: its credits
4564
+ // are the enterprise meter's (#1904). A personal account's
4565
+ // refusal of it (10001 "uid or enterpriseID is empty") leaves
4566
+ // the card as the summary said.
4567
+ if (!out.windows.length) {
4568
+ let ent = null
4569
+ try {
4570
+ ent = enterpriseUsageOf(await meter(site, a, "/billing/meter/get-enterprise-user-usage"))
4571
+ } catch {}
4572
+ if (ent) return { plan: auth.plan || "Enterprise", windows: await spareFree(site, a, [ent]), signIn: said }
4573
+ }
4574
+ // when the plan's credits start again (cycleOf), and when the credits
4575
+ // left run out, for routing to spend them first (runsOutOf);
4576
+ // a list that can't be read leaves it unknown, the card stands
4577
+ //
4578
+ // Split (usageOf), the plan's cycle is the plan window's alone;
4579
+ // the soonest credits to lapse, of any package, stay on the window
4580
+ // that stops the account, as routing reads none set aside, and
4581
+ // the window set aside says its own.
4582
+ const credits = out.windows.find((w) => w.name === "Credits")
4583
+ const extra = out.windows.find((w) => w.name === "Extra credits")
4584
+ if (credits) {
4585
+ try {
4586
+ const packages = await packagesOf(site, a)
4587
+ Object.assign(credits, cycleOf(sum, packages) ?? {})
4588
+ const ofPlan = planCodes(sum, site)
4589
+ if (extra) {
4590
+ // split by the summary (usageOf): each says its own
4591
+ // packages' soonest lapse, the whole the soonest of both
4592
+ Object.assign(credits, runsOutOf(sum, packages, Date.now(), ofPlan) ?? {})
4593
+ Object.assign(extra, runsOutOf(sum, packages, Date.now(), (code) => !ofPlan(code), site) ?? {})
4594
+ out.windows.splice(out.windows.findIndex((w) => w.name === "Total credits"), 1, totalOf(credits, extra))
4595
+ } else {
4596
+ // the summary of the plan's credits alone: the extra ones
4597
+ // only the detail lists have (listedExtra) are their window,
4598
+ // and the whole stops the account, as with the summary's
4599
+ // split (ferock on Discord: WorkBuddy goes on serving an
4600
+ // account at "500 / 500" on its extra credits)
4601
+ const kinds = kindsOf(sum, site)
4602
+ const more = kinds.plan.total > 0 && kinds.extra.total === 0 ? listedExtra(sum, packages, site) : null
4603
+ // with no window of their own, their lapse is the one window's
4604
+ Object.assign(credits, runsOutOf(sum, packages, Date.now(), () => true, more ? null : site) ?? {})
4605
+ if (more) {
4606
+ const { runsOutAt, runsOut, ...counts } = more
4607
+ const w = { ...creditWindow("Extra credits", counts), ...(runsOutAt ? { runsOutAt, runsOut } : {}) }
4608
+ out.windows.splice(out.windows.indexOf(credits) + 1, 0, w, totalOf(credits, w))
4609
+ }
4610
+ }
4611
+ } catch {}
4612
+ }
4613
+ await spareFree(site, a, out.windows)
4614
+ // each measured model's own window, which the credit meter above
4615
+ // does not show: what actually refuses a chat long before the
4616
+ // credits are spent. WorkBuddy AI has one (deepseek, 1e8, ten days
4617
+ // of refusals); the China build's are measured one model at a time
4618
+ // (deepseek at about 2e8, 2026-11-02), each its own card. Shown
4619
+ // only, set aside: the vendor's refusal is what stops a model
4620
+ // (see the window definitions above)
4621
+ {
4622
+ const account = a.accountId || a.user || a.uid || ""
4623
+ const wins = site.ai ? [FREE_WINDOW_AI] : CN_ESTIMATED_WINDOWS
4624
+ for (const win of wins) {
4625
+ const rows = await freeWindowRows(account, Date.now(), process.cwd(), process.env, homedir(), win)
4626
+ const w = rows && freeWindowOf(rows, account, Date.now(), win)
4627
+ if (w) out.windows.push(w)
4628
+ }
4629
+ }
4630
+ return { ...out, signIn: said }
4631
+ } catch (e) {
4632
+ return { error: e?.message ?? String(e), signIn: "kept" }
4633
+ }
4634
+ },
4635
+ // magpie's "Import accounts from a file…" (OpenCode ignores these)
4636
+ importFrom: importFrom(site).en,
4637
+ importFroms: importFrom(site).froms,
4638
+ import: (texts) => importSignIns(site, Array.isArray(texts) ? texts : [texts]),
4639
+ methods: [
4640
+ {
4641
+ type: "oauth",
4642
+ label: `${site.name} account (browser)`,
4643
+ authorize: () => browserSignIn(site),
4644
+ },
4645
+ {
4646
+ type: "oauth",
4647
+ label: `${site.name} desktop's sign-in`,
4648
+ authorize: async () => desktopSignIn(site),
4649
+ },
4650
+ {
4651
+ // a key made at site.keys, sent as WorkBuddy's CLI sends one
4652
+ // (keyAccount)
4653
+ type: "api",
4654
+ label: `${site.name} API key`,
4655
+ placeholder: `from ${site.keys.replace(/^https:\/\//, "")}`,
4656
+ },
4657
+ ],
4658
+ },
4659
+ }
4660
+ }
4661
+ }
4662
+
4663
+ // REFUSED_HINT is what the user can do about WorkBuddy's "Illegal API
4664
+ // invocation from an unapproved channel": both builds answer it to a chat
4665
+ // holding words they turn away, whatever the headers. Codex's and Claude
4666
+ // Code's were the first (magpie #182), DeepSeek Harness's and Claude
4667
+ // Desktop's came later (#279, #170), and WorkBuddy reads every message, so
4668
+ // it names no client. FLAGGED rewrites the words known; this is for ones it
4669
+ // doesn't know. It ends the error's message word for word as magpie's
4670
+ // Routing page has it (WB_REFUSED in its routing client.js), which says it
4671
+ // apart from WorkBuddy's own words.
4672
+ const REFUSED_HINT =
4673
+ "WorkBuddy refused words in this client's prompt (most often its system prompt); use it from Hermes, OpenCode or Pi, or add another provider to this group"
4674
+
4675
+ // REFUSED_DOC is where a refusal's fix is written down, for whoever holds the
4676
+ // error next: the person reading it, or the agent they paste it to. It goes
4677
+ // before the hint, never after, because magpie's Routing page tells the hint
4678
+ // from WorkBuddy's own words by the error ending in it.
4679
+ const REFUSED_DOC = "https://github.com/magpie-community/plugins/blob/main/packages/workbuddy/REFUSED.md"
4680
+
4681
+ const REFUSED = /unapproved channel|illegal api invocation/i
4682
+
4683
+ // BAD_SIGNATURE is WorkBuddy's refusal of a thinking block whose signature it
4684
+ // didn't make: internal code 11159, "Invalid `signature` in `thinking` block.
4685
+ // The block is bound to a different conversation", else 11133 wrapping
4686
+ // "thinking_signature_invalid: replay the original thinking block and
4687
+ // signature unchanged".
4688
+ const BAD_SIGNATURE = /thinking_signature_invalid|invalid\s+`?signature`?\s+in\s+`?thinking|block is bound to a different conversation|"internal_code"\s*:\s*"?11159/i
4689
+
4690
+ // RESTRICTED_HINT is what the user can do about WorkBuddy's 403 code 11140
4691
+ // "request illegal", whose displayMsg says "Your account has been restricted
4692
+ // due to unusual activity" (magpie #1849): the account is out until WorkBuddy
4693
+ // lifts the restriction, which an appeal asks for. It ends the error's
4694
+ // message as magpie's built-in puts it (provider.WBRestrictedHint), word for
4695
+ // word, so magpie rests the account for hours rather than minutes.
4696
+ const RESTRICTED_HINT =
4697
+ "WorkBuddy restricted this account for unusual activity; it stays out until WorkBuddy lifts that, which an appeal (Submit feedback in WorkBuddy) asks for"
4698
+ const RESTRICTED_CODE = 11140
4699
+ // The code is matched whole, as with 14018: 111400 is another error.
4700
+ const RESTRICTED_TEXT = /account has been restricted due to unusual activity|账号存在异常行为|帳號存在異常行為|["']code["']\s*:\s*["']?11140(?![\d.])/i
4701
+
4702
+ // EXHAUSTED_HINT explains WorkBuddy's requirement of an active package
4703
+ // even for 0-rate / free models. When an account has no packages or 0 credits,
4704
+ // WorkBuddy returns code 14018 ("Credits exhausted...").
4705
+ const EXHAUSTED_HINT =
4706
+ "WorkBuddy requires an active credit package even for 0-rate free models; check your account package balance"
4707
+ // The code is matched whole: a code that only begins with 14018 (140185) is
4708
+ // another error, and insufficient_quota would rest the account as out of credit.
4709
+ const EXHAUSTED_TEXT = /credits exhausted|额度已用尽|["']code["']\s*:\s*["']?14018(?![\d.])/i
4710
+
4711
+ // kept is an answer that went through, saying the sign-in is kept (the
4712
+ // built-in never cleared a WorkBuddy account's mark, as it never set one),
4713
+ // or "renewed" when it went through on a sign-in renewed for a 401, which
4714
+ // takes a mark off (see signedOut).
4715
+ function kept(res, said = "kept") {
4716
+ const headers = new Headers(res.headers)
4717
+ headers.set("X-Magpie-Sign-In", said)
4718
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
4719
+ }
4720
+
4721
+ // explained is res with REFUSED_HINT, RESTRICTED_HINT or EXHAUSTED_HINT added to that refusal's message.
4722
+ // Each refusal says the sign-in is kept: a 401 never comes here, it is
4723
+ // signedOut's.
4724
+ async function explained(res) {
4725
+ const text = await res.text()
4726
+ const again = (b) => {
4727
+ const headers = new Headers(res.headers)
4728
+ headers.delete("content-length")
4729
+ headers.delete("content-encoding")
4730
+ headers.set("X-Magpie-Sign-In", "kept")
4731
+ return new Response(b, { status: res.status, statusText: res.statusText, headers })
4732
+ }
4733
+ let v
4734
+ try {
4735
+ v = JSON.parse(text)
4736
+ } catch {}
4737
+ const at = v?.error && typeof v.error === "object" ? v.error : v && typeof v === "object" ? v : null
4738
+ // the Messages route words its code two more ways (seen 2026-10-24):
4739
+ // {"error": {"code": "400001", "internal_code": "11159", …}}, and
4740
+ // {"code": 11102, "error": "11158:…"}, the code that says what happened
4741
+ // first in a string error, where the outer one only says it failed
4742
+ const inner = at?.internal_code ?? (typeof v?.error === "string" ? v.error.match(/^(\d{5}):/)?.[1] : undefined)
4743
+ const codes = [inner, at?.data?.code, at?.code, v?.code, v?.data?.code].filter((c) => c != null).map(Number)
4744
+ const isRefused = REFUSED.test(text)
4745
+ const isRestricted = !isRefused && (codes.includes(RESTRICTED_CODE) || RESTRICTED_TEXT.test(text))
4746
+ const isExhausted = !isRestricted && (codes.includes(14018) || EXHAUSTED_TEXT.test(text))
4747
+ if (!isRefused && !isRestricted && !isExhausted) return again(text)
4748
+
4749
+ let msg = text.trim()
4750
+ if (at && typeof at.message === "string") msg = at.message
4751
+ else if (typeof at?.data?.msg === "string") msg = at.data.msg
4752
+ else if (typeof v?.error === "string") msg = v.error
4753
+ else if (typeof v?.msg === "string" && v.msg) msg = v.msg // WorkBuddy's own {"code", "msg"}
4754
+ else if (typeof v?.data?.msg === "string") msg = v.data.msg
4755
+
4756
+ const hint = isRefused ? REFUSED_HINT : isRestricted ? RESTRICTED_HINT : EXHAUSTED_HINT
4757
+ const type = isRefused || isRestricted ? "permission_error" : "insufficient_quota"
4758
+ const errCode = isRefused ? null : isRestricted ? RESTRICTED_CODE : 14018
4759
+ // a refusal says where its fix is written down, so whoever holds the error
4760
+ // — the person, or the agent they paste it to — can go and read it. It goes
4761
+ // before the hint, never after: the hint is the message's end.
4762
+ const where = isRefused ? `${REFUSED_DOC} — ` : ""
4763
+ msg = `${msg} — ${where}${hint}`
4764
+ const headers = new Headers(res.headers)
4765
+ headers.set("content-type", "application/json")
4766
+ headers.delete("content-length")
4767
+ headers.delete("content-encoding")
4768
+ headers.set("X-Magpie-Sign-In", "kept")
4769
+ return new Response(JSON.stringify({ error: { message: msg, type, code: errCode } }), { status: res.status, statusText: res.statusText, headers })
4770
+ }
4771
+
4772
+ export const WorkBuddyAuthPlugin = makePlugin(SITES.workbuddy)
4773
+ export const WorkBuddyAIAuthPlugin = makePlugin(SITES["workbuddy-ai"])
4774
+
4775
+ // for tests
4776
+ export const _internal = { endpointOf, moved, at, signInsIn, importSignIns, importFrom, otherSite, withGrowth, inputLengthOf, HIDE_DSH, hideDsh, dshHidden, planCodes, listedExtra, idFor, OFF_TAKEN, replyAfterToolsOn, withDefaultEffort, SMALL_BUDGET, defaultEffortOf, gzipped, FREE_ONLY, PRICE_TTL, keyAccount, remoteConfig, cycleOf, typeUnions, systemAsUser, systemKey, DEFAULT_SYSTEM, EDGE_READS, fitShape, replyAfterTools, AFTER_TOOLS_REFUSED, enterpriseUsageOf, accountName, notDesktop, textOnly, runsOutOf, packagesOf, endOf, enterpriseHeaders, enterpriseOf, liveModels, browserSignIn, withSystem, asReasoning, normalizeToolChoice, fitTools, fitted, renamed, unsaid, FILTER_SAYS, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, RESTRICTED_HINT, EXHAUSTED_HINT, REFUSED_DOC, commaPaused, commaPausedOn, opened, freeCredits, creditsOf, priceOf, fresh, SITES, renewing, renewed, SESSION, attend, scopeOf, turnKey, conversationKey, signatureOf, isMessages, withoutUnsigned, withoutSignedThinking, prepared, answeredBefore, nativeOf, modelOf, configModels, freeWindowOf, tokensShort, freeWindowRows, freeWindowLedger, freeWindowRouting, routingRefusalRows, readRoutingRefusals, readLedgerTail, pinned, pinning, rowTime, rowAccount, ofAccount, windowOffset, windowReset, CN_ESTIMATED_WINDOWS, FREE_WINDOW_AI, FREE_WINDOW_SPAN, FREE_WINDOW_GAP, FREE_WINDOW_LEAD, checkinOf, API_MESSAGES: NPM_MESSAGES, API_CHAT: NPM, routingReads, routingParsed, restIdentity, routingLines, ROUTING_LINE_MAX }